问:
Recusion - calculating sum of digits in a mixed string. (homework dead end)
I've got into a dead end while trying to fix some lines
in my code.

The task is writing a Recursion function which takes a string and calculating
the sum of the numbers in it.

For example -

```<code>input - "5a-f5-11"
output- The numbers are 5, 5 and 11, therefore the sum is 21.
</code>```

the Catch in this task is to sum numbers that are more than one digit.
(11 in our case)

I have not planned to use Char arrays or anything, but working with strings in some lines made it difficult.

My code doesn't compile so far but i'm sure the logic is in the right spot - (i made a helper function, which means its not the final function but its doing the main work).

```<code>public static int  sumNumbersInText(String str, int i, String subStr, int sum) {

    if(str.length() >= i) return sum;

    char[] array = new char[str.length()];
    str.getChars(0, str.length(), array, 0);

    char oneStr = array[i];
    String newSubStr = subStr;
    if(Character.isDigit(oneStr)); //if the new index is not a number and the index before IS a number>
    {

        if(Character.isDigit(subStr));// new index IS a number, therefore will sum up.
        {
            int num = 0;
            sum+=num;
            newSubStr = "";
        }
    }

    else
    {
        newSubStr += oneStr;
    }

    return sumNumbersInText(str, i+1, subStr, sum);
}
</code>```

答:
This is how I'd approach it:</p>

```<code>public class AddMultipleDigitsInStringRecursive
{
    public static void main(String[] args)
    {
        String input = "5a-f5-11";
        System.out.println("Input: " + input);
        int sum = sumDigits(input);
        System.out.println("Sum: " + sum);
    }

    public static int sumDigits(String input)
    {
        return addDigits(input, 0, "");
    }

    private static int addDigits(String input, int index, String curNumber)
    {
        if(index < input.length())
        {
            int curSum = 0;
            String curChar = input.substring(index, index + 1); // get the current character (as a String)
            if (Character.isDigit(curChar.charAt(0))) // if it's a digit, append it to the current number
            {
                curNumber = curNumber + curChar;
            }
            else // it's not a digit, do we have a number pending?
            {
                if (!curNumber.isEmpty())
                {
                    curSum = Integer.parseInt(curNumber); // convert current number to an Integer
                }
                curNumber = ""; // reset the current number so we can accumulate more digits when they are found
            }
            // return the sum of the current number (if any) with any other numbers that are found
            return curSum + addDigits(input, index + 1, curNumber);
        }
        else // reached the end of the string; was there a number pending?
        {
            int curSum = 0;
            if (!curNumber.isEmpty())
            {
                curSum = Integer.parseInt(curNumber);
            }
            return curSum;
        }
    }
}
</code>```

Body:
I've got into a dead end while trying to fix some lines
in my code.

The task is writing a Recursion function which takes a string and calculating
the sum of the numbers in it.

For example -

input - "5a-f5-11"
output- The numbers are 5, 5 and 11, therefore the sum is 21.

the Catch in this task is to sum numbers that are more than one digit.
(11 in our case)

I have not planned to use Char arrays or anything, but working with strings in some lines made it difficult.

My code doesn't compile so far but i'm sure the logic is in the right spot - (i made a helper function, which means its not the final function but its doing the main work).

public static int  sumNumbersInText(String str, int i, String subStr, int sum) {

    if(str.length() >= i) return sum;

    char[] array = new char[str.length()];
    str.getChars(0, str.length(), array, 0);

    char oneStr = array[i];
    String newSubStr = subStr;
    if(Character.isDigit(oneStr)); //if the new index is not a number and the index before IS a number>
    {

        if(Character.isDigit(subStr));// new index IS a number, therefore will sum up.
        {
            int num = 0;
            sum+=num;
            newSubStr = "";
        }
    }

    else
    {
        newSubStr += oneStr;
    }

    return sumNumbersInText(str, i+1, subStr, sum);
}

Body:
This is how I'd approach it:

public class AddMultipleDigitsInStringRecursive
{
    public static void main(String[] args)
    {
        String input = "5a-f5-11";
        System.out.println("Input: " + input);
        int sum = sumDigits(input);
        System.out.println("Sum: " + sum);
    }

    public static int sumDigits(String input)
    {
        return addDigits(input, 0, "");
    }

    private static int addDigits(String input, int index, String curNumber)
    {
        if(index < input.length())
        {
            int curSum = 0;
            String curChar = input.substring(index, index + 1); // get the current character (as a String)
            if (Character.isDigit(curChar.charAt(0))) // if it's a digit, append it to the current number
            {
                curNumber = curNumber + curChar;
            }
            else // it's not a digit, do we have a number pending?
            {
                if (!curNumber.isEmpty())
                {
                    curSum = Integer.parseInt(curNumber); // convert current number to an Integer
                }
                curNumber = ""; // reset the current number so we can accumulate more digits when they are found
            }
            // return the sum of the current number (if any) with any other numbers that are found
            return curSum + addDigits(input, index + 1, curNumber);
        }
        else // reached the end of the string; was there a number pending?
        {
            int curSum = 0;
            if (!curNumber.isEmpty())
            {
                curSum = Integer.parseInt(curNumber);
            }
            return curSum;
        }
    }
}


来源: stackexchange

问:
How you test your applications for reliability under badly behaving i/o
Almost every application out there performs i/o operations, either with disk or over network.

As my applications work fine under the development-time environment, I want to be sure they will still do when the Internet connection is slow or unstable, or when the user attempts to read data from badly-written CD.

What tools would you recommend to simulate:

slow i/o (opening files, closing files, reading and writing, enumeration of directory items)

occasional i/o errors

occasional 'access denied' responses

packet loss in tcp/ip

etc...

EDIT:

Windows:

The closest solution to do the job as described seems to be holodeck, commercial software (>$900).

Linux:

Open solution wasn't found by now, but the same effect
can be achived as specified by smcameron and krosenvold.

Decorator pattern is a good idea.
It would require to wrap my i/o classes, but resulting in a testing framework.
The only remaining untested code would be in 3rd party libraries.

Yet I decided not to go this way, but leave my code as it is and simulate i/o errors from outside.

I now know that what I need is called 'fault injection'.
I thought it was a common production-line part with plenty of solutions I just didn't know.
(By the way, another similar good idea is 'fuzz testing', thanks to Lennart)

On my mind, the problem is still not worth $900.
I'm going to implement my own open-source tool based on hooks (targeting win32).
I'll update this post when I'm done with it. Come back in 3 or 4 weeks or so...

答: Consider holodeck for some of the fault injection, if you have access to spare hardware you can simulate network impairment using Netem or a commercial product based on it the Mini-Maxwell, which is much more expensive than free but possibly easier to use.</p>

OwnerDisplayName: modosansreves

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: modosansreves

OwnerDisplayName: mmDonuts


问:
How to define an instance of Control.Functor.Constrained?
I'm trying to define an instance of Functor.Constrained, after successfully defining an instance of Category.Constrained. However the type of Functor.Constrained fmap is complex and the attempt I made led to an error that I can't explain. How do you define all the objects required by the fmap type?

```<code>Control.Functor.Constrained
fmap :: (Object r a, Object t (f a), Object r b, Object t (f b)) => r a b -> t (f a) (f b)
</code>```

http://hackage.haskell.org/package/constrained-categories-0.3.1.1

```<code>{-# LANGUAGE GADTs, TypeFamilies, ConstraintKinds #-}

module Question1 where

import Control.Category.Constrained
import Control.Functor.Constrained as FC
import Data.Map as M
import Data.Set as S

data RelationMS a b where
  IdRMS :: RelationMS a a
  RMS :: Map a (Set b) -> RelationMS a b

instance Category RelationMS where
    type Object RelationMS o = Ord o
    id = IdRMS
    (.) = compRMS

compRMS :: (Ord a, Ord k, Ord b) => RelationMS k b -> RelationMS a k -> RelationMS a b
RMS mp2 `compRMS` RMS mp1
  | M.null mp2 || M.null mp1 = RMS M.empty
  | otherwise = RMS $ M.foldrWithKey
        (\k s acc -> M.insert k (S.foldr (\x acc2 -> case M.lookup x mp2 of
                                                    Nothing -> acc2
                                                    Just s2 -> S.union s2 acc2
                                         ) S.empty s
                                ) acc
        ) M.empty mp1

pseudoFmap :: Ord c =>  (b -> c) -> RelationMS a b -> RelationMS a c
pseudoFmap f (RMS r) = RMS $ M.map (S.map f) r

instance FC.Functor RelationMS where
    -- error: ‘Object’ is not a (visible) associated type of class ‘Functor’
    type Object RelationMS o = Ord o
    fmap f (RMS r) = pseudoFmap f (RMS r)
</code>```

----------- TO CHECK THE PROPOSED SOLUTION ---------

```<code>instance (Show a, Show b) => Show (RelationMS a b) where
        show (IdRMS) = "IdRMS"
        show (RMS r) = show r

> FC.fmap (+1) (RMS $ M.fromList [(1,S.fromList [10,20]), (2,S.fromList [30,40])])
> fromList [(1,fromList [11,21]),(2,fromList [31,41])]
</code>```

答:
You probably don't mean to make RelationMS a Functor (it can be made one, but not with constrained-categories). You mean to make RelationMS a a Functor for all a; you want Functor (RelationMS a). Also, Functors exist between two Categorys, so you must define the Categorys that RelationMS a is a Functor between. The source category is ConstrainedCategory (->) Ord, and the output category is (->). However, there's a "default" instance Prelude.Functor f => FC.Functor f (->) (->) instance that stops instance FC.Functor (RelationMS a) (ConstrainedCategory (->) Ord) (->) from working, due to a fundep conflict. Define this newtype

```<code>newtype Fun a b = Fun { runFun :: a -> b }
instance Category Fun where
  id = Fun Prelude.id
  Fun f . Fun g = Fun (f Prelude.. g)
</code>```

That's two of Functor's superclasses satisfied, and the third one is satisfied as Object Fun o = (). So, you get

```<code>instance FC.Functor (RelationMS a) (ConstrainedCategory (->) Ord) Fun where
  fmap = Fun Prelude.. pseudoFmap Prelude.. unconstrained
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to define an instance of Functor.Constrained, after successfully defining an instance of Category.Constrained. However the type of Functor.Constrained fmap is complex and the attempt I made led to an error that I can't explain. How do you define all the objects required by the fmap type?

Control.Functor.Constrained
fmap :: (Object r a, Object t (f a), Object r b, Object t (f b)) => r a b -> t (f a) (f b)

http://hackage.haskell.org/package/constrained-categories-0.3.1.1

{-# LANGUAGE GADTs, TypeFamilies, ConstraintKinds #-}

module Question1 where

import Control.Category.Constrained
import Control.Functor.Constrained as FC
import Data.Map as M
import Data.Set as S

data RelationMS a b where
  IdRMS :: RelationMS a a
  RMS :: Map a (Set b) -> RelationMS a b

instance Category RelationMS where
    type Object RelationMS o = Ord o
    id = IdRMS
    (.) = compRMS

compRMS :: (Ord a, Ord k, Ord b) => RelationMS k b -> RelationMS a k -> RelationMS a b
RMS mp2 `compRMS` RMS mp1
  | M.null mp2 || M.null mp1 = RMS M.empty
  | otherwise = RMS $ M.foldrWithKey
        (\k s acc -> M.insert k (S.foldr (\x acc2 -> case M.lookup x mp2 of
                                                    Nothing -> acc2
                                                    Just s2 -> S.union s2 acc2
                                         ) S.empty s
                                ) acc
        ) M.empty mp1

pseudoFmap :: Ord c =>  (b -> c) -> RelationMS a b -> RelationMS a c
pseudoFmap f (RMS r) = RMS $ M.map (S.map f) r

instance FC.Functor RelationMS where
    -- error: ‘Object’ is not a (visible) associated type of class ‘Functor’
    type Object RelationMS o = Ord o
    fmap f (RMS r) = pseudoFmap f (RMS r)

----------- TO CHECK THE PROPOSED SOLUTION ---------

instance (Show a, Show b) => Show (RelationMS a b) where
        show (IdRMS) = "IdRMS"
        show (RMS r) = show r

> FC.fmap (+1) (RMS $ M.fromList [(1,S.fromList [10,20]), (2,S.fromList [30,40])])
> fromList [(1,fromList [11,21]),(2,fromList [31,41])]

Body:
You probably don't mean to make RelationMS a Functor (it can be made one, but not with constrained-categories). You mean to make RelationMS a a Functor for all a; you want Functor (RelationMS a). Also, Functors exist between two Categorys, so you must define the Categorys that RelationMS a is a Functor between. The source category is ConstrainedCategory (->) Ord, and the output category is (->). However, there's a "default" instance Prelude.Functor f => FC.Functor f (->) (->) instance that stops instance FC.Functor (RelationMS a) (ConstrainedCategory (->) Ord) (->) from working, due to a fundep conflict. Define this newtype

newtype Fun a b = Fun { runFun :: a -> b }
instance Category Fun where
  id = Fun Prelude.id
  Fun f . Fun g = Fun (f Prelude.. g)

That's two of Functor's superclasses satisfied, and the third one is satisfied as Object Fun o = (). So, you get

instance FC.Functor (RelationMS a) (ConstrainedCategory (->) Ord) Fun where
  fmap = Fun Prelude.. pseudoFmap Prelude.. unconstrained


问:
Iterator bounds checking exceeding vector size
My question is different because I am not looking for a range-3v solution. Also, I was specifically asking how to fix the issue with the 2nd for a loop. I accepted the answer below my question already. For I didn't need a second for loop, They showed me how to use a single index by anding it with 1 for odd iterations. This solved my problem!

I am writing a function that will take a vector assuming it is of even length of elements; In my function, I'm creating two temp vectors from the original vector where their elements are {0,2,4,6,...} and {1,3,5,7,...} respectively. Then I am adding the corresponding indexed elements and storing the results into my results vector.

Here is my function:

```<code>void sumElementPairsFromVector(const std::vector<int>& values, std::vector<int>& result)
{
    using It = std::vector<int>::const_iterator;
    std::vector<int> temp1, temp2;

    // First lets divide the original vector into two temp vectors
    for (It it1 = values.cbegin(); it1 != values.cend(); it1 += 2)
        temp1.push_back(*it1);

    for (It it2 = values.cbegin() + 1; it2 != values.cend() ; it2 += 2)
        temp2.push_back(*it2);

    // Add each corresponding vector and store that into our results.
    for (std::size_t i = 0; i < values.size() / 2; i++)
        result[i] = temp1[i] + temp2[i];
}
</code>```

Here is how I'm using it:

```<code>int main()
{
    std::vector<int> values{ 1,2,3,4,5,6 };
    for (auto i : values)
        std::cout << i << " ";
    std::cout << '\n';

    std::vector<int> results;

    sumElementPairsFromVector(values, results);
    for (auto i : results)
        std::cout << i << " ";
    std::cout << '\n';

    return 0;
}
</code>```

The expected output should be:

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

The debug assertion is failing on this line of code from the function:

```<code>for (It it2 = values.cbegin() + 1; it2 != values.cend(); it2 += 2 )
</code>```

I know what is causing the error; on the last iteration after it increments by 2 and goes to check if it2 != values.cend() it is going past the end of the vector. How do I fix this?

答:
Since you're not working with template functions, your function just uses a vector, you don't need iterators in my opinion.

You could just have something like

...
for (int i = 0; i < values.size(); i += 2) {
    result.push_back(values[i] + values[i + 1]);
}
...
```

<p>Well, if you are sure that <code>values.size()</code> is always even.
If that isn't the case, you could do something like </p>

<pre class="lang-cpp prettyprint-override"><code>void sumElementPairsFromVector(const std::vector<int>& values, std::vector<int>& result)
{
    for (int i = 1; i < values.size(); i += 2) {
        result.push_back(values[i] + values[i - 1]);
    }
    if (values.size() % 2) {
        // whatever you want to do with the last element of an uneven vector
        result.push_back(values[values.size() - 1]);
    }
}
</code>```

because if you're not sure if the size of values is always even, the first method will try to access the nth element where n is larger than the amount of elements, so you may get a garbage value.

Body:
My question is different because I am not looking for a range-3v solution. Also, I was specifically asking how to fix the issue with the 2nd for a loop. I accepted the answer below my question already. For I didn't need a second for loop, They showed me how to use a single index by anding it with 1 for odd iterations. This solved my problem!

I am writing a function that will take a vector assuming it is of even length of elements; In my function, I'm creating two temp vectors from the original vector where their elements are {0,2,4,6,...} and {1,3,5,7,...} respectively. Then I am adding the corresponding indexed elements and storing the results into my results vector.

Here is my function:

void sumElementPairsFromVector(const std::vector<int>& values, std::vector<int>& result)
{
    using It = std::vector<int>::const_iterator;
    std::vector<int> temp1, temp2;

    // First lets divide the original vector into two temp vectors
    for (It it1 = values.cbegin(); it1 != values.cend(); it1 += 2)
        temp1.push_back(*it1);

    for (It it2 = values.cbegin() + 1; it2 != values.cend() ; it2 += 2)
        temp2.push_back(*it2);

    // Add each corresponding vector and store that into our results.
    for (std::size_t i = 0; i < values.size() / 2; i++)
        result[i] = temp1[i] + temp2[i];
}

Here is how I'm using it:

int main()
{
    std::vector<int> values{ 1,2,3,4,5,6 };
    for (auto i : values)
        std::cout << i << " ";
    std::cout << '\n';

    std::vector<int> results;

    sumElementPairsFromVector(values, results);
    for (auto i : results)
        std::cout << i << " ";
    std::cout << '\n';

    return 0;
}

The expected output should be:

1 2 3 4 5 6
3 7 11

The debug assertion is failing on this line of code from the function:

for (It it2 = values.cbegin() + 1; it2 != values.cend(); it2 += 2 )

I know what is causing the error; on the last iteration after it increments by 2 and goes to check if it2 != values.cend() it is going past the end of the vector. How do I fix this?

Body:
Since you're not working with template functions, your function just uses a vector, you don't need iterators in my opinion.

You could just have something like

...
for (int i = 0; i < values.size(); i += 2) {
    result.push_back(values[i] + values[i + 1]);
}
...

Well, if you are sure that values.size() is always even.
If that isn't the case, you could do something like

void sumElementPairsFromVector(const std::vector<int>& values, std::vector<int>& result)
{
    for (int i = 1; i < values.size(); i += 2) {
        result.push_back(values[i] + values[i - 1]);
    }
    if (values.size() % 2) {
        // whatever you want to do with the last element of an uneven vector
        result.push_back(values[values.size() - 1]);
    }
}

because if you're not sure if the size of values is always even, the first method will try to access the nth element where n is larger than the amount of elements, so you may get a garbage value.


问:
Cannot read property 'length' of undefined error message in Javascript
I'm trying to solve a code challenge on code wars and don't understand why I'm getting an error message regarding the .length of a string inside of an array when I try to run it.

It's definitely the first .length in line 7.  I've tried running other arr[i].lengths and they work, I'm thinking it's a problem with scope?

function longestConsec(strarr, k) {
  var arr = [];
  if (strarr.length == 0 || k > strarr.length || k <= 0) {
    return "";
  }
  for (var i = 1; i <= strarr.length; i++) {
    if (strarr[i].length > strarr[0].length && arr.length < k) {
      arr.push(strarr[i]);
    }
  }
  arr.join('');
}

longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2);```

Should return "abigailtheta" as it's the 2 longest strings after the
first string which were the requirements.

VM304:7 Uncaught TypeError: Cannot read property 'length' of undefined

答:
The elements in an array go from 0 to length - 1.

You have 6 strings in the array, the last one having the index 5.

Because the condition set that you should iterate while the index is lower or equal to strarr.length it tries to iterate the 6th element, which doesn't exist.

You should change the condition for the iteration:

```<code>for (var i = 1; i < strarr.length; i++) {
</code>```

function longestConsec(strarr, k) {
  var arr = [];
  if (strarr.length == 0 || k > strarr.length || k <= 0) {
    return "";
  }
  for (var i = 1; i < strarr.length; i++) {
    if (strarr[i].length > strarr[0].length && arr.length < k) {
      arr.push(strarr[i]);
    }
  }
  arr.join('');
  alert(arr);
}

longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2);```

Body:
I'm trying to solve a code challenge on code wars and don't understand why I'm getting an error message regarding the .length of a string inside of an array when I try to run it.

It's definitely the first .length in line 7.  I've tried running other arr[i].lengths and they work, I'm thinking it's a problem with scope?

function longestConsec(strarr, k) {
  var arr = [];
  if (strarr.length == 0 || k > strarr.length || k <= 0) {
    return "";
  }
  for (var i = 1; i <= strarr.length; i++) {
    if (strarr[i].length > strarr[0].length && arr.length < k) {
      arr.push(strarr[i]);
    }
  }
  arr.join('');
}

longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2);

Should return "abigailtheta" as it's the 2 longest strings after the
first string which were the requirements.

VM304:7 Uncaught TypeError: Cannot read property 'length' of undefined

Body:
The elements in an array go from 0 to length - 1.

You have 6 strings in the array, the last one having the index 5.

Because the condition set that you should iterate while the index is lower or equal to strarr.length it tries to iterate the 6th element, which doesn't exist.

You should change the condition for the iteration:

for (var i = 1; i < strarr.length; i++) {

function longestConsec(strarr, k) {
  var arr = [];
  if (strarr.length == 0 || k > strarr.length || k <= 0) {
    return "";
  }
  for (var i = 1; i < strarr.length; i++) {
    if (strarr[i].length > strarr[0].length && arr.length < k) {
      arr.push(strarr[i]);
    }
  }
  arr.join('');
  alert(arr);
}

longestConsec(["zone", "abigail", "theta", "form", "libe", "zas"], 2);


问:
PHP Add arrays to another array without key
I need to create the following array:

```<code>$data = array(
   "invoice_info" => array(
       ...
    ),
    "product_info => array(
        array(
           "name" => "product 1",
           ...
        ),
        array(
           "name => "product 2",
            ...
        )
    )
);
</code>```

I am currently struggling to get the products into my "product_info" array. For each product I want to add I use the following line:

```<code>$product_info[] = array("name" => "product 1", ...);
</code>```

This works fine for the first one. Adding another one, however, overwrites it. The second problem is, that keys are added, that should not be there:

```<code>[product_info] => Array
    (
        [0] => Array
            (
                [name] => product 2
                [qty] => 293
                [price] => 44
                [sum] => 12892
            )

    )
</code>```

This is the output after adding 2 products. Just the second one is included. What am I doing wrong?

答:
This will generate you an array of arrays

```<code>$data = array(
    "invoice_info" => array(),
    "product_info" => array(),
    );

$data['product_info'][] = ['name' => 'prod1','qty'=>1, 'price'=> 44, 'sum'=>100];
$data['product_info'][] = ['name' => 'prod2','qty'=>22, 'price'=> 55, 'sum'=>200];

print_r($data);
</code>```

RESULT

```<code>Array
(
    [invoice_info] => Array
        (
        )

    [product_info] => Array
        (
            [0] => Array
                (
                    [name] => prod1
                    [qty] => 1
                    [price] => 44
                    [sum] => 100
                )

            [1] => Array
                (
                    [name] => prod2
                    [qty] => 22
                    [price] => 55
                    [sum] => 200
                )

        )

)
</code>```

Now if you had done something like this

```<code>$product_info =& $data['product_info'];
</code>```

to create your $product_info variable then note that you must use the =& or when you attempt to allocate a new array it will not work as you expect. So, adding that to the previous code would look like this

```<code>$data = array(
    "invoice_info" => array(),
    "product_info" => array(),
    );

$data['product_info'][] = ['name' => 'prod1','qty'=>1, 'price'=> 44, 'sum'=>100];
$data['product_info'][] = ['name' => 'prod2','qty'=>22, 'price'=> 55, 'sum'=>200];

$product_info =& $data['product_info'];

$product_info[] = ['name' => 'prod3','qty'=>99, 'price'=> 155, 'sum'=>300];

print_r($data);
</code>```

Will produce the result

```<code>Array
(
    [invoice_info] => Array
        (
        )
    [product_info] => Array
        (
            [0] => Array
                (
                    [name] => prod1
                    [qty] => 1
                    [price] => 44
                    [sum] => 100
                )
            [1] => Array
                (
                    [name] => prod2
                    [qty] => 22
                    [price] => 55
                    [sum] => 200
                )
            [2] => Array
                (
                    [name] => prod3
                    [qty] => 99
                    [price] => 155
                    [sum] => 300
                )
        )
)
</code>```

Body:
I need to create the following array:

$data = array(
   "invoice_info" => array(
       ...
    ),
    "product_info => array(
        array(
           "name" => "product 1",
           ...
        ),
        array(
           "name => "product 2",
            ...
        )
    )
);

I am currently struggling to get the products into my "product_info" array. For each product I want to add I use the following line:

$product_info[] = array("name" => "product 1", ...);

This works fine for the first one. Adding another one, however, overwrites it. The second problem is, that keys are added, that should not be there:

[product_info] => Array
    (
        [0] => Array
            (
                [name] => product 2
                [qty] => 293
                [price] => 44
                [sum] => 12892
            )

    )

This is the output after adding 2 products. Just the second one is included. What am I doing wrong?

Body:
This will generate you an array of arrays

$data = array(
    "invoice_info" => array(),
    "product_info" => array(),
    );

$data['product_info'][] = ['name' => 'prod1','qty'=>1, 'price'=> 44, 'sum'=>100];
$data['product_info'][] = ['name' => 'prod2','qty'=>22, 'price'=> 55, 'sum'=>200];

print_r($data);

RESULT

Array
(
    [invoice_info] => Array
        (
        )

    [product_info] => Array
        (
            [0] => Array
                (
                    [name] => prod1
                    [qty] => 1
                    [price] => 44
                    [sum] => 100
                )

            [1] => Array
                (
                    [name] => prod2
                    [qty] => 22
                    [price] => 55
                    [sum] => 200
                )

        )

)

Now if you had done something like this

$product_info =& $data['product_info'];

to create your $product_info variable then note that you must use the =& or when you attempt to allocate a new array it will not work as you expect. So, adding that to the previous code would look like this

$data = array(
    "invoice_info" => array(),
    "product_info" => array(),
    );

$data['product_info'][] = ['name' => 'prod1','qty'=>1, 'price'=> 44, 'sum'=>100];
$data['product_info'][] = ['name' => 'prod2','qty'=>22, 'price'=> 55, 'sum'=>200];

$product_info =& $data['product_info'];

$product_info[] = ['name' => 'prod3','qty'=>99, 'price'=> 155, 'sum'=>300];

print_r($data);

Will produce the result

Array
(
    [invoice_info] => Array
        (
        )
    [product_info] => Array
        (
            [0] => Array
                (
                    [name] => prod1
                    [qty] => 1
                    [price] => 44
                    [sum] => 100
                )
            [1] => Array
                (
                    [name] => prod2
                    [qty] => 22
                    [price] => 55
                    [sum] => 200
                )
            [2] => Array
                (
                    [name] => prod3
                    [qty] => 99
                    [price] => 155
                    [sum] => 300
                )
        )
)


问:
Using map to return a new array with a sentence for each object
I am trying to use map to return a new array containing sentences for each object.

I've tried a few things but can not seem to get the logic right for returning the values of each object.

An object as such:

```<code>const person = [
  {
    name: "James",
    nationality: "English",
    age: 26
  },
  {
    name: "Pierre",
    nationality: "French",
    age: "23"
  }
]
</code>```

Should return:

```<code>[
  "My name is James, I am English and I am 26",
  "My name is Pierre, I am French and I am 23"
]

</code>```

答:
```<code>let arr = person.map(x => {
  return `My name is ${x.name}, I am ${x.nationality} and I am ${x.age}`;
})
</code>```

If you'd like them combined, use

```<code>arr.join(', ');
</code>```

Body:
I am trying to use map to return a new array containing sentences for each object.

I've tried a few things but can not seem to get the logic right for returning the values of each object.

An object as such:

const person = [
  {
    name: "James",
    nationality: "English",
    age: 26
  },
  {
    name: "Pierre",
    nationality: "French",
    age: "23"
  }
]

Should return:

[
  "My name is James, I am English and I am 26",
  "My name is Pierre, I am French and I am 23"
]

Body:
let arr = person.map(x => {
  return `My name is ${x.name}, I am ${x.nationality} and I am ${x.age}`;
})

If you'd like them combined, use

arr.join(', ');


问:
How to make queries from multiple models in a single view
I am working on a school placement system and I have multiple models to query from. First I want to loop through the students' list and check if the two student's ID in the profile and result model match. Then I will check if the student has passed and then place the student.

I am using Django 2.2.1. I did a lot of search but to no avail. Below are some of my codes.

Here is my student model.

```<code>class StudentProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # Extra Fields
    student_ID = models.CharField(max_length=10)
    middle_Name = models.CharField(max_length=50, blank=True)
    gender = models.CharField(max_length=10, choices=STUDENT_GENDER_CHOICES)
    disability = models.CharField(max_length=5, choices=STUDENT_DISABILITY_CHOICES)
    locality = models.CharField(max_length=30, choices=STUDENT_LOCALITY_CHOICES)
    age = models.PositiveIntegerField()
    profile_picture = models.ImageField(upload_to='profile_photos', blank=True, default='profile_photos/default.svg')

    def __str__(self):
        return self.user.username
</code>```

This is my result upload model

```<code>class StudentResultsUpload(models.Model):
    student_ID = models.CharField(max_length=10)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)
</code>```

This is my school selection model.

NB: I removed the multiple school models and put everything in one model.

```<code>class SchoolSelection(models.Model):
    student = models.ForeignKey(User, on_delete=models.CASCADE)

    school_One = models.CharField(max_length=100)
    program_One = models.CharField(max_length=50)
    residential_Status_One = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Two = models.CharField(max_length=100)
    program_Two = models.CharField(max_length=50)
    residential_Status_Two = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Three = models.CharField(max_length=100)
    program_Three = models.CharField(max_length=50)
    residential_Status_Three = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Four = models.CharField(max_length=100)
    program_Four = models.CharField(max_length=50)
    residential_Status_Four = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Five = models.CharField(max_length=100)
    program_Five = models.CharField(max_length=50)
    residential_Status_Five = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)
</code>```

And this is my views.py for placement.

```<code>def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    schools = SchoolSelection.objects.all()

    placements = []
    for candidate in profile:
        for pl in place:

            if candidate.student_ID == pl.student_ID:
                if (pl.english >= 50 and pl.mathematics >= 50 and pl.integrated_Science >= 50 and pl.social_Studies >= 50):

                    raw_score = (pl.english + pl.mathematics + pl.integrated_Science + pl.social_Studies + pl.basic_Design_Technology + pl.home_Economics)
                    for school in schools:
                        if raw_score >= 480:
                            place_me = school.school_One
                        elif raw_score >= 420:
                            place_me = school.school_Two
                        elif raw_score >= 360:
                            place_me = school.school_Three
                        elif raw_score >= 300:
                            place_me = school.school_Four
                        else:
                            place_me = school.school_Five

                        placements.append({'student': candidate, 'school': place_me})
                    return render(request, 'schools/placement.html', {'place_me': placements})

                else:
                    return HttpResponse("Sorry, you did not qualify for placement.")
</code>```

Here is my placement.html file

```<code><div class="container">
<p id="success">
    Placement Here.
</p>
{% for placement in place_me %}
    Stdudent ID: {{ placement.student.student_ID }}<br>
    Stdudent username: {{ placement.student.user }}<br>
    Stdudent gender: {{ placement.student.gender }}<br>
    School: {{ placement.school }}<br><br>

{% endfor %}
</div>
</code>```

But when I run it, it is not iterating properly through all the students in the system. It is only retaining multiple instances of one student but it will pick the schools of other students and display for the one student that it is returning its multiple instances.

答:
As Daniel Roseman indicated you should use Foreign Keys to associate different models. A refactoring of your code should be something like the codes below.

The StudentResultsUpload model

```<code>class StudentResultsUpload(models.Model):
    student = models.ForeignKey(StudentProfile, on_delete=models.CASCADE, null=True)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)
</code>```

The SchoolSelectionOne model

```<code>class SchoolSelectionOne(models.Model):
    student = models.ForeignKey(StudentProfile, on_delete=models.CASCADE, null=True)
    name_of_School = models.CharField(max_length=100)
    program = models.CharField(max_length=50)
    residential_Status = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES
</code>```

The placement function

```<code>def placement(request):
    profiles = StudentProfile.objects.all()
    uploads = StudentResultsUpload.objects.all()
    school_one = SchoolSelectionOne.objects.all()
    school_two = SchoolSelectionTwo.objects.all()
    school_three = SchoolSelectionThree.objects.all()
    school_four = SchoolSelectionFour.objects.all()
    school_five = SchoolSelectionFive.objects.all()

    profile_dicts = []
    for profile in profiles:
        try:
            upload = [u for u in uploads if u.student.pk == profile.pk][0]
            one = [s for s in school_one if s.student.pk == profile.pk][0]
            two = [s for s in school_two if s.student.pk == profile.pk][0]
            three = [s for s in school_three if s.student.pk == profile.pk][0]
            four = [s for s in school_four if s.student.pk == profile.pk][0]
            five = [s for s in school_five if s.student.pk == profile.pk][0]
        except (AttributeError, IndexError):
            continue

        profile_dicts.append({
            'upload': upload,
            'school_one': one,
            'school_two': two,
            'school_three': three,
            'school_four': four,
            'school_five': five
        })

    place_me_list = []
    for profile in profile_dicts:
        upload = profile['upload']

        if (
                upload.english >= 50 and
                upload.mathematics >= 50 and
                upload.integrated_Science >= 50 and
                upload.social_Studies >= 50
        ):
            raw_score = (
                upload.english +
                upload.mathematics +
                upload.integrated_Science +
                upload.social_Studies +
                upload.basic_Design_Technology +
                upload.home_Economics
            )

            if raw_score >= 480:
                place_me = profile['school_one']
            elif raw_score >= 420:
                place_me = profile['school_two']
            elif raw_score >= 360:
                place_me = profile['school_three']
            elif raw_score >= 300:
                place_me = profile['school_four']
            else:
                place_me = profile['school_five']

            place_me_list.append(place_me)

    return render(request, 'schools/placements.html', {'place_me': place_me_list})
</code>```

In placement function to avoid using the nested for I firstly found the desired information for each candidate (supposing that each one is associated with schools and upload models) and then I made the calculations.

Body:
I am working on a school placement system and I have multiple models to query from. First I want to loop through the students' list and check if the two student's ID in the profile and result model match. Then I will check if the student has passed and then place the student.

I am using Django 2.2.1. I did a lot of search but to no avail. Below are some of my codes.

Here is my student model.

class StudentProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # Extra Fields
    student_ID = models.CharField(max_length=10)
    middle_Name = models.CharField(max_length=50, blank=True)
    gender = models.CharField(max_length=10, choices=STUDENT_GENDER_CHOICES)
    disability = models.CharField(max_length=5, choices=STUDENT_DISABILITY_CHOICES)
    locality = models.CharField(max_length=30, choices=STUDENT_LOCALITY_CHOICES)
    age = models.PositiveIntegerField()
    profile_picture = models.ImageField(upload_to='profile_photos', blank=True, default='profile_photos/default.svg')

    def __str__(self):
        return self.user.username

This is my result upload model

class StudentResultsUpload(models.Model):
    student_ID = models.CharField(max_length=10)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)

This is my school selection model.

NB: I removed the multiple school models and put everything in one model.

class SchoolSelection(models.Model):
    student = models.ForeignKey(User, on_delete=models.CASCADE)

    school_One = models.CharField(max_length=100)
    program_One = models.CharField(max_length=50)
    residential_Status_One = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Two = models.CharField(max_length=100)
    program_Two = models.CharField(max_length=50)
    residential_Status_Two = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Three = models.CharField(max_length=100)
    program_Three = models.CharField(max_length=50)
    residential_Status_Three = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Four = models.CharField(max_length=100)
    program_Four = models.CharField(max_length=50)
    residential_Status_Four = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

    school_Five = models.CharField(max_length=100)
    program_Five = models.CharField(max_length=50)
    residential_Status_Five = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES)

And this is my views.py for placement.

def placement(request):
    profile = StudentProfile.objects.all()
    place = StudentResultsUpload.objects.all()
    schools = SchoolSelection.objects.all()

    placements = []
    for candidate in profile:
        for pl in place:

            if candidate.student_ID == pl.student_ID:
                if (pl.english >= 50 and pl.mathematics >= 50 and pl.integrated_Science >= 50 and pl.social_Studies >= 50):

                    raw_score = (pl.english + pl.mathematics + pl.integrated_Science + pl.social_Studies + pl.basic_Design_Technology + pl.home_Economics)
                    for school in schools:
                        if raw_score >= 480:
                            place_me = school.school_One
                        elif raw_score >= 420:
                            place_me = school.school_Two
                        elif raw_score >= 360:
                            place_me = school.school_Three
                        elif raw_score >= 300:
                            place_me = school.school_Four
                        else:
                            place_me = school.school_Five

                        placements.append({'student': candidate, 'school': place_me})
                    return render(request, 'schools/placement.html', {'place_me': placements})

                else:
                    return HttpResponse("Sorry, you did not qualify for placement.")

Here is my placement.html file

    Placement Here.

{% for placement in place_me %}
    Stdudent ID: {{ placement.student.student_ID }}

    Stdudent username: {{ placement.student.user }}

    Stdudent gender: {{ placement.student.gender }}

    School: {{ placement.school }}

{% endfor %}

But when I run it, it is not iterating properly through all the students in the system. It is only retaining multiple instances of one student but it will pick the schools of other students and display for the one student that it is returning its multiple instances.

Body:
As Daniel Roseman indicated you should use Foreign Keys to associate different models. A refactoring of your code should be something like the codes below.

The StudentResultsUpload model

class StudentResultsUpload(models.Model):
    student = models.ForeignKey(StudentProfile, on_delete=models.CASCADE, null=True)
    english = models.PositiveIntegerField()
    mathematics = models.PositiveIntegerField()
    integrated_Science = models.PositiveIntegerField()
    social_Studies = models.PositiveIntegerField()
    basic_Design_Technology = models.PositiveIntegerField()
    home_Economics = models.PositiveIntegerField()
    ghanaian_Language = models.PositiveIntegerField()
    french = models.PositiveIntegerField(blank=True)

The SchoolSelectionOne model

class SchoolSelectionOne(models.Model):
    student = models.ForeignKey(StudentProfile, on_delete=models.CASCADE, null=True)
    name_of_School = models.CharField(max_length=100)
    program = models.CharField(max_length=50)
    residential_Status = models.CharField(max_length=50, choices=RESIDENTIAL_STATUS_CHOICES

The placement function

def placement(request):
    profiles = StudentProfile.objects.all()
    uploads = StudentResultsUpload.objects.all()
    school_one = SchoolSelectionOne.objects.all()
    school_two = SchoolSelectionTwo.objects.all()
    school_three = SchoolSelectionThree.objects.all()
    school_four = SchoolSelectionFour.objects.all()
    school_five = SchoolSelectionFive.objects.all()

    profile_dicts = []
    for profile in profiles:
        try:
            upload = [u for u in uploads if u.student.pk == profile.pk][0]
            one = [s for s in school_one if s.student.pk == profile.pk][0]
            two = [s for s in school_two if s.student.pk == profile.pk][0]
            three = [s for s in school_three if s.student.pk == profile.pk][0]
            four = [s for s in school_four if s.student.pk == profile.pk][0]
            five = [s for s in school_five if s.student.pk == profile.pk][0]
        except (AttributeError, IndexError):
            continue

        profile_dicts.append({
            'upload': upload,
            'school_one': one,
            'school_two': two,
            'school_three': three,
            'school_four': four,
            'school_five': five
        })

    place_me_list = []
    for profile in profile_dicts:
        upload = profile['upload']

        if (
                upload.english >= 50 and
                upload.mathematics >= 50 and
                upload.integrated_Science >= 50 and
                upload.social_Studies >= 50
        ):
            raw_score = (
                upload.english +
                upload.mathematics +
                upload.integrated_Science +
                upload.social_Studies +
                upload.basic_Design_Technology +
                upload.home_Economics
            )

            if raw_score >= 480:
                place_me = profile['school_one']
            elif raw_score >= 420:
                place_me = profile['school_two']
            elif raw_score >= 360:
                place_me = profile['school_three']
            elif raw_score >= 300:
                place_me = profile['school_four']
            else:
                place_me = profile['school_five']

            place_me_list.append(place_me)

    return render(request, 'schools/placements.html', {'place_me': place_me_list})

In placement function to avoid using the nested for I firstly found the desired information for each candidate (supposing that each one is associated with schools and upload models) and then I made the calculations.


问:
How to get from outside value inside subscriber
I'm developing dashboard with chartjs and Angular 7 and I need to display some information from an object inside tooltip.

I'm able to get the object in console log, but I'don't know how to get the value from a subscriber inside function that permits me to display custom tooltip on screen.

this is my code.

```<code>ngOnInit() {

this.batches.forEach(batch => {
        let batchID = batch.batch_id;
        this.dashboardService.getBatchId(batchID).subscribe(singleBatch => {
          this.batch = singleBatch;
          console.log(this.batch)
          let batchName = this.batch.name //<-- THIS IS MY VARIABLE
          console.log(batchName)
        })
      })
}

Duration = {
    tooltips: {
      // Disable the on-canvas tooltip
      enabled: false,

      custom: function(tooltipModel) {
          // Tooltip Element
          var tooltipEl = document.getElementById('chartjs-tooltip');

          // Create element on first render
          if (!tooltipEl) {
              tooltipEl = document.createElement('div');
              tooltipEl.id = 'chartjs-tooltip';
              tooltipEl.innerHTML = '<table style="background-color: #eee;"></table>';
              document.body.appendChild(tooltipEl);
          }

          function getBody(bodyItem) {
              return bodyItem.lines;
          }

          // Set Text
          if (tooltipModel.body) {
              var titleLines = tooltipModel.title || [];
              var bodyLines = tooltipModel.body.map(getBody);
              innerHtml += '<tbody>';

              bodyLines.forEach(function(body, i) {
                  var span = '<span>' +
                  '<p>Batch: </p>' + //<----HERE IT IS THE PLACE WHERE I WANT TO PUT BATCHNAME
                  '</span>';
                  innerHtml += '<tr><td>' + span + body + '</td></tr>';
              });
              innerHtml += '</tbody>';
          }
      }

  }
};

</code>```

thanks in advance.

答:
I'm going to Pseudo-code this because i'm not on my development machine.

From your code you already have a variable for your batches e.g this.batches, So why are you going back to your service to obtain your batches? e.g

```<code> this.batches.forEach(batch => { console.log(batch.name) });
</code>```

You just need a function in to display the tooltip e.g

```<code> tooltip(batch: Batch) => { batch.name }
</code>```

Then you should just call it from your html

```<code><div *ngFor="let batch in batches">
    <div class="tooltip">{{tooltip(batch)}}</div>
</div>
</code>```

Body:
I'm developing dashboard with chartjs and Angular 7 and I need to display some information from an object inside tooltip.

I'm able to get the object in console log, but I'don't know how to get the value from a subscriber inside function that permits me to display custom tooltip on screen.

this is my code.

ngOnInit() {

this.batches.forEach(batch => {
        let batchID = batch.batch_id;
        this.dashboardService.getBatchId(batchID).subscribe(singleBatch => {
          this.batch = singleBatch;
          console.log(this.batch)
          let batchName = this.batch.name //<-- THIS IS MY VARIABLE
          console.log(batchName)
        })
      })
}

Duration = {
    tooltips: {
      // Disable the on-canvas tooltip
      enabled: false,

      custom: function(tooltipModel) {
          // Tooltip Element
          var tooltipEl = document.getElementById('chartjs-tooltip');

          // Create element on first render
          if (!tooltipEl) {
              tooltipEl = document.createElement('div');
              tooltipEl.id = 'chartjs-tooltip';
              tooltipEl.innerHTML = '

';
              document.body.appendChild(tooltipEl);
          }

          function getBody(bodyItem) {
              return bodyItem.lines;
          }

          // Set Text
          if (tooltipModel.body) {
              var titleLines = tooltipModel.title || [];
              var bodyLines = tooltipModel.body.map(getBody);
              innerHtml += '
';

              bodyLines.forEach(function(body, i) {
                  var span = '' +
                  '
Batch:
' + //<----HERE IT IS THE PLACE WHERE I WANT TO PUT BATCHNAME
                  '';
                  innerHtml += '
' + span + body + '
';
              });
              innerHtml += '
';
          }
      }

  }
};

thanks in advance.

Body:
I'm going to Pseudo-code this because i'm not on my development machine.

From your code you already have a variable for your batches e.g this.batches, So why are you going back to your service to obtain your batches? e.g

 this.batches.forEach(batch => { console.log(batch.name) });

You just need a function in to display the tooltip e.g

 tooltip(batch: Batch) => { batch.name }

Then you should just call it from your html

<div *ngFor="let batch in batches">
    <div class="tooltip">{{tooltip(batch)}}</div>
</div>


问:
update the height of a DOM element by adding a resize event listener
I would like to make sure that my component has the same height as width. To achieve this I added the resize event listener. Currently I have this code

```<code><template>
    <div
        :ref="cellId"
    >
    </div>
</template>

<script>
export default {
    data: function() {
        return {
            cellId: '_' + Math.random().toString(36).substr(2, 9)
        };
    },
    methods: {
        updateCellHeight: function() {
            this.$refs[this.cellId].clientHeight = this.$refs[this.cellId].clientWidth;
        }
    },
    created: function() {
        window.addEventListener("resize", this.updateCellHeight);
        this.updateCellHeight();
    },
    destroyed: function() {
        window.removeEventListener("resize", this.updateCellHeight);
    }
}
</script>
</code>```

So all I do is generating a unique ID to access the DOM element within the Vue instance. Further I run my event and set the height equal to the width.

When creating multiple components via looping and resizing the window I get this error

Uncaught TypeError: Cannot assign to read only property 'clientHeight'
  of object '#'
      at VueComponent.updateCellHeight

How can I access my HTML element and make sure that its height is equal to its width?

答:
As the error message is trying to tell you, clientHeight is a read only property. You'll probably want to modify the style.height property, but keep in mind clientHeight includes the padding. Try getting the element style using Window.getComputedStyle() and getting the width from there.

However, you can actually achieve this without using any JS at all: http://www.mademyday.de/css-height-equals-width-with-pure-css.html

Body:
I would like to make sure that my component has the same height as width. To achieve this I added the resize event listener. Currently I have this code

<template>

</template>

So all I do is generating a unique ID to access the DOM element within the Vue instance. Further I run my event and set the height equal to the width.

When creating multiple components via looping and resizing the window I get this error

Uncaught TypeError: Cannot assign to read only property 'clientHeight'
  of object '#'
      at VueComponent.updateCellHeight

How can I access my HTML element and make sure that its height is equal to its width?


答:
You’re iterating on the array with the wrong boundaries .

You should change it to strarr.length - 1.

Or remove the less than or equal and use only less than operator

Because the index of the last accessible element in an array is the array length minus 1

Title: Cannot read property 'length' of undefined error message in Javascript


问:
How to construct nested UI elements in Xamarin.Mac and Xcode to bind to nested view models
I am moving my application development from WPF via Xamarin.Forms to Xamarin.Mac.

I have a nested view model structure with view models exposing child view models via properties. Nested UI elements are bound to the view model properties exposed by the containing view model.

For example:

ViewModel_1 bound to View_1

ViewModel_11 bound to View_11

ViewModel_12 bound to View_12

These view models are the DataContext of nested UserControls in WPF and the BindingContext of nested ContentViews in Xamarin.Forms.

What is the corresponding approach when working with Xamarin.Mac? I am not asking about the specifics of data binding (though I will need to get a handle on this), more the UI structure. Is it done by using nested view controllers? Nested views?

I am using Xcode Interface Builder to construct the UI.

If I am barking up the wrong tree, what is the right approach?

答:
Turns out what I am after is a Container View. Tutorial here.

A container view is a placeholder for another view and comes with its own View Controller.


问:
How Do I display current date and time in Toad for Oracle?
I have a sql statement that counts the units(cable boxes) that were refurbished (had damaged parts replaced) and total units(cable boxes that just went through refurb and had nothing replaced) and it's supposed to do this count regularly (every time a unit is processed the count). Can someone please help me? Thank you.

Justin

Heres my sql code so far:

SELECT COUNT(*)
FROM  cxadminn.repair_part

WHERE repair_type = 'REFURB' and created_date >?

答:
I think you want the current date and time when you run the query, which is not the same as created_date, right?

```<code>select COUNT(*),
to_char(sysdate, 'Dy DD-Mon-YYYY HH24:MI:SS') as "Current Time"
FROM cxadminn.repair_part
WHERE repair_type = 'REFURB'
</code>```

I removed the  and created_date >? from the WHERE clause because it doesn't make sense to me, unless you can have items in your table whose created_date is in the future.

ContentLicense: CC BY-SA 3.0

Body:
I think you want the current date and time when you run the query, which is not the same as created_date, right?

select COUNT(*),
to_char(sysdate, 'Dy DD-Mon-YYYY HH24:MI:SS') as "Current Time"
FROM cxadminn.repair_part
WHERE repair_type = 'REFURB'

I removed the  and created_date >? from the WHERE clause because it doesn't make sense to me, unless you can have items in your table whose created_date is in the future.


问:
Research y’a college
I’m practicing Python using IDLE at college and I have a problem concerning a program calculating a distance between two points in a cartesian plane. I wrote a dist function as:

```<code>def_dist(L1, L2):
    s=0
    n=len(L1)
    for k in range (n):
        s+=L1[k]-L2[k]
    return s**0,5
</code>```

With L1 and L2 being two lists of data. The problem is about my interactive platform which doesn’t show me the results and lines to write my data's lists.

Is there a syntax mistake or is it another problem?

答:
Your first problem is not your interactive platform at all, but the fact that your code is invalid and won't run. Define your function without an underscore:

```<code>def dist(L1, L2):
</code>```

If you want to see intermediate results in a calculation loop the normal approach is print():

```<code>for k in range (n):
    s+=L1[k]-L2[k]
    print(s)
</code>```

Title: Research y’a college

Body:
I’m practicing Python using IDLE at college and I have a problem concerning a program calculating a distance between two points in a cartesian plane. I wrote a dist function as:

def_dist(L1, L2):
    s=0
    n=len(L1)
    for k in range (n):
        s+=L1[k]-L2[k]
    return s**0,5

With L1 and L2 being two lists of data. The problem is about my interactive platform which doesn’t show me the results and lines to write my data's lists.

Is there a syntax mistake or is it another problem?

Body:
Your first problem is not your interactive platform at all, but the fact that your code is invalid and won't run. Define your function without an underscore:

def dist(L1, L2):

If you want to see intermediate results in a calculation loop the normal approach is print():

for k in range (n):
    s+=L1[k]-L2[k]
    print(s)


问:
How to cut two digits after my float? In Java script without changing to string
I want to take 2 digits after float like below example:</p>

```<code>function cut() {

var num1=8.844

// should be return 8.84

var num2=8.847

// should be return 8.84
}
</code>```

答:
You could multiply the value with 100, take the floorished value and divide by 100.

You may witness the wonderful world of floating point arithmetic, where numbers have some more or less decimals, like Is floating point math broken?

function cut(value) {
    return Math.floor(value * 100) / 100;
}

console.log(cut(8.844));
console.log(cut(8.847));```

Body:
I want to take 2 digits after float like below example:

function cut() {

var num1=8.844

// should be return 8.84

var num2=8.847

// should be return 8.84
}


问:
Converting \u003c to < character with linux tools
From an ajax call, I got back something like this:

```<code>{"d":"\u003cdiv class=\"popup_title\"\u003eBENTELER Autótechnika Kft.\u003c/div\u003e\u003cdiv style=\"font-size:10pt;font-weight:bold;\"\u003e8060 Mór, Akai út 5.
</code>```

I' d like to convert it to a "usable" format, so \u0003c will simply be a < character.

The header of the ajax call says that this is an iso-8859-2 coding (content-type: text/plain; charset=iso-8859-2), but I' m unsure.

I tried to use iconv with many options, but no luck.

What is interesting is that for instance this site:

```<code>https://www.online-toolz.com/tools/text-unicode-entities-convertor.php
</code>```

does the trick without anything, I just can' t find out what the "from encoding" should be.

I' d be happy to use iconv.

答:
The easiest way to do this is with a JSON parser for your language of choice, which will convert it into an appropriate data structure and unescape it. What you're seeing is a Unicode escape representing U+003C, which is the < character. JSON parsers often escape angle brackets since they have special meaning in HTML and XML, and escaping them means that the JSON can be literally inserted into those types of documents.

Alternately, if you want to escape them from the command line without processing them, you can pipe it to Perl or Ruby to do so, like this:

```<code>perl -pe 's/\\u([0-9a-f]+)/"\u{$1}"/ge;'
</code>```

or

```<code>ruby -pe '$_.gsub!(/\\u([0-9a-f]+)/) { |m| m.to_i(16).chr }'
</code>```

Note that the encoding that you get from the server is likely a red herring. JSON is required to be in Unicode, and it's likely that the server is just misconfigured. If you're certain the data is actually in ISO-8859-2, in violation of the spec, you can fix it by piping the output of the following command to one of the perl or ruby command above:

```<code>iconv -f ISO-8859-2 -t UTF-8
</code>```

Body:
From an ajax call, I got back something like this:

{"d":"\u003cdiv class=\"popup_title\"\u003eBENTELER Autótechnika Kft.\u003c/div\u003e\u003cdiv style=\"font-size:10pt;font-weight:bold;\"\u003e8060 Mór, Akai út 5.

I' d like to convert it to a "usable" format, so \u0003c will simply be a < character.

The header of the ajax call says that this is an iso-8859-2 coding (content-type: text/plain; charset=iso-8859-2), but I' m unsure.

I tried to use iconv with many options, but no luck.

What is interesting is that for instance this site:

https://www.online-toolz.com/tools/text-unicode-entities-convertor.php

does the trick without anything, I just can' t find out what the "from encoding" should be.

I' d be happy to use iconv.

Body:
The easiest way to do this is with a JSON parser for your language of choice, which will convert it into an appropriate data structure and unescape it. What you're seeing is a Unicode escape representing U+003C, which is the < character. JSON parsers often escape angle brackets since they have special meaning in HTML and XML, and escaping them means that the JSON can be literally inserted into those types of documents.

Alternately, if you want to escape them from the command line without processing them, you can pipe it to Perl or Ruby to do so, like this:

perl -pe 's/\\u([0-9a-f]+)/"\u{$1}"/ge;'

or

ruby -pe '$_.gsub!(/\\u([0-9a-f]+)/) { |m| m.to_i(16).chr }'

Note that the encoding that you get from the server is likely a red herring. JSON is required to be in Unicode, and it's likely that the server is just misconfigured. If you're certain the data is actually in ISO-8859-2, in violation of the spec, you can fix it by piping the output of the following command to one of the perl or ruby command above:

iconv -f ISO-8859-2 -t UTF-8


问:
Using a single service to communicate between unrelated components
I am working on an Angular 7 app. I have a lot of cross-component communication happening in my project, and the components do not have a parent-child relationship.

As I know a good solution for such problems are services. Can I have a single service that handles all communication app-wide(information will be very different) or do I have to write a different Service for each pair of components? That seems like a lot of repeated code. Otherwise, if used in each component that needs to send or receive information, on each subscribe it will actually subscribe to all the information ever sent through this service which is definitely not the desired behavior.

My service looks like this:

```<code>@Injectable({providedIn: 'root'})
export class ComponentService {
  private subject = new Subject<any>();

  sendData(data: any) {
    this.subject.next(data);
  }

  getData(): any {
    return this.subject.asObservable();
  }
}
</code>```

Information is sent like this:

```<code>this.componentService.sendData(element);
</code>```

And is received in another component like this:

```<code> constructor(private componentService: ComponentService) {
  }

  ngOnInit() {
    this.componentService.getData().subscribe(data => data);
  }
</code>```

Obviously, if ComponentService is used all over the app, this will make all components(that communicate to others) subscribe to information they do not expect to receive, and do not need to receive.
What approach should be used?

答:
Technically you could have a single service with a Subject that emits an object with a property that determines what type of data it is, like:

```<code>{ type: 'CustomerId', value: 35 }
</code>```

However, you won't benefit from TypeScript's type-hinting. The good thing about TypeScript is that you can declare a type alias/interface (like CustomerData) and then have a typed subject that emits this data:

```<code>private subject: Subject<CustomerData> = new Subject<CustomerData>();
</code>```

When you subscribe to this subject in a component, you will have a typed result, instead of the any type, which should be used as sparringly as possible (or never).

If you're concerned with code duplication you could make an abstract generic base service and have your other services extend it:

```<code>@Injectable({providedIn: 'root'})
export abstract class BaseComponentService<T> {
  private subject = new Subject<T>();

  sendData(data: T) {
    this.subject.next(data);
  }

  getData(): any {
    return this.subject.asObservable();
  }
}
</code>```

So when you create new services you extend the class with a defined type:

```<code>type SubType = {
  name: string;
  age: number;
};

@Injectable()
export class SubService extends BaseComponentService<SubType> {
}
</code>```

Body:
I am working on an Angular 7 app. I have a lot of cross-component communication happening in my project, and the components do not have a parent-child relationship.

As I know a good solution for such problems are services. Can I have a single service that handles all communication app-wide(information will be very different) or do I have to write a different Service for each pair of components? That seems like a lot of repeated code. Otherwise, if used in each component that needs to send or receive information, on each subscribe it will actually subscribe to all the information ever sent through this service which is definitely not the desired behavior.

My service looks like this:

@Injectable({providedIn: 'root'})
export class ComponentService {
  private subject = new Subject<any>();

  sendData(data: any) {
    this.subject.next(data);
  }

  getData(): any {
    return this.subject.asObservable();
  }
}

Information is sent like this:

this.componentService.sendData(element);

And is received in another component like this:

 constructor(private componentService: ComponentService) {
  }

  ngOnInit() {
    this.componentService.getData().subscribe(data => data);
  }

Obviously, if ComponentService is used all over the app, this will make all components(that communicate to others) subscribe to information they do not expect to receive, and do not need to receive.
What approach should be used?

Body:
Technically you could have a single service with a Subject that emits an object with a property that determines what type of data it is, like:

{ type: 'CustomerId', value: 35 }

However, you won't benefit from TypeScript's type-hinting. The good thing about TypeScript is that you can declare a type alias/interface (like CustomerData) and then have a typed subject that emits this data:

private subject: Subject<CustomerData> = new Subject<CustomerData>();

When you subscribe to this subject in a component, you will have a typed result, instead of the any type, which should be used as sparringly as possible (or never).

If you're concerned with code duplication you could make an abstract generic base service and have your other services extend it:

@Injectable({providedIn: 'root'})
export abstract class BaseComponentService<T> {
  private subject = new Subject<T>();

  sendData(data: T) {
    this.subject.next(data);
  }

  getData(): any {
    return this.subject.asObservable();
  }
}

So when you create new services you extend the class with a defined type:

type SubType = {
  name: string;
  age: number;
};

@Injectable()
export class SubService extends BaseComponentService<SubType> {
}


答:
The character set is simply ASCII. These are escape codes used e.g. by JavaScript (and Python).

If the value you get from the AJAX call is valid JSON (as presumably it will be), use a JSON tool to extract it.

```<code>bash$ jq -r .d <<\:
{"d":"\u003cdiv class=\"popup_title\"\u003eBENTELER Autótechnika Kft.\u003c/div\u003e\u003cdiv style=\"font-size:10pt;font-weight:bold;\"\u003e8060 Mór, Akai út 5."}
:
<div class="popup_title">BENTELER Autótechnika Kft.</div><div style="font-size:10pt;font-weight:bold;">8060 Mór, Akai út 5.
</code>```

Title: Converting \u003c to < character with linux tools

Body:
The character set is simply ASCII. These are escape codes used e.g. by JavaScript (and Python).

If the value you get from the AJAX call is valid JSON (as presumably it will be), use a JSON tool to extract it.

bash$ jq -r .d <<\:
{"d":"\u003cdiv class=\"popup_title\"\u003eBENTELER Autótechnika Kft.\u003c/div\u003e\u003cdiv style=\"font-size:10pt;font-weight:bold;\"\u003e8060 Mór, Akai út 5."}
:
<div class="popup_title">BENTELER Autótechnika Kft.</div><div style="font-size:10pt;font-weight:bold;">8060 Mór, Akai út 5.


问:
Silent updates on Mac
I have written silent updates on Windows. I would have an update service running which would check with a web service to see if there are any updates and if so, copy the dll to the location. I am using Mono to write my application on Mac. The entire bundle gets copied to the folder. So how can I selectively copy only certain dlls. Should I always delete the old version and copy the new version of the software. </p>

答: Don't write your own. Take a look at Sparkle.  It has become the de-facto standard for updates for third-party (non-Apple) apps on Mac OS X.</p>

Title: Silent updates on Mac


问:
when new props passed, update functional component states

const {useMemo, useState} = React
const DATA = {
              1:{name: 'John', children: ['Smith','Mary','Chris']},
              2:{name:'Ama', children: ['Natalia','Obama']}
             };

const List = ()=>{
  const generateList = useMemo(() => {
    let arr = [];
    for (let i in DATA) {
      arr.push(<Item key={i} id={i} {...DATA[i]} /> );
    }
    return arr;
  }, [DATA])
  return (

{generateList}

  );
}

const Item = (props) =>{

  const [isShow, setIsShow] = useState(false);
  const [name, setName] = useState(props.name);
  const toggle = () => setIsShow(!isShow)
  const handleClick = (e,name) => {
    e.stopPropagation();
    setName(name);
    toggle();
  }
  return(
  <React.Fragment>

{props.name}

      {props.children.map((i,j)=>(<button key={j} onClick={(e)=>handleClick(e,i)} >{i}</button>))}

    <Modal visible={isShow} toggle={toggle} name={name}/>
  </React.Fragment>
  );
}
const Modal = (props) => {
  const [name, setName] = useState(props.name);
  return props.visible ?  ReactDOM.createPortal(
    <React.Fragment>

       <input type="text" value={name} onChange={(e)=>setName(e.target.value)} />
       <button onClick={props.toggle}>close</button>

    </React.Fragment>, document.getElementById("modal")
  ) : null
}

ReactDOM.render(
  <List/>,document.getElementById('root')
)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dimmer{
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(0,0,0,0.16);
}

.modal{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background-color: white;
  width: 200px;
  height: 120px;
}
li:hover{ background-color: #f0f0f0; cursor: pointer; }</code>```

```

present problem

When I clicked
 or
<button />
, I would see only parent's name.

What I try to achieve

when I clicked one of the children buttons, I would like to see input value about children name.

答:
const {useMemo, useState, useRef} = React
const DATA = {
              1:{name: 'John', children: ['Smith','Mary','Chris']},
              2:{name:'Ama', children: ['Natalia','Obama']}
             };

const List = ()=>{
  const generateList = useMemo(() => {
    let arr = [];
    for (let i in DATA) {
      arr.push(<Item key={i} id={i} {...DATA[i]} /> );
    }
    return arr;
  }, [DATA])
  return (

{generateList}

  );
}

const Item = (props) =>{

  const [isShow, setIsShow] = useState(false);
  const [name, setName] = useState(props.name);
  const toggle = () => setIsShow(!isShow)
  const handleClick = (e,name) => {
    e.stopPropagation();
    setName(name);
    toggle();
  }
  return(
  <React.Fragment>

{props.name}

      {props.children.map((i,j)=>(<button key={j} onClick={(e)=>handleClick(e,i)} >{i}</button>))}

    <Modal visible={isShow} toggle={toggle} name={name}/>
  </React.Fragment>
  );
}
const Modal = (props) => {
  const prevName = useRef(props.name);
  const [name, setName] = useState(props.name);

  if(prevName.current !== props.name){
    prevName.current=name;
    setName(props.name)
  };

  return props.visible ?  ReactDOM.createPortal(
    <React.Fragment>

       <input type="text" value={name} onChange={(e)=>setName(e.target.value)} />
       <button onClick={props.toggle}>close</button>

    </React.Fragment>, document.getElementById("modal")
  ) : null
}

ReactDOM.render(
  <List/>,document.getElementById('root')
)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dimmer{
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(0,0,0,0.16);
}

.modal{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background-color: white;
  width: 200px;
  height: 120px;
}
li:hover{ background-color: #f0f0f0; cursor: pointer; }</code>```

```
</div>
</div>
</p>

<p>I solved it using <code>useRef()</code>.</p>

``` const Modal = (props) => {
      const prevName = useRef(props.name);
      const [name, setName] = useState(props.name);

      if(prevName.current !== props.name){
        prevName.current=name;
        setName(props.name)
      };

      return props.visible ?  ReactDOM.createPortal(
        <React.Fragment>

           <input type="text" value={name} onChange={(e)=>setName(e.target.value)} />
           <button onClick={props.toggle}>close</button>

        </React.Fragment>, document.getElementById("modal")
      ) : null
    }
```

Body:
const {useMemo, useState} = React
const DATA = {
              1:{name: 'John', children: ['Smith','Mary','Chris']},
              2:{name:'Ama', children: ['Natalia','Obama']}
             };

const List = ()=>{
  const generateList = useMemo(() => {
    let arr = [];
    for (let i in DATA) {
      arr.push(<Item key={i} id={i} {...DATA[i]} /> );
    }
    return arr;
  }, [DATA])
  return (

{generateList}

  );
}

const Item = (props) =>{

  const [isShow, setIsShow] = useState(false);
  const [name, setName] = useState(props.name);
  const toggle = () => setIsShow(!isShow)
  const handleClick = (e,name) => {
    e.stopPropagation();
    setName(name);
    toggle();
  }
  return(
  <React.Fragment>

{props.name}

      {props.children.map((i,j)=>(<button key={j} onClick={(e)=>handleClick(e,i)} >{i}</button>))}

    <Modal visible={isShow} toggle={toggle} name={name}/>
  </React.Fragment>
  );
}
const Modal = (props) => {
  const [name, setName] = useState(props.name);
  return props.visible ?  ReactDOM.createPortal(
    <React.Fragment>

       <input type="text" value={name} onChange={(e)=>setName(e.target.value)} />
       <button onClick={props.toggle}>close</button>

    </React.Fragment>, document.getElementById("modal")
  ) : null
}

ReactDOM.render(
  <List/>,document.getElementById('root')
)

.dimmer{
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(0,0,0,0.16);
}

.modal{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background-color: white;
  width: 200px;
  height: 120px;
}
li:hover{ background-color: #f0f0f0; cursor: pointer; }

present problem

When I clicked
 or
<button />
, I would see only parent's name.

What I try to achieve

when I clicked one of the children buttons, I would like to see input value about children name.

Body:
const {useMemo, useState, useRef} = React
const DATA = {
              1:{name: 'John', children: ['Smith','Mary','Chris']},
              2:{name:'Ama', children: ['Natalia','Obama']}
             };

const List = ()=>{
  const generateList = useMemo(() => {
    let arr = [];
    for (let i in DATA) {
      arr.push(<Item key={i} id={i} {...DATA[i]} /> );
    }
    return arr;
  }, [DATA])
  return (
    <ul>{generateList}</ul>
  );
}

const Item = (props) =>{

  const [isShow, setIsShow] = useState(false);
  const [name, setName] = useState(props.name);
  const toggle = () => setIsShow(!isShow)
  const handleClick = (e,name) => {
    e.stopPropagation();
    setName(name);
    toggle();
  }
  return(
  <React.Fragment>
    <li onClick={toggle}>
      <p>{props.name}</p>
      {props.children.map((i,j)=>(<button key={j} onClick={(e)=>handleClick(e,i)} >{i}</button>))}
    </li>
    <Modal visible={isShow} toggle={toggle} name={name}/>
  </React.Fragment>
  );
}
const Modal = (props) => {
  const prevName = useRef(props.name);
  const [name, setName] = useState(props.name);

  if(prevName.current !== props.name){
    prevName.current=name;
    setName(props.name)
  };

  return props.visible ?  ReactDOM.createPortal(
    <React.Fragment>
      <div className="dimmer"/>
      <div className="modal">
       <input type="text" value={name} onChange={(e)=>setName(e.target.value)} />
       <button onClick={props.toggle}>close</button>
      </div>
    </React.Fragment>, document.getElementById("modal")
  ) : null
}

ReactDOM.render(
  <List/>,document.getElementById('root')
)

.dimmer{
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(0,0,0,0.16);
}

.modal{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background-color: white;
  width: 200px;
  height: 120px;
}
li:hover{ background-color: #f0f0f0; cursor: pointer; }

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
<div id="modal"></div>

I solved it using useRef().

 const Modal = (props) => {
      const prevName = useRef(props.name);
      const [name, setName] = useState(props.name);

      if(prevName.current !== props.name){
        prevName.current=name;
        setName(props.name)
      };

      return props.visible ?  ReactDOM.createPortal(
        <React.Fragment>
          <div className="dimmer"/>
          <div className="modal">
           <input type="text" value={name} onChange={(e)=>setName(e.target.value)} />
           <button onClick={props.toggle}>close</button>
          </div>
        </React.Fragment>, document.getElementById("modal")
      ) : null
    }


问:
How to convert function returning [] to Traversable?
I have the following module which implements a directory walk:

module Walk
  ( walk
  ) where

import           Control.Monad
import           Control.Monad.IO.Class
import           Data.List
import           System.Directory
import           System.FilePath

walk :: (MonadIO m) => FilePath -> m [(FilePath, [FilePath])]
walk root = do
  entries <- liftIO $ listDirectory root
  (files, dirs) <- partition snd <$> liftM2 (<$>) zip (mapM (liftIO . doesFileExist . (root </>))) entries
  ((root, map fst files) :) . concat <$> mapM (walk . (root </>) . fst) dirs
```

<p>It currently returns a list, but I'd like it to return a <code>Traversable</code> instead:</p>

<pre class="lang-hs prettyprint-override"><code>walk :: (MonadIO m, Traversable t) => FilePath -> m (t (FilePath, [FilePath]))
</code>```

If I change the signature, I get the following error:

```<code>    • Couldn't match type ‘t’ with ‘[]’
      ‘t’ is a rigid type variable bound by
        the type signature for:
          walk :: forall (m :: * -> *) (t :: * -> *).
                  (MonadIO m, Traversable t) =>
                  FilePath -> m (t (FilePath, [FilePath]))
      Expected type: m (t (FilePath, [FilePath]))
        Actual type: m [(FilePath, [FilePath])]
    • In a stmt of a 'do' block:
        ((root, map fst files) :) . concat
          <$> mapM (walk . (root </>) . fst) dirs
      In the expression:
        do entries <- liftIO $ listDirectory root
           (files, dirs) <- partition snd
                              <$>
                                liftM2
                                  (<$>) zip (mapM (liftIO . doesFileExist .
(root </>))) entries
           ((root, map fst files) :) . concat
             <$> mapM (walk . (root </>) . fst) dirs
      In an equation for ‘walk’:
          walk root
            = do entries <- liftIO $ listDirectory root
                 (files, dirs) <- partition snd
                                    <$>
                                      liftM2
                                        (<$>)
                                        zip
                                        (mapM (liftIO . doesFileExist .
(root </>)))
                                        entries
                 ((root, map fst files) :) . concat
                   <$> mapM (walk . (root </>) . fst) dirs
    • Relevant bindings include
        walk :: FilePath -> m (t (FilePath, [FilePath]))
</code>```

I think it's failing on the :? I can't be sure. How do I fix this?

答:
Polymorphic production of lists, and designing classes for polymorphic containers in general, has proven to be more difficult than it might first appear.  GHC's current solution for producing fully polymorphic containers, vs just operating over a pre-existing container such as with Traversable, is the IsList class.

Defined in GHC.Exts as:

```<code>class IsList l where
  type Item l
  fromList  :: [Item l] -> l
  ...
</code>```

There are already instances for lists, non empty lists, maps, and most other types coming from what you'd think of as standard Haskell libraries.

Notice the type parameter, l, is of kind * and not what you might expect from a container of * -> *.  You provide the fully applied type and can constrain the Item l type with type equality if desired.  For example:

```<code>{-# LANGUAGE TypeFamilies #-}
module Walk
  ( walk
  ) where

import           Control.Monad
import           Control.Monad.IO.Class
import           Data.List
import           System.Directory
import           System.FilePath
import           GHC.Exts

walk :: (IsList l, Item l ~ (FilePath,[FilePath]), MonadIO m) => FilePath -> m l
walk root =
  do entries <- liftIO $ listDirectory root
     (files, dirs) <- partition snd <$> liftM2 (<$>) zip (mapM (liftIO . doesFileExist . (root </>))) entries
     fromList . ((root, map fst files) :) . concat <$> mapM (walk . (root </>) . fst) dirs
</code>```

Body:
I have the following module which implements a directory walk:

module Walk
  ( walk
  ) where

import           Control.Monad
import           Control.Monad.IO.Class
import           Data.List
import           System.Directory
import           System.FilePath

walk :: (MonadIO m) => FilePath -> m [(FilePath, [FilePath])]
walk root = do
  entries <- liftIO $ listDirectory root
  (files, dirs) <- partition snd <$> liftM2 (<$>) zip (mapM (liftIO . doesFileExist . (root </>))) entries
  ((root, map fst files) :) . concat <$> mapM (walk . (root </>) . fst) dirs

It currently returns a list, but I'd like it to return a Traversable instead:

walk :: (MonadIO m, Traversable t) => FilePath -> m (t (FilePath, [FilePath]))

If I change the signature, I get the following error:

    • Couldn't match type ‘t’ with ‘[]’
      ‘t’ is a rigid type variable bound by
        the type signature for:
          walk :: forall (m :: * -> *) (t :: * -> *).
                  (MonadIO m, Traversable t) =>
                  FilePath -> m (t (FilePath, [FilePath]))
      Expected type: m (t (FilePath, [FilePath]))
        Actual type: m [(FilePath, [FilePath])]
    • In a stmt of a 'do' block:
        ((root, map fst files) :) . concat
          <$> mapM (walk . (root </>) . fst) dirs
      In the expression:
        do entries <- liftIO $ listDirectory root
           (files, dirs) <- partition snd
                              <$>
                                liftM2
                                  (<$>) zip (mapM (liftIO . doesFileExist .
(root </>))) entries
           ((root, map fst files) :) . concat
             <$> mapM (walk . (root </>) . fst) dirs
      In an equation for ‘walk’:
          walk root
            = do entries <- liftIO $ listDirectory root
                 (files, dirs) <- partition snd
                                    <$>
                                      liftM2
                                        (<$>)
                                        zip
                                        (mapM (liftIO . doesFileExist .
(root </>)))
                                        entries
                 ((root, map fst files) :) . concat
                   <$> mapM (walk . (root </>) . fst) dirs
    • Relevant bindings include
        walk :: FilePath -> m (t (FilePath, [FilePath]))

I think it's failing on the :? I can't be sure. How do I fix this?

Body:
Polymorphic production of lists, and designing classes for polymorphic containers in general, has proven to be more difficult than it might first appear.  GHC's current solution for producing fully polymorphic containers, vs just operating over a pre-existing container such as with Traversable, is the IsList class.

Defined in GHC.Exts as:

class IsList l where
  type Item l
  fromList  :: [Item l] -> l
  ...

There are already instances for lists, non empty lists, maps, and most other types coming from what you'd think of as standard Haskell libraries.

Notice the type parameter, l, is of kind * and not what you might expect from a container of * -> *.  You provide the fully applied type and can constrain the Item l type with type equality if desired.  For example:

{-# LANGUAGE TypeFamilies #-}
module Walk
  ( walk
  ) where

import           Control.Monad
import           Control.Monad.IO.Class
import           Data.List
import           System.Directory
import           System.FilePath
import           GHC.Exts

walk :: (IsList l, Item l ~ (FilePath,[FilePath]), MonadIO m) => FilePath -> m l
walk root =
  do entries <- liftIO $ listDirectory root
     (files, dirs) <- partition snd <$> liftM2 (<$>) zip (mapM (liftIO . doesFileExist . (root </>))) entries
     fromList . ((root, map fst files) :) . concat <$> mapM (walk . (root </>) . fst) dirs


问:
How to update child's(from the created list) props from parent
This might refer to other relevant general questions like how to update a child component from the parent, though I'd like to hear any fair judgement of my design solution to the following scenario.

I have a parent class where I store css attributes for 2 children objects.

```<code>import React from 'react'
import Item from './item/Item'

class Small_gallery extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chosenVal: 0,
    };

    this.listObjParams = [
    // Style 1
      {
        left: 300,
        zIndex: 0
      },
     //Style 2
      {
        left: 320,
        zIndex: 1
      }
    ];

    this.handleClick = this.handleClick.bind(this);
    this.calculateShift = this.applyNewStyle.bind(this);
    this.listItems = this.listObjParams.map((objStyle, i) =>
        <Item
            key={i}
            id={i}
            objStyle={objStyle}
            onClick={this.handleClick}
        />
    );
  }

  handleClick = (indexFromChild) => {
    this.setState({chosenVal: indexFromChild});
    this.applyNewStyle(indexFromChild)
  };

  applyNewStyle = (clickedIndex) => {
   if (clickedIndex === 0) {
   // somehow I want to apply new css style 2 to the clicked? <Item> child
  };
  render() {
    return (
        <div>
          {this.listItems}
        </div>
    )
  }
</code>```

Child component is rather trivial:

```<code>class Item extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
        <div
            onClick={(e) => {
              e.preventDefault();
              this.props.onClick(this.props.id)
            }}
            style={{
              left: this.props.objStyle.left,
              zIndex: this.props.objStyle.zIndex
            }}
        >
        </div>
    );
  }
}
</code>```

The question is: how can I apply style 1 or 2 to the clicked Item component(depending on the index I am returning)? I've read about getDerivedStateFromProps instead of using deprecated componentWillReceiveProps here https://hackernoon.com/replacing-componentwillreceiveprops-with-getderivedstatefromprops-c3956f7ce607 but it's not a solution for me.

I expect number of created Items to grow in the future to 10-20, so it makes no sense to populate state of Item with this.listObjParams when creating it, or am I wrong here?

答:
I have a working example below, so to cover what I did:

Create a prop that takes an array of items, more items more looped <Item />'s will appear.

Styles are either activeStyles || inactiveStyles it is based on the currentId matching the id from object (from array prop = items).

```<code>import React from "react";

const inactiveStyles = {
  left: 300,
  zIndex: 0,
  backgroundColor: "#E9573F"
};

const activeStyles = {
  left: 320,
  zIndex: 1,
  backgroundColor: "#00B1E1"
};

const inboundItems = [
  {
    id: 0
  },
  {
    id: 1
  },
  {
    id: 2
  }
];

// Note - added to show it working not needed
const defaultStyles = {
  display: "block",
  border: "1px solid black",
  width: 50,
  height: 50
};

export const Item = ({ id, onClick, style }) => (
  <>
    ```{JSON.stringify({ styles: style }, null, 2)}```

    <div
      {...{ id }}
      style={{ ...defaultStyles, ...style }}
      onClick={e => {
        e.preventDefault();

        onClick(id);
      }}
    />
  </>
);

export const SmallGallery = ({ items = inboundItems }) => {
  const [currentId, setCurrentId] = React.useState(null);

  const getStyles = selectedId => {
    return currentId === selectedId ? activeStyles : inactiveStyles;
  };

  return items.map(({ id, ...item }) => (
    <Item
      key={id}
      {...{ id }}
      {...item}
      style={getStyles(id)}
      onClick={selectedId => setCurrentId(selectedId)}
    />
  ));
};

export default SmallGallery;
</code>```

Let me know what you think, I added a screenshot to show styles being added.

<img src="https://i.stack.imgur.com/rSzZK.png" alt="<SmallGallery /> working">

Body:
This might refer to other relevant general questions like how to update a child component from the parent, though I'd like to hear any fair judgement of my design solution to the following scenario.

I have a parent class where I store css attributes for 2 children objects.

import React from 'react'
import Item from './item/Item'

class Small_gallery extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chosenVal: 0,
    };

    this.listObjParams = [
    // Style 1
      {
        left: 300,
        zIndex: 0
      },
     //Style 2
      {
        left: 320,
        zIndex: 1
      }
    ];

    this.handleClick = this.handleClick.bind(this);
    this.calculateShift = this.applyNewStyle.bind(this);
    this.listItems = this.listObjParams.map((objStyle, i) =>
        <Item
            key={i}
            id={i}
            objStyle={objStyle}
            onClick={this.handleClick}
        />
    );
  }

  handleClick = (indexFromChild) => {
    this.setState({chosenVal: indexFromChild});
    this.applyNewStyle(indexFromChild)
  };

  applyNewStyle = (clickedIndex) => {
   if (clickedIndex === 0) {
   // somehow I want to apply new css style 2 to the clicked? <Item> child
  };
  render() {
    return (

          {this.listItems}

    )
  }

Child component is rather trivial:

class Item extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (

 {
              e.preventDefault();
              this.props.onClick(this.props.id)
            }}
            style={{
              left: this.props.objStyle.left,
              zIndex: this.props.objStyle.zIndex
            }}
        >

    );
  }
}

The question is: how can I apply style 1 or 2 to the clicked Item component(depending on the index I am returning)? I've read about getDerivedStateFromProps instead of using deprecated componentWillReceiveProps here https://hackernoon.com/replacing-componentwillreceiveprops-with-getderivedstatefromprops-c3956f7ce607 but it's not a solution for me.

I expect number of created Items to grow in the future to 10-20, so it makes no sense to populate state of Item with this.listObjParams when creating it, or am I wrong here?

Body:
I have a working example below, so to cover what I did:

Create a prop that takes an array of items, more items more looped <Item />'s will appear.

Styles are either activeStyles || inactiveStyles it is based on the currentId matching the id from object (from array prop = items).

import React from "react";

const inactiveStyles = {
  left: 300,
  zIndex: 0,
  backgroundColor: "#E9573F"
};

const activeStyles = {
  left: 320,
  zIndex: 1,
  backgroundColor: "#00B1E1"
};

const inboundItems = [
  {
    id: 0
  },
  {
    id: 1
  },
  {
    id: 2
  }
];

// Note - added to show it working not needed
const defaultStyles = {
  display: "block",
  border: "1px solid black",
  width: 50,
  height: 50
};

export const Item = ({ id, onClick, style }) => (
  <>
    <pre>{JSON.stringify({ styles: style }, null, 2)}</pre>

    <div
      {...{ id }}
      style={{ ...defaultStyles, ...style }}
      onClick={e => {
        e.preventDefault();

        onClick(id);
      }}
    />
  </>
);

export const SmallGallery = ({ items = inboundItems }) => {
  const [currentId, setCurrentId] = React.useState(null);

  const getStyles = selectedId => {
    return currentId === selectedId ? activeStyles : inactiveStyles;
  };

  return items.map(({ id, ...item }) => (
    <Item
      key={id}
      {...{ id }}
      {...item}
      style={getStyles(id)}
      onClick={selectedId => setCurrentId(selectedId)}
    />
  ));
};

export default SmallGallery;

Let me know what you think, I added a screenshot to show styles being added.