问:
How to Add and Compare Results from Subqueries
I have the following code written for a larger report that I have been working on. I have three columns resulting from subqueries: req_hrs, e_hrs, inprog_hrs. I need to add together the e_hrs and inprog_hrs, thus seeing whether that number is greater than or equal to req_hrs. If that is true, I need to return either an * or a null value.

Can someone please explain to me how I can add the two subquery results (e_hrs and inprog_hrs) together, and then compare that result to req_hrs thus returning said * or NVL? Code is below, Thank you:

```<code>SELECT
spriden_last_name lname,
spriden_first_name fname,
spriden_mi mi,
spriden_id id,
x.shrdgmr_majr_code_1 majr,
x.shrdgmr_grad_date grad_dt,
x.shrdgmr_degs_code degs,
DECODE(stvdegs_award_status_ind,'A','*',NULL) award_ind,

**DECODE(NVL(m.smbagen_req_credits_overall,0),0,
  DECODE(NVL(sorcmjr_req_hours_ssdf,0),0,
  DECODE(stvdegc_acat_code,'22',32,'23',64,'24',124,'42',42,999),
  sorcmjr_req_hours_ssdf),m.smbagen_req_credits_overall) req_hrs,**

**TRUNC(shrlgpa_hours_earned,2) AS e_hrs,**

**(SELECT
     NVL(SUM(sfrstcr_credit_hr),0)
 FROM
     sfrstcr
 WHERE
     sfrstcr_term_code = '&inprog_term'
 AND sfrstcr_pidm = x.shrdgmr_pidm
 AND sfrstcr_rsts_code IN ('RE','RW')
 AND NOT EXISTS (
     SELECT
         'Y'
     FROM
         shrtckn,
         shrtckg j
     WHERE
         shrtckn_pidm = sfrstcr_pidm
     AND shrtckn_term_code = sfrstcr_term_code
     AND shrtckn_crn = sfrstcr_crn
     AND j.shrtckg_pidm = shrtckn_pidm
     AND j.shrtckg_term_code = shrtckn_term_code
     AND j.shrtckg_tckn_seq_no = shrtckn_seq_no
     AND j.shrtckg_seq_no = (
         SELECT
             MAX(k.shrtckg_seq_no)
         FROM
             shrtckg k
         WHERE
             k.shrtckg_pidm = shrtckn_pidm
         AND k.shrtckg_term_code = shrtckn_term_code
         AND k.shrtckg_tckn_seq_no = shrtckn_seq_no))) AS inprog_hrs,**

ROUND(shrlgpa_gpa,2) gpa,
DECODE(SIGN(shrlgpa_gpa - 3.90),0,'S',1,'S',
  DECODE(SIGN(shrlgpa_gpa - 3.75),0,'M',1,'M',
  DECODE(SIGN(shrlgpa_gpa - 3.50),0,'C',1,'C',NULL))) latin,
(SELECT
     m.shrasdl_astd_code_dl
 FROM
     shrasdl m
 WHERE
     m.shrasdl_term_code_effective = (
     SELECT
         MAX(n.shrasdl_term_code_effective)
     FROM
         shrasdl n)
 AND m.shrasdl_min_gpa_term = (
     SELECT
         MAX(n.shrasdl_min_gpa_term)
     FROM
         shrasdl n
     WHERE
         n.shrasdl_term_code_effective = m.shrasdl_term_code_effective
     AND shrlgpa_gpa >= n.shrasdl_min_gpa_term)) honors
FROM
shrdgmr x,
stvdegs,
stvdegc,
spriden,
sorcmjr,
smbagen m,
shrlgpa
WHERE
TO_CHAR(x.shrdgmr_grad_date,'MON-YY') IN ('&grad_dt1', NVL('&grad_dt2','XXX-
00'))
AND x.shrdgmr_seq_no = (
SELECT
    MAX(z.shrdgmr_seq_no)
FROM
    shrdgmr z
WHERE
    z.shrdgmr_pidm = x.shrdgmr_pidm
AND z.shrdgmr_majr_code_1 = x.shrdgmr_majr_code_1
AND z.shrdgmr_grad_date IS NOT NULL)
AND stvdegs_code = x.shrdgmr_degs_code
AND stvdegc_code = x.shrdgmr_degc_code
AND spriden_pidm = x.shrdgmr_pidm
AND spriden_change_ind IS NULL
AND sorcmjr_cmjr_rule(+) = x.shrdgmr_cmjr_rule_1_1
AND REPLACE(m.smbagen_area(+),'-CORE','') = x.shrdgmr_majr_code_1
AND m.smbagen_active_ind(+) = 'Y'
AND m.smbagen_term_code_eff(+) <= x.shrdgmr_term_code_grad
AND ((m.smbagen_area IS NULL)
OR   (m.smbagen_area IS NOT NULL
AND   m.smbagen_term_code_eff = (
  SELECT
      MAX(n.smbagen_term_code_eff)
  FROM
      smbagen n
  WHERE
      REPLACE(n.smbagen_area,'-CORE','') = x.shrdgmr_majr_code_1
  AND n.smbagen_active_ind = 'Y'
  AND n.smbagen_term_code_eff <= x.shrdgmr_term_code_grad)))
AND shrlgpa_pidm(+) = x.shrdgmr_pidm
AND shrlgpa_levl_code(+) = x.shrdgmr_levl_code
AND shrlgpa_gpa_type_ind(+) = 'O'
ORDER BY
spriden_last_name,
spriden_first_name,
spriden_mi
;
</code>```

答:
Compare the sum of the union of the two sources with the required amount.

In simplified form:

```<code>select somekey, sum(hrs) worked_hrs, sum(req_hrs) required_hrs
from (
     select
        somekey,
        e_hrs hrs
    from e_hrs_table
    where ...
    union all   -- the "all" is important to leave in!
    select
        somekey,
        inprog_hrs
    from inprog_hrs_table
    where ...
    ) x
join req_hrs_table on req_hrs_table.somekey = x.somekey
where ... -- add req_hrs_table conditions here
group by somekey
</code>```

You can add

```<code>having sum(hrs) < sum(req_hrs)
</code>```

if you want only those rows that did not meet the quota.

Body:
I have the following code written for a larger report that I have been working on. I have three columns resulting from subqueries: req_hrs, e_hrs, inprog_hrs. I need to add together the e_hrs and inprog_hrs, thus seeing whether that number is greater than or equal to req_hrs. If that is true, I need to return either an * or a null value.

Can someone please explain to me how I can add the two subquery results (e_hrs and inprog_hrs) together, and then compare that result to req_hrs thus returning said * or NVL? Code is below, Thank you:

SELECT
spriden_last_name lname,
spriden_first_name fname,
spriden_mi mi,
spriden_id id,
x.shrdgmr_majr_code_1 majr,
x.shrdgmr_grad_date grad_dt,
x.shrdgmr_degs_code degs,
DECODE(stvdegs_award_status_ind,'A','*',NULL) award_ind,

**DECODE(NVL(m.smbagen_req_credits_overall,0),0,
  DECODE(NVL(sorcmjr_req_hours_ssdf,0),0,
  DECODE(stvdegc_acat_code,'22',32,'23',64,'24',124,'42',42,999),
  sorcmjr_req_hours_ssdf),m.smbagen_req_credits_overall) req_hrs,**

**TRUNC(shrlgpa_hours_earned,2) AS e_hrs,**

**(SELECT
     NVL(SUM(sfrstcr_credit_hr),0)
 FROM
     sfrstcr
 WHERE
     sfrstcr_term_code = '&inprog_term'
 AND sfrstcr_pidm = x.shrdgmr_pidm
 AND sfrstcr_rsts_code IN ('RE','RW')
 AND NOT EXISTS (
     SELECT
         'Y'
     FROM
         shrtckn,
         shrtckg j
     WHERE
         shrtckn_pidm = sfrstcr_pidm
     AND shrtckn_term_code = sfrstcr_term_code
     AND shrtckn_crn = sfrstcr_crn
     AND j.shrtckg_pidm = shrtckn_pidm
     AND j.shrtckg_term_code = shrtckn_term_code
     AND j.shrtckg_tckn_seq_no = shrtckn_seq_no
     AND j.shrtckg_seq_no = (
         SELECT
             MAX(k.shrtckg_seq_no)
         FROM
             shrtckg k
         WHERE
             k.shrtckg_pidm = shrtckn_pidm
         AND k.shrtckg_term_code = shrtckn_term_code
         AND k.shrtckg_tckn_seq_no = shrtckn_seq_no))) AS inprog_hrs,**

ROUND(shrlgpa_gpa,2) gpa,
DECODE(SIGN(shrlgpa_gpa - 3.90),0,'S',1,'S',
  DECODE(SIGN(shrlgpa_gpa - 3.75),0,'M',1,'M',
  DECODE(SIGN(shrlgpa_gpa - 3.50),0,'C',1,'C',NULL))) latin,
(SELECT
     m.shrasdl_astd_code_dl
 FROM
     shrasdl m
 WHERE
     m.shrasdl_term_code_effective = (
     SELECT
         MAX(n.shrasdl_term_code_effective)
     FROM
         shrasdl n)
 AND m.shrasdl_min_gpa_term = (
     SELECT
         MAX(n.shrasdl_min_gpa_term)
     FROM
         shrasdl n
     WHERE
         n.shrasdl_term_code_effective = m.shrasdl_term_code_effective
     AND shrlgpa_gpa >= n.shrasdl_min_gpa_term)) honors
FROM
shrdgmr x,
stvdegs,
stvdegc,
spriden,
sorcmjr,
smbagen m,
shrlgpa
WHERE
TO_CHAR(x.shrdgmr_grad_date,'MON-YY') IN ('&grad_dt1', NVL('&grad_dt2','XXX-
00'))
AND x.shrdgmr_seq_no = (
SELECT
    MAX(z.shrdgmr_seq_no)
FROM
    shrdgmr z
WHERE
    z.shrdgmr_pidm = x.shrdgmr_pidm
AND z.shrdgmr_majr_code_1 = x.shrdgmr_majr_code_1
AND z.shrdgmr_grad_date IS NOT NULL)
AND stvdegs_code = x.shrdgmr_degs_code
AND stvdegc_code = x.shrdgmr_degc_code
AND spriden_pidm = x.shrdgmr_pidm
AND spriden_change_ind IS NULL
AND sorcmjr_cmjr_rule(+) = x.shrdgmr_cmjr_rule_1_1
AND REPLACE(m.smbagen_area(+),'-CORE','') = x.shrdgmr_majr_code_1
AND m.smbagen_active_ind(+) = 'Y'
AND m.smbagen_term_code_eff(+) <= x.shrdgmr_term_code_grad
AND ((m.smbagen_area IS NULL)
OR   (m.smbagen_area IS NOT NULL
AND   m.smbagen_term_code_eff = (
  SELECT
      MAX(n.smbagen_term_code_eff)
  FROM
      smbagen n
  WHERE
      REPLACE(n.smbagen_area,'-CORE','') = x.shrdgmr_majr_code_1
  AND n.smbagen_active_ind = 'Y'
  AND n.smbagen_term_code_eff <= x.shrdgmr_term_code_grad)))
AND shrlgpa_pidm(+) = x.shrdgmr_pidm
AND shrlgpa_levl_code(+) = x.shrdgmr_levl_code
AND shrlgpa_gpa_type_ind(+) = 'O'
ORDER BY
spriden_last_name,
spriden_first_name,
spriden_mi
;

Body:
Compare the sum of the union of the two sources with the required amount.

In simplified form:

select somekey, sum(hrs) worked_hrs, sum(req_hrs) required_hrs
from (
     select
        somekey,
        e_hrs hrs
    from e_hrs_table
    where ...
    union all   -- the "all" is important to leave in!
    select
        somekey,
        inprog_hrs
    from inprog_hrs_table
    where ...
    ) x
join req_hrs_table on req_hrs_table.somekey = x.somekey
where ... -- add req_hrs_table conditions here
group by somekey

You can add

having sum(hrs) < sum(req_hrs)

if you want only those rows that did not meet the quota.


来源: stackexchange

问:
iOS - Creating a dynamic User Interface from a database
I have a requirement that I need to build a View for an iPAD application from reading values from a database.

When loading the application, I will make a server call to PHP and PHP will return JSON back to me.  From that result set, I would like to be able to dynamically build my UI on the iPAD.

Can someone please point me in the right direction or give me some suggestions?

答:
There's a WWDC 2010 session video on exactly this method.  Was called "Building a server-driven user experience".

You have a server send an app XML, JSON, or a compressed plist (recommended), with all the UI object coordinates, colors, visibility, text, images, etc., then parse the data, and instantiate the apps UI from that data.  Save the UI data in a local database for offline use. etc.

You are not allowed to download scripts (*) to an App store app, but you can include lots of built-in script options from which you select at runtime the desired behavior.

Added: As of 2017 (dev agreement section 3.3.2), Apple now allows downloading certain kinds of scripts to apps, but only for educational/tutorial purposes, not if they significantly change the behavior of the app.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Speed up recursive method by converting into iterative
I'm writing a dynamic programming algorithm in Python which seems to be working perfectly for smaller inputs but it times out for large inputs probably because of the recursive calls. I read this article online which says that most modern programming languages don't deal with recursion well and it's a better idea to convert them into an iterative method.

My algorithm is as follows:

```<code>def get_val(x,y,g,i,xlast,ylast):
    # checks if array over
    if(i>(len(x)-1)):
        return 0
    # else returns the max of the two values
    # dist returns the euclidian distance between the two points
    # the max condition just decides if it's profitable to move to the
    # next x and y coordinate or if it would be better to skip this particular (x, y)
    return max(g[i]-dist(x[i],y[i],xlast,ylast) + get_val(x,y,g,i+1,x[i],y[i]),get_val(x,y,g,i+1,xlast,ylast))
</code>```

I have been trying to improve its performance but I'm not really sure about the steps I should take to ensure that it doesn't time out on large inputs.

答:
Writing a dynamic programming algorithm implies that you are already dealing with the recursive calls, so your current code is not dynamic programming yet.

You need to identify what is causing the problem and then provide a solution which take less steps to compute your function in exchange of memory consumption, this is, storing function calls results to avoid a new calculation of the same call.

I don't know all the details of your problem but it seems to have an optimal substructure property.

You will find a guide on how to tell what kind of problem you are dealing with and how to solve it here

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a dynamic programming algorithm in Python which seems to be working perfectly for smaller inputs but it times out for large inputs probably because of the recursive calls. I read this article online which says that most modern programming languages don't deal with recursion well and it's a better idea to convert them into an iterative method.

My algorithm is as follows:

def get_val(x,y,g,i,xlast,ylast):
    # checks if array over
    if(i>(len(x)-1)):
        return 0
    # else returns the max of the two values
    # dist returns the euclidian distance between the two points
    # the max condition just decides if it's profitable to move to the
    # next x and y coordinate or if it would be better to skip this particular (x, y)
    return max(g[i]-dist(x[i],y[i],xlast,ylast) + get_val(x,y,g,i+1,x[i],y[i]),get_val(x,y,g,i+1,xlast,ylast))

I have been trying to improve its performance but I'm not really sure about the steps I should take to ensure that it doesn't time out on large inputs.


问:
ERROR using a class as a vector type - "Undeclared identifier"
Hello Stack Overflow!

I have encountered a problem which I have tried to solve but have not succeeded with, therefore I am turning my head towards you programmers hoping for answers.

What I am suspecting the problem is, is that it has to do with my main.cpp which I haven't started coding in yet for reasons. Could be very wrong though.

Any tips/hints are appreciated!

The error is about this part located in the BankFunctions header

```<code>// Vector
   static std::vector<accounts> users;
</code>```

The error messages are listed at the bottom.

I have included the two class header files.

Main.cpp:

```<code>// Classes
#include "BankFunctions.h" // Handles the bank functions
#include "accounts.h" // Handles the customer accounts

// Libraries
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <Windows.h>
#include <sstream>

int main() {

    return 0;
}
</code>```

Class 1: Accounts

Header:

```<code>#pragma once

// Libraries
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <Windows.h>
#include <sstream>

// Classes
#include "BankFunctions.h"

class accounts
{
    public:
        // Constructor
        accounts(
            unsigned int newId,
            unsigned int newAge,
            unsigned int newSSN,
            std::string newFirstName,
            std::string newLastName,
            std::string newAdress,
            std::string newEmail,
            double newBalance
        );

        // Overload constructor
        accounts(std::string eId, std::string eNAge, std::string eSSN, std::string eFName, std::string eLName, std::string eEmail, std::string eAdress, std::string eNBalance);

        // Mutators
        inline void setId(unsigned int i) { id = i; }
        inline void setAge(unsigned int a) { age = a; }
        inline void setSSN(unsigned int ssn) { SSN = ssn; }
        inline void setFirstName(std::string FN) { firstName = FN; }
        inline void setLastName(std::string LN) { lastName = LN; }
        inline void setEmail(std::string em) { email = em; }
        inline void setAdress(std::string adr) { adress = adr; }
        inline void setBalance(double newBalance, bool t);

        // Accessors
        inline unsigned int getId() const { return id; }
        inline unsigned int getAge() const { return age; }
        inline unsigned int getSSN() const { return SSN; }
        inline std::string getFirstName() const { return firstName; }
        inline std::string getLastName() const { return lastName; }
        inline std::string getEmail() const { return email; }
        inline std::string getAdress() const { return adress; }
        inline double getBalance() const { return balance; }

    private:
        // Customer account details
        unsigned int id;
        unsigned int age;
        unsigned int SSN; // Social Security Number
        std::string firstName;
        std::string lastName;
        std::string adress;
        std::string email;
        double balance;
};
</code>```

Class 2: BankFunctions

Header:

```<code>#pragma once

// Libraries
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <Windows.h>
#include <sstream>

// Classes
#include "accounts.h"

class BankFunctions
{
    public:
        BankFunctions();
        static void loadVector(); // Loads in customer account information into objects that get stored into a vector. (All the existing accounts get loaded in)
        static void newCustomer(); // Create new customer account
        static void existingCustomer(); // View customer account
        static void deposit(unsigned int accId); // Deposit money function
        static void withdraw(unsigned int accId); // Withdraw money function

        // Edit customer account
        static void editCustomerDetails(unsigned int accId);
            // Related Functions
            static void editAge(unsigned int accId);
            static void editSSN(unsigned int accId);
            static void editFirstName(unsigned int accId);
            static void editLastName(unsigned int accId);
            static void editAdress(unsigned int accId);
            static void editEmail(unsigned int accId);
            static void editBalance(unsigned int accId);

    private:
        // Vector
        static std::vector<accounts> users;

        static unsigned int amountOfAccounts;

};
</code>```

ERROR Message:

```<code>...bankfunctions.h(36): error C2065: 'accounts': undeclared identifier
...bankfunctions.h(36): error C2923: 'std::vector': 'accounts' is not a valid template type argument for parameter '_Ty'
...bankfunctions.h(36): error C3203: 'allocator': unspecialized class template can't be used as a template argument for template parameter '_Alloc', expected a real type
</code>```

答:
Try just to remove the include BankFunctions.h from the accounts.h.

The problem, I think, is that an include performs simply an inserting of the whole header file at the position where the include is done, but pragma once ensures that you do not include a header twice into a cpp file.
When your headers include each other it is possible to get the class definition of accounts past the line 36 of BankFunctions.h where you need it.

You may also put an extra class accounts; on the very top of main.cpp. This should also work, but is not a pretty solution.

Body:
Hello Stack Overflow!

I have encountered a problem which I have tried to solve but have not succeeded with, therefore I am turning my head towards you programmers hoping for answers.

What I am suspecting the problem is, is that it has to do with my main.cpp which I haven't started coding in yet for reasons. Could be very wrong though.

Any tips/hints are appreciated!

The error is about this part located in the BankFunctions header

// Vector
   static std::vector<accounts> users;

The error messages are listed at the bottom.

I have included the two class header files.

Main.cpp:

// Classes
#include "BankFunctions.h" // Handles the bank functions
#include "accounts.h" // Handles the customer accounts

// Libraries
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <Windows.h>
#include <sstream>

int main() {

    return 0;
}

Class 1: Accounts

Header:

#pragma once

// Libraries
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <Windows.h>
#include <sstream>

// Classes
#include "BankFunctions.h"

class accounts
{
    public:
        // Constructor
        accounts(
            unsigned int newId,
            unsigned int newAge,
            unsigned int newSSN,
            std::string newFirstName,
            std::string newLastName,
            std::string newAdress,
            std::string newEmail,
            double newBalance
        );

        // Overload constructor
        accounts(std::string eId, std::string eNAge, std::string eSSN, std::string eFName, std::string eLName, std::string eEmail, std::string eAdress, std::string eNBalance);

        // Mutators
        inline void setId(unsigned int i) { id = i; }
        inline void setAge(unsigned int a) { age = a; }
        inline void setSSN(unsigned int ssn) { SSN = ssn; }
        inline void setFirstName(std::string FN) { firstName = FN; }
        inline void setLastName(std::string LN) { lastName = LN; }
        inline void setEmail(std::string em) { email = em; }
        inline void setAdress(std::string adr) { adress = adr; }
        inline void setBalance(double newBalance, bool t);

        // Accessors
        inline unsigned int getId() const { return id; }
        inline unsigned int getAge() const { return age; }
        inline unsigned int getSSN() const { return SSN; }
        inline std::string getFirstName() const { return firstName; }
        inline std::string getLastName() const { return lastName; }
        inline std::string getEmail() const { return email; }
        inline std::string getAdress() const { return adress; }
        inline double getBalance() const { return balance; }

    private:
        // Customer account details
        unsigned int id;
        unsigned int age;
        unsigned int SSN; // Social Security Number
        std::string firstName;
        std::string lastName;
        std::string adress;
        std::string email;
        double balance;
};

Class 2: BankFunctions

Header:

#pragma once

// Libraries
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <Windows.h>
#include <sstream>

// Classes
#include "accounts.h"

class BankFunctions
{
    public:
        BankFunctions();
        static void loadVector(); // Loads in customer account information into objects that get stored into a vector. (All the existing accounts get loaded in)
        static void newCustomer(); // Create new customer account
        static void existingCustomer(); // View customer account
        static void deposit(unsigned int accId); // Deposit money function
        static void withdraw(unsigned int accId); // Withdraw money function

        // Edit customer account
        static void editCustomerDetails(unsigned int accId);
            // Related Functions
            static void editAge(unsigned int accId);
            static void editSSN(unsigned int accId);
            static void editFirstName(unsigned int accId);
            static void editLastName(unsigned int accId);
            static void editAdress(unsigned int accId);
            static void editEmail(unsigned int accId);
            static void editBalance(unsigned int accId);

    private:
        // Vector
        static std::vector<accounts> users;

        static unsigned int amountOfAccounts;

};

ERROR Message:

...bankfunctions.h(36): error C2065: 'accounts': undeclared identifier
...bankfunctions.h(36): error C2923: 'std::vector': 'accounts' is not a valid template type argument for parameter '_Ty'
...bankfunctions.h(36): error C3203: 'allocator': unspecialized class template can't be used as a template argument for template parameter '_Alloc', expected a real type


问:
How to get an XML node value as string when deserializing
I am sending a XML to a aspnet core web api.   The value for the namespace prefix cfdi: is defined in a containing node:

```<code><cfdi:Comprobante>
  <cfdi:Conceptos>
  </cfdi:Conceptos>
  <cfdi:Addenda>
    <bfa2:AddendaBuzonFiscal version="2.0" xmlns:bfa2="http://www.buzonfiscal.com/ns/addenda/bf/2"><bfa2:TipoDocumento nombreCorto="FAC" descripcion="Factura"/><bfa2:CFD totalConLetra="CINCUENTA Y DOS MIL QUINIENTOS OCHENTA Y NUEVE PESOS 64/100 M.N." observaciones="OBSERVACIONES"/><bfa2:Extra atributo="ClaveTransportista" valor="00328"/><bfa2:Extra atributo="NoRelacionPemex" valor="1-2"/>
    <bfa2:Extra atributo="NoConvenio" valor="5"/>
    </bfa2:AddendaBuzonFiscal>
    <Encabezado NumOrden="" NumFacturaOriginal="" FechaDePedido=""/>
    <Envio Calle="" NoExterior="" Colonia="" Localidad="" Municipio="" Estado="" Pais="" CodigoPostal="" NombreEnviar=""/><Detalle OrdenCompraLinea="10" GRNumber="GRN"/><Detalle OrdenCompraLinea="10" GRNumber="GRN"/><Detalle OrdenCompraLinea="10" GRNumber="GRN"/>
  </cfdi:Addenda>
</cfdi:Comprobante>
</code>```

To deserialize this I made the class Comprobante:

```<code>public class Comprobante : IValidatableObject
{
    [Required]
    [XmlArray("Conceptos"), XmlArrayItem(typeof(Concepto), ElementName = "Concepto")]
    public List<Concepto> Conceptos { get; set; }

    public Addenda Addenda { get; set; }
}
</code>```

Everything is mapped to the class properties but the Addenda node could receive anything -- any number of valid XML nodes -- so I don´t have a class definition.  I.e. the Addenda node could contain n nodes that I don’t know about, the information is validated in the recipient end. For example a customer could ask to add a node with a PO number, another could ask for buyer name. Etc.

If I need to get all the Addenda node content as string, how should I declare it in the class?

答:
You can deserialize arbitrary, free-form XML data using XmlSerializer by marking target properties with [XmlAnyElement].

E.g. you can define your Addenda type as follows:

```<code>[XmlRoot("Comprobante", Namespace = "http://cfdi")]
public class Comprobante : IValidatableObject
{
    [Required]
    [XmlArray("Conceptos"), XmlArrayItem(typeof(Concepto), ElementName = "Concepto")]
    public List<Concepto> Conceptos { get; set; }

    public Addenda Addenda { get; set; }
}

public class Addenda
{
    [XmlAnyElement]
    [XmlText]
    public XmlNode[] Nodes { get; set; }
}
</code>```

Sample working .Net fiddle #1.

Or, you could eliminate the Addenda type completely and replace it with an XmlElement property in the containing type:

```<code>[XmlRoot("Comprobante", Namespace = "http://cfdi")]
public class Comprobante : IValidatableObject
{
    [Required]
    [XmlArray("Conceptos"), XmlArrayItem(typeof(Concepto), ElementName = "Concepto")]
    public List<Concepto> Conceptos { get; set; }

    [XmlAnyElement("Addenda")]
    public XmlElement Addenda { get; set; }
}
</code>```

Sample working .Net fiddle #2.

Notes:

When applied without an element name, [XmlAnyElement] specifies that the member is an array of XmlElement or XmlNode objects which will contain all arbitrary XML data that is not bound to some other member in the containing type.

When applied with an element name (and optional namespace), [XmlAnyElement("Addenda")] specifies that the member is a either a single XmlElement object or an array of such objects, and will contain all arbitrary XML elements named <Addenda>.  Using this form eliminates the need for the extra Addenda type.

Combining [XmlText] with [XmlAnyElement] allows arbitrary mixed content to be deserialized.

If you are using .NET Core you may need to nuget System.Xml.XmlDocument.

Body:
I am sending a XML to a aspnet core web api.   The value for the namespace prefix cfdi: is defined in a containing node:

<cfdi:Comprobante>
  <cfdi:Conceptos>
  </cfdi:Conceptos>
  <cfdi:Addenda>
    <bfa2:AddendaBuzonFiscal version="2.0" xmlns:bfa2="http://www.buzonfiscal.com/ns/addenda/bf/2"><bfa2:TipoDocumento nombreCorto="FAC" descripcion="Factura"/><bfa2:CFD totalConLetra="CINCUENTA Y DOS MIL QUINIENTOS OCHENTA Y NUEVE PESOS 64/100 M.N." observaciones="OBSERVACIONES"/><bfa2:Extra atributo="ClaveTransportista" valor="00328"/><bfa2:Extra atributo="NoRelacionPemex" valor="1-2"/>
    <bfa2:Extra atributo="NoConvenio" valor="5"/>
    </bfa2:AddendaBuzonFiscal>
    <Encabezado NumOrden="" NumFacturaOriginal="" FechaDePedido=""/>
    <Envio Calle="" NoExterior="" Colonia="" Localidad="" Municipio="" Estado="" Pais="" CodigoPostal="" NombreEnviar=""/><Detalle OrdenCompraLinea="10" GRNumber="GRN"/><Detalle OrdenCompraLinea="10" GRNumber="GRN"/><Detalle OrdenCompraLinea="10" GRNumber="GRN"/>
  </cfdi:Addenda>
</cfdi:Comprobante>

To deserialize this I made the class Comprobante:

public class Comprobante : IValidatableObject
{
    [Required]
    [XmlArray("Conceptos"), XmlArrayItem(typeof(Concepto), ElementName = "Concepto")]
    public List<Concepto> Conceptos { get; set; }

    public Addenda Addenda { get; set; }
}

Everything is mapped to the class properties but the Addenda node could receive anything -- any number of valid XML nodes -- so I don´t have a class definition.  I.e. the Addenda node could contain n nodes that I don’t know about, the information is validated in the recipient end. For example a customer could ask to add a node with a PO number, another could ask for buyer name. Etc.

If I need to get all the Addenda node content as string, how should I declare it in the class?

Body:
You can deserialize arbitrary, free-form XML data using XmlSerializer by marking target properties with [XmlAnyElement].

E.g. you can define your Addenda type as follows:

[XmlRoot("Comprobante", Namespace = "http://cfdi")]
public class Comprobante : IValidatableObject
{
    [Required]
    [XmlArray("Conceptos"), XmlArrayItem(typeof(Concepto), ElementName = "Concepto")]
    public List<Concepto> Conceptos { get; set; }

    public Addenda Addenda { get; set; }
}

public class Addenda
{
    [XmlAnyElement]
    [XmlText]
    public XmlNode[] Nodes { get; set; }
}

Sample working .Net fiddle #1.

Or, you could eliminate the Addenda type completely and replace it with an XmlElement property in the containing type:

[XmlRoot("Comprobante", Namespace = "http://cfdi")]
public class Comprobante : IValidatableObject
{
    [Required]
    [XmlArray("Conceptos"), XmlArrayItem(typeof(Concepto), ElementName = "Concepto")]
    public List<Concepto> Conceptos { get; set; }

    [XmlAnyElement("Addenda")]
    public XmlElement Addenda { get; set; }
}

Sample working .Net fiddle #2.

Notes:

When applied without an element name, [XmlAnyElement] specifies that the member is an array of XmlElement or XmlNode objects which will contain all arbitrary XML data that is not bound to some other member in the containing type.

When applied with an element name (and optional namespace), [XmlAnyElement("Addenda")] specifies that the member is a either a single XmlElement object or an array of such objects, and will contain all arbitrary XML elements named <Addenda>.  Using this form eliminates the need for the extra Addenda type.

Combining [XmlText] with [XmlAnyElement] allows arbitrary mixed content to be deserialized.

If you are using .NET Core you may need to nuget System.Xml.XmlDocument.


问:
chat web app: flex-boxes inside div position:fixed
I have a chat web app with a bottom bar consisting of: button, text entry, button:

```<code><div id="bottom-bar">
  <div class="button-left">
    <img src="https://placeholdit.co//i/40x40">
  </div>
  <div class="textentry">
    <input type="text" id="chatmsg" name="chatmsg">
  </div>
  <div class="button-right">
    <img src="https://placeholdit.co//i/40x40">
  </div>
</div>

#bottom-bar {
    position: fixed;
    bottom: 0px;
    height: 40px;
    width: 100%;
}
</code>```

What I want to achieve: (1) place the left button to the left of the bottom-bar, (2) place the right button to the right of the bottom-bar and (3) have an input field that stretches in the middle using all the space that is available.

I tried:

#bottom-bar {
   ...the css above and additionally ...
   display: flex;
   flex-direction: row;
   flex-wrap: nowrap;
   justify-content:space-between;
   align-items: center;
}

#chatmsg{
  width: auto;
}
```

But this got me nowhere. Any help is much appreciated.

答:
the textentry has to grow and take all the place left:

#bottom-bar {
    position: fixed;
    bottom: 0px;
    height: 40px;
    width: 100%;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content:space-between;
    align-items: center;
}
.button-left,
.button-right {
  width: 40px;
}
.textentry{
  flex-grow: 1;
}
#chatmsg {
  width: 100%;
}
```

check this: https://jsfiddle.net/43Lqzznt/3/

Body:
I have a chat web app with a bottom bar consisting of: button, text entry, button:

    <input type="text" id="chatmsg" name="chatmsg">

#bottom-bar {
    position: fixed;
    bottom: 0px;
    height: 40px;
    width: 100%;
}

What I want to achieve: (1) place the left button to the left of the bottom-bar, (2) place the right button to the right of the bottom-bar and (3) have an input field that stretches in the middle using all the space that is available.

I tried:

#bottom-bar {
   ...the css above and additionally ...
   display: flex;
   flex-direction: row;
   flex-wrap: nowrap;
   justify-content:space-between;
   align-items: center;
}

#chatmsg{
  width: auto;
}

But this got me nowhere. Any help is much appreciated.

Body:
the textentry has to grow and take all the place left:

#bottom-bar {
    position: fixed;
    bottom: 0px;
    height: 40px;
    width: 100%;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content:space-between;
    align-items: center;
}
.button-left,
.button-right {
  width: 40px;
}
.textentry{
  flex-grow: 1;
}
#chatmsg {
  width: 100%;
}

check this: https://jsfiddle.net/43Lqzznt/3/


问:
Loop Through Immutable JS Record
I'm new to using the ImmutableJS library and I've been having some trouble figuring this out. I have an Immutable Record object called Options. I want to be able to loop through this Record, getting the key and value for each item in the Record. Here's what my Options model looks like:

```<code>export class Option extends Record ({
  height: '10px',
  width: '47px',
  title: 'foo',
  isAvailable: false
}) {
  constructor(props) {
    if (!props) {
      super();
      return;
    }
  }
}
</code>```

I've written the following to loop through each element inside my Options Record, but it doesn't seem to work:

```<code>var options = new Options();
options.toSeq().map((value, key) => {
  console.log(key + ': ' + value);
});
</code>```

I would expect that this writes each key/value pair inside my Options Immutable Record to the console window. However, it doesn't print anything and doesn't even seem to run the code within the map function at all.

Please let me know if you have any idea what is wrong here. Thanks in advance! :)

答:
I like to use the _values, _keys, and _defaultValues and _iterate properties of the Record. I think the underscore means they are private but I can't find another way of doing it!

```<code>class Option extends Immutable.Record({
  height: '10px',
  width: '47px',
  title: 'foo',
  isAvailable: false
}) {}

var option = new Option();

console.log(option._keys);
//  ["height", "width", "title", "isAvailable"]

console.log(option._values.toJS());
//  [undefined, undefined, undefined, undefined]

console.log(option._defaultValues);
// {
//   height: '10px',
//   width: '47px',
//   title: 'foo',
//   isAvailable: false
// }

// i like this one the best
option.__iterate((item, key) => console.log(key, item));
// height, 10px
// width, 47px
// title, foo
// isAvailable, false
</code>```

Title: Loop Through Immutable JS Record

Body:
I'm new to using the ImmutableJS library and I've been having some trouble figuring this out. I have an Immutable Record object called Options. I want to be able to loop through this Record, getting the key and value for each item in the Record. Here's what my Options model looks like:

export class Option extends Record ({
  height: '10px',
  width: '47px',
  title: 'foo',
  isAvailable: false
}) {
  constructor(props) {
    if (!props) {
      super();
      return;
    }
  }
}

I've written the following to loop through each element inside my Options Record, but it doesn't seem to work:

var options = new Options();
options.toSeq().map((value, key) => {
  console.log(key + ': ' + value);
});

I would expect that this writes each key/value pair inside my Options Immutable Record to the console window. However, it doesn't print anything and doesn't even seem to run the code within the map function at all.

Please let me know if you have any idea what is wrong here. Thanks in advance! :)

Body:
I like to use the _values, _keys, and _defaultValues and _iterate properties of the Record. I think the underscore means they are private but I can't find another way of doing it!

class Option extends Immutable.Record({
  height: '10px',
  width: '47px',
  title: 'foo',
  isAvailable: false
}) {}

var option = new Option();

console.log(option._keys);
//  ["height", "width", "title", "isAvailable"]

console.log(option._values.toJS());
//  [undefined, undefined, undefined, undefined]

console.log(option._defaultValues);
// {
//   height: '10px',
//   width: '47px',
//   title: 'foo',
//   isAvailable: false
// }

// i like this one the best
option.__iterate((item, key) => console.log(key, item));
// height, 10px
// width, 47px
// title, foo
// isAvailable, false


问:
I'm build a webscraper for security news but links are duplicated
I'm building a web-scraper to scrape multiple websites so I don't have to directly visit the website.

Currently I'm having problems with duplicated URLs, the script does what I want, but links are being duplicated and I don't want that.

Here's My code:

```<code>def HackerNews():
hackerNews = ['https://www.darkreading.com/attacks-breaches.asp','https://www.darkreading.com/application-security.asp',
           'https://www.darkreading.com/vulnerabilities-threats.asp', 'https://www.darkreading.com/endpoint-security.asp',
           'https://www.darkreading.com/IoT.asp','https://www.darkreading.com/vulnerabilities-threats.asp'
           ]
keywords = ["bitcoin", "bit", "BTC", "Bit", "Security","Attack", "Breach","Cyber",
"Ransomware","Botnet","Worm","Hacked","Hack","Hackers","Flaw", "Risk","Danger" ]

for link in hackerNews:
   request = urllib2.Request(link)
   request.add_header('User-Agent', 'Mozilla 5.0')
   websitecontent = urllib2.urlopen(request).read()
   soup = BeautifulSoup(websitecontent, 'html.parser')

   headers = soup.findAll('header', {'class' : 'strong medium'})

   for h in headers:
       a = h.find("a")

       for keyword in keywords:
           if keyword in a["title"]:
               print("Title: " + a["title"] + " \nLink: " "https://darkreading.com" + a["href"])

HackerNews()
</code>```

Here's an Example of the output:

Title: Android Ransomware Kits on the Rise in the Dark Web

Link: https://darkreading.com/mobile/android-ransomware-kits-on-the-rise-in-the-dark-web-/d/d-id/1330591

Title: Bitcoin Miner NiceHash Hacked, Possibly Losing $62 Million in Bitcoin
Link: https://darkreading.com/cloud/bitcoin-miner-nicehash-hacked-possibly-losing-$62-million-in-bitcoin/d/d-id/1330585

Title: Bitcoin Miner NiceHash Hacked, Possibly Losing $62 Million in Bitcoin
Link: https://darkreading.com/cloud/bitcoin-miner-nicehash-hacked-possibly-losing-$62-million-in-bitcoin/d/d-id/1330585

Title: Bitcoin Miner NiceHash Hacked, Possibly Losing $62 Million in Bitcoin
Link: https://darkreading.com/cloud/bitcoin-miner-nicehash-hacked-possibly-losing-$62-million-in-bitcoin/d/d-id/1330585

Title: Uber Used $100K Bug Bounty to Pay, Silence Florida Hacker: Report
Link: https://darkreading.com/attacks-breaches/uber-used-$100k-bug-bounty-to-pay-silence-florida-hacker-report/d/d-id/1330584

答:
Well, instead of printing it directly, you can make a dictionary with all the links. Or if you want to keep it in order a list of tupils.
Before appending, you can check if it is already in the list.

```<code>def HackerNews():
hackerNews = ['https://www.darkreading.com/attacks-breaches.asp','https://www.darkreading.com/application-security.asp',
           'https://www.darkreading.com/vulnerabilities-threats.asp', 'https://www.darkreading.com/endpoint-security.asp',
           'https://www.darkreading.com/IoT.asp','https://www.darkreading.com/vulnerabilities-threats.asp'
           ]
keywords = ["bitcoin", "bit", "BTC", "Bit", "Security","Attack", "Breach","Cyber",
"Ransomware","Botnet","Worm","Hacked","Hack","Hackers","Flaw", "Risk","Danger" ]

output = []

for link in hackerNews:
   request = urllib2.Request(link)
   request.add_header('User-Agent', 'Mozilla 5.0')
   websitecontent = urllib2.urlopen(request).read()
   soup = BeautifulSoup(websitecontent, 'html.parser')

   headers = soup.findAll('header', {'class' : 'strong medium'})

   for h in headers:
       a = h.find("a")

       for keyword in keywords:
           if keyword in a["title"]:
               if (a["title"], a["href"]) not in output:
                   output.append((a["title"], a["href"]))

   for link in output:
       print("Title: " + link[0] + " \nLink: " "https://darkreading.com" + link[1])

HackerNews()
</code>```

Did not fix your indentation problem, also didnt test it. But it should convey my point :)

edit: worked for python 3 with:

```<code>from urllib.request import Request, urlopen
from bs4 import BeautifulSoup

def HackerNews():
    hackerNews = ['https://www.darkreading.com/attacks-breaches.asp','https://www.darkreading.com/application-security.asp',
               'https://www.darkreading.com/vulnerabilities-threats.asp', 'https://www.darkreading.com/endpoint-security.asp',
               'https://www.darkreading.com/IoT.asp','https://www.darkreading.com/vulnerabilities-threats.asp'
               ]
    keywords = ["bitcoin", "bit", "BTC", "Bit", "Security","Attack", "Breach","Cyber",
    "Ransomware","Botnet","Worm","Hacked","Hack","Hackers","Flaw", "Risk","Danger" ]

    output = []

    for link in hackerNews:
       request = Request(link)
       request.add_header('User-Agent', 'Mozilla 5.0')
       websitecontent = urlopen(request).read()
       soup = BeautifulSoup(websitecontent, 'html.parser')

       headers = soup.findAll('header', {'class' : 'strong medium'})

       for h in headers:
           a = h.find("a")

           for keyword in keywords:
               if keyword in a["title"]:
                   if (a["title"], a["href"]) not in output:
                       output.append((a["title"], a["href"]))

       for link in output:
           print("Title: " + link[0] + " \nLink: " "https://darkreading.com" + link[1])

HackerNews()
</code>```

Body:
I'm building a web-scraper to scrape multiple websites so I don't have to directly visit the website.

Currently I'm having problems with duplicated URLs, the script does what I want, but links are being duplicated and I don't want that.

Here's My code:

def HackerNews():
hackerNews = ['https://www.darkreading.com/attacks-breaches.asp','https://www.darkreading.com/application-security.asp',
           'https://www.darkreading.com/vulnerabilities-threats.asp', 'https://www.darkreading.com/endpoint-security.asp',
           'https://www.darkreading.com/IoT.asp','https://www.darkreading.com/vulnerabilities-threats.asp'
           ]
keywords = ["bitcoin", "bit", "BTC", "Bit", "Security","Attack", "Breach","Cyber",
"Ransomware","Botnet","Worm","Hacked","Hack","Hackers","Flaw", "Risk","Danger" ]

for link in hackerNews:
   request = urllib2.Request(link)
   request.add_header('User-Agent', 'Mozilla 5.0')
   websitecontent = urllib2.urlopen(request).read()
   soup = BeautifulSoup(websitecontent, 'html.parser')

   headers = soup.findAll('header', {'class' : 'strong medium'})

   for h in headers:
       a = h.find("a")

       for keyword in keywords:
           if keyword in a["title"]:
               print("Title: " + a["title"] + " \nLink: " "https://darkreading.com" + a["href"])

HackerNews()

Here's an Example of the output:

Title: Android Ransomware Kits on the Rise in the Dark Web

Link: https://darkreading.com/mobile/android-ransomware-kits-on-the-rise-in-the-dark-web-/d/d-id/1330591

Title: Bitcoin Miner NiceHash Hacked, Possibly Losing $62 Million in Bitcoin
Link: https://darkreading.com/cloud/bitcoin-miner-nicehash-hacked-possibly-losing-$62-million-in-bitcoin/d/d-id/1330585

Title: Bitcoin Miner NiceHash Hacked, Possibly Losing $62 Million in Bitcoin
Link: https://darkreading.com/cloud/bitcoin-miner-nicehash-hacked-possibly-losing-$62-million-in-bitcoin/d/d-id/1330585

Title: Bitcoin Miner NiceHash Hacked, Possibly Losing $62 Million in Bitcoin
Link: https://darkreading.com/cloud/bitcoin-miner-nicehash-hacked-possibly-losing-$62-million-in-bitcoin/d/d-id/1330585

Title: Uber Used $100K Bug Bounty to Pay, Silence Florida Hacker: Report
Link: https://darkreading.com/attacks-breaches/uber-used-$100k-bug-bounty-to-pay-silence-florida-hacker-report/d/d-id/1330584

Body:
Well, instead of printing it directly, you can make a dictionary with all the links. Or if you want to keep it in order a list of tupils.
Before appending, you can check if it is already in the list.

def HackerNews():
hackerNews = ['https://www.darkreading.com/attacks-breaches.asp','https://www.darkreading.com/application-security.asp',
           'https://www.darkreading.com/vulnerabilities-threats.asp', 'https://www.darkreading.com/endpoint-security.asp',
           'https://www.darkreading.com/IoT.asp','https://www.darkreading.com/vulnerabilities-threats.asp'
           ]
keywords = ["bitcoin", "bit", "BTC", "Bit", "Security","Attack", "Breach","Cyber",
"Ransomware","Botnet","Worm","Hacked","Hack","Hackers","Flaw", "Risk","Danger" ]

output = []

for link in hackerNews:
   request = urllib2.Request(link)
   request.add_header('User-Agent', 'Mozilla 5.0')
   websitecontent = urllib2.urlopen(request).read()
   soup = BeautifulSoup(websitecontent, 'html.parser')

   headers = soup.findAll('header', {'class' : 'strong medium'})

   for h in headers:
       a = h.find("a")

       for keyword in keywords:
           if keyword in a["title"]:
               if (a["title"], a["href"]) not in output:
                   output.append((a["title"], a["href"]))

   for link in output:
       print("Title: " + link[0] + " \nLink: " "https://darkreading.com" + link[1])

HackerNews()

Did not fix your indentation problem, also didnt test it. But it should convey my point :)

edit: worked for python 3 with:

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup

def HackerNews():
    hackerNews = ['https://www.darkreading.com/attacks-breaches.asp','https://www.darkreading.com/application-security.asp',
               'https://www.darkreading.com/vulnerabilities-threats.asp', 'https://www.darkreading.com/endpoint-security.asp',
               'https://www.darkreading.com/IoT.asp','https://www.darkreading.com/vulnerabilities-threats.asp'
               ]
    keywords = ["bitcoin", "bit", "BTC", "Bit", "Security","Attack", "Breach","Cyber",
    "Ransomware","Botnet","Worm","Hacked","Hack","Hackers","Flaw", "Risk","Danger" ]

    output = []

    for link in hackerNews:
       request = Request(link)
       request.add_header('User-Agent', 'Mozilla 5.0')
       websitecontent = urlopen(request).read()
       soup = BeautifulSoup(websitecontent, 'html.parser')

       headers = soup.findAll('header', {'class' : 'strong medium'})

       for h in headers:
           a = h.find("a")

           for keyword in keywords:
               if keyword in a["title"]:
                   if (a["title"], a["href"]) not in output:
                       output.append((a["title"], a["href"]))

       for link in output:
           print("Title: " + link[0] + " \nLink: " "https://darkreading.com" + link[1])

HackerNews()


问:
Angular 2 render page without router-outlet
I have HTML template with slide menu and top nav menu and block for render main path page.
like this:

```<code>...
<div class="content-wrapper">
    <router-outlet></router-outlet>
</div>
...
</code>```

But after it, my login page render in this content-wrapper block.
How to write some code for render LoginPage without route-outline component? (for not render top nav and slide menus)

答:
The correct solution to your problem is not go around router-outlet, but using one extra component (lets call it RootComponent) with router-outlet (RO1), but without nav and side menu. In RO1 you should load either your component NavMenuComponent (with the nav, side menu and its own router-outlet RO2). Then you can use child routes to ensure that in RO1 in RootComponent is loaded either NavMenuComponent (which will have nav and side menu) or LoginComponent (which will have no nav and side menu). In RO2 will be loaded the content as you have it now.

Assuming RootComponent is the deafult component in your module, routes will look like this:

```<code> const appRoutes: Routes = [

  { path: 'login', component: LoginComponent },
  {
    path: '',
    redirectTo: 'login',
    pathMatch: 'full'
  },

  {
    path: 'app', component: NavMenuComponent,
    children: [
      { path: 'youorldpath1', component: YourOld1Component }, //the path will /app/youroldpath1 instead of /youroldpath1
      { path: 'youorldpath2', component: YourOld2Component, canActivate: [CanActivateViaAuthGuard] },
      { path: '**', component: ErrorComponent }
    ]
  },

  { path: '**', component: ErrorComponent }

];
</code>```

RootComponent can have only :

```<code><router-outlet></router-outlet>
</code>```

More info here: https://angular.io/guide/router#child-routing-component

Body:
I have HTML template with slide menu and top nav menu and block for render main path page.
like this:

...

    <router-outlet></router-outlet>

...

But after it, my login page render in this content-wrapper block.
How to write some code for render LoginPage without route-outline component? (for not render top nav and slide menus)

Body:
The correct solution to your problem is not go around router-outlet, but using one extra component (lets call it RootComponent) with router-outlet (RO1), but without nav and side menu. In RO1 you should load either your component NavMenuComponent (with the nav, side menu and its own router-outlet RO2). Then you can use child routes to ensure that in RO1 in RootComponent is loaded either NavMenuComponent (which will have nav and side menu) or LoginComponent (which will have no nav and side menu). In RO2 will be loaded the content as you have it now.

Assuming RootComponent is the deafult component in your module, routes will look like this:

 const appRoutes: Routes = [

  { path: 'login', component: LoginComponent },
  {
    path: '',
    redirectTo: 'login',
    pathMatch: 'full'
  },

  {
    path: 'app', component: NavMenuComponent,
    children: [
      { path: 'youorldpath1', component: YourOld1Component }, //the path will /app/youroldpath1 instead of /youroldpath1
      { path: 'youorldpath2', component: YourOld2Component, canActivate: [CanActivateViaAuthGuard] },
      { path: '**', component: ErrorComponent }
    ]
  },

  { path: '**', component: ErrorComponent }

];

RootComponent can have only :

<router-outlet></router-outlet>

More info here: https://angular.io/guide/router#child-routing-component


问:
Importing blank Excel columns using SSIS
I'm creating an SSIS package to import Excel files (which have different layouts) into a SQL Server table with 150 columns.

The SSIS package has a Foreach Loop Container within which is a Data Flow Task which has an Excel Source component and an OLE DB Destination component.

The Data Flow Task will be ran for each Excel file so the Excel Source component needs to work for every file.

I've set up the Excel Source component with 150 Unicode string columns of length 255, and I've set ValidateExternalMetadata to False, however I'm getting the error: 'Column "F143" cannot be found at the datasource' when testing the package on an Excel file with 142 columns of data.

My question is: How do I get the package to ignore this error and import the columns that exist, or is there another way of dealing with the above situation?

答:
In the Excel Source, select the source type as SQL command and use the following command (Assuming that the worksheet name is Sheet1)

```<code>Select * from [Sheet1$A1:ET]
</code>```

ET is the column with index = 150, so with this query you are forcing the Excel Source to read the 150 column, even if they contains some empty columns.

For additional info on importing excel with dynamic headers, just follow my answer below:

Importing excel files having variable headers

Body:
In the Excel Source, select the source type as SQL command and use the following command (Assuming that the worksheet name is Sheet1)

Select * from [Sheet1$A1:ET]

ET is the column with index = 150, so with this query you are forcing the Excel Source to read the 150 column, even if they contains some empty columns.

For additional info on importing excel with dynamic headers, just follow my answer below:

Importing excel files having variable headers


问:
An issue of C in 64 bit architecture: pthread_kill()
The question is quite simple: my application runs perfectly on a 32 bit architecture, but on a 64 bit arch. I got segmentation fault. I guess that the cause is the execution of a pthread_kill() call. Is it possible or my supposition is just wrong?

答:
Segmentation fault is almost certainly not a result of pthread_kill(), but a plain old bug in the application (many bugs show up only in 64-bit compiles, or only with certain memory layouts; nothing special about your particular application here).

Instead of guessing what the cause might be, run your application under GDB or Valgrind. Both will likely make it painfully clear where your bug is.


问:
Watch for changes in local folder and upload them to SFTP server
Linux user here trying to write a script in PowerShell to automate SFTP transfers from a Windows server to a remote server. I have everything working for the most part (though I still have some testing to do). My current issue is after the script runs one time it is done. I need the FileSystemWatcher to run every time it finds a new file creation. I realize this is because of the exit but when I remove that portion and a user drops in a directory it loops through every file in the directory and uploads every file in the directory over and over. What I need it to do is run through the process once and then remain active to listen for another file creation event. My issue may be my limited workings with coding in Windows so any help is appreciated!

And yes I realize the duplication of code in the handling of my files vs my folders is redundant. I will most likely make that portion a function that accepts parameters depending on if it is given a file or folder.

I am posting my entire code in case it can help someone later

```<code>###Watches a directory for new files and fires off the batch file to push to Connexxion

$folder = "C:\pathTo\watchfolder"
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $folder
$watcher.Filter  = "*.csv"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

### LISTEN FOR CREATE
Register-ObjectEvent $watcher Created -SourceIdentifier FileCreated -Action {
$folderpath = $(split-path -LiteralPath $event.SourceEventArgs.FullPath)
$filename = $event.SourceEventArgs.Name
$filepath = (Join-Path $folderpath $filename.split("\")[-1])

Write-Host folderpath: $folderpath
Write-Host filename: $filename
Write-Host filepath: $filepath

$remotePath = "/data/"

If($filename.contains("\")){
  Write-Host "Here is directory"
  try
  {
    #Set path to winscp
    $assemblyPath = "C:\Program Files (x86)\WinSCP"
    Add-Type -Path (Join-Path $assemblyPath "WinSCPnet.dll")

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "hostname"
        UserName = "username"
        Password = "passwd"
        SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx"
    }

    $session = New-Object WinSCP.Session

    try
    {
      # Connect
      $session.Open($sessionOptions)
      # Upload files, collect results
      $transferOptions = New-Object WinSCP.TransferOptions
      $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

      $transferResult =
          $session.PutFiles($folderpath, $remotePath, $False, $transferOptions)

      # Throw on any error
      $transferResult.Check()

      # Print results
      foreach ($transfer in $transferResult.Transfers)
      {
          Write-Host "Upload of $($transfer.FileName) succeeded"
      }
    }
    finally
    {
      # Disconnect, clean up
      $session.Dispose()
    }

    exit 0
  }#end of first try
  catch
  {
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
  }
}
Else{
  Write-Host "Here is a file"
  try
  {
    #Set path to winscp
    $assemblyPath = "C:\Program Files (x86)\WinSCP"
    Add-Type -Path (Join-Path $assemblyPath "WinSCPnet.dll")

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "hostname"
        UserName = "username"
        Password = "passwd"
        SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx"
    }

    $session = New-Object WinSCP.Session

    try
    {
      # Connect
      $session.Open($sessionOptions)
      # Upload files, collect results
      $transferOptions = New-Object WinSCP.TransferOptions
      $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

      $transferResult =
          $session.PutFiles($filepath, $remotePath, $False, $transferOptions)

      # Throw on any error
      $transferResult.Check()

      # Print results
      foreach ($transfer in $transferResult.Transfers)
      {
          Write-Host "Upload of $($transfer.FileName) succeeded"
      }
    }
    finally
    {
      # Disconnect, clean up
      $session.Dispose()
    }

    exit 0
  }#end of first try
  catch
    {
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
    }
  }

}#end of action
while ($true) {sleep 5}
</code>```

答:
Just take the path to the new file and use RemotePath.TranslateLocalPathToRemote to map it to a server path, and upload the file there.

The code will be a lot simpler. All you need to do is to make sure new folders are re-created on the server.

```<code># Watches a directory for new files and
# fires off the batch file to push to connection

$remotePath = "/data"
$localPath = "C:\pathTo\watchfolder"
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $localPath
$watcher.Filter  = "*.csv"
$watcher.IncludeSubdirectories = $True
$watcher.EnableRaisingEvents = $True

### LISTEN FOR CREATE
Register-ObjectEvent $watcher Created -SourceIdentifier FileCreated -Action {
    try
    {
        $localFilePath = $event.SourceEventArgs.FullPath
        Write-Host "Local path: $localFilePath"

        $assemblyPath = "C:\Program Files (x86)\WinSCP"
        Add-Type -Path (Join-Path $assemblyPath "WinSCPnet.dll")

        # Setup session options
        $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
            Protocol = [WinSCP.Protocol]::Sftp
            HostName = "example.com"
            UserName = "username"
            Password = "password"
            SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
        }

        $session = New-Object WinSCP.Session

        try
        {
            $remoteFilePath =
                [WinSCP.RemotePath]::TranslateLocalPathToRemote(
                    $localFilePath, $localPath, $remotePath)
            Write-Host "Remote path: $remoteFilePath"

            # Connect
            $session.Open($sessionOptions)

            # Check if corresponding remote directory exists, if not, create it
            $i = $remoteFilePath.LastIndexOf("/")
            $remoteDirPath = $remoteFilePath.SubString(0, $i)
            if (($remoteDirPath.Length -gt 0) -and
                !$session.FileExists($remoteDirPath))
            {
                Write-Host "New subdirectory, creating $remoteDirPath on server"
                $session.CreateDirectory($remoteDirPath)
            }

            $session.PutFiles($localFilePath, $remoteFilePath).Check()

            Write-Host "Upload of $localFilePath succeeded"
        }
        finally
        {
            # Disconnect, clean up
            $session.Dispose()
        }

    } #end of first try
    catch
    {
        Write-Host "Error: $($_.Exception.Message)"
    }
} #end of action

while ($True) { sleep 5 }
</code>```

Body:
Linux user here trying to write a script in PowerShell to automate SFTP transfers from a Windows server to a remote server. I have everything working for the most part (though I still have some testing to do). My current issue is after the script runs one time it is done. I need the FileSystemWatcher to run every time it finds a new file creation. I realize this is because of the exit but when I remove that portion and a user drops in a directory it loops through every file in the directory and uploads every file in the directory over and over. What I need it to do is run through the process once and then remain active to listen for another file creation event. My issue may be my limited workings with coding in Windows so any help is appreciated!

And yes I realize the duplication of code in the handling of my files vs my folders is redundant. I will most likely make that portion a function that accepts parameters depending on if it is given a file or folder.

I am posting my entire code in case it can help someone later

###Watches a directory for new files and fires off the batch file to push to Connexxion

$folder = "C:\pathTo\watchfolder"
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $folder
$watcher.Filter  = "*.csv"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

### LISTEN FOR CREATE
Register-ObjectEvent $watcher Created -SourceIdentifier FileCreated -Action {
$folderpath = $(split-path -LiteralPath $event.SourceEventArgs.FullPath)
$filename = $event.SourceEventArgs.Name
$filepath = (Join-Path $folderpath $filename.split("\")[-1])

Write-Host folderpath: $folderpath
Write-Host filename: $filename
Write-Host filepath: $filepath

$remotePath = "/data/"

If($filename.contains("\")){
  Write-Host "Here is directory"
  try
  {
    #Set path to winscp
    $assemblyPath = "C:\Program Files (x86)\WinSCP"
    Add-Type -Path (Join-Path $assemblyPath "WinSCPnet.dll")

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "hostname"
        UserName = "username"
        Password = "passwd"
        SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx"
    }

    $session = New-Object WinSCP.Session

    try
    {
      # Connect
      $session.Open($sessionOptions)
      # Upload files, collect results
      $transferOptions = New-Object WinSCP.TransferOptions
      $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

      $transferResult =
          $session.PutFiles($folderpath, $remotePath, $False, $transferOptions)

      # Throw on any error
      $transferResult.Check()

      # Print results
      foreach ($transfer in $transferResult.Transfers)
      {
          Write-Host "Upload of $($transfer.FileName) succeeded"
      }
    }
    finally
    {
      # Disconnect, clean up
      $session.Dispose()
    }

    exit 0
  }#end of first try
  catch
  {
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
  }
}
Else{
  Write-Host "Here is a file"
  try
  {
    #Set path to winscp
    $assemblyPath = "C:\Program Files (x86)\WinSCP"
    Add-Type -Path (Join-Path $assemblyPath "WinSCPnet.dll")

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "hostname"
        UserName = "username"
        Password = "passwd"
        SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx"
    }

    $session = New-Object WinSCP.Session

    try
    {
      # Connect
      $session.Open($sessionOptions)
      # Upload files, collect results
      $transferOptions = New-Object WinSCP.TransferOptions
      $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

      $transferResult =
          $session.PutFiles($filepath, $remotePath, $False, $transferOptions)

      # Throw on any error
      $transferResult.Check()

      # Print results
      foreach ($transfer in $transferResult.Transfers)
      {
          Write-Host "Upload of $($transfer.FileName) succeeded"
      }
    }
    finally
    {
      # Disconnect, clean up
      $session.Dispose()
    }

    exit 0
  }#end of first try
  catch
    {
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
    }
  }

}#end of action
while ($true) {sleep 5}

Body:
Just take the path to the new file and use RemotePath.TranslateLocalPathToRemote to map it to a server path, and upload the file there.

The code will be a lot simpler. All you need to do is to make sure new folders are re-created on the server.

# Watches a directory for new files and
# fires off the batch file to push to connection

$remotePath = "/data"
$localPath = "C:\pathTo\watchfolder"
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $localPath
$watcher.Filter  = "*.csv"
$watcher.IncludeSubdirectories = $True
$watcher.EnableRaisingEvents = $True

### LISTEN FOR CREATE
Register-ObjectEvent $watcher Created -SourceIdentifier FileCreated -Action {
    try
    {
        $localFilePath = $event.SourceEventArgs.FullPath
        Write-Host "Local path: $localFilePath"

        $assemblyPath = "C:\Program Files (x86)\WinSCP"
        Add-Type -Path (Join-Path $assemblyPath "WinSCPnet.dll")

        # Setup session options
        $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
            Protocol = [WinSCP.Protocol]::Sftp
            HostName = "example.com"
            UserName = "username"
            Password = "password"
            SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
        }

        $session = New-Object WinSCP.Session

        try
        {
            $remoteFilePath =
                [WinSCP.RemotePath]::TranslateLocalPathToRemote(
                    $localFilePath, $localPath, $remotePath)
            Write-Host "Remote path: $remoteFilePath"

            # Connect
            $session.Open($sessionOptions)

            # Check if corresponding remote directory exists, if not, create it
            $i = $remoteFilePath.LastIndexOf("/")
            $remoteDirPath = $remoteFilePath.SubString(0, $i)
            if (($remoteDirPath.Length -gt 0) -and
                !$session.FileExists($remoteDirPath))
            {
                Write-Host "New subdirectory, creating $remoteDirPath on server"
                $session.CreateDirectory($remoteDirPath)
            }

            $session.PutFiles($localFilePath, $remoteFilePath).Check()

            Write-Host "Upload of $localFilePath succeeded"
        }
        finally
        {
            # Disconnect, clean up
            $session.Dispose()
        }

    } #end of first try
    catch
    {
        Write-Host "Error: $($_.Exception.Message)"
    }
} #end of action

while ($True) { sleep 5 }


问:
Sum values recursively in one line
I am pretty sure that it can be done in one line using things like map, sum etc. I cannot figure out how exactly, because I just started learning ruby. Could someone help? Thanks</p>

```<code> class Something < ApplicationRecord
 def function
    res = items.count
    items.each do |i|
      res += i.function
    end
    res
  end
</code>```

答:
I'm not sure why you need to do it recursively and in one line, but you can try something like this:

edit:

```<code>def add(arr)
    return 0 if arr.length == 0
    # if the arr argument is an empty array, return 0.

    arr[0] + add(arr[1..-1])
    # add the first element of the array to the result of calling add
    # on the array minus the first element.
end
</code>```

If you just want to sum an array as concisely as possible, all you need to do is [1, 2, 3].sum or [1,2,3,4].reduce(&:+). No recursion needed.

Title: Sum values recursively in one line

Body:
I am pretty sure that it can be done in one line using things like map, sum etc. I cannot figure out how exactly, because I just started learning ruby. Could someone help? Thanks

 class Something < ApplicationRecord
 def function
    res = items.count
    items.each do |i|
      res += i.function
    end
    res
  end

Body:
I'm not sure why you need to do it recursively and in one line, but you can try something like this:

edit:

def add(arr)
    return 0 if arr.length == 0
    # if the arr argument is an empty array, return 0.

    arr[0] + add(arr[1..-1])
    # add the first element of the array to the result of calling add
    # on the array minus the first element.
end

If you just want to sum an array as concisely as possible, all you need to do is [1, 2, 3].sum or [1,2,3,4].reduce(&:+). No recursion needed.


问:
Simplify overlapping And condition statements
I'm trying to figure out the best way to simplify conditional statements that are of the form:

```<code>if( ( A() && B() ) || ( B() && C() ) || ( C() && D() ) || .... )
{
    code
}
</code>```

The A/B/C/D/etc functions are relatively expensive, so it's not ideal that they could each be called twice.

Two alternatives I've thought of:

```<code>bool a = A();
bool b = B();
bool c = C();
bool d = D();
if( ( a && b ) || ( b && c ) || ( c && d ) || .... )
{
    code
}
</code>```

This version is not ideal because C(), D(), and any additional conditions are evaluated every time even if A() and B() were both true.  In the original version, they wouldn't have been called at all in that case.

```<code>bool b = B();
if( ( A() && b ) )
{
    code
}
else
{
    bool c = C();
    if( ( b && c ) )
    {
        code
    }
    else
    {
        bool d = D();
        if( ( c && D ) )
        {
            code
        }
        else
        {
            ...
        }
    }
}
</code>```

This version avoids any duplicate and unnecessary conditions from being evaluated, but is incredibly verbose and painful to write.

So I'm hopeful that there's some simpler but equally effective way to write it that I'm not thinking of...?

答:
Solve the problem with Template Meta-Programming!

```<code>//If we run out of functions and didn't find a pair that both returned true, we return false
bool evaluate_impl(bool) {
    return false;
}

//At this point, we're guaranteed to have at least 1 cached result and 1 unevaluated function call.
template<typename Func, typename ... Funcs>
bool evaluate_impl(bool cached, Func && func, Funcs&& ... funcs) {
    //store the result of the function
    bool result = func();
    if (cached && result)
        return true;
    else {
        //the result of this call becomes the new cached value
        return evaluate_impl(result, std::forward<Funcs>(funcs)...);
    }
}

//We receive all the functions
template<typename Func, typename ... Funcs>
bool evaluate_tmp(Func && func, Funcs&& ... funcs) {
    //We cache the result of calling the first function and pass along to the next step
    return evaluate_impl(func(), std::forward<Funcs>(funcs)...);
}

int main() {
    bool result = evaluate_tmp(A, B, C, D);
}
</code>```

This efficiently expands to support any number of function calls (up to what your compiler will allow, at any rate).

```<code>int main() {
    bool result = evaluate_tmp(A, B, A, C, A, A, A, A, D, A, B, A, C, A, D, A);
}
</code>```

Body:
I'm trying to figure out the best way to simplify conditional statements that are of the form:

if( ( A() && B() ) || ( B() && C() ) || ( C() && D() ) || .... )
{
    code
}

The A/B/C/D/etc functions are relatively expensive, so it's not ideal that they could each be called twice.

Two alternatives I've thought of:

bool a = A();
bool b = B();
bool c = C();
bool d = D();
if( ( a && b ) || ( b && c ) || ( c && d ) || .... )
{
    code
}

This version is not ideal because C(), D(), and any additional conditions are evaluated every time even if A() and B() were both true.  In the original version, they wouldn't have been called at all in that case.

bool b = B();
if( ( A() && b ) )
{
    code
}
else
{
    bool c = C();
    if( ( b && c ) )
    {
        code
    }
    else
    {
        bool d = D();
        if( ( c && D ) )
        {
            code
        }
        else
        {
            ...
        }
    }
}

This version avoids any duplicate and unnecessary conditions from being evaluated, but is incredibly verbose and painful to write.

So I'm hopeful that there's some simpler but equally effective way to write it that I'm not thinking of...?

Body:
Solve the problem with Template Meta-Programming!

//If we run out of functions and didn't find a pair that both returned true, we return false
bool evaluate_impl(bool) {
    return false;
}

//At this point, we're guaranteed to have at least 1 cached result and 1 unevaluated function call.
template<typename Func, typename ... Funcs>
bool evaluate_impl(bool cached, Func && func, Funcs&& ... funcs) {
    //store the result of the function
    bool result = func();
    if (cached && result)
        return true;
    else {
        //the result of this call becomes the new cached value
        return evaluate_impl(result, std::forward<Funcs>(funcs)...);
    }
}

//We receive all the functions
template<typename Func, typename ... Funcs>
bool evaluate_tmp(Func && func, Funcs&& ... funcs) {
    //We cache the result of calling the first function and pass along to the next step
    return evaluate_impl(func(), std::forward<Funcs>(funcs)...);
}

int main() {
    bool result = evaluate_tmp(A, B, C, D);
}

This efficiently expands to support any number of function calls (up to what your compiler will allow, at any rate).

int main() {
    bool result = evaluate_tmp(A, B, A, C, A, A, A, A, D, A, B, A, C, A, D, A);
}


问:
Telosb Mote Time taken by Turning Radio off
I am having trouble with telosb Mote, because I don't know how much time it takes when a command to turn it off is executed. Can anybody help me out, please? </p>

答:
I think it's very fast. You can set it to be 192us. But note that if you have a lot of code before the turn off command, the telosb will do them before been turned off. Say if you have an infinite loop before the turn-off, your telosb will never be turned off.

So consider that I think you may be looking for the turnaround time rather than the turn it off command time. The turnaround time is the time the radio switch from the Receive to Transmit or from transmit to receive. The time is 12 symbol. You can refer to the CC2420 radio documents which used by the telosb motes. https://inst.eecs.berkeley.edu/~cs150/Documents/CC2420.pdf


问:
Ensure that c# Assemby are deterministic
It is possible to restrict specific classes, such as Random or DateTime, or the use of float in an AppDomain. Is it possible to detect it by reflection if you use them? or should we look at the IL code?

I would like to make a plugin system, but I have to make sure that the executed code is deterministic. Any other ideas on how to deal with it?

Thanks.

答:
Creating Type white list is possible to do that job</p>

```<code> readonly static List<string> WhiteList = new List<string>()
    {
        #region Basics
        typeof(Boolean).FullName,
        typeof(Char).FullName,
        typeof(String).FullName,
        typeof(Byte).FullName,
        typeof(SByte).FullName,
        typeof(UInt16).FullName,
        typeof(Int16).FullName,
        typeof(UInt32).FullName,
        typeof(Int32).FullName,
        typeof(UInt64).FullName,
        typeof(Int64).FullName,
        typeof(Decimal).FullName,
        typeof(Double).FullName,
        typeof(Single).FullName,
        typeof(TimeSpan).FullName,

        typeof(Array).FullName,
        typeof(Enum).FullName,
        #endregion

        #region Exceptions
        typeof(Exception).FullName,
        typeof(NotImplementedException).FullName,
        typeof(IOException).FullName,
        #endregion

        #region Delegates
        typeof(Delegate).FullName,
        #endregion

        #region Parallel
        typeof(Parallel).FullName,
        #endregion

        #region Conversions
        typeof(Convert).FullName,
        typeof(BitConverter).FullName,
        #endregion

        #region Streams
        typeof(Stream).FullName,
        typeof(MemoryStream).FullName,
        typeof(BinaryReader).FullName,
        typeof(BinaryWriter).FullName,
        #endregion

        #region Interfaces
        typeof(IDisposable).FullName,
        typeof(IComparable).FullName,
        typeof(IConvertible).FullName,
        typeof(IFormatProvider).FullName,
        typeof(IFormattable).FullName,
        typeof(IOrderedQueryable).FullName,
        #endregion

        #region Attributes
        typeof(Attribute).FullName,

        // Compilation JIT
        typeof(CompilationRelaxationsAttribute).FullName,
        typeof(RuntimeCompatibilityAttribute).FullName,
        typeof(CompilerGeneratedAttribute).FullName,
        #endregion

        #region Generic Types
        typeof(IDictionary<object,object>).Namespace+"."+typeof(IDictionary<object,object>).Name,
        typeof(Dictionary<object,object>).Namespace+"."+typeof(Dictionary<object,object>).Name,
        typeof(List<object>).Namespace+"."+typeof(List<object>).Name,
        typeof(IList<object>).Namespace+"."+typeof(IList<object>).Name,
        typeof(IEnumerable<object>).Namespace+"."+typeof(IEnumerable<object>).Name,
        typeof(IEnumerator<object>).Namespace+"."+typeof(IEnumerator<object>).Name,
        typeof(IOrderedEnumerable<object>).Namespace+"."+typeof(IOrderedEnumerable<object>).Name,
        typeof(IOrderedQueryable<object>).Namespace+"."+typeof(IOrderedQueryable<object>).Name,
        typeof(ICollection<object>).Namespace+"."+typeof(ICollection<object>).Name,
        typeof(IComparable<object>).Namespace+"."+typeof(IComparable<object>).Name,
        typeof(IEquatable<object>).Namespace+"."+typeof(IEquatable<object>).Name,
        typeof(IObservable<object>).Namespace+"."+typeof(IObservable<object>).Name,
        #endregion
    };

    const string WhiteListedNamespace = "XX.XXXXXXXXXX.";

    /// <summary>
    /// Check white list
    /// </summary>
    /// <param name="binary">Binary</param>
    public static void CheckWhiteList(byte[] binary)
    {
        using (MemoryStream ms = new MemoryStream(binary))
        {
            AssemblyDefinition def = AssemblyDefinition.ReadAssembly(ms, new ReaderParameters(ReadingMode.Immediate));

            List<string> ls = new List<string>();
            foreach (ModuleDefinition mdef in def.Modules)
                foreach (TypeReference tdef in mdef.GetTypeReferences())
                {
                    if (!WhiteList.Contains(tdef.FullName) &&
                        !tdef.FullName.StartsWith(WhiteListedNamespace, StringComparison.InvariantCulture))
                        ls.Add(tdef.FullName);
                }

            if (ls.Count > 0)
                throw (new TypeNotAllowedException(ls.ToArray()));
        }
    }
</code>```

Body:
Creating Type white list is possible to do that job

 readonly static List<string> WhiteList = new List<string>()
    {
        #region Basics
        typeof(Boolean).FullName,
        typeof(Char).FullName,
        typeof(String).FullName,
        typeof(Byte).FullName,
        typeof(SByte).FullName,
        typeof(UInt16).FullName,
        typeof(Int16).FullName,
        typeof(UInt32).FullName,
        typeof(Int32).FullName,
        typeof(UInt64).FullName,
        typeof(Int64).FullName,
        typeof(Decimal).FullName,
        typeof(Double).FullName,
        typeof(Single).FullName,
        typeof(TimeSpan).FullName,

        typeof(Array).FullName,
        typeof(Enum).FullName,
        #endregion

        #region Exceptions
        typeof(Exception).FullName,
        typeof(NotImplementedException).FullName,
        typeof(IOException).FullName,
        #endregion

        #region Delegates
        typeof(Delegate).FullName,
        #endregion

        #region Parallel
        typeof(Parallel).FullName,
        #endregion

        #region Conversions
        typeof(Convert).FullName,
        typeof(BitConverter).FullName,
        #endregion

        #region Streams
        typeof(Stream).FullName,
        typeof(MemoryStream).FullName,
        typeof(BinaryReader).FullName,
        typeof(BinaryWriter).FullName,
        #endregion

        #region Interfaces
        typeof(IDisposable).FullName,
        typeof(IComparable).FullName,
        typeof(IConvertible).FullName,
        typeof(IFormatProvider).FullName,
        typeof(IFormattable).FullName,
        typeof(IOrderedQueryable).FullName,
        #endregion

        #region Attributes
        typeof(Attribute).FullName,

        // Compilation JIT
        typeof(CompilationRelaxationsAttribute).FullName,
        typeof(RuntimeCompatibilityAttribute).FullName,
        typeof(CompilerGeneratedAttribute).FullName,
        #endregion

        #region Generic Types
        typeof(IDictionary<object,object>).Namespace+"."+typeof(IDictionary<object,object>).Name,
        typeof(Dictionary<object,object>).Namespace+"."+typeof(Dictionary<object,object>).Name,
        typeof(List<object>).Namespace+"."+typeof(List<object>).Name,
        typeof(IList<object>).Namespace+"."+typeof(IList<object>).Name,
        typeof(IEnumerable<object>).Namespace+"."+typeof(IEnumerable<object>).Name,
        typeof(IEnumerator<object>).Namespace+"."+typeof(IEnumerator<object>).Name,
        typeof(IOrderedEnumerable<object>).Namespace+"."+typeof(IOrderedEnumerable<object>).Name,
        typeof(IOrderedQueryable<object>).Namespace+"."+typeof(IOrderedQueryable<object>).Name,
        typeof(ICollection<object>).Namespace+"."+typeof(ICollection<object>).Name,
        typeof(IComparable<object>).Namespace+"."+typeof(IComparable<object>).Name,
        typeof(IEquatable<object>).Namespace+"."+typeof(IEquatable<object>).Name,
        typeof(IObservable<object>).Namespace+"."+typeof(IObservable<object>).Name,
        #endregion
    };

    const string WhiteListedNamespace = "XX.XXXXXXXXXX.";

    /// <summary>
    /// Check white list
    /// </summary>
    /// <param name="binary">Binary</param>
    public static void CheckWhiteList(byte[] binary)
    {
        using (MemoryStream ms = new MemoryStream(binary))
        {
            AssemblyDefinition def = AssemblyDefinition.ReadAssembly(ms, new ReaderParameters(ReadingMode.Immediate));

            List<string> ls = new List<string>();
            foreach (ModuleDefinition mdef in def.Modules)
                foreach (TypeReference tdef in mdef.GetTypeReferences())
                {
                    if (!WhiteList.Contains(tdef.FullName) &&
                        !tdef.FullName.StartsWith(WhiteListedNamespace, StringComparison.InvariantCulture))
                        ls.Add(tdef.FullName);
                }

            if (ls.Count > 0)
                throw (new TypeNotAllowedException(ls.ToArray()));
        }
    }


问:
Json.NET Deserialize Returning Object with Default Values

I'm trying to deserialize a JSON string but it keeps returning an object with default values (false, null, etc).

The JSON I'm working with is coming from a web service and is quite long. I've pasted it here: https://pastebin.com/6LrfSVJE

The structure is of the following:

```<code>"Data": [SITE, SITE, SITE, etc.]
"Success": BOOLEAN,
"Message": STRING,
</code>```

Where a Site looks like this:

```<code>"__type" : STRING
"ID": INTEGER,
"UniqueIdentifier": GUID/STRING,
"Network": INTEGER,
"LandOwner": INTEGER (nullable),
"PermitHolder": INTEGER (nullable),
"Name": STRING,
"Alias": STRING (unique),
"Notes": STRING,
"Latitude": DOUBLE (nullable),
"Longitude": DOUBLE (nullable),
"Elevation": DOUBLE (nullable),
"TimeZoneName": STRING,
"TimeZoneAbbreviation": STRING,
"TimeZoneOffset": INTEGER,
"CreationDate": STRING ISO-8601,
"ModificationDate": STRING ISO-8601,
"GPSLandmark": STRING
</code>```

I've replicated these in C# to use with Json.NET:

```<code>public class SiteList
{
    public bool Success { get; set; }
    public string Message { get; set; }
    public IList<Site> Data { get; set; }
}

public class Site
{
    public string __type { get; set; }
    public int ID { get; set; }
    public string UniqueIdentifier { get; set; }
    public int Network { get; set; }
    public int LandOwner { get; set; }
    public int PermitHolder { get; set; }
    public string Name { get; set; }
    public string Alias { get; set; }
    public string Notes { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public double Elevation { get; set; }
    public string TimeZoneName { get; set; }
    public string TimeZoneAbbreviation { get; set; }
    public int TimeZoneOffset { get; set; }
    public string CreationDate { get; set; }
    public string ModificationDate { get; set; }
    public string GPSLandmark { get; set; }
}
</code>```

And I'm deserializing it as such:

```<code>string message = /* I make my service call here - same string as the JSON pasted above */
var sitelist = JsonConvert.DeserializeObject<Infrastructure.SiteList>(message);
</code>```

If my data structures were incorrect, I'd expect the Json.NET function to return null. But it actually does return a SiteList, just with values of data=null, message=null, success=false.

This code was working a few days ago, but recently the web service was changed and the site data structure now contains the __type field. And ever since then the deserialization is failing.

I've tried not including the __type field at all, naming it "type", "Type", "__type", "__Type", but I always get the same result. I'm not exactly sure how Json.NET matches variable names but the introduction of the __type field does seem to have caused the issue, and it doesn't help that the name doesn't follow the previous convention.

Does anyone have a solution or see any mistake I may have overlooked?

答:
FIX:

I never mentioned that my SiteList and Site inherited from an abstract base class - the fact that it was inherited never messed up the functionality before. However I recently added the [DataContract] attribute to this base class so that I can use some of its inherited classes in my own web service, and it turns out that was what was breaking the deserialization. Removing the attribute or not inheriting from a DataContract class fixes the issue.

Body:
I'm trying to deserialize a JSON string but it keeps returning an object with default values (false, null, etc).

The JSON I'm working with is coming from a web service and is quite long. I've pasted it here: https://pastebin.com/6LrfSVJE

The structure is of the following:

"Data": [SITE, SITE, SITE, etc.]
"Success": BOOLEAN,
"Message": STRING,

Where a Site looks like this:

"__type" : STRING
"ID": INTEGER,
"UniqueIdentifier": GUID/STRING,
"Network": INTEGER,
"LandOwner": INTEGER (nullable),
"PermitHolder": INTEGER (nullable),
"Name": STRING,
"Alias": STRING (unique),
"Notes": STRING,
"Latitude": DOUBLE (nullable),
"Longitude": DOUBLE (nullable),
"Elevation": DOUBLE (nullable),
"TimeZoneName": STRING,
"TimeZoneAbbreviation": STRING,
"TimeZoneOffset": INTEGER,
"CreationDate": STRING ISO-8601,
"ModificationDate": STRING ISO-8601,
"GPSLandmark": STRING

I've replicated these in C# to use with Json.NET:

public class SiteList
{
    public bool Success { get; set; }
    public string Message { get; set; }
    public IList<Site> Data { get; set; }
}

public class Site
{
    public string __type { get; set; }
    public int ID { get; set; }
    public string UniqueIdentifier { get; set; }
    public int Network { get; set; }
    public int LandOwner { get; set; }
    public int PermitHolder { get; set; }
    public string Name { get; set; }
    public string Alias { get; set; }
    public string Notes { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public double Elevation { get; set; }
    public string TimeZoneName { get; set; }
    public string TimeZoneAbbreviation { get; set; }
    public int TimeZoneOffset { get; set; }
    public string CreationDate { get; set; }
    public string ModificationDate { get; set; }
    public string GPSLandmark { get; set; }
}

And I'm deserializing it as such:

string message = /* I make my service call here - same string as the JSON pasted above */
var sitelist = JsonConvert.DeserializeObject<Infrastructure.SiteList>(message);

If my data structures were incorrect, I'd expect the Json.NET function to return null. But it actually does return a SiteList, just with values of data=null, message=null, success=false.

This code was working a few days ago, but recently the web service was changed and the site data structure now contains the __type field. And ever since then the deserialization is failing.

I've tried not including the __type field at all, naming it "type", "Type", "__type", "__Type", but I always get the same result. I'm not exactly sure how Json.NET matches variable names but the introduction of the __type field does seem to have caused the issue, and it doesn't help that the name doesn't follow the previous convention.

Does anyone have a solution or see any mistake I may have overlooked?


问:
How to generate a file for download in a Google Chrome Extension?
I want to generate a CSV file as the result of some user interactions and then prompt the user to download it. How can I do that?

I don't think it's possible in straight JS, but perhaps Chrome gives me some elevated privileges?

答:
You can now use HTML5 File API to download a file. It is still in development, but you can use a BlobBuilder and redirect your use to download that file:

```<code>var bb = new BlobBuilder();
bb.append(csvContents);
var blob = bb.getBlob();
location.href = window.webkitURL.createObjectURL(blob);
</code>```

For more information regarding the File API, HTML5Rocks has a great tutorial:

http://www.html5rocks.com/tutorials/file/filesystem/

Body:
You can now use HTML5 File API to download a file. It is still in development, but you can use a BlobBuilder and redirect your use to download that file:

var bb = new BlobBuilder();
bb.append(csvContents);
var blob = bb.getBlob();
location.href = window.webkitURL.createObjectURL(blob);

For more information regarding the File API, HTML5Rocks has a great tutorial:

http://www.html5rocks.com/tutorials/file/filesystem/


问:
.animate scroll nested div
I am setting up a site that has parallaxing nested divs and I'm attempting to animate the scroll to each div. The problem im running into is that most .animate scrollto's I'm finding are relying on the html,body which is where I think I'm having a problem since the scrolling happens to the parent div vs. the body of the page. I've set up a fiddle that gives the basic outline of the site with simple anchor tags that take you to the next nested div/section. I am attempting to animate the scroll between each one vs. jumping to the next anchor. Can someone point me in the right direction? Here is the fiddle link

```<code><html>
    <head>
        <script>
        function scrollToAnchor(group1) {
            var aTag = $("a[name='" + group1 + "']");
            $('parent-container').animate({
                scrollTop: aTag.offset().top
            }, 'slow');
        }
        $("#group1").click(function() {
            scrollToAnchor('#group2');
        });

        function scrollToAnchor(group2) {
            var aTag = $("a[name='" + group2 + "']");
            $('parent-container').animate({
                scrollTop: aTag.offset().top
            }, 'slow');
        }
        $("#group2").click(function() {
            scrollToAnchor('#group3');
        });

        function scrollToAnchor(group3) {
            var aTag = $("a[name='" + group3 + "']");
            $('parent-container').animate({
                scrollTop: aTag.offset().top
            }, 'slow');
        }
        $("#group3").click(function() {
            scrollToAnchor('#group4');
        });

        function scrollToAnchor(group4) {
            var aTag = $("a[name='" + group4 + "']");
            $('parent-container').animate({
                scrollTop: aTag.offset().top
            }, 'slow');
        }
        $("#group4").click(function() {
            scrollToAnchor('#group1');
        });
        </script>
    </head>
    <body>
        <div id="parent-container" class="master-wrap"> // overflow:scroll, 100vh
            <div id="group1" class="wrap"> //100vh
                <h1>Some Title Here - box1</h1>
                <p>some content here.</p>
                <a href="#group2" class="next_button">↓</a>
            </div>
            <div id="group2" class="wrap"> //100vh
                <h1>Some Title Here - box3</h1>
                <p>some content here</p>
                <a href="#group3" class="next_button">↓</a>
            </div>
            <div id="group3" class="wrap"> //100vh
                <a href="#group4" class="next_button">↓</a>
                <h1>Some Title Here - box3</h1>
                <p>some content here</p>
            </div>
            <div id="group4" class="wrap"> //100vh
                <h1>Some Title Here - box4</h1>
                <p>some content here</p>
                <a href="#group1" class="next_button">↑</a>
            </div>
        </div>
    </body>

</html>
</code>```

答:
I would approach this doing a more generic solution, where you use a data attribute to indicate which element should be scrolled to upon clicking the element.

For instance,
···
 would scroll to the element with id other-element. Please see the following for a working example:

$('[data-scroll-to]').on('click', function(event) {
  var target = $("#" + $(event.target).data('scroll-to'))
  var offset = target.offset().top
  $('html, body').animate({
    scrollTop: offset
  }, 'slow')

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  height: 200px;
  background-color: rgb(200, 200, 200);
}

.box:nth-child(even) {
  background-color: rgb(150, 150, 150);
}</code>```

  Box 1 > Box 2

  Box 2 > Box 3

  Box 3 > Box 1

```

Title: .animate scroll nested div

Body:
I am setting up a site that has parallaxing nested divs and I'm attempting to animate the scroll to each div. The problem im running into is that most .animate scrollto's I'm finding are relying on the html,body which is where I think I'm having a problem since the scrolling happens to the parent div vs. the body of the page. I've set up a fiddle that gives the basic outline of the site with simple anchor tags that take you to the next nested div/section. I am attempting to animate the scroll between each one vs. jumping to the next anchor. Can someone point me in the right direction? Here is the fiddle link

 // overflow:scroll, 100vh

 //100vh

Some Title Here - box1

some content here.

                ↓

 //100vh

Some Title Here - box3

some content here

                ↓

 //100vh
                ↓

Some Title Here - box3

some content here

 //100vh

Some Title Here - box4

some content here

                ↑

Body:
I would approach this doing a more generic solution, where you use a data attribute to indicate which element should be scrolled to upon clicking the element.

For instance, <div data-scroll-to="other-element">···</div> would scroll to the element with id other-element. Please see the following for a working example:

$('[data-scroll-to]').on('click', function(event) {
  var target = $("#" + $(event.target).data('scroll-to'))
  var offset = target.offset().top
  $('html, body').animate({
    scrollTop: offset
  }, 'slow')

})

.box {
  height: 200px;
  background-color: rgb(200, 200, 200);
}

.box:nth-child(even) {
  background-color: rgb(150, 150, 150);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1" data-scroll-to="box2" class="box">
  Box 1 > Box 2
</div>

<div id="box2" data-scroll-to="box3" class="box">
  Box 2 > Box 3
</div>

<div id="box3" data-scroll-to="box1" class="box">
  Box 3 > Box 1
</div>


问:
chromeless is not saving image in correct location
[OSX] [node 8.4.0] [chromeless 1.3.0]

I am trying to implement a test using chromeless.  I am running the sample in a local instance, with one change of specifying the imagePath to save the image. It is running and saving an image however the image is being saved in the default location still. Any ideas on what I am doing wrong? My desire is to save the image relative to the directory the test was executed in.

Modified line below.

```<code>.screenshot({ filePath: './images/test1.png'} );
</code>```

As I said it all runs but the image is still saved in the following location

```<code>/var/folders/r1/4xfjz/T/cjavyrbo70000kk.png
</code>```

答: Looks like a known problem. See https://github.com/graphcool/chromeless/issues/282</p>

Body:
[OSX] [node 8.4.0] [chromeless 1.3.0]

I am trying to implement a test using chromeless.  I am running the sample in a local instance, with one change of specifying the imagePath to save the image. It is running and saving an image however the image is being saved in the default location still. Any ideas on what I am doing wrong? My desire is to save the image relative to the directory the test was executed in.

Modified line below.

.screenshot({ filePath: './images/test1.png'} );

As I said it all runs but the image is still saved in the following location

/var/folders/r1/4xfjz/T/cjavyrbo70000kk.png


问:
Error: invalid_scope - This app hasn't been verified to access
Has anyone experienced this error before? I have been researching, testing, and banging my head to get this error to go away but nothing seems to work.

This is a similar question to the following posts:

Error: invalid_scope google read contact

Google Api:: Error: invalid_scope

403 error when calling Google People API

Unfortunately, these posts never were resolved or aren't helpful.

What is puzzling is, i'm following the examples listed here: https://developers.google.com/api-client-library/javascript/samples/samples. Along with testing the ONLY the scopes I need here: https://developers.google.com/people/api/rest/v1/people/get.

However, I cannot seem to get past the popup screen that states i'm passing an invalid scope.

FYI, I have the API Console setup to use Google People API, Google+, and Google Contacts. I'm using my client id and api key in the "gapi.auth2.init" config call.

Any insight would be super helpful! Thank you for your time and response.

答:
after googling some time I've come across this question and the list of scopes of google:

https://developers.google.com/identity/protocols/googlescopes

Just in case this helps.