问:
Accessing class member of std:vector of std:vector in a class with another std:vector
I am puzzled by how to access a std::vector in a class with another a std::vector. A previous discussion(Why is it OK to return a 'vector' from a function?) deals with a similar issue, but it seems I must have misunderstood something.

Here is a sketch of my code:

```<code>class Employee
    m_id;
public:
    set_id(int id);
    id();

In Employee.cpp
void Employee::set_id(const int id)
{
    m_id = id;          // m_id is 5
}

int Employee::id() const
{
    return m_id;        // m_id is rubbish
}

class Company
public:
    std::vector<Employee> m_employees;

In Company.cpp
void Company::addEmployee(const addEmployee employee) // A vant to pass a copy of employee
{
    m_employees.push_back(employee);
}
std::vector<Employee> Company::employees()
{
    return m_employees;
}

in myClass.h
std::vector<Company> m_companies;

in myClass.cpp

int empl_id = 5;   // test value
m_companyIndex = 0;   // for test
m_emplIndex = 0;   //

Company company;
Employee employee;
m_companies.push_back(company);
m_companies.at(m_companyIndex).addEmployee(employee);

            m_companies.at(m_companyIndex).employees().at(m_emplIndex).set_id(empl_id);
int idRet = m_companies.at(m_companyIndex).employees().at(m_emplIndex).id();

idRet contans an apparently random number, instead of 5. Using a debugger shos that
</code>```

If I instantiate Employee in myClass I can set and read back m_id; idem for Company, so the problem seems to be realted to std::vector m_employees; in class Company. Could it have something to do with "Return Value Optimisation"? By the way, I am using gcc 7.5.4.

答:
As @dxiv points out, your Company::employees function constructs and returns a copy of the m_employees list. Thus your code

```<code>m_companies.at(m_companyIndex).employees().at(m_emplIndex).set_id(empl_id);
</code>```

translates to:

```<code>Get the element of m_companies at the index m_companyIndex,
then construct a copy of its m_employees list,
then get the element of that copy at index m_emplIndex,
then set the id of that element to empl_id,
and then destroy the copy.
</code>```

This of course does not change the contents of the m_employees list at all.

You could make your code work more or less correctly by making Company::employees return a non-const reference to the employees list, rather than a copy. However, such a function could not be called on a 'const' Company object, so you would probably also want a 'const' version of it that returned a const reference as well.

However, exposing a class's private implementation details, such as m_employees, even via a non-const reference, is dangerous, because if outside code uses this reference to modify the m_employees vector, then the Employees class is not notified, and any other internal data that it has which may depend on the contents of the m_employees vector can't be updated at the same time.

It is therefore generally better for outside code to ask the containing class (Employees) to make the change rather than asking the containing class to return a non-const reference that can be used by outside code to make the change. That way, the Employees class can make the change and also update any other internal data that it has that may depend on the m_employees contents.

For instance, you could add an Employees::at function which returns a reference to an element so that the above line of code could be rewritten as:

```<code>m_companies.at(m_companyIndex).at(m_emplIndex).set_id(empl_id);
</code>```

or even better:

```<code>m_companies.at(m_companyIndex).set_id(m_emplIndex, empl_id);
</code>```

or even better, if m_companies was contained in a Companies object named 'companies':

```<code>companies.set_id(m_companyIndex, m_emplIndex, empl_id);
</code>```

With these functions, you could change Employees::m_employees to use a completely different data structure (say, a sorted list, linked list or set) without affecting your interface at all. This reduces the coupling between outside code and the internals of your class, and makes things easier to change in the future if you need to.

In general, it's wise to consider the Law of Demeter when designing interfaces of this sort, especially with regard to interfaces for mutating the contents of objects: Many objects don't react well to having their internal contents changed by outside classes without their knowledge, so it's best to ask the containing object to change its subobjects when possible, rather than allowing non-const references to them to be accessible from outside the class.

Body:
I am puzzled by how to access a std::vector in a class with another a std::vector. A previous discussion(Why is it OK to return a 'vector' from a function?) deals with a similar issue, but it seems I must have misunderstood something.

Here is a sketch of my code:

class Employee
    m_id;
public:
    set_id(int id);
    id();

In Employee.cpp
void Employee::set_id(const int id)
{
    m_id = id;          // m_id is 5
}

int Employee::id() const
{
    return m_id;        // m_id is rubbish
}

class Company
public:
    std::vector<Employee> m_employees;

In Company.cpp
void Company::addEmployee(const addEmployee employee) // A vant to pass a copy of employee
{
    m_employees.push_back(employee);
}
std::vector<Employee> Company::employees()
{
    return m_employees;
}

in myClass.h
std::vector<Company> m_companies;

in myClass.cpp

int empl_id = 5;   // test value
m_companyIndex = 0;   // for test
m_emplIndex = 0;   //

Company company;
Employee employee;
m_companies.push_back(company);
m_companies.at(m_companyIndex).addEmployee(employee);

            m_companies.at(m_companyIndex).employees().at(m_emplIndex).set_id(empl_id);
int idRet = m_companies.at(m_companyIndex).employees().at(m_emplIndex).id();

idRet contans an apparently random number, instead of 5. Using a debugger shos that

If I instantiate Employee in myClass I can set and read back m_id; idem for Company, so the problem seems to be realted to std::vector m_employees; in class Company. Could it have something to do with "Return Value Optimisation"? By the way, I am using gcc 7.5.4.

Body:
As @dxiv points out, your Company::employees function constructs and returns a copy of the m_employees list. Thus your code

m_companies.at(m_companyIndex).employees().at(m_emplIndex).set_id(empl_id);

translates to:

Get the element of m_companies at the index m_companyIndex,
then construct a copy of its m_employees list,
then get the element of that copy at index m_emplIndex,
then set the id of that element to empl_id,
and then destroy the copy.

This of course does not change the contents of the m_employees list at all.

You could make your code work more or less correctly by making Company::employees return a non-const reference to the employees list, rather than a copy. However, such a function could not be called on a 'const' Company object, so you would probably also want a 'const' version of it that returned a const reference as well.

However, exposing a class's private implementation details, such as m_employees, even via a non-const reference, is dangerous, because if outside code uses this reference to modify the m_employees vector, then the Employees class is not notified, and any other internal data that it has which may depend on the contents of the m_employees vector can't be updated at the same time.

It is therefore generally better for outside code to ask the containing class (Employees) to make the change rather than asking the containing class to return a non-const reference that can be used by outside code to make the change. That way, the Employees class can make the change and also update any other internal data that it has that may depend on the m_employees contents.

For instance, you could add an Employees::at function which returns a reference to an element so that the above line of code could be rewritten as:

m_companies.at(m_companyIndex).at(m_emplIndex).set_id(empl_id);

or even better:

m_companies.at(m_companyIndex).set_id(m_emplIndex, empl_id);

or even better, if m_companies was contained in a Companies object named 'companies':

companies.set_id(m_companyIndex, m_emplIndex, empl_id);

With these functions, you could change Employees::m_employees to use a completely different data structure (say, a sorted list, linked list or set) without affecting your interface at all. This reduces the coupling between outside code and the internals of your class, and makes things easier to change in the future if you need to.

In general, it's wise to consider the Law of Demeter when designing interfaces of this sort, especially with regard to interfaces for mutating the contents of objects: Many objects don't react well to having their internal contents changed by outside classes without their knowledge, so it's best to ask the containing object to change its subobjects when possible, rather than allowing non-const references to them to be accessible from outside the class.


来源: stackexchange

问:
Importing "0000" or "0030" into DataTable
I am importing values like 0000,0002,0023,0034 from a text file. However, the table shows them as 0, 2, 23, 34. Does anyone know why it is removing the leading zeros?

Here is my code:

```<code>private DataTable ImportTabFile()
{
    string dataSourcePath = @"C:\Documents and Settings\agordon\Desktop";
    string dataFileName = "ACTIVITYEX.txt";
    string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataSourcePath + @";Extended Properties=""text;HDR=No;FMT=Delimited""";
    OleDbConnection conn = new OleDbConnection(connString);
    OleDbCommand cmd = conn.CreateCommand();
    cmd.CommandText = String.Format("SELECT * FROM [{0}]", dataFileName);
    DataSet ds = new DataSet();
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);

    da.Fill(ds);

    return ds.Tables[0];
}
</code>```

How can I keep the leading zeroes during the import?

here is what my schema file looks like:

```<code>[ACTIVITYEX.txt]
Format=TabDelimited
ColNameHeader=False
Col13=ErrorCode Text
</code>```

答:
JET will infer types based on the first row. It is probably inferring your fields are INT because 0000 can be converted to a number. As mentioned above, leading zeroes are useless.

You can use schema.ini to explicitly define the column types. As noted in the comments above, you need to specify each column as per the documentation:

You must specify each column by number and designate the column name, data type, and width for fixed-length files.

Alternatively this article has some information on controlling how the types are inferred.

ContentLicense: CC BY-SA 3.0

Body:
I am importing values like 0000,0002,0023,0034 from a text file. However, the table shows them as 0, 2, 23, 34. Does anyone know why it is removing the leading zeros?

Here is my code:

private DataTable ImportTabFile()
{
    string dataSourcePath = @"C:\Documents and Settings\agordon\Desktop";
    string dataFileName = "ACTIVITYEX.txt";
    string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataSourcePath + @";Extended Properties=""text;HDR=No;FMT=Delimited""";
    OleDbConnection conn = new OleDbConnection(connString);
    OleDbCommand cmd = conn.CreateCommand();
    cmd.CommandText = String.Format("SELECT * FROM [{0}]", dataFileName);
    DataSet ds = new DataSet();
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);

    da.Fill(ds);

    return ds.Tables[0];
}

How can I keep the leading zeroes during the import?

here is what my schema file looks like:

[ACTIVITYEX.txt]
Format=TabDelimited
ColNameHeader=False
Col13=ErrorCode Text


问:
Color theme for VS Code integrated terminal
Can we change color settings of VS Code Integrated Terminal? Mine looks dull with just white.

答: Simply. You can go to 'File -> Preferences -> Color Theme' option in visual studio and change the color of you choice.</p>

ContentLicense: CC BY-SA 4.0


问:
C++ return value and move rule exceptions
When we return a value from a C++ function copy-initialisation happens. Eg:

std::string hello() {
    std::string x = "Hello world";
    return x; // copy-init
}
```

<p><em>Assume that RVO is disabled.</em></p>

<p>As per copy-init rule if <code>x</code> is a non-POD class type, then the copy constructor should be called. However for C++11 onward, I see move-constrtuctor being called. I could not find or understand the rules regarding this https://en.cppreference.com/w/cpp/language/copy_initialization. So my first question is - </p>

<ol>
<li><p>What does the C++ standard say about move happening for copy-init when value is returned from function?</p></li>
<li><p>As an extension to the above question, I would also like to know in what cases move does not happen. I came up with the following case where copy-constructor is called instead of move:</p></li>
</ol>

<pre class="lang-c++ prettyprint-override"><code>std::string hello2(std::string& param) {
    return param;
}
</code>```

Finally, in some library code I saw that std::move was being explicitly used when returning (even if RVO or move should happen). Eg:

std::string hello3() {
    std::string x = "Hello world";
    return std::move(x);
}
```

What is the advantage and disadvantage of explicitly using std::move when returning?

答:
You are confused by the fact that initialization via the move constructor is a special case of "copy initialization", and does not come as seperate concept. Check the notes on the cppreference page.

If other is an rvalue expression, move constructor will be selected by overload resolution and called during copy-initialization. There is no such term as move-initialization.

For returning a value from the function, check the description of returning on cppreference. It says in a box called "automatic move from local variables and parameters", where expression refers to what you return (warning: that quote is shortened! read the original for full details about other cases):

If expression is a (possibly parenthesized) id-expression that names a variable whose type is [...] a non-volatile object type [...] and that variable is declared [...] in the body or as a parameter of the [...] function, then overload resolution to select the constructor to use for initialization of the returned value is performed twice: first as if expression were an rvalue expression (thus it may select the move constructor), and if the first overload resolution failed [...] then overload resolution is performed as usual, with expression considered as an lvalue (so it may select the copy constructor).

So in the special case of returning a local variable, the variable can be treated as r-value, even if normal syntactic rules would make it a l-value. The spirit of the rule is that after the return, you can't find out whether the value of the local variable has been destroyed during the copy-initialization of the returned value, so moving it does not do any damage.

Regarding your second question: It is considered bad style to use std::move while returning, because moving will happen anyway, and it inhibits NRVO.

Quoting the C++ core guidelines linked above:

Never write return move(local_variable);, because the language already knows the variable is a move candidate. Writing move in this code won’t help, and can actually be detrimental because on some compilers it interferes with RVO (the return value optimization) by creating an additional reference alias to the local variable.

So that library code you quote is suboptimal.

Also, you can not implicitly move from anything that is not local to the function (that is local variables and value parameters), because implicit moving may move from something that is still visible after the function returned. In the quote from cppreference, the important point is "a non-volatile object type". When you return std::string& param, that is a variable with reference type.

Body:
When we return a value from a C++ function copy-initialisation happens. Eg:

std::string hello() {
    std::string x = "Hello world";
    return x; // copy-init
}

Assume that RVO is disabled.

As per copy-init rule if x is a non-POD class type, then the copy constructor should be called. However for C++11 onward, I see move-constrtuctor being called. I could not find or understand the rules regarding this https://en.cppreference.com/w/cpp/language/copy_initialization. So my first question is -

What does the C++ standard say about move happening for copy-init when value is returned from function?

As an extension to the above question, I would also like to know in what cases move does not happen. I came up with the following case where copy-constructor is called instead of move:

std::string hello2(std::string& param) {
    return param;
}

Finally, in some library code I saw that std::move was being explicitly used when returning (even if RVO or move should happen). Eg:

std::string hello3() {
    std::string x = "Hello world";
    return std::move(x);
}

What is the advantage and disadvantage of explicitly using std::move when returning?


问:
using a list of regressors and storing the values of betas
I have a list of circumstances and effects:
I want to generate a matrix with betas containing the values of betas. I am going to run the loop 10 times, because i am in fact going to bootstrap my observations.

So far I have tried:

```<code>local circumstances height weight

local effort training diet

foreach i in 1 10 {

    reg outcome  `circumstances' `effects'

    * store in column i the values of betas of circumstances

    * store in column i the values of betas of effort

 }
</code>```

Does anyone know what should the code look like in order to store those values?
Thank you

答:
The pseudocode would first store in "column 1" the first lot of betas and then overwrite them (column 1) with the second lot of betas. Then it would do the same again for column 10 with the first lot of betas and the second lot of betas. That is a long way from anything that makes sense. Nothing in your pseudocode takes bootstrap samples from the dataset, although perhaps you are intending to add code for that later.

Stata doesn't really work with any idea of column numbers, although the idea makes sense to Mata.

Unless there are very specific reasons -- which you would need to spell out -- there is no need to write your own code ab initio for bootstrapping, as the whole point of bootstrap is to do that for you.

Here is complete code for a reproducible example of bootstrapping a silly regression:

```<code>sysuse auto, clear
bootstrap b_weight=_b[weight] b_price=_b[price] , reps(1000) seed(2803) : regress mpg weight price
</code>```

See also the help for bootstrap to learn about its other options, including saving().

10 repetitions would be regarded as absurdly small for the number of bootstrap samples.

Body:
I have a list of circumstances and effects:
I want to generate a matrix with betas containing the values of betas. I am going to run the loop 10 times, because i am in fact going to bootstrap my observations.

So far I have tried:

local circumstances height weight

local effort training diet

foreach i in 1 10 {

    reg outcome  `circumstances' `effects'

    * store in column i the values of betas of circumstances

    * store in column i the values of betas of effort

 }

Does anyone know what should the code look like in order to store those values?
Thank you

Body:
The pseudocode would first store in "column 1" the first lot of betas and then overwrite them (column 1) with the second lot of betas. Then it would do the same again for column 10 with the first lot of betas and the second lot of betas. That is a long way from anything that makes sense. Nothing in your pseudocode takes bootstrap samples from the dataset, although perhaps you are intending to add code for that later.

Stata doesn't really work with any idea of column numbers, although the idea makes sense to Mata.

Unless there are very specific reasons -- which you would need to spell out -- there is no need to write your own code ab initio for bootstrapping, as the whole point of bootstrap is to do that for you.

Here is complete code for a reproducible example of bootstrapping a silly regression:

sysuse auto, clear
bootstrap b_weight=_b[weight] b_price=_b[price] , reps(1000) seed(2803) : regress mpg weight price

See also the help for bootstrap to learn about its other options, including saving().

10 repetitions would be regarded as absurdly small for the number of bootstrap samples.


问:
can i initialize const instance so that i can use it as const to initialize array?
(small reference):

```<code>template<typename T>
struct IVector2 {
    T x, y;

    IVector2(T x, T y) :
        x(x), y(y) { }
};
</code>```

Is there a way to do this:

```<code>    static const IVector2<int> floors;  // lowest / highest floor

    std::vector<std::array<IPerson, floors.x - floors.y>> requestQueue;
</code>```

I need to initialize array size to be diffrence between floors.x and floors.y.
i've been searching for answer on how to initialize floors and i've got this

```<code>const IVector2<int> IElevatorHandler::floors(-1, 4);
</code>```

but that doesn't do it.

答:
You can try using literal classes for that. I made a few changes to your code</p>

```<code>template<typename T>
struct IVector2 {
    T x, y;

    constexpr IVector2(T x, T y) : //constexpr constructor
        x(x), y(y) { }
};

static constexpr IVector2<int> floors(10,1);  // Initialized constexpr object. Now available at compile time
</code>```

Body:
(small reference):

template<typename T>
struct IVector2 {
    T x, y;

    IVector2(T x, T y) :
        x(x), y(y) { }
};

Is there a way to do this:

    static const IVector2<int> floors;  // lowest / highest floor

    std::vector<std::array<IPerson, floors.x - floors.y>> requestQueue;

I need to initialize array size to be diffrence between floors.x and floors.y.
i've been searching for answer on how to initialize floors and i've got this

const IVector2<int> IElevatorHandler::floors(-1, 4);

but that doesn't do it.

Body:
You can try using literal classes for that. I made a few changes to your code

template<typename T>
struct IVector2 {
    T x, y;

    constexpr IVector2(T x, T y) : //constexpr constructor
        x(x), y(y) { }
};

static constexpr IVector2<int> floors(10,1);  // Initialized constexpr object. Now available at compile time


问:
ASP.NET: how to validate
I have a simple ASP.NET (VB) page with a CompareValidator. I can check to ensure the value is numeric, but I have no idea how to check for the length (business rules require a 7 digit number). Existing code is below:

```<code><asp:TextBox ID="txtPolicyNo" runat="server"
                    BorderStyle="Ridge"></asp:TextBox>

<asp:CompareValidator ID="cvCheckPolicy" runat="server"
                    ErrorMessage="Must be a valid policy number" ControlToValidate="txtPolicyNo"
                    Type="Integer" Operator="DataTypeCheck">
</asp:CompareValidator>
</code>```

How can I accomplish this?

Thanks,

Jason

答:
To Check business rules, the CustomValidator is normally used.

```<code><asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="invalid text"></asp:CustomValidator>
</code>```

But if you only want to validate 7 digits, you can use RegularExpressionValidator with the validation expression: ValidationExpression=^\d{7}$

Title: ASP.NET: how to validate

Body:
I have a simple ASP.NET (VB) page with a CompareValidator. I can check to ensure the value is numeric, but I have no idea how to check for the length (business rules require a 7 digit number). Existing code is below:

<asp:TextBox ID="txtPolicyNo" runat="server"
                    BorderStyle="Ridge"></asp:TextBox>

<asp:CompareValidator ID="cvCheckPolicy" runat="server"
                    ErrorMessage="Must be a valid policy number" ControlToValidate="txtPolicyNo"
                    Type="Integer" Operator="DataTypeCheck">
</asp:CompareValidator>

How can I accomplish this?

Thanks,

Jason

Body:
To Check business rules, the CustomValidator is normally used.

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="invalid text"></asp:CustomValidator>

But if you only want to validate 7 digits, you can use RegularExpressionValidator with the validation expression: ValidationExpression=^\d{7}$


问:
LZW Decompression
I am implementing a LZW algorithm in C++.

The size of the dictionary is a user input, but the minimum is 256, so it should work with binary files. If it reaches the end of the dictionary it goes around to the index 0 and works up overwriting it from there.

For example, if i put in a alice in wonderland script and compress it with a dictionary size 512 i get this dictionary.

But i have a problem with decompression and the output dictionary from decompressing the compressed file looks like this.

And my code for decompressing looks like this

```<code>struct dictionary
{
    vector<unsigned char> entry;
    vector<bool> bits;
};

void decompress(dictionary dict[], vector<bool> file, int dictionarySize, int numberOfBits)
{
    //in this example
    //dictionarySize = 512, tells the max size of the dictionary, and goes back to 0 if it reaches 513
    //numberOfBits = log2(512) = 9
    //dictionary dict[] contains bits and strings (strings can be empty)
    // dict[0] =
    //            entry = (unsigned char)0
    //            bits = (if numberOfBits = 9) 000000001
    // dict[255] =
    //            entry = (unsigned char)255
    //            bits = (if numberOfBits = 9) 011111111
    // so the next entry will be dict[next] (next is currently 256)
    // dict[256] =
    //            entry = what gets added in the code below
    //            bits = 100000000
    // all the bits are already set previously (dictionary size is int dictionarySize) so in this case all the bits from 0 to 511 are already set, entries are set from 0 to 255, so extended ASCII

    vector<bool> currentCode;
    vector<unsigned char> currentString;
    vector<unsigned char> temp;

    int next=256;
    bool found=false;

    for(int i=0;i<file.size();i+=numberOfBits)
    {
        for(int j=0;j<numberOfBits;j++)
        {
            currentCode.push_back(file[i+j]);
        }

        for(int j=0;j<dictionarySize;j++)
        {
            // when the currentCode (size numberOfBits) gets found in the dictionary
            if(currentCode==dict[j].bits)
            {
                currentString = dict[j].entry;

                // if the current string isnt empty, then it means it found the characted in the dictionary
                if(!currentString.empty())
                {
                    found = true;
                }
            }
        }

        //if the currentCode in the dictionary has a string value attached to it
        if(found)
        {
            for(int j=0;j<currentString.size();j++)
            {
                cout<<currentString[j];
            }

            temp.push_back(currentString[0]);

            // so it doesnt just push 1 character into the dictionary
            // example, if first read character is 'r', it is already in the dictionary so it doesnt get added
            if(temp.size()>1)
            {
                // if next is more than 511, writing to that index would cause an error, so it resets back to 0 and goes back up
                if(next>dictionarySize-1) //next > 512-1
                {
                    next = 0;
                }
                dict[next].entry.clear();
                dict[next].entry = temp;
                next++;
            }

            //temp = currentString;
        }
        else
        {
            currentString = temp;
            currentString.push_back(temp[0]);

            for(int j=0;j<currentString.size();j++)
            {
                cout<<currentString[j];
            }

            // if next is more than 511, writing to that index would cause an error, so it resets back to 0 and goes back up
            if(next>dictionarySize-1)
            {
                next = 0;
            }
            dict[next].entry.clear();
            dict[next].entry = currentString;
            next++;

            //break;
        }

        temp = currentString;

        // currentCode gets cleared, and written into in the next iteration
        currentCode.clear();

        //cout<<endl;
        found = false;
    }
}
</code>```

Im am currently stuck and dont know what to fix here to fix the output.
I have also noticed, that if i put a dictionary big enough, so it doesnt go around the dictionary (it doesnt reach the end and begin again at 0) it works.

答:
start small

you are using files that is too much data to debug. Start small with strings. I took this nice example from Wikli:

```<code>Input: "abacdacacadaad"

step    input           match   output  new_entry   new_index
                                        a           0
                                        b           1
                                        c           2
                                        d           3
1       abacdacacadaad  a       0       ab          4
2       bacdacacadaad   b       1       ba          5
3       acdacacadaad    a       0       ac          6
4       cdacacadaad     c       2       cd          7
5       dacacadaad      d       3       da          8
6       acacadaad       ac      6       aca         9
7       acadaad         aca     9       acad        10
8       daad            da      8       daa         11
9       ad              a       0       ad          12
10      d               d       3

Output: "0102369803"
</code>```

So you can debug your code step by step with cross matching both input/output and dictionary contents. Once that is done correctly then you can do the same for decoding:

```<code>Input: "0102369803"

step    input   output  new_entry   new_index
                        a           0
                        b           1
                        c           2
                        d           3
1       0       a
2       1       b       ab          4
3       0       a       ba          5
4       2       c       ac          6
5       3       d       cd          7
6       6       ac      da          8
7       9       aca     aca         9
8       8       da      acad        10
9       0       a       daa         11
10      3       d       ad          12

Output: "abacdacacadaad"
</code>```

Only then move to files and clear dictionary handling.

bitstream

once you succesfully done the LZW on small alphabet you can try to use the full alphabet and bit encoding. You know the LZW stream can be encoded at any bitlength (not just 8/16/32/64 bits) which can greatly affect compression ratios (in respect to used data properties). So I would try to do univeral access to data at variable (or predefined bitlength).

Was a bit curious so I encoded a simple C++/VCL example for the compression:

//---------------------------------------------------------------------------
// LZW
const int LZW_bits=12;              // encoded bitstream size
const int LZW_size=1<<LZW_bits;     // dictinary size
// bitstream R/W
DWORD bitstream_tmp=0;
//---------------------------------------------------------------------------
// return LZW_bits from dat[adr,bit] and increment position (adr,bit)
DWORD bitstream_read(BYTE *dat,int siz,int &adr,int &bit,int bits)
    {
    DWORD a=0,m=(1<<bits)-1;
    // save tmp if enough bits
    if (bit>=bits){ a=(bitstream_tmp>>(bit-bits))&m; bit-=bits; return a; }
    for (;;)
        {
        // insert byte
        bitstream_tmp<<=8;
        bitstream_tmp&=0xFFFFFF00;
        bitstream_tmp|=dat[adr]&255;
        adr++; bit+=8;
        // save tmp if enough bits
        if (bit>=bits){ a=(bitstream_tmp>>(bit-bits))&m; bit-=bits; return a; }
        // end of data
        if (adr>=siz) return 0;
        }
    }
//---------------------------------------------------------------------------
// write LZW_bits from a to dat[adr,bit] and increment position (adr,bit)
// return true if buffer is full
bool bitstream_write(BYTE *dat,int siz,int &adr,int &bit,int bits,DWORD a)
    {
    a<<=32-bits;        // align to MSB
    // save tmp if aligned
    if ((adr<siz)&&(bit==32)){ dat[adr]=(bitstream_tmp>>24)&255; adr++; bit-=8; }
    if ((adr<siz)&&(bit==24)){ dat[adr]=(bitstream_tmp>>16)&255; adr++; bit-=8; }
    if ((adr<siz)&&(bit==16)){ dat[adr]=(bitstream_tmp>> 8)&255; adr++; bit-=8; }
    if ((adr<siz)&&(bit== 8)){ dat[adr]=(bitstream_tmp    )&255; adr++; bit-=8; }
    // process all bits of a
    for (;bits;bits--)
        {
        // insert bit
        bitstream_tmp<<=1;
        bitstream_tmp&=0xFFFFFFFE;
        bitstream_tmp|=(a>>31)&1;
        a<<=1; bit++;
        // save tmp if aligned
        if ((adr<siz)&&(bit==32)){ dat[adr]=(bitstream_tmp>>24)&255; adr++; bit-=8; }
        if ((adr<siz)&&(bit==24)){ dat[adr]=(bitstream_tmp>>16)&255; adr++; bit-=8; }
        if ((adr<siz)&&(bit==16)){ dat[adr]=(bitstream_tmp>> 8)&255; adr++; bit-=8; }
        if ((adr<siz)&&(bit== 8)){ dat[adr]=(bitstream_tmp    )&255; adr++; bit-=8; }
        }
    return (adr>=siz);
    }
//---------------------------------------------------------------------------
bool str_compare(char *s0,int l0,char *s1,int l1)
    {
    if (l1<l0) return false;
    for (;l0;l0--,s0++,s1++)
     if (*s0!=*s1) return false;
    return true;
    }
//---------------------------------------------------------------------------
AnsiString LZW_encode(AnsiString raw)
    {
    AnsiString lzw="";
    int i,j,k,l;
    int adr,bit;
    DWORD a;
    const int siz=32;                   // bitstream buffer
    BYTE buf[siz];
    AnsiString dict[LZW_size];          // dictionary
    int dicts=0;                        // actual size of dictionary

    // init dictionary
    for (dicts=0;dicts<256;dicts++) dict[dicts]=char(dicts);    // full 8bit binary alphabet
//  for (dicts=0;dicts<4;dicts++) dict[dicts]=char('a'+dicts);  // test alphabet "a,b,c,d"

    l=raw.Length();
    adr=0; bit=0;
    for (i=0;i<l;)
        {
        i&=i;
        // find match in dictionary
        for (j=dicts-1;j>=0;j--)
         if (str_compare(dict[j].c_str(),dict[j].Length(),raw.c_str()+i,l-i))
            {
            i+=dict[j].Length();
            if (i<l)    // add new entry in dictionary (if not end of input)
                {
                // clear dictionary if full
                if (dicts>=LZW_size) dicts=256; // full 8bit binary alphabet
//              if (dicts>=LZW_size) dicts=4;   // test alphabet "a,b,c,d"
                else{
                    dict[dicts]=dict[j]+AnsiString(raw[i+1]); // AnsiString index starts from 1 hence the +1
                    dicts++;
                    }
                }
            a=j; j=-1; break;       // full binary output
//          a='0'+j; j=-1; break;   // test ASCII output
            }
        // store result to bitstream
        if (bitstream_write(buf,siz,adr,bit,LZW_bits,a))
            {
            // append buf to lzw
            k=lzw.Length();
            lzw.SetLength(k+adr);
            for (j=0;j<adr;j++) lzw[j+k+1]=buf[j];
            // reset buf
            adr=0;
            }
        }
    if (bit)
        {
        // store the remainding bits with zeropad
        bitstream_write(buf,siz,adr,bit,LZW_bits-bit,0);
        }
    if (adr)
        {
        // append buf to lzw
        k=lzw.Length();
        lzw.SetLength(k+adr);
        for (j=0;j<adr;j++) lzw[j+k+1]=buf[j];
        }
    return lzw;
    }
//---------------------------------------------------------------------------
AnsiString LZW_decode(AnsiString lzw)
    {
    AnsiString raw="";
    int adr,bit,siz,ix;
    DWORD a;
    AnsiString dict[LZW_size];          // dictionary
    int dicts=0;                        // actual size of dictionary

    // init dictionary
    for (dicts=0;dicts<256;dicts++) dict[dicts]=char(dicts);    // full 8bit binary alphabet
//  for (dicts=0;dicts<4;dicts++) dict[dicts]=char('a'+dicts);  // test alphabet "a,b,c,d"

    siz=lzw.Length();
    adr=0; bit=0; ix=-1;
    for (adr=0;(adr<siz)||(bit>=LZW_bits);)
        {
        a=bitstream_read(lzw.c_str(),siz,adr,bit,LZW_bits);
//      a-='0';                         // test ASCII input
        // clear dictionary if full
        if (dicts>=LZW_size){ dicts=4; ix=-1; }
        // new dictionary entry
        if (ix>=0)
            {
            if (a>=dicts){ dict[dicts]=dict[ix]+AnsiString(dict[ix][1]); dicts++; }
            else         { dict[dicts]=dict[ix]+AnsiString(dict[a ][1]); dicts++; }
            } ix=a;
        // update decoded output
        raw+=dict[a];
        }
    return raw;
    }
//---------------------------------------------------------------------------
```

<p>and output using <code>// test ASCII input</code> lines:</p>

```txt="abacdacacadaad"
enc="0102369803"
dec="abacdacacadaad"
```

<p>where <code>AnsiString</code> is the only VCL stuff I used and its just self allocating string variable beware its indexes starts at <code>1</code>.</p>

```AnsiString s;
s[5]              // character access (1 is first character)
s.Length()        // returns size
s.c_str()         // returns char*
s.SetLength(size) // resize
```

<p>So just use any string you got ...</p>

<p>In case you do not have <code>BYTE,DWORD</code> use <code>unsigned char</code> and <code>unsigned int</code> instead ...</p>

<p>Looks like its working for long texts too (bigger than dictionary and or bitstream buffer sizes). However beware that the clearing might be done in few different places of code but must be synchronized in both encoder/decoder otherwise after clearing the data would corrupt.</p>

<p>The example can use either just <code>"a,b,c,d"</code> alphabet or full 8it one. Currently is set for 8bit. If you want to change it just un-rem the <code>// test ASCII input</code> lines and rem out the <code>// full 8bit binary alphabet</code> lines in the code. </p>

<p>To test crossing buffers and boundary you can play with: </p>

```const int LZW_bits=12;              // encoded bitstream size
const int LZW_size=1<<LZW_bits;     // dictinary size
```

<p>and also with:</p>

```const int siz=32;                   // bitstream buffer
```

<p>constants... The also affect performance so tweak to your liking.
Beware the <code>bitstream_write</code> is not optimized and can be speed up considerably ...</p>

<p>Also in order to debug 4bit aligned coding I am using hex print of encoded data (hex string is twice as long as its ASCII version) like this (ignore the VCL stuff):</p>

```AnsiString txt="abacdacacadaadddddddaaaaaaaabcccddaaaaaaaaa",enc,dec,hex;
enc=LZW_encode(txt);
dec=LZW_decode(enc);

// convert to hex
hex=""; for (int i=1,l=enc.Length();i<=l;i++) hex+=AnsiString().sprintf("%02X",enc[i]);

mm_log->Lines->Add("\""+txt+"\"");
mm_log->Lines->Add("\""+hex+"\"");
mm_log->Lines->Add("\""+dec+"\"");
mm_log->Lines->Add(AnsiString().sprintf("ratio: %i%",(100*enc.Length()/dec.Length())));
```

<p>and result:</p>

```"abacdacacadaadddddddaaaaaaaabcccddaaaaaaaaa"
"06106206106306410210510406106410FFFFFF910A10706110FFFFFFD10E06206311110910FFFFFFE11410FFFFFFD0"
"abacdacacadaadddddddaaaaaaaabcccddaaaaaaaaa"
ratio: 81%
```

Title: LZW Decompression

Body:
I am implementing a LZW algorithm in C++.

The size of the dictionary is a user input, but the minimum is 256, so it should work with binary files. If it reaches the end of the dictionary it goes around to the index 0 and works up overwriting it from there.

For example, if i put in a alice in wonderland script and compress it with a dictionary size 512 i get this dictionary.

But i have a problem with decompression and the output dictionary from decompressing the compressed file looks like this.

And my code for decompressing looks like this

struct dictionary
{
    vector<unsigned char> entry;
    vector<bool> bits;
};

void decompress(dictionary dict[], vector<bool> file, int dictionarySize, int numberOfBits)
{
    //in this example
    //dictionarySize = 512, tells the max size of the dictionary, and goes back to 0 if it reaches 513
    //numberOfBits = log2(512) = 9
    //dictionary dict[] contains bits and strings (strings can be empty)
    // dict[0] =
    //            entry = (unsigned char)0
    //            bits = (if numberOfBits = 9) 000000001
    // dict[255] =
    //            entry = (unsigned char)255
    //            bits = (if numberOfBits = 9) 011111111
    // so the next entry will be dict[next] (next is currently 256)
    // dict[256] =
    //            entry = what gets added in the code below
    //            bits = 100000000
    // all the bits are already set previously (dictionary size is int dictionarySize) so in this case all the bits from 0 to 511 are already set, entries are set from 0 to 255, so extended ASCII

    vector<bool> currentCode;
    vector<unsigned char> currentString;
    vector<unsigned char> temp;

    int next=256;
    bool found=false;

    for(int i=0;i<file.size();i+=numberOfBits)
    {
        for(int j=0;j<numberOfBits;j++)
        {
            currentCode.push_back(file[i+j]);
        }

        for(int j=0;j<dictionarySize;j++)
        {
            // when the currentCode (size numberOfBits) gets found in the dictionary
            if(currentCode==dict[j].bits)
            {
                currentString = dict[j].entry;

                // if the current string isnt empty, then it means it found the characted in the dictionary
                if(!currentString.empty())
                {
                    found = true;
                }
            }
        }

        //if the currentCode in the dictionary has a string value attached to it
        if(found)
        {
            for(int j=0;j<currentString.size();j++)
            {
                cout<<currentString[j];
            }

            temp.push_back(currentString[0]);

            // so it doesnt just push 1 character into the dictionary
            // example, if first read character is 'r', it is already in the dictionary so it doesnt get added
            if(temp.size()>1)
            {
                // if next is more than 511, writing to that index would cause an error, so it resets back to 0 and goes back up
                if(next>dictionarySize-1) //next > 512-1
                {
                    next = 0;
                }
                dict[next].entry.clear();
                dict[next].entry = temp;
                next++;
            }

            //temp = currentString;
        }
        else
        {
            currentString = temp;
            currentString.push_back(temp[0]);

            for(int j=0;j<currentString.size();j++)
            {
                cout<<currentString[j];
            }

            // if next is more than 511, writing to that index would cause an error, so it resets back to 0 and goes back up
            if(next>dictionarySize-1)
            {
                next = 0;
            }
            dict[next].entry.clear();
            dict[next].entry = currentString;
            next++;

            //break;
        }

        temp = currentString;

        // currentCode gets cleared, and written into in the next iteration
        currentCode.clear();

        //cout<<endl;
        found = false;
    }
}

Im am currently stuck and dont know what to fix here to fix the output.
I have also noticed, that if i put a dictionary big enough, so it doesnt go around the dictionary (it doesnt reach the end and begin again at 0) it works.

Body:
start small

you are using files that is too much data to debug. Start small with strings. I took this nice example from Wikli:

Input: "abacdacacadaad"

step    input           match   output  new_entry   new_index
                                        a           0
                                        b           1
                                        c           2
                                        d           3
1       abacdacacadaad  a       0       ab          4
2       bacdacacadaad   b       1       ba          5
3       acdacacadaad    a       0       ac          6
4       cdacacadaad     c       2       cd          7
5       dacacadaad      d       3       da          8
6       acacadaad       ac      6       aca         9
7       acadaad         aca     9       acad        10
8       daad            da      8       daa         11
9       ad              a       0       ad          12
10      d               d       3

Output: "0102369803"

So you can debug your code step by step with cross matching both input/output and dictionary contents. Once that is done correctly then you can do the same for decoding:

Input: "0102369803"

step    input   output  new_entry   new_index
                        a           0
                        b           1
                        c           2
                        d           3
1       0       a
2       1       b       ab          4
3       0       a       ba          5
4       2       c       ac          6
5       3       d       cd          7
6       6       ac      da          8
7       9       aca     aca         9
8       8       da      acad        10
9       0       a       daa         11
10      3       d       ad          12

Output: "abacdacacadaad"

Only then move to files and clear dictionary handling.

bitstream

once you succesfully done the LZW on small alphabet you can try to use the full alphabet and bit encoding. You know the LZW stream can be encoded at any bitlength (not just 8/16/32/64 bits) which can greatly affect compression ratios (in respect to used data properties). So I would try to do univeral access to data at variable (or predefined bitlength).

Was a bit curious so I encoded a simple C++/VCL example for the compression:

//---------------------------------------------------------------------------
// LZW
const int LZW_bits=12;              // encoded bitstream size
const int LZW_size=1<<LZW_bits;     // dictinary size
// bitstream R/W
DWORD bitstream_tmp=0;
//---------------------------------------------------------------------------
// return LZW_bits from dat[adr,bit] and increment position (adr,bit)
DWORD bitstream_read(BYTE *dat,int siz,int &adr,int &bit,int bits)
    {
    DWORD a=0,m=(1<<bits)-1;
    // save tmp if enough bits
    if (bit>=bits){ a=(bitstream_tmp>>(bit-bits))&m; bit-=bits; return a; }
    for (;;)
        {
        // insert byte
        bitstream_tmp<<=8;
        bitstream_tmp&=0xFFFFFF00;
        bitstream_tmp|=dat[adr]&255;
        adr++; bit+=8;
        // save tmp if enough bits
        if (bit>=bits){ a=(bitstream_tmp>>(bit-bits))&m; bit-=bits; return a; }
        // end of data
        if (adr>=siz) return 0;
        }
    }
//---------------------------------------------------------------------------
// write LZW_bits from a to dat[adr,bit] and increment position (adr,bit)
// return true if buffer is full
bool bitstream_write(BYTE *dat,int siz,int &adr,int &bit,int bits,DWORD a)
    {
    a<<=32-bits;        // align to MSB
    // save tmp if aligned
    if ((adr<siz)&&(bit==32)){ dat[adr]=(bitstream_tmp>>24)&255; adr++; bit-=8; }
    if ((adr<siz)&&(bit==24)){ dat[adr]=(bitstream_tmp>>16)&255; adr++; bit-=8; }
    if ((adr<siz)&&(bit==16)){ dat[adr]=(bitstream_tmp>> 8)&255; adr++; bit-=8; }
    if ((adr<siz)&&(bit== 8)){ dat[adr]=(bitstream_tmp    )&255; adr++; bit-=8; }
    // process all bits of a
    for (;bits;bits--)
        {
        // insert bit
        bitstream_tmp<<=1;
        bitstream_tmp&=0xFFFFFFFE;
        bitstream_tmp|=(a>>31)&1;
        a<<=1; bit++;
        // save tmp if aligned
        if ((adr<siz)&&(bit==32)){ dat[adr]=(bitstream_tmp>>24)&255; adr++; bit-=8; }
        if ((adr<siz)&&(bit==24)){ dat[adr]=(bitstream_tmp>>16)&255; adr++; bit-=8; }
        if ((adr<siz)&&(bit==16)){ dat[adr]=(bitstream_tmp>> 8)&255; adr++; bit-=8; }
        if ((adr<siz)&&(bit== 8)){ dat[adr]=(bitstream_tmp    )&255; adr++; bit-=8; }
        }
    return (adr>=siz);
    }
//---------------------------------------------------------------------------
bool str_compare(char *s0,int l0,char *s1,int l1)
    {
    if (l1<l0) return false;
    for (;l0;l0--,s0++,s1++)
     if (*s0!=*s1) return false;
    return true;
    }
//---------------------------------------------------------------------------
AnsiString LZW_encode(AnsiString raw)
    {
    AnsiString lzw="";
    int i,j,k,l;
    int adr,bit;
    DWORD a;
    const int siz=32;                   // bitstream buffer
    BYTE buf[siz];
    AnsiString dict[LZW_size];          // dictionary
    int dicts=0;                        // actual size of dictionary

    // init dictionary
    for (dicts=0;dicts<256;dicts++) dict[dicts]=char(dicts);    // full 8bit binary alphabet
//  for (dicts=0;dicts<4;dicts++) dict[dicts]=char('a'+dicts);  // test alphabet "a,b,c,d"

    l=raw.Length();
    adr=0; bit=0;
    for (i=0;i<l;)
        {
        i&=i;
        // find match in dictionary
        for (j=dicts-1;j>=0;j--)
         if (str_compare(dict[j].c_str(),dict[j].Length(),raw.c_str()+i,l-i))
            {
            i+=dict[j].Length();
            if (i<l)    // add new entry in dictionary (if not end of input)
                {
                // clear dictionary if full
                if (dicts>=LZW_size) dicts=256; // full 8bit binary alphabet
//              if (dicts>=LZW_size) dicts=4;   // test alphabet "a,b,c,d"
                else{
                    dict[dicts]=dict[j]+AnsiString(raw[i+1]); // AnsiString index starts from 1 hence the +1
                    dicts++;
                    }
                }
            a=j; j=-1; break;       // full binary output
//          a='0'+j; j=-1; break;   // test ASCII output
            }
        // store result to bitstream
        if (bitstream_write(buf,siz,adr,bit,LZW_bits,a))
            {
            // append buf to lzw
            k=lzw.Length();
            lzw.SetLength(k+adr);
            for (j=0;j<adr;j++) lzw[j+k+1]=buf[j];
            // reset buf
            adr=0;
            }
        }
    if (bit)
        {
        // store the remainding bits with zeropad
        bitstream_write(buf,siz,adr,bit,LZW_bits-bit,0);
        }
    if (adr)
        {
        // append buf to lzw
        k=lzw.Length();
        lzw.SetLength(k+adr);
        for (j=0;j<adr;j++) lzw[j+k+1]=buf[j];
        }
    return lzw;
    }
//---------------------------------------------------------------------------
AnsiString LZW_decode(AnsiString lzw)
    {
    AnsiString raw="";
    int adr,bit,siz,ix;
    DWORD a;
    AnsiString dict[LZW_size];          // dictionary
    int dicts=0;                        // actual size of dictionary

    // init dictionary
    for (dicts=0;dicts<256;dicts++) dict[dicts]=char(dicts);    // full 8bit binary alphabet
//  for (dicts=0;dicts<4;dicts++) dict[dicts]=char('a'+dicts);  // test alphabet "a,b,c,d"

    siz=lzw.Length();
    adr=0; bit=0; ix=-1;
    for (adr=0;(adr<siz)||(bit>=LZW_bits);)
        {
        a=bitstream_read(lzw.c_str(),siz,adr,bit,LZW_bits);
//      a-='0';                         // test ASCII input
        // clear dictionary if full
        if (dicts>=LZW_size){ dicts=4; ix=-1; }
        // new dictionary entry
        if (ix>=0)
            {
            if (a>=dicts){ dict[dicts]=dict[ix]+AnsiString(dict[ix][1]); dicts++; }
            else         { dict[dicts]=dict[ix]+AnsiString(dict[a ][1]); dicts++; }
            } ix=a;
        // update decoded output
        raw+=dict[a];
        }
    return raw;
    }
//---------------------------------------------------------------------------

and output using // test ASCII input lines:

txt="abacdacacadaad"
enc="0102369803"
dec="abacdacacadaad"

where AnsiString is the only VCL stuff I used and its just self allocating string variable beware its indexes starts at 1.

AnsiString s;
s[5]              // character access (1 is first character)
s.Length()        // returns size
s.c_str()         // returns char*
s.SetLength(size) // resize

So just use any string you got ...

In case you do not have BYTE,DWORD use unsigned char and unsigned int instead ...

Looks like its working for long texts too (bigger than dictionary and or bitstream buffer sizes). However beware that the clearing might be done in few different places of code but must be synchronized in both encoder/decoder otherwise after clearing the data would corrupt.

The example can use either just "a,b,c,d" alphabet or full 8it one. Currently is set for 8bit. If you want to change it just un-rem the // test ASCII input lines and rem out the // full 8bit binary alphabet lines in the code.

To test crossing buffers and boundary you can play with:

const int LZW_bits=12;              // encoded bitstream size
const int LZW_size=1<<LZW_bits;     // dictinary size

and also with:

const int siz=32;                   // bitstream buffer

constants... The also affect performance so tweak to your liking.
Beware the bitstream_write is not optimized and can be speed up considerably ...

Also in order to debug 4bit aligned coding I am using hex print of encoded data (hex string is twice as long as its ASCII version) like this (ignore the VCL stuff):

AnsiString txt="abacdacacadaadddddddaaaaaaaabcccddaaaaaaaaa",enc,dec,hex;
enc=LZW_encode(txt);
dec=LZW_decode(enc);

// convert to hex
hex=""; for (int i=1,l=enc.Length();i<=l;i++) hex+=AnsiString().sprintf("%02X",enc[i]);

mm_log->Lines->Add("\""+txt+"\"");
mm_log->Lines->Add("\""+hex+"\"");
mm_log->Lines->Add("\""+dec+"\"");
mm_log->Lines->Add(AnsiString().sprintf("ratio: %i%",(100*enc.Length()/dec.Length())));

and result:

"abacdacacadaadddddddaaaaaaaabcccddaaaaaaaaa"
"06106206106306410210510406106410FFFFFF910A10706110FFFFFFD10E06206311110910FFFFFFE11410FFFFFFD0"
"abacdacacadaadddddddaaaaaaaabcccddaaaaaaaaa"
ratio: 81%


问:
try/except issue in Python
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

```<code>sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)
</code>```

答:
You have to put the check if the entered input is a number after every input statement.

```<code>try:
    sh = input("Enter hours:")
    fh = float(sh)
    sr = input("Enter Rate:")
    fr = float(sr)
except:
    print('Error, please enter numeric input')
</code>```

In your example you are getting both inputs and then check both of them.
And to your question, I personally would prefer to only put the code that probabla produces errors in the try-statement, like you did.

Title: try/except issue in Python

Body:
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

Body:
You have to put the check if the entered input is a number after every input statement.

try:
    sh = input("Enter hours:")
    fh = float(sh)
    sr = input("Enter Rate:")
    fr = float(sr)
except:
    print('Error, please enter numeric input')

In your example you are getting both inputs and then check both of them.
And to your question, I personally would prefer to only put the code that probabla produces errors in the try-statement, like you did.


问:
generate .exe file from .py
I tried to create .exe file from my python code, and it's fine on my computer but .exe file does not work on another computer. The command is:
pyinstaller  --onefile <filename>.py
And part of my code is:

```<code>hex_user = []
int_user = []
for i in range(size_username):
    hex_user.append(hex(ord(username[i])))
    int_user.append(int(format(ord(username[i]), "x"), 16))

while index <= 4:
    if counter+1 >= len(ebx):
        data = "0" + ebx[counter]
    else:
        data = ebx[counter+1]+ebx[counter]
    if int(data, 16) > 9:
        data = format(int("37", 16)+int(data, 16), 'x')
    else:
        data = format(orWith30(data), 'x')
    out += data
    serial += bytes.fromhex(data).decode("ASCII")
    index += 1
    counter += 2

print(serial)

input()
input()
</code>```

I read character and change to hex then do some transition on them and finally, I convert them to ASCII code and don't import any library, but the error is :

'no module named encodings'

答: Import the encodings module using pip on the target computer.</p>

Title: generate .exe file from .py

Body:
I tried to create .exe file from my python code, and it's fine on my computer but .exe file does not work on another computer. The command is:
pyinstaller  --onefile <filename>.py
And part of my code is:

hex_user = []
int_user = []
for i in range(size_username):
    hex_user.append(hex(ord(username[i])))
    int_user.append(int(format(ord(username[i]), "x"), 16))

while index <= 4:
    if counter+1 >= len(ebx):
        data = "0" + ebx[counter]
    else:
        data = ebx[counter+1]+ebx[counter]
    if int(data, 16) > 9:
        data = format(int("37", 16)+int(data, 16), 'x')
    else:
        data = format(orWith30(data), 'x')
    out += data
    serial += bytes.fromhex(data).decode("ASCII")
    index += 1
    counter += 2

print(serial)

input()
input()

I read character and change to hex then do some transition on them and finally, I convert them to ASCII code and don't import any library, but the error is :

'no module named encodings'


问:
Highlight words that do not match the given string
What I'd like to do: when the user finishes typing in some text, I want this text to be tested against another string. If they don't match, I want the symbols that failed the test to be highlighted / colored red. So far I was only able to come up with the following code

let string = "The quick brown fox jumps over the lazy dog";

let input = document.querySelector(".js-textarea");

let receivedValue = "";

let checkValue = function() {
  let regex = new RegExp(string,"g");

  receivedValue = input.value;
  if(!regex.test(receivedValue)) {
    input.classList.add("error");
  };
}

input.addEventListener("change",checkValue);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.error {
  border: 1px solid red;
}</code>```

  <textarea class="js-textarea"></textarea>

```

Just to see whether it is actually being tested, I color the border; but how can I get the symbols/words that don't pass the test?

答:
The textarea element does not provide a way to apply styling to individual words so the easiest way would be to add an error message below the input element. This answer shows how that can be accomplished.

There is the hard way, though.

You can use an HTML element with the contenteditable attribute. This lets users edit the contents of the HTML element. If you give it a border and a use a white background it will look just like a textarea element.

In this example I chose to highlight with green the text that matches the string and everything else with red.

let string = "The quick brown fox jumps over the lazy dog";

let input = document.querySelector("div");

input.addEventListener("focus", () => {
  // Remove styling so as to not distract the user.
  for (let i = 0; i < input.children.length; i++) {
      input.children[i].className = "";
  }
});

input.addEventListener("blur", () => {
  // We will recreate styling tags. This is under the assumption that the
  // element will not have a lot of text.
  let value = input.textContent;
  input.textContent= "";

  let failPoint = -1;

  for (var i = 0; i < string.length && i < value.length; i++) {
      if (value[i].toLowerCase() !== string[i].toLowerCase()) {
          failPoint = i;
          break;
      }
  }

  let good = document.createElement("span");
  good.classList.add("success");
  good.textContent = value.substring(0, failPoint !== -1 ? failPoint : value.length);
  input.append(good);

  if (failPoint !== -1) {
      let bad = document.createElement("span");
      bad.classList.add("error");
      bad.textContent = value.substring(i);
      input.append(bad);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editable {
    border: 1px solid #ccc;
    width: 300px;
    height: 100px;
    overflow: auto;
    background: white;
    color: #020202;
    padding: 2px;
    word-break: break-all;
    font-family: sans-serif;
}

.success {
  color: green;
}

.error {
  color: red;
}</code>```

```

Body:
What I'd like to do: when the user finishes typing in some text, I want this text to be tested against another string. If they don't match, I want the symbols that failed the test to be highlighted / colored red. So far I was only able to come up with the following code

let string = "The quick brown fox jumps over the lazy dog";

let input = document.querySelector(".js-textarea");

let receivedValue = "";

let checkValue = function() {
  let regex = new RegExp(string,"g");

  receivedValue = input.value;
  if(!regex.test(receivedValue)) {
    input.classList.add("error");
  };
}

input.addEventListener("change",checkValue);

.error {
  border: 1px solid red;
}

  <textarea class="js-textarea"></textarea>

Just to see whether it is actually being tested, I color the border; but how can I get the symbols/words that don't pass the test?

Body:
The textarea element does not provide a way to apply styling to individual words so the easiest way would be to add an error message below the input element. This answer shows how that can be accomplished.

There is the hard way, though.

You can use an HTML element with the contenteditable attribute. This lets users edit the contents of the HTML element. If you give it a border and a use a white background it will look just like a textarea element.

In this example I chose to highlight with green the text that matches the string and everything else with red.

let string = "The quick brown fox jumps over the lazy dog";

let input = document.querySelector("div");

input.addEventListener("focus", () => {
  // Remove styling so as to not distract the user.
  for (let i = 0; i < input.children.length; i++) {
      input.children[i].className = "";
  }
});

input.addEventListener("blur", () => {
  // We will recreate styling tags. This is under the assumption that the
  // element will not have a lot of text.
  let value = input.textContent;
  input.textContent= "";

  let failPoint = -1;

  for (var i = 0; i < string.length && i < value.length; i++) {
      if (value[i].toLowerCase() !== string[i].toLowerCase()) {
          failPoint = i;
          break;
      }
  }

  let good = document.createElement("span");
  good.classList.add("success");
  good.textContent = value.substring(0, failPoint !== -1 ? failPoint : value.length);
  input.append(good);

  if (failPoint !== -1) {
      let bad = document.createElement("span");
      bad.classList.add("error");
      bad.textContent = value.substring(i);
      input.append(bad);
  }
});

.editable {
    border: 1px solid #ccc;
    width: 300px;
    height: 100px;
    overflow: auto;
    background: white;
    color: #020202;
    padding: 2px;
    word-break: break-all;
    font-family: sans-serif;
}

.success {
  color: green;
}

.error {
  color: red;
}

<div class="editable" contenteditable spellcheck="false"></div>


问:
function for showing unique cells
VBA function which deletes duplicates and writes with comma

I need a formula (function) which will have two arguments:
1.range (will be selected)
2.separator character between duplicates.
Example I have in a range some codes of products 0001, 0015, 0015, 0015, 0015, 0015, 0015, 0015, 0015, 0020 in different cells. I want to get 0001, 0015, 0020 using formula.

What I have written:

```<code>Function UNIQUE_NUMBER(RangeD As Range, SepCharacter As String)
Dim UNIQUE As String
On Error GoTo msg
For Each cell In RangeD
If Not IsEmpty(cell) Then
    If Cells(cell.Row, cell.Column) = "" Then Resume Next
    r = cell.Row
    C = cell.Column
    a_length = Len(a)
    a = a & SepCharacter & Cells(r, C)

        If WorksheetFunction.Search(Cells(r, C) & SepCharacter, a, a_length + 1) > 1 And Cells(r, C) <> "" Then
        a = WorksheetFunction.Substitute(a, Cells(r, C) & SepCharacter, "", 1)

        End If
End If

Next cell
SepCharacter2 = SepCharacter & SepCharacter
UNIQUE = Mid(a, Len(SepCharacter) + 1, Len(a))
UNIQUE_NUMBER = Replace(Replace(Replace(Replace(Replace(Replace(Replace(UNIQUE, SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, "")
Exit Function
msg:
Resume Next
End Function
</code>```

And it sometimes work correctly (somehow), but sometimes doesn’t
What do you offer?

答:
the problem was solved</p>

```<code>Function UNIQUE_WELDER(RangeD As Range, sepChar As String)

'we will gather all unique values into VAL1
VAL1 = ""
For Each cell In RangeD

'if value is added into VAL1 we will not add again
'and using replace function for deleting spaces
qty = InStr(VAL1, Replace(Replace(Replace(Replace(Replace(Replace(cell, " ", ""), " ", ""), " ", ""), " ", ""), " ", ""), " ", ""))
If qty > 0 Then VAL1 = VAL1 Else VAL1 = Replace(VAL1 & sepChar & cell, sepChar & sepChar, sepChar)
Next cell
'deleting first symbol
VAL2 = Mid(VAL1, Len(sepChar) + 1, 1000)
UNIQUE_WELDER = VAL2
End Function
</code>```

Title: function for showing unique cells

Body:
VBA function which deletes duplicates and writes with comma

I need a formula (function) which will have two arguments:
1.range (will be selected)
2.separator character between duplicates.
Example I have in a range some codes of products 0001, 0015, 0015, 0015, 0015, 0015, 0015, 0015, 0015, 0020 in different cells. I want to get 0001, 0015, 0020 using formula.

What I have written:

Function UNIQUE_NUMBER(RangeD As Range, SepCharacter As String)
Dim UNIQUE As String
On Error GoTo msg
For Each cell In RangeD
If Not IsEmpty(cell) Then
    If Cells(cell.Row, cell.Column) = "" Then Resume Next
    r = cell.Row
    C = cell.Column
    a_length = Len(a)
    a = a & SepCharacter & Cells(r, C)

        If WorksheetFunction.Search(Cells(r, C) & SepCharacter, a, a_length + 1) > 1 And Cells(r, C) <> "" Then
        a = WorksheetFunction.Substitute(a, Cells(r, C) & SepCharacter, "", 1)

        End If
End If

Next cell
SepCharacter2 = SepCharacter & SepCharacter
UNIQUE = Mid(a, Len(SepCharacter) + 1, Len(a))
UNIQUE_NUMBER = Replace(Replace(Replace(Replace(Replace(Replace(Replace(UNIQUE, SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, "")
Exit Function
msg:
Resume Next
End Function

And it sometimes work correctly (somehow), but sometimes doesn’t
What do you offer?

Body:
the problem was solved

Function UNIQUE_WELDER(RangeD As Range, sepChar As String)

'we will gather all unique values into VAL1
VAL1 = ""
For Each cell In RangeD

'if value is added into VAL1 we will not add again
'and using replace function for deleting spaces
qty = InStr(VAL1, Replace(Replace(Replace(Replace(Replace(Replace(cell, " ", ""), " ", ""), " ", ""), " ", ""), " ", ""), " ", ""))
If qty > 0 Then VAL1 = VAL1 Else VAL1 = Replace(VAL1 & sepChar & cell, sepChar & sepChar, sepChar)
Next cell
'deleting first symbol
VAL2 = Mid(VAL1, Len(sepChar) + 1, 1000)
UNIQUE_WELDER = VAL2
End Function


问:
How to analyze crawl results
I crawled and saved the user's website usage lists.
I want to analyze the results of the crawl, but I wonder how there is a way.
First of all, what I thought was Word Cloud.
I am looking for a way to track user's personal preferences with user's computer history.

I want a way to visualize personal tendencies, etc. at a glance. Or I'm looking for a way to find out if there's no risk of suicide or addiction as a result of the search.
thank you.

答: If you want to visualize data and make analysis on it matplotlib would be good start , again it depends a lot on your data. Matplotlib and seaborn are plotting libraries that are good for representing quantitative data and get some basic analysis at least.</p>

Title: How to analyze crawl results


问:
Flutter calling a method inside the build method
I have a screen with two widgets, one has a button the other one has a bottom sheet function.
I want to invoke the bottom sheet function from the other widget the problem is that my bottom sheet function needs context which makes it must be invoked inside the build function. I can invoke any function using a voidcallback on widget 1 which has the button and a constructor method on widget 2 but I need context to invoke this function. How is it possible to achieve that?

答: just make your method accept a BuildContext context as parameter, then when you call it you can pass the context of the widget that makes the call.


问:
Interface declaration location in IDL files
I'm working on a project that's upgrading a (very) old (and considerably large) program written extensively with COM / MFC to using WPF / managed .NET components, and part of it is trying to port over old COM interfaces declared in IDLs to managed C# interfaces.  What's the difference between interfaces declared inside and outside 'library' blocks ?

答: There isn't one.  Declaring an interface inside library {} just ensures it is present in the type library even if it isn't referenced by any coclasses.  Nothing that matters to your C# declarations.


问:
How to sort a dataframe columns by the median of all its columns
How can I sort this datfarame by the median of its columns?

```<code>A    B    C

1    2    3
4    5    6
7    8    9
10   11   12
</code>```

So, the output would be

```<code>C    B    A
3    2    1
6    5    4
9    8    7
12   11   10

</code>```

I know, with this example, is easy to sort the dataframe by reverting the order of the columns, but, I would like to know how to sort the columns of this dataframe by the median of all of them.

Thanks!

答:
Here is another base R solution</p>

```<code>> df[names(sort(-sapply(df,median)))]
   C  B  A
1  3  2  1
2  6  5  4
3  9  8  7
4 12 11 10
</code>```

Body:
How can I sort this datfarame by the median of its columns?

A    B    C

1    2    3
4    5    6
7    8    9
10   11   12

So, the output would be

C    B    A
3    2    1
6    5    4
9    8    7
12   11   10

I know, with this example, is easy to sort the dataframe by reverting the order of the columns, but, I would like to know how to sort the columns of this dataframe by the median of all of them.

Thanks!

Body:
Here is another base R solution

> df[names(sort(-sapply(df,median)))]
   C  B  A
1  3  2  1
2  6  5  4
3  9  8  7
4 12 11 10


问:
using tidygraph to merge two edges from the same two nodes into one
I'm struggling to figure out how to collapse 2 edges between the same 2 nodes into 1 and then calculate the sum of these edges.

I believe there's a way of doing it in igraph:

simplify(gcon, edge.attr.comb = list(weight = "sum", function(x)length(x)))

but I'd like to do it with tidygraph if possible as I've had success in implementing up to this point with tidygraph and I'm much more familiar with the tidyverse way of working.

My data looks like this:

```<code>  from to Strength Dataframe Question                Topic
1    0 32        4    weekly        1 Connection Frequency
2    0 19        5    weekly        1 Connection Frequency
3    0  8        3    weekly        1 Connection Frequency
4    0  6        5    weekly        1 Connection Frequency
5    0  2        4    weekly        1 Connection Frequency
6    0 14        5    weekly        1 Connection Frequency
</code>```

With both 'from' and 'to' containing the same id's (e.g. from-to; 0-1 & 1-0). I'd like to condense so that only one iteration of the 0-1 relationship exists, with a summed Strength calculated.

Here's my code thus far:

```<code>graph <- data %>%
  filter(Dataframe == "weekly" & Question == 1) %>%
  as_tbl_graph(directed = FALSE) %>%
  activate(edges) %>% # first manipulate edges
  filter(!edge_is_loop()) %>% # remove any loops
  activate(nodes) %>% # now manipulate nodes
  left_join(node.group, by = "name") %>%
  mutate(
    Popularity = centrality_degree(mode = 'in'),
    Centre = node_is_center(),
    Keyplayer = node_is_keyplayer(k = 5))
</code>```

Is it possible to merge the two corresponding edges into a single edge? I've searched the forum but have only come across references where the same nodes are repeated in the same columns (i.e. 0-1's across multiple rows).

答:
```<code>library(tidygraph) # v1.2.0
library(dplyr) # v0.8.5
library(purrr) # v0.3.4

dat <- data.frame(
  from = c("a", "a", "b", "c"),
  to = c("b", "b", "a", "b"),
  n = 1:4
)
</code>```

Call to_simple() within convert() to collapse parallel edges. The corresponding edges and weights are stored in .orig_data as a list of tibbles. Then, extract the sum of the weight of collapsed edges from .orig_data.

```<code>dat %>%
  as_tbl_graph() %>%
  convert(to_simple) %>%
  activate(edges) %>%
  mutate(n_sum = map_dbl(.orig_data, ~ sum(.x$n)))

# A tbl_graph: 3 nodes and 3 edges
#
# A directed simple graph with 1 component
#
# Edge Data: 3 x 5 (active)
   from    to .tidygraph_edge_index .orig_data       n_sum
  <int> <int> <list>                <list>           <dbl>
1     1     2 <int [2]>             <tibble [2 x 3]>     3
2     2     1 <int [1]>             <tibble [1 x 3]>     3
3     3     2 <int [1]>             <tibble [1 x 3]>     4
#
# Node Data: 3 x 2
  name  .tidygraph_node_index
  <chr>                 <int>
1 a                         1
2 b                         2
3 c                         3
</code>```

Body:
I'm struggling to figure out how to collapse 2 edges between the same 2 nodes into 1 and then calculate the sum of these edges.

I believe there's a way of doing it in igraph:

simplify(gcon, edge.attr.comb = list(weight = "sum", function(x)length(x)))

but I'd like to do it with tidygraph if possible as I've had success in implementing up to this point with tidygraph and I'm much more familiar with the tidyverse way of working.

My data looks like this:

  from to Strength Dataframe Question                Topic
1    0 32        4    weekly        1 Connection Frequency
2    0 19        5    weekly        1 Connection Frequency
3    0  8        3    weekly        1 Connection Frequency
4    0  6        5    weekly        1 Connection Frequency
5    0  2        4    weekly        1 Connection Frequency
6    0 14        5    weekly        1 Connection Frequency

With both 'from' and 'to' containing the same id's (e.g. from-to; 0-1 & 1-0). I'd like to condense so that only one iteration of the 0-1 relationship exists, with a summed Strength calculated.

Here's my code thus far:

graph <- data %>%
  filter(Dataframe == "weekly" & Question == 1) %>%
  as_tbl_graph(directed = FALSE) %>%
  activate(edges) %>% # first manipulate edges
  filter(!edge_is_loop()) %>% # remove any loops
  activate(nodes) %>% # now manipulate nodes
  left_join(node.group, by = "name") %>%
  mutate(
    Popularity = centrality_degree(mode = 'in'),
    Centre = node_is_center(),
    Keyplayer = node_is_keyplayer(k = 5))

Is it possible to merge the two corresponding edges into a single edge? I've searched the forum but have only come across references where the same nodes are repeated in the same columns (i.e. 0-1's across multiple rows).

Body:
library(tidygraph) # v1.2.0
library(dplyr) # v0.8.5
library(purrr) # v0.3.4

dat <- data.frame(
  from = c("a", "a", "b", "c"),
  to = c("b", "b", "a", "b"),
  n = 1:4
)

Call to_simple() within convert() to collapse parallel edges. The corresponding edges and weights are stored in .orig_data as a list of tibbles. Then, extract the sum of the weight of collapsed edges from .orig_data.

dat %>%
  as_tbl_graph() %>%
  convert(to_simple) %>%
  activate(edges) %>%
  mutate(n_sum = map_dbl(.orig_data, ~ sum(.x$n)))

# A tbl_graph: 3 nodes and 3 edges
#
# A directed simple graph with 1 component
#
# Edge Data: 3 x 5 (active)
   from    to .tidygraph_edge_index .orig_data       n_sum
  <int> <int> <list>                <list>           <dbl>
1     1     2 <int [2]>             <tibble [2 x 3]>     3
2     2     1 <int [1]>             <tibble [1 x 3]>     3
3     3     2 <int [1]>             <tibble [1 x 3]>     4
#
# Node Data: 3 x 2
  name  .tidygraph_node_index
  <chr>                 <int>
1 a                         1
2 b                         2
3 c                         3


问:
Easy Twitter API PHP Question
This should be fairly easy, but I think I am being a bit stupid ....

I want to get the full_name from twitter:places - can anyone help me please?

To get the other elements I use $entry->title for example, but $entry->twitter:places->full_name doesnt work.

```<code><?xml version="1.0" encoding="UTF-8"?>
<feed xmlns:google="http://base.google.com/ns/1.0" xml:lang="en-US" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns="http://www.w3.org/2005/Atom" xmlns:twitter="http://api.twitter.com/">
  <id></id>
  <link type="text/html" href="http://search.twitter.com/search?q=" rel="alternate"/>
  <link type="application/atom+xml" href="http://search.twitter.com/search.atom?q=" rel="self"/>
  <title>Twitter Search</title>
  <link type="application/opensearchdescription+xml" href="http://search.twitter.com/opensearch.xml" rel="search"/>
  <link type="application/atom+xml" href="http://search.twitter.com/search.atom?&since_id=" rel="refresh"/>
  <updated>2011-06-01T18:32:50Z</updated>
  <openSearch:itemsPerPage>15</openSearch:itemsPerPage>
  <entry>
    <id></id>
    <published>2011-06-01T18:32:50Z</published>
    <link type="text/html" href="" rel="alternate"/>
    <title></title>
    <content type="html"></content>
    <updated>2011-06-01T18:32:50Z</updated>
    <link type="image/png" href="" rel="image"/>
    <twitter:geo>
    </twitter:geo>
    <twitter:metadata>
      <twitter:result_type>recent</twitter:result_type>
    </twitter:metadata>
    <twitter:place>
      <twitter:id></twitter:id>
      <twitter:full_name>London</twitter:full_name>
      <twitter:type>city</twitter:type>
    </twitter:place>
    <twitter:source></twitter:source>
    <twitter:lang>en</twitter:lang>
    <author>
      <name></name>
      <uri></uri>
    </author>
  </entry>
</feed>
</code>```

Can anyone help please!?

答:
To deal with the prefixed elements (which indicate a non-default namespace), you can filter by namespace:

```<code>$name = $xml->entry->children('http://api.twitter.com/')->place->full_name
</code>```

or by bound prefix:

```<code>$name = $xml->entry->children('twitter', true)->place->full_name
</code>```

Your other option would be to use XPath:

```<code>$xml->registerXPathNamespace('t', 'http://api.twitter.com/');
$names = $xml->xpath('//t:full_name');
$name = $names[0];
</code>```

If you want to use an exact XPath, it gets more complicated, since there are different namespaces in your path:

```<code>// Set up our own prefix for default namespace (we could also just use the Atom prefix explicitly as we do below with Twitter)
$namespaces = $xml->getDocNamespaces();
$xml->registerXPathNamespace('atom', $namespaces['']);
// Set up our own Twitter prefix
$xml->registerXPathNamespace('t', 'http://api.twitter.com/');
$names = $xml->xpath('/atom:feed/atom:entry/t:place/t:full_name');
$name = $names[0];
</code>```

XML namespace prefixes are generally arbitrary--the important thing is the namespace (as indicated by our ability to bind whatever prefix we want in our code above).

Title: Easy Twitter API PHP Question

Body:
This should be fairly easy, but I think I am being a bit stupid ....

I want to get the full_name from twitter:places - can anyone help me please?

To get the other elements I use $entry->title for example, but $entry->twitter:places->full_name doesnt work.

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns:google="http://base.google.com/ns/1.0" xml:lang="en-US" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns="http://www.w3.org/2005/Atom" xmlns:twitter="http://api.twitter.com/">
  <id></id>
  <link type="text/html" href="http://search.twitter.com/search?q=" rel="alternate"/>
  <link type="application/atom+xml" href="http://search.twitter.com/search.atom?q=" rel="self"/>
  <title>Twitter Search</title>
  <link type="application/opensearchdescription+xml" href="http://search.twitter.com/opensearch.xml" rel="search"/>
  <link type="application/atom+xml" href="http://search.twitter.com/search.atom?&since_id=" rel="refresh"/>
  <updated>2011-06-01T18:32:50Z</updated>
  <openSearch:itemsPerPage>15</openSearch:itemsPerPage>
  <entry>
    <id></id>
    <published>2011-06-01T18:32:50Z</published>
    <link type="text/html" href="" rel="alternate"/>
    <title></title>
    <content type="html"></content>
    <updated>2011-06-01T18:32:50Z</updated>
    <link type="image/png" href="" rel="image"/>
    <twitter:geo>
    </twitter:geo>
    <twitter:metadata>
      <twitter:result_type>recent</twitter:result_type>
    </twitter:metadata>
    <twitter:place>
      <twitter:id></twitter:id>
      <twitter:full_name>London</twitter:full_name>
      <twitter:type>city</twitter:type>
    </twitter:place>
    <twitter:source></twitter:source>
    <twitter:lang>en</twitter:lang>
    <author>
      <name></name>
      <uri></uri>
    </author>
  </entry>
</feed>

Can anyone help please!?

Body:
To deal with the prefixed elements (which indicate a non-default namespace), you can filter by namespace:

$name = $xml->entry->children('http://api.twitter.com/')->place->full_name

or by bound prefix:

$name = $xml->entry->children('twitter', true)->place->full_name

Your other option would be to use XPath:

$xml->registerXPathNamespace('t', 'http://api.twitter.com/');
$names = $xml->xpath('//t:full_name');
$name = $names[0];

If you want to use an exact XPath, it gets more complicated, since there are different namespaces in your path:

// Set up our own prefix for default namespace (we could also just use the Atom prefix explicitly as we do below with Twitter)
$namespaces = $xml->getDocNamespaces();
$xml->registerXPathNamespace('atom', $namespaces['']);
// Set up our own Twitter prefix
$xml->registerXPathNamespace('t', 'http://api.twitter.com/');
$names = $xml->xpath('/atom:feed/atom:entry/t:place/t:full_name');
$name = $names[0];

XML namespace prefixes are generally arbitrary--the important thing is the namespace (as indicated by our ability to bind whatever prefix we want in our code above).


问:
R combining duplicate rows in a time series with different column types in a datatable
This question is building up on another question R combining duplicate rows by ID with different column types in a dataframe. I have a datatable with a column time and some other columns of different types (factors and numerics). Here is an example:

```<code>dt <- data.table(time  = c(1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4),
             abst  = c(0, NA, 2, NA, NA, NA, 0, 0, NA, 2, NA, 3, 4),
             farbe = as.factor(c("keine", NA, "keine", NA, NA, NA, "keine", "keine", NA, NA, NA, "rot", "blau")),
             gier  = c(0, NA, 5, NA, NA, NA, 0, 0, NA, 1, NA, 6, 2),
             goff  = as.factor(c("haus", "maus", "toll", NA, "haus", NA, "maus", NA, NA, NA, NA, NA, "maus")),
             huft  = as.factor(c(NA, NA, NA, NA, NA, "wolle", NA, NA, "wolle", NA, NA, "holz", NA)),
             mode  = c(4, 2, NA, NA, 6, 5, 0, NA, NA, NA, NA, NA, 3))
</code>```

Now I want to combine the duplicate times in column time. The numeric columns are defined as the mean value of all identical IDs (without the NAs!). The factor columns are combined into one. The NAs can be omitted.

```<code>dtRes <- data.table(time  = c(1, 1, 1, 2, 3, 4, 4),
                abst  = c(1, 1, 1, 0, 0, 3, 3),
                farbe = as.factor(c("keine", "keine", "keine", "keine", "keine", "rot", "blau")),
                gier  = c(2.5, 2.5, 2.5, 0, 0, 3, 3),
                goff  = as.factor(c("haus", "maus", "toll", "maus", NA, "maus", "maus")),
                huft  = as.factor(c(NA, NA, NA, "wolle", "wolle", "holz", "holz")),
                mode  = c(4, 4, 4, 2.5, NA, 3, 3))
</code>```

I need some fast calculation for this, because I have about a million observations.

Some extra thoughts to this problem: farbe may not be unique. In this case I think the best idea for my data is to have a duplicate row but only with a different farbe, so there are 2 identical times and all the rest stays the same but different values for farbe. This should be just very rare case, but would be a great addition.

Also: I have a lot more numeric and factor columns in my real data so I don't want to define every single column separately. In some data tables there are no factor columns. So the solution has to work even if there are no numeric (time is always there and numeric) or factor columns.

Thx in advance!

答:
The expected result (for the given sample dataset) can also be achieved without a subsequent call to separate_rows() or cSplit():

```<code>library(data.table) # version 1.12.9
dt[, lapply(.SD, function(x) if (is.numeric(x)) mean(x, na.rm = TRUE)
            else unlist(na.omit(unique(x)))), by = time]

   time abst farbe gier goff  huft mode
1:    1    1 keine  2.5 haus  <NA>  4.0
2:    1    1 keine  2.5 maus  <NA>  4.0
3:    1    1 keine  2.5 toll  <NA>  4.0
4:    2    0 keine  0.0 maus wolle  2.5
5:    3    0 keine  0.0 <NA> wolle  NaN
6:    4    3   rot  3.0 maus  holz  3.0
7:    4    3  blau  3.0 maus  holz  3.0
</code>```

Please, note that this approach will work for an arbitrary mix of numeric and factor columns; no column names need to be stated explicitly.

However, I do believe the correct answer to the underlying problem is to return one row per time instead of a kind of partial aggregate (your mileage may vary, of course):

```<code>dt[, lapply(.SD, function(x) if (is.numeric(x)) mean(x, na.rm = TRUE)
                   else list(na.omit(unique(x)))), by = time]
</code>```

```<code>   time abst    farbe gier           goff  huft mode
1:    1    1    keine  2.5 haus,maus,toll        4.0
2:    2    0    keine  0.0           maus wolle  2.5
3:    3    0    keine  0.0                wolle  NaN
4:    4    3 rot,blau  3.0           maus  holz  3.0
</code>```

Please, note that list() instead of toString() has been used to aggregate the factor columns. This has the benefit to avoid problems in case one of the factor levels includes a comma , by chance. Furthermore, it is easier to identify cases with non-unique factors per time in a large production dataset:

```<code># compute aggregate as before
dtRes <- dt[, lapply(.SD, function(x) if (is.numeric(x)) mean(x, na.rm = TRUE)
                   else list(na.omit(unique(x)))), by = time]
# find cases with non-unique factors per group
# note .SDcols = is.list is available with data.table version 1.12.9
tmp <- dtRes[, which(Reduce(sum, lapply(.SD, function(x) lengths(x) > 1L)) > 0), .SDcols = is.list, by = time]
tmp
</code>```

```<code>   time V1
1:    1  1
2:    4  1
</code>```

```<code># show affected rows
dtRes[tmp, on = "time"]
</code>```

```<code>   time abst    farbe gier           goff huft mode V1
1:    1    1    keine  2.5 haus,maus,toll         4  1
2:    4    3 rot,blau  3.0           maus holz    3  1
</code>```

```<code># show not affected rows
dtRes[!tmp, on = "time"]
</code>```

```<code>   time abst farbe gier goff  huft mode
1:    2    0 keine    0 maus wolle  2.5
2:    3    0 keine    0      wolle  NaN
</code>```

Body:
This question is building up on another question R combining duplicate rows by ID with different column types in a dataframe. I have a datatable with a column time and some other columns of different types (factors and numerics). Here is an example:

dt <- data.table(time  = c(1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4),
             abst  = c(0, NA, 2, NA, NA, NA, 0, 0, NA, 2, NA, 3, 4),
             farbe = as.factor(c("keine", NA, "keine", NA, NA, NA, "keine", "keine", NA, NA, NA, "rot", "blau")),
             gier  = c(0, NA, 5, NA, NA, NA, 0, 0, NA, 1, NA, 6, 2),
             goff  = as.factor(c("haus", "maus", "toll", NA, "haus", NA, "maus", NA, NA, NA, NA, NA, "maus")),
             huft  = as.factor(c(NA, NA, NA, NA, NA, "wolle", NA, NA, "wolle", NA, NA, "holz", NA)),
             mode  = c(4, 2, NA, NA, 6, 5, 0, NA, NA, NA, NA, NA, 3))

Now I want to combine the duplicate times in column time. The numeric columns are defined as the mean value of all identical IDs (without the NAs!). The factor columns are combined into one. The NAs can be omitted.

dtRes <- data.table(time  = c(1, 1, 1, 2, 3, 4, 4),
                abst  = c(1, 1, 1, 0, 0, 3, 3),
                farbe = as.factor(c("keine", "keine", "keine", "keine", "keine", "rot", "blau")),
                gier  = c(2.5, 2.5, 2.5, 0, 0, 3, 3),
                goff  = as.factor(c("haus", "maus", "toll", "maus", NA, "maus", "maus")),
                huft  = as.factor(c(NA, NA, NA, "wolle", "wolle", "holz", "holz")),
                mode  = c(4, 4, 4, 2.5, NA, 3, 3))

I need some fast calculation for this, because I have about a million observations.

Some extra thoughts to this problem: farbe may not be unique. In this case I think the best idea for my data is to have a duplicate row but only with a different farbe, so there are 2 identical times and all the rest stays the same but different values for farbe. This should be just very rare case, but would be a great addition.

Also: I have a lot more numeric and factor columns in my real data so I don't want to define every single column separately. In some data tables there are no factor columns. So the solution has to work even if there are no numeric (time is always there and numeric) or factor columns.

Thx in advance!

Body:
The expected result (for the given sample dataset) can also be achieved without a subsequent call to separate_rows() or cSplit():

library(data.table) # version 1.12.9
dt[, lapply(.SD, function(x) if (is.numeric(x)) mean(x, na.rm = TRUE)
            else unlist(na.omit(unique(x)))), by = time]

   time abst farbe gier goff  huft mode
1:    1    1 keine  2.5 haus  <NA>  4.0
2:    1    1 keine  2.5 maus  <NA>  4.0
3:    1    1 keine  2.5 toll  <NA>  4.0
4:    2    0 keine  0.0 maus wolle  2.5
5:    3    0 keine  0.0 <NA> wolle  NaN
6:    4    3   rot  3.0 maus  holz  3.0
7:    4    3  blau  3.0 maus  holz  3.0

Please, note that this approach will work for an arbitrary mix of numeric and factor columns; no column names need to be stated explicitly.

However, I do believe the correct answer to the underlying problem is to return one row per time instead of a kind of partial aggregate (your mileage may vary, of course):

dt[, lapply(.SD, function(x) if (is.numeric(x)) mean(x, na.rm = TRUE)
                   else list(na.omit(unique(x)))), by = time]

   time abst    farbe gier           goff  huft mode
1:    1    1    keine  2.5 haus,maus,toll        4.0
2:    2    0    keine  0.0           maus wolle  2.5
3:    3    0    keine  0.0                wolle  NaN
4:    4    3 rot,blau  3.0           maus  holz  3.0

Please, note that list() instead of toString() has been used to aggregate the factor columns. This has the benefit to avoid problems in case one of the factor levels includes a comma , by chance. Furthermore, it is easier to identify cases with non-unique factors per time in a large production dataset:

# compute aggregate as before
dtRes <- dt[, lapply(.SD, function(x) if (is.numeric(x)) mean(x, na.rm = TRUE)
                   else list(na.omit(unique(x)))), by = time]
# find cases with non-unique factors per group
# note .SDcols = is.list is available with data.table version 1.12.9
tmp <- dtRes[, which(Reduce(sum, lapply(.SD, function(x) lengths(x) > 1L)) > 0), .SDcols = is.list, by = time]
tmp

   time V1
1:    1  1
2:    4  1

# show affected rows
dtRes[tmp, on = "time"]

   time abst    farbe gier           goff huft mode V1
1:    1    1    keine  2.5 haus,maus,toll         4  1
2:    4    3 rot,blau  3.0           maus holz    3  1

# show not affected rows
dtRes[!tmp, on = "time"]

   time abst farbe gier goff  huft mode
1:    2    0 keine    0 maus wolle  2.5
2:    3    0 keine    0      wolle  NaN


问:
Javascript carousel works, but not as I would like
Here is the code for my javascript carousel:

var carousel = document.getElementById("carosello");

function myMoveLeft() {
  carousel.scrollTo(-50, 0);
}

function myMoveRight() {
  carousel.scrollTo(+50, 0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="arrowLeft" onclick="myMoveLeft()">
    <i class="fas fa-chevron-left fa-5x"></i>
  </div>
  <div class="caroselloContainer">
    <div id="carosello">
      <div class="caroselloCard">
        <img class="active first" src="..." alt="">
      </div>
      <div class="caroselloCard">
        <img src="..." alt="">
      </div>
      <div class="caroselloCard">
        <img class="last" src="..." alt="">
      </div>
    </div>
  </div>
  <div class="arrowRight" onclick="myMoveRight()">
    <i class="fas fa-chevron-right fa-5x"></i>
  </div>
</div></code>```

This works but only on the first click. How do I make it work at all clicks?

I would like it so that every time I click, scrollTo increases by 50. Something that simulates scrolling would be even better, but the first solution would also suffice.

答:
You can scrollPosition in a variable and then increase/decrease it.

What happens now is no matter how many times you click, your scrollPosition is set to -50 or 50, you have to keep updating that values on clicks.

Like

```<code><script>
  var carousel = document.getElementById("carosello");
  var scrollPosition = 0;
  function myMoveLeft() {
    scrollPosition = scrollPosition - 50;
    carousel.scrollTo(scrollPosition, 0);
  }
  function myMoveRight() {
    scrollPosition = scrollPosition + 50;
    carousel.scrollTo(scrollPosition, 0);
  }
</script>
</code>```

Body:
Here is the code for my javascript carousel:

var carousel = document.getElementById("carosello");

function myMoveLeft() {
  carousel.scrollTo(-50, 0);
}

function myMoveRight() {
  carousel.scrollTo(+50, 0);
}

This works but only on the first click. How do I make it work at all clicks?

I would like it so that every time I click, scrollTo increases by 50. Something that simulates scrolling would be even better, but the first solution would also suffice.

Body:
You can scrollPosition in a variable and then increase/decrease it.

What happens now is no matter how many times you click, your scrollPosition is set to -50 or 50, you have to keep updating that values on clicks.

Like

<script>
  var carousel = document.getElementById("carosello");
  var scrollPosition = 0;
  function myMoveLeft() {
    scrollPosition = scrollPosition - 50;
    carousel.scrollTo(scrollPosition, 0);
  }
  function myMoveRight() {
    scrollPosition = scrollPosition + 50;
    carousel.scrollTo(scrollPosition, 0);
  }
</script>