问:
How to use IF-ELSE in RPN(Reverse Polish Notation)?
i have done a RPN class to calculate strings which end-user input like
"1.0+3/2-tan(45)/(1+1)+sin(30)*abs(-1)+Abs(-10)"

Then, I want to parsing conditional statements and multi-parameters function such as "if(1>2,3/3,2*1)","max(1,2,3,4)"

So, my questions how to use IF-ELSE in the RPN?

Here's my code: enter link description here

答:
i try to parse multi-parameters function such as if\Max before RPN.Parse()</p>

```<code>public class MultiParameterFunctionParser
    {
        public readonly List<string> Funcs = new List<string> {"IF", "MAX"};

        public string Parse(string exp)
        {
            while (IsFunction(exp,out var index,out var funcName))//
            {
                var parameters = GetParameters(exp, index, funcName, out var before, out var after);
                var list = GetParameterList(parameters);

                var value = Evaluate(list, funcName);
                exp= $"{before}({value}){after}";
            }

            return exp;
        }

        /// <summary>
        ///  Is Exp Contains a function?
        /// </summary>
        /// <param name="exp"></param>
        /// <param name="index"></param>
        /// <param name="funcName"></param>
        /// <returns></returns>
        private bool IsFunction(string exp, out int index, out string funcName)
        {
            index = -1;
            funcName = "";
            foreach (var func in Funcs)
            {
                var idx = exp.IndexOf($"{func}(", StringComparison.CurrentCultureIgnoreCase);
                if (idx == -1 || idx + 3 >= exp.Length - 1)
                    continue;
                index = idx;
                funcName = func;
                break;
            }

            return index != -1 && index + 3 < exp.Length - 1;
        }

        /// <summary>
        /// Get Parameters' string
        /// </summary>
        /// <param name="exp">8+if(12,sin(90),0)+1.2</param>
        /// <param name="index">2 if's start index</param>
        /// <param name="before">8+</param>
        /// <param name="after">+1.2</param>
        /// <returns>12,sin(90),0</returns>
        private static string GetParameters(string exp,int index, string funcName, out string before, out string after)
        {
            before = exp.Substring(0, index);

            index += funcName.Length + 1;

            var leftCount = 1; // '(' count
            var rightCount = 0;// ')' count
            var results = "";

            while (index < exp.Length && leftCount != rightCount)
            {
                var c = exp[index];
                if (c.Equals('('))
                    leftCount++;
                else if (c.Equals(')'))
                    rightCount++;

                if (leftCount > rightCount)
                    results += c;
                else
                    break;

                index++;
            }

            after = exp.Substring(index + 1, exp.Length - index - 1);

            return results;
        }

        /// <summary>
        /// Parse Parameter string to list.
        /// </summary>
        /// <param name="exp">MAX(1,-1),1,0</param>
        /// <returns>{"MAX(1,-1)","1","0"}</returns>
        private static List<string> GetParameterList(string exp)
        {
            var count = exp.Length;

            for (var i = count - 1; i > -1 && exp.Length > 0; i--)
            {
                var c = exp[i];
                if (c != ',')
                    continue;

                var after = exp.Substring(i + 1);
                var before = exp.Substring(0,i);

                if (after.Count(a => a == '(').Equals(after.Count(a => a == ')')))
                {
                    exp = before + '#' + after;
                }
            }

            var results = exp.Split('#').ToList();

            return results;
        }

        private static double Evaluate(List<string> parameters, string funcName)
        {
            if (funcName.Equals("MAX", StringComparison.CurrentCultureIgnoreCase))
                return EvaluateMax(parameters);
            if (funcName.Equals("IF", StringComparison.CurrentCultureIgnoreCase))
                return EvaluateIF(parameters);

            return 0;
        }

        private static double EvaluateIF(List<string> parameters)
        {
            if (parameters == null || parameters.Count != 3)
                throw new Exception("EvaluateIF parameters.Count()!=3");

            var results = new List<double>();
            foreach (var parameter in parameters)
            {
                var rpn = new RPN();
                rpn.Parse(parameter);
                var obj = rpn.Evaluate();

                if (obj == null)
                {
                    throw new Exception("EvaluateIF Not Number!");
                }
                if (obj.ToString().Equals("true", StringComparison.CurrentCultureIgnoreCase))
                {
                    results.Add(1);
                }
                else if (obj.ToString().Equals("false", StringComparison.CurrentCultureIgnoreCase))
                {
                    results.Add(-1);
                }
                else
                {
                    if (double.TryParse(obj.ToString(), out var d))
                        results.Add(d);
                    else
                        throw new Exception("EvaluateIF Not Number!");
                }
            }

            return results[0] >= 0 ? results[1] : results[2];
        }

        private static double EvaluateMax(IEnumerable<string> parameters)
        {
            var results = new List<double>();
            foreach (var parameter in parameters)
            {
                var rpn = new RPN();
                rpn.Parse(parameter);
                var obj = rpn.Evaluate();
                if (double.TryParse(obj.ToString(), out var d))
                    results.Add(d);
            }

            return results.Count > 0 ? results.Max() : 0;
        }
    }
</code>```

Body:
i try to parse multi-parameters function such as if\Max before RPN.Parse()

public class MultiParameterFunctionParser
    {
        public readonly List<string> Funcs = new List<string> {"IF", "MAX"};

        public string Parse(string exp)
        {
            while (IsFunction(exp,out var index,out var funcName))//
            {
                var parameters = GetParameters(exp, index, funcName, out var before, out var after);
                var list = GetParameterList(parameters);

                var value = Evaluate(list, funcName);
                exp= $"{before}({value}){after}";
            }

            return exp;
        }

        /// <summary>
        ///  Is Exp Contains a function?
        /// </summary>
        /// <param name="exp"></param>
        /// <param name="index"></param>
        /// <param name="funcName"></param>
        /// <returns></returns>
        private bool IsFunction(string exp, out int index, out string funcName)
        {
            index = -1;
            funcName = "";
            foreach (var func in Funcs)
            {
                var idx = exp.IndexOf($"{func}(", StringComparison.CurrentCultureIgnoreCase);
                if (idx == -1 || idx + 3 >= exp.Length - 1)
                    continue;
                index = idx;
                funcName = func;
                break;
            }

            return index != -1 && index + 3 < exp.Length - 1;
        }

        /// <summary>
        /// Get Parameters' string
        /// </summary>
        /// <param name="exp">8+if(12,sin(90),0)+1.2</param>
        /// <param name="index">2 if's start index</param>
        /// <param name="before">8+</param>
        /// <param name="after">+1.2</param>
        /// <returns>12,sin(90),0</returns>
        private static string GetParameters(string exp,int index, string funcName, out string before, out string after)
        {
            before = exp.Substring(0, index);

            index += funcName.Length + 1;

            var leftCount = 1; // '(' count
            var rightCount = 0;// ')' count
            var results = "";

            while (index < exp.Length && leftCount != rightCount)
            {
                var c = exp[index];
                if (c.Equals('('))
                    leftCount++;
                else if (c.Equals(')'))
                    rightCount++;

                if (leftCount > rightCount)
                    results += c;
                else
                    break;

                index++;
            }

            after = exp.Substring(index + 1, exp.Length - index - 1);

            return results;
        }

        /// <summary>
        /// Parse Parameter string to list.
        /// </summary>
        /// <param name="exp">MAX(1,-1),1,0</param>
        /// <returns>{"MAX(1,-1)","1","0"}</returns>
        private static List<string> GetParameterList(string exp)
        {
            var count = exp.Length;

            for (var i = count - 1; i > -1 && exp.Length > 0; i--)
            {
                var c = exp[i];
                if (c != ',')
                    continue;

                var after = exp.Substring(i + 1);
                var before = exp.Substring(0,i);

                if (after.Count(a => a == '(').Equals(after.Count(a => a == ')')))
                {
                    exp = before + '#' + after;
                }
            }

            var results = exp.Split('#').ToList();

            return results;
        }

        private static double Evaluate(List<string> parameters, string funcName)
        {
            if (funcName.Equals("MAX", StringComparison.CurrentCultureIgnoreCase))
                return EvaluateMax(parameters);
            if (funcName.Equals("IF", StringComparison.CurrentCultureIgnoreCase))
                return EvaluateIF(parameters);

            return 0;
        }

        private static double EvaluateIF(List<string> parameters)
        {
            if (parameters == null || parameters.Count != 3)
                throw new Exception("EvaluateIF parameters.Count()!=3");

            var results = new List<double>();
            foreach (var parameter in parameters)
            {
                var rpn = new RPN();
                rpn.Parse(parameter);
                var obj = rpn.Evaluate();

                if (obj == null)
                {
                    throw new Exception("EvaluateIF Not Number!");
                }
                if (obj.ToString().Equals("true", StringComparison.CurrentCultureIgnoreCase))
                {
                    results.Add(1);
                }
                else if (obj.ToString().Equals("false", StringComparison.CurrentCultureIgnoreCase))
                {
                    results.Add(-1);
                }
                else
                {
                    if (double.TryParse(obj.ToString(), out var d))
                        results.Add(d);
                    else
                        throw new Exception("EvaluateIF Not Number!");
                }
            }

            return results[0] >= 0 ? results[1] : results[2];
        }

        private static double EvaluateMax(IEnumerable<string> parameters)
        {
            var results = new List<double>();
            foreach (var parameter in parameters)
            {
                var rpn = new RPN();
                rpn.Parse(parameter);
                var obj = rpn.Evaluate();
                if (double.TryParse(obj.ToString(), out var d))
                    results.Add(d);
            }

            return results.Count > 0 ? results.Max() : 0;
        }
    }


来源: stackexchange

问:
Laravel Query with Sum of value from child table if value column in parent table greater than sum of value in child
I am trying to query for rows from transaction table where the amount is less than sum of allocations against that transaction row in allocations table. This works halfway. It is giving me all transaction queries with an additional field of "allocated_amount".

```<code>$all_transactions = Transaction::
    withCount([
        'allocations AS amount_allocated' => function ($query) {
            $query->select(
                DB::raw("CAST(SUM(amount) AS INTEGER)"
            ));
        }
    ])
    ->where('contact_type','supplier')
    ->where('contact_id',$ehead->supplier_id)
    ->get()->toArray();
</code>```

Result

```<code> 0 => array:12 [▼
    "id" => 4
    "amount" => 10000
    "created_by" => 1
    "amount_allocated" => 7500
  ]
  1 => array:12 [▼
    "id" => 5
    "amount" => 10000
    "created_by" => 1
    "amount_allocated" => 10000
  ]
</code>```

But I don't want the second result to come up because amount = amount allocated. How to fix this query?

Tried using:

```<code>->where('amount','>','allocated_amount')
</code>```

but maybe because it is additionally added filed, throws an error saying allocated field does not exist. I need it within the query, not as a separate addition.

答:
Well, in this case you can simply use map()</p>

```<code>$all_transactions = collect($all_transactions)->map(function ($row) {
    if ($row['amount'] > $row['amount_allocated']) {
        return $row;
    }
})->filter()->toArray();  // filter() to remove null values
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to query for rows from transaction table where the amount is less than sum of allocations against that transaction row in allocations table. This works halfway. It is giving me all transaction queries with an additional field of "allocated_amount".

$all_transactions = Transaction::
    withCount([
        'allocations AS amount_allocated' => function ($query) {
            $query->select(
                DB::raw("CAST(SUM(amount) AS INTEGER)"
            ));
        }
    ])
    ->where('contact_type','supplier')
    ->where('contact_id',$ehead->supplier_id)
    ->get()->toArray();

Result

 0 => array:12 [▼
    "id" => 4
    "amount" => 10000
    "created_by" => 1
    "amount_allocated" => 7500
  ]
  1 => array:12 [▼
    "id" => 5
    "amount" => 10000
    "created_by" => 1
    "amount_allocated" => 10000
  ]

But I don't want the second result to come up because amount = amount allocated. How to fix this query?

Tried using:

->where('amount','>','allocated_amount')

but maybe because it is additionally added filed, throws an error saying allocated field does not exist. I need it within the query, not as a separate addition.

Body:
Well, in this case you can simply use map()

$all_transactions = collect($all_transactions)->map(function ($row) {
    if ($row['amount'] > $row['amount_allocated']) {
        return $row;
    }
})->filter()->toArray();  // filter() to remove null values


问:
Emacs bookmark-jump: how to jump to bmark and only one of the split-windows changes contents?
I start with a file visible in one window; then i do a split-window, therefore now both windows show the same contents (at same buffer point).

Now I want to jump to a different location in the file via a bookmark in only 1 of the 2 windows, but when i execute the bookmark-jump, both windows end up at the bookmark's point.

Leave the other window's point alone!

How can i configure this?

Thanks

(running on linux, GNU Emacs 23.2.1; xemacs does not behave this way)

post-note:

What I'd like to do is to have the same file shown on both windows, and while one window (w1) shows a section of the file, in the other window (w2) I jump around to different sections, using the various bookmarks, while w1's position does not change.

答:
There may be a direct answer, but in general, I find that all kinds of things get inconvenient when displaying the same buffer in multiple windows. I recommend using indirect buffers. Run M-x clone-indirect-buffer to create another buffer, or C-x 4 c (clone-indirect-buffer-other-window) to also show the new buffer in another window. An indirect buffer has the same contents as the original, and saving saves to the same files, but the buffers have

independent points, marks, markers;

independent modes (and more generally independent local variables);

independent views (narrowing, hidden text, faces, …).

ContentLicense: CC BY-SA 3.0


问:
How to add a list with a list of lists so that each index would be a list containing a an element and a list in python
I have two lists to start with.

Say I had a list like
ls_1 = ["2", "1", "2", "1"] and a second list which contains lists ls_2 = [[2, 7], [1, 2], [4, 6], [5,2]]

how would I combine them into:

```<code>final_ls = [["2", [2, 7]], ["1", [1, 2]], ["2", [4, 6]], ["1", [5, 2]]]
</code>```

where final_ls[0][0] would be "2"?
and final_ls[1][0] would be "1"?

I've tried to append the lists but that doesn't work

Body:
I have two lists to start with.

Say I had a list like
ls_1 = ["2", "1", "2", "1"] and a second list which contains lists ls_2 = [[2, 7], [1, 2], [4, 6], [5,2]]

how would I combine them into:

final_ls = [["2", [2, 7]], ["1", [1, 2]], ["2", [4, 6]], ["1", [5, 2]]]

where final_ls[0][0] would be "2"?
and final_ls[1][0] would be "1"?

I've tried to append the lists but that doesn't work

Body:
Use zip:

ls_1 = ["2", "1", "2", "1"]

ls_2 = [[2, 7], [1, 2], [4, 6], [5,2]]

final_ls = [[n,m] for n,m in zip(ls_1,ls_2)]

print(final_ls)

Output:

[['2', [2, 7]], ['1', [1, 2]], ['2', [4, 6]], ['1', [5, 2]]]


问:
C# SOAP - Error in deserializing body of reply message (Magento API)
I'm trying to connect a C# app to Magento 1.6 (through Magento SOAP V2) using the following code:

```<code>using (Mage_Api_Model_Server_Wsi_HandlerPortTypeClient proxy = new Mage_Api_Model_Server_Wsi_HandlerPortTypeClient())
{
  string sessionId = proxy.login("XXXXXXX", "XXXXXXXXXXX");
  Console.WriteLine(sessionId);
}
</code>```

and I get the following error:

```<code>Error in deserializing body of reply message for operation 'login'.
</code>```

I used Fiddler to inspect the transfer and this is the result:

```<code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:Magento">
<SOAP-ENV:Body>
<ns1:loginResponseParam>
<result>fc094df96480dbbcdXXXXXXXXXXXXXXX</result>
</ns1:loginResponseParam>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

I'm using:

Magento V 1.6

Magento SOAP V2

WS-I Compliance (ie System/Configuration/Services/Magento Core API/WS-I Compliance is set to Yes)

Content type fix: Content Type Error Consuming Magento 1.5 Webservices from .Net

VS 2010

.Net 3.5

Any ideas how I can fix (or debug) this problem?

答:
I updated the Web Service reference and it works for me.

Because the third party services may changed / updated and you should be also updated in your environment.

Body:
I'm trying to connect a C# app to Magento 1.6 (through Magento SOAP V2) using the following code:

using (Mage_Api_Model_Server_Wsi_HandlerPortTypeClient proxy = new Mage_Api_Model_Server_Wsi_HandlerPortTypeClient())
{
  string sessionId = proxy.login("XXXXXXX", "XXXXXXXXXXX");
  Console.WriteLine(sessionId);
}

and I get the following error:

Error in deserializing body of reply message for operation 'login'.

I used Fiddler to inspect the transfer and this is the result:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:Magento">
<SOAP-ENV:Body>
<ns1:loginResponseParam>
<result>fc094df96480dbbcdXXXXXXXXXXXXXXX</result>
</ns1:loginResponseParam>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

I'm using:

Magento V 1.6

Magento SOAP V2

WS-I Compliance (ie System/Configuration/Services/Magento Core API/WS-I Compliance is set to Yes)

Content type fix: Content Type Error Consuming Magento 1.5 Webservices from .Net

VS 2010

.Net 3.5

Any ideas how I can fix (or debug) this problem?


问:
System Security Exception in Silverlight app making GET request
I am new to silverlight. I have been trying to patch up a silverlight app that makes a get request to some site over the net, say google. However, I keep getting the system.security exception again nd again. I read various other posts and what i gathered is that for these things to work u need to choose HOST APPLICATION IN A NEW WEBSITE option while creation of the project, i have done that, but still get the same exception. I downloaded the app from http://www.shinedraw.com/data-handling/flash-vs-silverlight-simple-http-post-request/ and ran it by clicking debug in VS2010, still it gave the same exception.
Please tell me what i am doing wrong, i know its cross domain issues, but dont know what else to do.
The second answer at this post - WebClient.DownloadStringAsync throwing Security Exception in Silverlight, I think, offers a workaround, but does this means there is no way to access such services from silverlight directly?? -

Experienced users please explain.

答: You cannot call a web service other than from your own domain directly from a Silverlight application. If you want to to this, you would have to install a cross-domain policy on the server that hosts the service. But you can always install a web service within your own web application (that hosts the Sivlerlight app) and call the other service from that service. It's one sercie call more but it works also with services you don't own.</p>


问:
Service not available while calling geoCoder.getFromLocation()
I know sometimes google back-end service might not be available.

Hence a solution might be to loop until i get the data.

```<code>private class getLocationDetails extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        Log.d("looping", "" + count + "");
        count++;
        double lat = Double.parseDouble(params[0]);
        double lng = Double.parseDouble(params[1]);
        List<Address> addresses = null;
        try {

            Geocoder gCoder = new Geocoder(ImageAndLocationActivity.this,
                    Locale.getDefault());
            addresses = gCoder.getFromLocation(lat, lng, 1);
            Address addr = addresses.get(0);
            user_country = addr.getCountryName();
            user_city = addr.getLocality();
            user_district = addr.getSubAdminArea();

            if (user_city == null) {

                user_city = user_district;
            }
        } catch (Exception e) {

            Log.e("Exception in getLocationDetails - ", e.getMessage());
            return null;
        }

        return "";
    }

    @Override
    protected void onPostExecute(String result) {

        if (result != null) {

            Log.d("user_city = ", "" + user_city);
        } else {

            new getLocationDetails().execute(CurrentLat + "", CurrentLng
                    + "");
        }
    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected void onProgressUpdate(Void... values) {

    }
}
</code>```

But i am not able to get the location at all:

LogCat:

```<code>02-27 16:29:49.568: D/looping(10966): 110355
02-27 16:29:49.568: E/Exception in getLocationDetails -(10966): Service not Available
02-27 16:29:49.573: D/looping(10966): 110356
02-27 16:29:49.573: E/Exception in getLocationDetails -(10966): Service not Available
02-27 16:29:49.573: D/looping(10966): 110357
02-27 16:29:49.573: E/Exception in getLocationDetails -(10966): Service not Available
</code>```

and ofcourse i have added all the needed permissions:

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

I am trying this on Samsung Galaxy Note GT-N7000 (4.0.4 version)

Am i missing any settings? related to device or application ? Or this usually happens? If so any better solution to resolve this??

Thank You

答: You can go to a map app in your phone and clear cached and will find the address work correctly.</p>

Body:
I know sometimes google back-end service might not be available.

Hence a solution might be to loop until i get the data.

private class getLocationDetails extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        Log.d("looping", "" + count + "");
        count++;
        double lat = Double.parseDouble(params[0]);
        double lng = Double.parseDouble(params[1]);
        List<Address> addresses = null;
        try {

            Geocoder gCoder = new Geocoder(ImageAndLocationActivity.this,
                    Locale.getDefault());
            addresses = gCoder.getFromLocation(lat, lng, 1);
            Address addr = addresses.get(0);
            user_country = addr.getCountryName();
            user_city = addr.getLocality();
            user_district = addr.getSubAdminArea();

            if (user_city == null) {

                user_city = user_district;
            }
        } catch (Exception e) {

            Log.e("Exception in getLocationDetails - ", e.getMessage());
            return null;
        }

        return "";
    }

    @Override
    protected void onPostExecute(String result) {

        if (result != null) {

            Log.d("user_city = ", "" + user_city);
        } else {

            new getLocationDetails().execute(CurrentLat + "", CurrentLng
                    + "");
        }
    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected void onProgressUpdate(Void... values) {

    }
}

But i am not able to get the location at all:

LogCat:

02-27 16:29:49.568: D/looping(10966): 110355
02-27 16:29:49.568: E/Exception in getLocationDetails -(10966): Service not Available
02-27 16:29:49.573: D/looping(10966): 110356
02-27 16:29:49.573: E/Exception in getLocationDetails -(10966): Service not Available
02-27 16:29:49.573: D/looping(10966): 110357
02-27 16:29:49.573: E/Exception in getLocationDetails -(10966): Service not Available

and ofcourse i have added all the needed permissions:

<uses-permission android:name="android.permission.INTERNET" />

I am trying this on Samsung Galaxy Note GT-N7000 (4.0.4 version)

Am i missing any settings? related to device or application ? Or this usually happens? If so any better solution to resolve this??

Thank You


问:
OOP PHP authentication and authorization to projects
Now i want to implement authorization to the functions to my project but i do not know where to begin for oop php project

or the best approach to design user roles and giving user privileges or authority to READ,EDIT,UPDATE and DELETE according to their role (or to access part of file depending on the role) in PHP and mysql

答:
It very much depends what the project is and the structure of it but in general yes, you would assign roles to a user and then limit access to page elements AND methods depending on the role.

So in my project I have user roles:

1 - Admin

2 - Editor

3 - Viewer

I set the user role at login through a $_SESSION['userRole'] variable.

I may have a function as follows:

```<code>public function editPost() {
    if($_SESSION['userRole']<3) {
        // edit post code here
    } else {
        echo "You don't have permission to edit posts";
    }
}
</code>```

Body:
It very much depends what the project is and the structure of it but in general yes, you would assign roles to a user and then limit access to page elements AND methods depending on the role.

So in my project I have user roles:

1 - Admin

2 - Editor

3 - Viewer

I set the user role at login through a $_SESSION['userRole'] variable.

I may have a function as follows:

public function editPost() {
    if($_SESSION['userRole']<3) {
        // edit post code here
    } else {
        echo "You don't have permission to edit posts";
    }
}


问:
How to make a rectangle of characters?
How to make a rectangle of characters?
I need to make such a picture appear in the console

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

But I get this:

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

Sides a and b are entered from the console.

```<code>    int a = requestNumber();
    int b = requestNumber();
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            if (j == 0 || j < (b - 1))
            System.out.print("*");
            else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}
</code>```

答:
```<code>public class Rectangle {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle();
        rectangle.printRectangle(7,9);
    }

    private void printRectangle(int row, int col) {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if ((isFirstOrLastRow(i, row) && isFirstOrLastCol(j, col))
                        || !(isFirstOrLastRow(i, row) || isFirstOrLastCol(j, col))) {
                    System.out.print(" ");
                }
                else {
                    System.out.print("*");
                }
            }
            System.out.println();
        }
    }

    private boolean isFirstOrLastRow(int currentRow, int row) {
        return currentRow == 0 || currentRow == row - 1;
    }

    private boolean isFirstOrLastCol(int currentCol, int col) {
        return currentCol == 0 || currentCol == col - 1;
    }
}
</code>```

The four corners and the middle position should output spaces, so we should judge whether it is the four corners or the middle position，I use isFirstOrLastRow and isFirstOrLastCol to help judge.

here is the result for input 7,9

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

Title: How to make a rectangle of characters?

Body:
How to make a rectangle of characters?
I need to make such a picture appear in the console

 **********
*          *
*          *
*          *
 **********

But I get this:

*********
*********
*********
*********
*********

Sides a and b are entered from the console.

    int a = requestNumber();
    int b = requestNumber();
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            if (j == 0 || j < (b - 1))
            System.out.print("*");
            else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}

Body:
public class Rectangle {
    public static void main(String[] args) {
        Rectangle rectangle = new Rectangle();
        rectangle.printRectangle(7,9);
    }

    private void printRectangle(int row, int col) {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if ((isFirstOrLastRow(i, row) && isFirstOrLastCol(j, col))
                        || !(isFirstOrLastRow(i, row) || isFirstOrLastCol(j, col))) {
                    System.out.print(" ");
                }
                else {
                    System.out.print("*");
                }
            }
            System.out.println();
        }
    }

    private boolean isFirstOrLastRow(int currentRow, int row) {
        return currentRow == 0 || currentRow == row - 1;
    }

    private boolean isFirstOrLastCol(int currentCol, int col) {
        return currentCol == 0 || currentCol == col - 1;
    }
}

The four corners and the middle position should output spaces, so we should judge whether it is the four corners or the middle position，I use isFirstOrLastRow and isFirstOrLastCol to help judge.

here is the result for input 7,9

 *******
*       *
*       *
*       *
*       *
*       *
 *******


问:
Is it possible to have different return types for a overloaded method?
In method overloading, is it possible to have different return types for a overloaded method?
for example,

```<code>void foo(int x) ;
int foo(int x,int y);
double foo(String str);
</code>```

in general object oriented programming, is it possible?

答:
In short, overloading the return type needs a powerful typing system which can derive the function to be used from the calling result.

Haskell and ML family can accomplish this job.

It's not right to define overloading to be restricted in changing the args since changing the return type leaves enough information for the compiler to derive which function to be used.

ContentLicense: CC BY-SA 2.5

Body:
In method overloading, is it possible to have different return types for a overloaded method?
for example,

void foo(int x) ;
int foo(int x,int y);
double foo(String str);

in general object oriented programming, is it possible?


问:
PHP/SQL problem: Data from sql wont display
I have this problem on my payroll processing system.
Below the area where the data are added is a table where the data added into the pay table are shown (except for the empID since the payroll details shown on the table must be from those that are associated to the employee that was selected.)

Payroll System image

Please refer to the link above to see image to further understand what's written below.

*[A]*is where the user selects which employee's payroll details be updated. After selecting the radio button and clicking the "Update Payroll Details" button, the user shall be brought to the Update Payroll Details page which is B.

*[B]*The upper part is where the user enters all the payroll details associated to the employee selected. Once the user clicks save the data shall be added to the database (pay table) and these details shall be shown on the table located below the input area.

However, although I have data in my pay table it wouldn't seem to display on the table below that's why the message shows "No Records Found". Here is my code for the entire Update Payroll Data page:

```<code>elseif ($_GET["k"]==41)
{
    session_start();
    if (isset($_SESSION["uname"]))
    {
            $empID=$_POST["empID"];
            $aBulan=0; $aPetsa=0; $aTuig=0; $tuigYana=date("Y"); $tuigHadto=$tuigYana-5;

            $anoBulan=array("January","February","March","April","May","June","July","August","September","October","November","December");

            if ($_POST["sButton"]=="Update Payroll Details")
            {
                    $anoSulod ="Payroll Details<hr>";
                    $anoSulod.="<form method='post' action='logged.php?k=42'>";
                    $anoSulod.="<input type='hidden' name='empID' value='".$empID."'>";
                    $anoSulod.="<table>";
                    $anoSulod.="    <tr><td>Name of employee : </td><td>".accessDatabase::hinoEmployee($empID)."</td></tr>";
                    $anoSulod.="    <tr>";
                    $anoSulod.="            <td>For the month ending : </td>";
                    $anoSulod.="            <td>";

// Kanan month ini dinhi
                    $anoSulod.="                    <select name='bBulan'>";
                    for ($bulan=1; $bulan<=12; $bulan++)
                    {
                        if ($bulan==$aBulan) $anoSulod.="       <option value='".$bulan."' selected>".$anoBulan[$bulan-1];
                        else $anoSulod.="       <option value='".$bulan."'>".$anoBulan[$bulan-1];
                    }
                    $anoSulod.="                    </select> ";

// Kanan year ini dinhi
                    $anoSulod.="                    <select name='bTuig'>";
                    for ($tuig=$tuigYana; $tuig>=$tuigHadto; $tuig--)
                    {
                        if ($tuig==$aTuig) $anoSulod.=" <option value='".$tuig."' selected>".$tuig;
                        else $anoSulod.="       <option value='".$tuig."'>".$tuig;
                    }
                    $anoSulod.="                    </select>";
                    $anoSulod.="            </td>";
                    $anoSulod.="    <tr>";
                    $anoSulod.="    <tr><td>Basic Salary : PhP</td><td><input type='text' name='bs'></td></tr>";
                    $anoSulod.="    <tr><td>PERA/ACA : PhP</td><td><input type='text' name='pa'></td></tr>";
                    $anoSulod.="    <tr><td>PAIC : PhP</td><td><input type='text' name='pc'></td></tr>";
                    $anoSulod.="    <tr><td>REL : PhP</td><td><input type='text' name='rl'></td></tr>";
                    $anoSulod.="    <tr><td>GSIS Premium/Loans : PhP</td><td><input type='text' name='gs'></td></tr>";
                    $anoSulod.="    <tr><td>HDMF Premium/Loans : PhP</td><td><input type='text' name='hd'></td></tr>";
                    $anoSulod.="    <tr><td>Coop Loans : PhP</td><td><input type='text' name='cl'></td></tr>";
                    $anoSulod.="    <tr><td>Union Dues : PhP</td><td><input type='text' name='ud'></td></tr>";
                    $anoSulod.="    <tr><td>Withholding Tax : PhP</td><td><input type='text' name='tx'></td></tr>";
                    $anoSulod.="    <tr><td colspan='2'><hr></tr>";
                    $anoSulod.="    <tr><td colspan='2'><input type='submit' value='Save'></tr>";
                    $anoSulod.="    <tr><td colspan='2'><hr></tr>";
                    $anoSulod.="    <tr>";
                    $anoSulod.="     <td colspan='2'>";
                    $anoSulod.="     <table border='1'>";

                    $anoSulod.="     <caption>Payroll Details</caption>";
                    $anoSulod.="     <tr>";
                    $anoSulod.="     <td> </td>";
                    $anoSulod.="     <td>Pay period</td>";
                    $anoSulod.="     <td>Basic Salary</td>";
                    $anoSulod.="     <td>PERA/ACA</td>";
                    $anoSulod.="     <td>PAIC</td>";
                    $anoSulod.="     <td>REL</td>";
                    $anoSulod.="     <td>GSIS Premium/Loans</td>";
                    $anoSulod.="     <td>HDMF Premium/Loans</td>";
                    $anoSulod.="     <td>Coop Loans</td>";
                    $anoSulod.="     <td>Union Dues</td>";
                    $anoSulod.="     <td>Withholding Tax</td>";
                    $anoSulod.="     </tr>";

                    $k="select b.payID, a.empname, date_format(b.date,'%M %Y') as date, b.bs, b.pa, b.pc, b.rl, b.gs, b.hd, b.cl, b.ud, b.tx, from emp a, pay b where a.empID=b.empID and a.empID=".$empID;
                    $q=mysql_query($k);
                    if (mysql_num_rows($q)>0)
                    {
                        while ($akonRows=mysql_fetch_array($q))
                        {
                            $anoSulod.="    <tr>";
                            $anoSulod.="     <td><input type='radio' name='payID' value='".$akonRows["payID"]."'></td>";
                            $anoSulod.="     <td>".$akonRows["date"]."</td>";
                            $anoSulod.="     <td>".$akonRows["bs"]."</td>";
                            $anoSulod.="     <td>".$akonRows["pa"]."</td>";
                            $anoSulod.="     <td>".$akonRows["pc"]."</td>";
                            $anoSulod.="     <td>".$akonRows["rl"]."</td>";
                            $anoSulod.="     <td>".$akonRows["gs"]."</td>";
                            $anoSulod.="     <td>".$akonRows["hd"]."</td>";
                            $anoSulod.="     <td>".$akonRows["cl"]."</td>";
                            $anoSulod.="     <td>".$akonRows["ud"]."</td>";
                            $anoSulod.="     <td>".$akonRows["tx"]."</td>";
                            $anoSulod.="    </tr>";
                        }
                    }
                    else
                    {
                        $anoSulod.="    <tr>";
                        $anoSulod.="     <td colspan='11' align='center'>No records found</td>";
                        $anoSulod.="    </tr>";
                    }

                    $anoSulod.="     </table>";

                    $anoSulod.="     </td>";
                    $anoSulod.="    </tr>";
                    $anoSulod.="</table>";
                    $anoSulod.="</form>";
                    $kadamoTD=2;
           }

      }
}
</code>```

Please help. I really can't figure out what went wrong. Please do... Thanks so much!

答: Ok, remove the comma before FROM - "b.tx," should be "b.tx"</p>

Body:
I have this problem on my payroll processing system.
Below the area where the data are added is a table where the data added into the pay table are shown (except for the empID since the payroll details shown on the table must be from those that are associated to the employee that was selected.)

Payroll System image

Please refer to the link above to see image to further understand what's written below.

*[A]*is where the user selects which employee's payroll details be updated. After selecting the radio button and clicking the "Update Payroll Details" button, the user shall be brought to the Update Payroll Details page which is B.

*[B]*The upper part is where the user enters all the payroll details associated to the employee selected. Once the user clicks save the data shall be added to the database (pay table) and these details shall be shown on the table located below the input area.

However, although I have data in my pay table it wouldn't seem to display on the table below that's why the message shows "No Records Found". Here is my code for the entire Update Payroll Data page:

elseif ($_GET["k"]==41)
{
    session_start();
    if (isset($_SESSION["uname"]))
    {
            $empID=$_POST["empID"];
            $aBulan=0; $aPetsa=0; $aTuig=0; $tuigYana=date("Y"); $tuigHadto=$tuigYana-5;

            $anoBulan=array("January","February","March","April","May","June","July","August","September","October","November","December");

            if ($_POST["sButton"]=="Update Payroll Details")
            {
                    $anoSulod ="Payroll Details
";
                    $anoSulod.="<form method='post' action='logged.php?k=42'>";
                    $anoSulod.="<input type='hidden' name='empID' value='".$empID."'>";
                    $anoSulod.="
";
                    $anoSulod.="
Name of employee : 	".accessDatabase::hinoEmployee($empID)."
";
                    $anoSulod.="
";
                    $anoSulod.="            For the month ending : 	";
                    $anoSulod.="            ";

// Kanan month ini dinhi
                    $anoSulod.="                    <select name='bBulan'>";
                    for ($bulan=1; $bulan<=12; $bulan++)
                    {
                        if ($bulan==$aBulan) $anoSulod.="       <option value='".$bulan."' selected>".$anoBulan[$bulan-1];
                        else $anoSulod.="       <option value='".$bulan."'>".$anoBulan[$bulan-1];
                    }
                    $anoSulod.="                    </select> ";

// Kanan year ini dinhi
                    $anoSulod.="                    <select name='bTuig'>";
                    for ($tuig=$tuigYana; $tuig>=$tuigHadto; $tuig--)
                    {
                        if ($tuig==$aTuig) $anoSulod.=" <option value='".$tuig."' selected>".$tuig;
                        else $anoSulod.="       <option value='".$tuig."'>".$tuig;
                    }
                    $anoSulod.="                    </select>";
                    $anoSulod.="            	";
                    $anoSulod.="
";
                    $anoSulod.="
Basic Salary : PhP	<input type='text' name='bs'>
";
                    $anoSulod.="
PERA/ACA : PhP	<input type='text' name='pa'>
";
                    $anoSulod.="
PAIC : PhP	<input type='text' name='pc'>
";
                    $anoSulod.="
REL : PhP	<input type='text' name='rl'>
";
                    $anoSulod.="
GSIS Premium/Loans : PhP	<input type='text' name='gs'>
";
                    $anoSulod.="
HDMF Premium/Loans : PhP	<input type='text' name='hd'>
";
                    $anoSulod.="
Coop Loans : PhP	<input type='text' name='cl'>
";
                    $anoSulod.="
Union Dues : PhP	<input type='text' name='ud'>
";
                    $anoSulod.="
Withholding Tax : PhP	<input type='text' name='tx'>
";
                    $anoSulod.="

";
                    $anoSulod.="
<input type='submit' value='Save'>
";
                    $anoSulod.="

";
                    $anoSulod.="
";
                    $anoSulod.="     ";
                    $anoSulod.="
";

                    $anoSulod.="
Payroll Details
";
                    $anoSulod.="
";
                    $anoSulod.="      	";
                    $anoSulod.="     Pay period	";
                    $anoSulod.="     Basic Salary	";
                    $anoSulod.="     PERA/ACA	";
                    $anoSulod.="     PAIC	";
                    $anoSulod.="     REL	";
                    $anoSulod.="     GSIS Premium/Loans	";
                    $anoSulod.="     HDMF Premium/Loans	";
                    $anoSulod.="     Coop Loans	";
                    $anoSulod.="     Union Dues	";
                    $anoSulod.="     Withholding Tax	";
                    $anoSulod.="
";

                    $k="select b.payID, a.empname, date_format(b.date,'%M %Y') as date, b.bs, b.pa, b.pc, b.rl, b.gs, b.hd, b.cl, b.ud, b.tx, from emp a, pay b where a.empID=b.empID and a.empID=".$empID;
                    $q=mysql_query($k);
                    if (mysql_num_rows($q)>0)
                    {
                        while ($akonRows=mysql_fetch_array($q))
                        {
                            $anoSulod.="
";
                            $anoSulod.="     <input type='radio' name='payID' value='".$akonRows["payID"]."'>	";
                            $anoSulod.="     ".$akonRows["date"]."	";
                            $anoSulod.="     ".$akonRows["bs"]."	";
                            $anoSulod.="     ".$akonRows["pa"]."	";
                            $anoSulod.="     ".$akonRows["pc"]."	";
                            $anoSulod.="     ".$akonRows["rl"]."	";
                            $anoSulod.="     ".$akonRows["gs"]."	";
                            $anoSulod.="     ".$akonRows["hd"]."	";
                            $anoSulod.="     ".$akonRows["cl"]."	";
                            $anoSulod.="     ".$akonRows["ud"]."	";
                            $anoSulod.="     ".$akonRows["tx"]."	";
                            $anoSulod.="
";
                        }
                    }
                    else
                    {
                        $anoSulod.="
";
                        $anoSulod.="     No records found	";
                        $anoSulod.="
";
                    }

                    $anoSulod.="
";

                    $anoSulod.="     	";
                    $anoSulod.="
";
                    $anoSulod.="
";
                    $anoSulod.="</form>";
                    $kadamoTD=2;
           }

      }
}

Please help. I really can't figure out what went wrong. Please do... Thanks so much!


问:
How can I change text color of items in safe area in React Native?
I am trying to change the color of text and other icons in SafeAreaView (check this Screenshot) based on theme in react-native-ui-kitten. I tried setting color in stylesheet but no good.

答:
I think you should use StatusBar - a react native base component to change your item color.
https://reactnative.dev/docs/statusbar#barstyle


问:
How can I loop a jsonlite function on a data frame of urls?
I am trying to run a jsonlite function on a set of API URLs I accumulated. Specifically, I have a dataframe called url_df which has a column called URL with 162800 rows of API URLs. When I write a script and manually insert the each URL at a time it works perfectly fine. This is the script I use to run it manually on one URL at a time:

```<code>May28 <- 'https://example.example.com/example'.
May28 <- httr::GET(May28)
May28 <- httr::content(May28, as = 'text')
May28 <- jsonlite::fromJSON(May28)
dplyr::glimpse(May28)
May28 <- as.data.frame(May28)
write.table(May28, file="May28.csv", sep=",")
</code>```

However, because I have over 100K lines of API URLs to go through, I wanted to create a loop function that repeats the above function to each row (each API URL) in the column URL so that I don't have to manually cut and paste each URL to the script 100K+ times. So I saved this information to the dataframe called "url_df" and attempted the following code:

```<code>j <- 1

for (j in 1:nrow(url_df)){
    url <- url_df$URL[[j]] %>%
  getdata <- GET(url) %>%
  rawdata <- httr::content(getdata, as='text') %>%
  data <- jsonlite::fromJSON(rawdata)
  data_df <- as.data.frame(data)
    print(j)
  j <- j+1
  Sys.sleep(0.5)
}
</code>```

For some reason, it will not run. One of the errors I got were:

Error in jsonlite::fromJSON(rawdata) : object 'rawdata' not found.

One caveat that might be important: each API URL doesn't return just 1 data point value (e.g., 1). Instead, it returns a list of values (e.g., Sunday, 1, Tuesday, 2, etc).

Any ideas on why this might be happening or how I can overcome this?

After solving this first issue, I'd like to then rbind all of the data I collected if possible.

答:
The reason the for loop fails is because you have some invalid or problematic URLs.

See if something like this would solve your problem:

```<code>library(tidyverse)

# Function to download - it takes two inputs: (1) url and (2) save file name
dl_my_url <- function(url_address, file_name_to_save){

  x <- httr::GET(url_address)
  y <- httr::content(x, as = 'text')
  z  <- jsonlite::fromJSON(z)

  print(dplyr::glimpse(z))

  output <- as.data.frame(z)

  write.table(output, file = file_name_to_save, sep=",")

}

# make the function safe in case some url fails
safe_dl_my_url <- safely(dl_my_url)

# Run the function (make sure you create a save name for each url)
url_result <- map2(urldf$address, urldf$file_name_to_save, ~safe_dl_my_url(.x, .y))

# To get your results
map(url_result, "result") %>% bind_rows() # or bind_cols which ever works for you

# Check what is failing
map(url_result, "error")
</code>```

Body:
I am trying to run a jsonlite function on a set of API URLs I accumulated. Specifically, I have a dataframe called url_df which has a column called URL with 162800 rows of API URLs. When I write a script and manually insert the each URL at a time it works perfectly fine. This is the script I use to run it manually on one URL at a time:

May28 <- 'https://example.example.com/example'.
May28 <- httr::GET(May28)
May28 <- httr::content(May28, as = 'text')
May28 <- jsonlite::fromJSON(May28)
dplyr::glimpse(May28)
May28 <- as.data.frame(May28)
write.table(May28, file="May28.csv", sep=",")

However, because I have over 100K lines of API URLs to go through, I wanted to create a loop function that repeats the above function to each row (each API URL) in the column URL so that I don't have to manually cut and paste each URL to the script 100K+ times. So I saved this information to the dataframe called "url_df" and attempted the following code:

j <- 1

for (j in 1:nrow(url_df)){
    url <- url_df$URL[[j]] %>%
  getdata <- GET(url) %>%
  rawdata <- httr::content(getdata, as='text') %>%
  data <- jsonlite::fromJSON(rawdata)
  data_df <- as.data.frame(data)
    print(j)
  j <- j+1
  Sys.sleep(0.5)
}

For some reason, it will not run. One of the errors I got were:

Error in jsonlite::fromJSON(rawdata) : object 'rawdata' not found.

One caveat that might be important: each API URL doesn't return just 1 data point value (e.g., 1). Instead, it returns a list of values (e.g., Sunday, 1, Tuesday, 2, etc).

Any ideas on why this might be happening or how I can overcome this?

After solving this first issue, I'd like to then rbind all of the data I collected if possible.

Body:
The reason the for loop fails is because you have some invalid or problematic URLs.

See if something like this would solve your problem:

library(tidyverse)

# Function to download - it takes two inputs: (1) url and (2) save file name
dl_my_url <- function(url_address, file_name_to_save){

  x <- httr::GET(url_address)
  y <- httr::content(x, as = 'text')
  z  <- jsonlite::fromJSON(z)

  print(dplyr::glimpse(z))

  output <- as.data.frame(z)

  write.table(output, file = file_name_to_save, sep=",")

}

# make the function safe in case some url fails
safe_dl_my_url <- safely(dl_my_url)

# Run the function (make sure you create a save name for each url)
url_result <- map2(urldf$address, urldf$file_name_to_save, ~safe_dl_my_url(.x, .y))

# To get your results
map(url_result, "result") %>% bind_rows() # or bind_cols which ever works for you

# Check what is failing
map(url_result, "error")


问:
Unable to install yarn packages via docker build
I'm trying to speed up spinning up docker by having all current packages in yarn.lock be installed on the image already. I think I'm doing yarn install incorrectly, that it is working somewhere else?

relevant part of dockerfile:

```<code># Create a dir
WORKDIR /(WORKDIR)
# Time to install all our dependencies
COPY package.json /(WORKDIR)/package.json
COPY yarn.lock /(WORKDIR)/yarn.lock

# Need the executables to be in the path
ENV PATH /(WORKDIR)/node_modules/.bin:$PATH
RUN yarn check --verify-tree || yarn install --frozen-lockfile
</code>```

I think my last line is incorrect. It is installing somewhere, but not on the package itself? Either that or caching might be an issue. If I start the image I find the output of yarn check --verify-tree is still the current state of the image.

答:
Just RUN yarn and make sure COPY code base after yarn.

```<code>FROM        node:12.14.0-alpine3.11

ENV         NODE_ENV=production
WORKDIR     /app

COPY        package.json ./
COPY        yarn.lock ./
RUN         yarn

COPY        src ./
</code>```

I test it in my machine, you can see if I change yarn.lock. And if I don't change my yarn.lock

```<code>$ docker build -t demo .
Step 1/6 : FROM        node:12.14.0-alpine3.11
 ---> 1cbcaddb8074
Step 2/6 : ENV         NODE_ENV=production
 ---> Using cache
 ---> dc7f1a2f7d90
Step 3/6 : WORKDIR     /app
 ---> Using cache
 ---> eec9363713a5
Step 4/6 : COPY        package.json ./
 ---> Using cache
 ---> fde6cf7bb577
Step 5/6 : COPY        yarn.lock ./
 ---> 6a1369622d79
Step 6/6 : RUN         yarn
 ---> Running in ff6433969bea
yarn install v1.21.1
[1/4] Resolving packages...
[2/4] Fetching packages...
warning sha.js@2.4.11: Invalid bin entry for "sha.js" (in "sha.js").
warning url-loader@1.1.2: Invalid bin field for "url-loader".
info fsevents@1.2.9: The platform "linux" is incompatible with this module.
info "fsevents@1.2.9" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
warning " > styled-components@5.0.1" has unmet peer dependency "react-is@>= 16.8.0".
[4/4] Building fresh packages...
Done in 35.97s.
Removing intermediate container ff6433969bea
 ---> 8dcd2124289d
Successfully built 8dcd2124289d

$docker build -t demo .
Step 1/6 : FROM        node:12.14.0-alpine3.11
 ---> 1cbcaddb8074
Step 2/6 : ENV         NODE_ENV=production
 ---> Using cache
 ---> dc7f1a2f7d90
Step 3/6 : WORKDIR     /app
 ---> Using cache
 ---> eec9363713a5
Step 4/6 : COPY        package.json ./
 ---> Using cache
 ---> fde6cf7bb577
Step 5/6 : COPY        yarn.lock ./
 ---> Using cache
 ---> 6a1369622d79
Step 6/6 : RUN         yarn
 ---> Using cache
 ---> 8dcd2124289d
Step 7/7 : COPY        src ./
 ---> 13474b882e11
</code>```

Body:
I'm trying to speed up spinning up docker by having all current packages in yarn.lock be installed on the image already. I think I'm doing yarn install incorrectly, that it is working somewhere else?

relevant part of dockerfile:

# Create a dir
WORKDIR /(WORKDIR)
# Time to install all our dependencies
COPY package.json /(WORKDIR)/package.json
COPY yarn.lock /(WORKDIR)/yarn.lock

# Need the executables to be in the path
ENV PATH /(WORKDIR)/node_modules/.bin:$PATH
RUN yarn check --verify-tree || yarn install --frozen-lockfile

I think my last line is incorrect. It is installing somewhere, but not on the package itself? Either that or caching might be an issue. If I start the image I find the output of yarn check --verify-tree is still the current state of the image.

Body:
Just RUN yarn and make sure COPY code base after yarn.

FROM        node:12.14.0-alpine3.11

ENV         NODE_ENV=production
WORKDIR     /app

COPY        package.json ./
COPY        yarn.lock ./
RUN         yarn

COPY        src ./

I test it in my machine, you can see if I change yarn.lock. And if I don't change my yarn.lock

$ docker build -t demo .
Step 1/6 : FROM        node:12.14.0-alpine3.11
 ---> 1cbcaddb8074
Step 2/6 : ENV         NODE_ENV=production
 ---> Using cache
 ---> dc7f1a2f7d90
Step 3/6 : WORKDIR     /app
 ---> Using cache
 ---> eec9363713a5
Step 4/6 : COPY        package.json ./
 ---> Using cache
 ---> fde6cf7bb577
Step 5/6 : COPY        yarn.lock ./
 ---> 6a1369622d79
Step 6/6 : RUN         yarn
 ---> Running in ff6433969bea
yarn install v1.21.1
[1/4] Resolving packages...
[2/4] Fetching packages...
warning sha.js@2.4.11: Invalid bin entry for "sha.js" (in "sha.js").
warning url-loader@1.1.2: Invalid bin field for "url-loader".
info fsevents@1.2.9: The platform "linux" is incompatible with this module.
info "fsevents@1.2.9" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
warning " > styled-components@5.0.1" has unmet peer dependency "react-is@>= 16.8.0".
[4/4] Building fresh packages...
Done in 35.97s.
Removing intermediate container ff6433969bea
 ---> 8dcd2124289d
Successfully built 8dcd2124289d

$docker build -t demo .
Step 1/6 : FROM        node:12.14.0-alpine3.11
 ---> 1cbcaddb8074
Step 2/6 : ENV         NODE_ENV=production
 ---> Using cache
 ---> dc7f1a2f7d90
Step 3/6 : WORKDIR     /app
 ---> Using cache
 ---> eec9363713a5
Step 4/6 : COPY        package.json ./
 ---> Using cache
 ---> fde6cf7bb577
Step 5/6 : COPY        yarn.lock ./
 ---> Using cache
 ---> 6a1369622d79
Step 6/6 : RUN         yarn
 ---> Using cache
 ---> 8dcd2124289d
Step 7/7 : COPY        src ./
 ---> 13474b882e11


问:
Not getting the Token in Azure API Apps - ADAL
I have created a API where I am trying to get token & then getting the data using that token
Its working fine in Visual Studio debug mode/locally, Prompting for User Credential, as MFA is enabled , also OTP will be asked and working fine

Problem is when I deploy in Azure API/WEb apps, its not working and failing at the line where getting the token. Also noticed, it never prompts for USer credential while deployed in web app. I want to get the Token silently if not possible, Prompting for credential also OK. Atleast it should work after deeployment in web app. Here the Code snippet:

```<code>using Microsoft.IdentityModel.Clients.ActiveDirectory;

//API Method
public async Task<IEnumerable<string>> Get()
    {
        try
        {
    private static string authority = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}" ,"575d120d-78ae-41fc-b5a0-4072a4349b");

    AuthenticationResult result = null;
            HttpClient httpClient = new HttpClient();
            AuthenticationContext authContext = new AuthenticationContext(authority);
            result = await authContext.AcquireTokenAsync(todoListResourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Auto));//new PlatformParameters(PromptBehavior.Auto)
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            // Call the To Do list service.
            HttpResponseMessage response = await httpClient.GetAsync(todoListBaseAddress + "locations");//+ "/api/values/4"
            if (response.IsSuccessStatusCode)
            {
                //MessageBox.Show(response.RequestMessage.ToString());
                string s = await response.Content.ReadAsStringAsync();
            }

  }
        catch (HttpRequestException ex)
        {
            return new string[] { ex.Message, ex.StackTrace };
        }
        catch (Exception ex)
        {
            return new string[] { ex.Message, ex.StackTrace };
        }
    }
</code>```

答:
Ensure both applications are registered in Azure AD and user consent has been granted for the on-behalf-of flow.

For silent token acquisition, follow the recommended pattern and call AcquireTokenSilentAsync first and fall-back to AcquireTokenAsync only upon failure.

Body:
I have created a API where I am trying to get token & then getting the data using that token
Its working fine in Visual Studio debug mode/locally, Prompting for User Credential, as MFA is enabled , also OTP will be asked and working fine

Problem is when I deploy in Azure API/WEb apps, its not working and failing at the line where getting the token. Also noticed, it never prompts for USer credential while deployed in web app. I want to get the Token silently if not possible, Prompting for credential also OK. Atleast it should work after deeployment in web app. Here the Code snippet:

using Microsoft.IdentityModel.Clients.ActiveDirectory;

//API Method
public async Task<IEnumerable<string>> Get()
    {
        try
        {
    private static string authority = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}" ,"575d120d-78ae-41fc-b5a0-4072a4349b");

    AuthenticationResult result = null;
            HttpClient httpClient = new HttpClient();
            AuthenticationContext authContext = new AuthenticationContext(authority);
            result = await authContext.AcquireTokenAsync(todoListResourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Auto));//new PlatformParameters(PromptBehavior.Auto)
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            // Call the To Do list service.
            HttpResponseMessage response = await httpClient.GetAsync(todoListBaseAddress + "locations");//+ "/api/values/4"
            if (response.IsSuccessStatusCode)
            {
                //MessageBox.Show(response.RequestMessage.ToString());
                string s = await response.Content.ReadAsStringAsync();
            }

  }
        catch (HttpRequestException ex)
        {
            return new string[] { ex.Message, ex.StackTrace };
        }
        catch (Exception ex)
        {
            return new string[] { ex.Message, ex.StackTrace };
        }
    }


问:
Is it possible to use React Hooks outside of functional component, or i have to use mobx or redux?
I am new to React, and when I was reading about the docs, I found there were two ways to implement React components, functional-based and class-based. I know before React 16.8 it's not possible to manage state in functional components, but after that there is React Hooks.

The problem is, there seems to be one restriction for React Hooks, they can only be used inside functional components. Take a server-client as an example, which needs to change an isAuthenticated state while 401 received.

```<code>//client.js
import { useUserDispatch, signOut } from "auth";

export function request(url, args) {
  var dispatch = useUserDispatch();
  return fetch(url, args).then(response => {
  if (response.status === 401) {
    logout(dispatch);
  }
}
);

//auth.js
import React from "react";

var UserStateContext = React.createContext();
var UserDispatchContext = React.createContext();

function userReducer(state, action) {
  ...
}

function UserProvider({ children }) {
  var [state, dispatch] = React.useReducer(userReducer, {
    isAuthenticated: false,
  });

  return (
    <UserStateContext.Provider value={state}>
      <UserDispatchContext.Provider value={dispatch}>
        {children}
      </UserDispatchContext.Provider>
    </UserStateContext.Provider>
  );
}

function useUserState() {
  return React.useContext(UserStateContext);
}

function useUserDispatch() {
  return React.useContext(UserDispatchContext);
}

function signOut(dispatch) {
  dispatch({});
}

export { UserProvider, useUserState, useUserDispatch, loginUser, signOut };

</code>```

The client code above will produce error "Hooks can only be called inside of the body of a function component".
So maybe I have to move line var dispatch = useUserDispatch() upward to the component where request is called, and pass dispatch as props to request.
I feel this is not right, no only request is forced to care about some meaningless(to it) dispatch, but also this dispatch will spread everywhere a component needs to request.

For class-based components, this.state doesn't solve this problem either, but at least I can use mobx.

So are there some other ideal ways to solve this problem?

答:
Yes, you have to use Redux or MobX to solve this problem. You have to maintain isAuthenticated state in the global state of Redux or MobX. Then make an action that could be named like, toggleAuthState and pass is to the child component and toggle the state from there.

Also you can use functional components for this case. Class based components is not mandatory to use MobX or Redux. If you maintain a HOC as a Container then you can pass the actions and states to the child.

I am showing an example of using a container as a HOC:

// Container
import React from "react"
import * as actions from "../actions"
import ChildComponent from "../components/ChildComponent"
import { connect } from "react-redux"
import { bindActionCreators } from "redux"

const Container = props => <ChildComponent { ...props } />

const mapStateToProps = state => ({ ...state })

const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch)

export default connect(mapStateToProps, mapDispatchToProps)(Container)
```

Then in ChildComponent you can use your states and dispatch actions whenever you need.

Body:
I am new to React, and when I was reading about the docs, I found there were two ways to implement React components, functional-based and class-based. I know before React 16.8 it's not possible to manage state in functional components, but after that there is React Hooks.

The problem is, there seems to be one restriction for React Hooks, they can only be used inside functional components. Take a server-client as an example, which needs to change an isAuthenticated state while 401 received.

//client.js
import { useUserDispatch, signOut } from "auth";

export function request(url, args) {
  var dispatch = useUserDispatch();
  return fetch(url, args).then(response => {
  if (response.status === 401) {
    logout(dispatch);
  }
}
);

//auth.js
import React from "react";

var UserStateContext = React.createContext();
var UserDispatchContext = React.createContext();

function userReducer(state, action) {
  ...
}

function UserProvider({ children }) {
  var [state, dispatch] = React.useReducer(userReducer, {
    isAuthenticated: false,
  });

  return (
    <UserStateContext.Provider value={state}>
      <UserDispatchContext.Provider value={dispatch}>
        {children}
      </UserDispatchContext.Provider>
    </UserStateContext.Provider>
  );
}

function useUserState() {
  return React.useContext(UserStateContext);
}

function useUserDispatch() {
  return React.useContext(UserDispatchContext);
}

function signOut(dispatch) {
  dispatch({});
}

export { UserProvider, useUserState, useUserDispatch, loginUser, signOut };

The client code above will produce error "Hooks can only be called inside of the body of a function component".
So maybe I have to move line var dispatch = useUserDispatch() upward to the component where request is called, and pass dispatch as props to request.
I feel this is not right, no only request is forced to care about some meaningless(to it) dispatch, but also this dispatch will spread everywhere a component needs to request.

For class-based components, this.state doesn't solve this problem either, but at least I can use mobx.

So are there some other ideal ways to solve this problem?

Body:
Yes, you have to use Redux or MobX to solve this problem. You have to maintain isAuthenticated state in the global state of Redux or MobX. Then make an action that could be named like, toggleAuthState and pass is to the child component and toggle the state from there.

Also you can use functional components for this case. Class based components is not mandatory to use MobX or Redux. If you maintain a HOC as a Container then you can pass the actions and states to the child.

I am showing an example of using a container as a HOC:

// Container
import React from "react"
import * as actions from "../actions"
import ChildComponent from "../components/ChildComponent"
import { connect } from "react-redux"
import { bindActionCreators } from "redux"

const Container = props => <ChildComponent { ...props } />

const mapStateToProps = state => ({ ...state })

const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch)

export default connect(mapStateToProps, mapDispatchToProps)(Container)

Then in ChildComponent you can use your states and dispatch actions whenever you need.


问:
Task failed because "LC.exe" was not found, or the .NET Framework SDK v2.0 is not installed

Anyone have the same problem with me? With visual studio 2005.

Task failed because "LC.exe" was not found, or the .NET Framework SDK v2.0 is not installed.  The task is looking for "LC.exe" in the "bin" subdirectory beneath the location specified in the SDKInstallRootv2.0 value of the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework.  You may be able to solve the problem by doing one of the following:  1.) Install the .NET Framework SDK v2.0.  2.) Manually set the above registry key to the correct location.  3.) Pass the correct location into the "ToolPath" parameter of the task

I had done with below link but still don't work:

Task failed because "LC.exe" was not found after upgrade to Windows 8.1

And I downloaded the .net 2.0 sdk from https://www.microsoft.com/en-us/download/confirmation.aspx?id=1639 but can't install on windows 10

答: Ok I just fixed my issue by reinstalling VS2005. Thanks for viewing that</p>


问:
Change FAB background color with MotionLayout and MotionScene
I have a FloatingActionButton that I want to transition to another color with the use of MotionLayout and MotionScene.

This is my FAB in my layout file

```<code><androidx.constraintlayout.motion.widget.MotionLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/motion_layout"
        app:layoutDescription="@xml/map_activity_scene"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="75dp"
            android:layout_marginEnd="32dp"
            android:id="@+id/fab"
            android:visibility="invisible"
            app:backgroundTint="@color/lightPurple"
            app:srcCompat="@drawable/ic_layers_24px"
            app:tint="@color/white"
            app:layout_constraintBottom_toBottomOf="@+id/map"
            app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.motion.widget.MotionLayout>
</code>```

And this is my MotionScene

```<code><MotionScene xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:android="http://schemas.android.com/apk/res/android">
    <Transition
            app:constraintSetStart="@+id/start"
            app:constraintSetEnd="@+id/end"
            app:duration="400">

    </Transition>

    <ConstraintSet android:id="@+id/start">
        <Constraint
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="75dp"
                    android:layout_marginEnd="32dp"
                    android:id="@+id/fab"
                    android:visibility="visible"
                    app:backgroundTint="@color/lightPurple"
                    app:srcCompat="@drawable/ic_layers_24px"
                    app:tint="@color/white"
                    app:layout_constraintBottom_toBottomOf="@+id/map"
                    app:layout_constraintEnd_toEndOf="parent">

            <CustomAttribute
                app:attributeName="backgroundTint"
                app:customColorValue="@color/lightPurple" />
        </Constraint>

    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint
                android:id="@+id/fab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:visibility="visible"
                app:backgroundTint="@color/map_fab_transform"
                app:layout_constraintEnd_toEndOf="@+id/revealLayout"
                app:layout_constraintStart_toStartOf="@+id/revealLayout"
                app:layout_constraintBottom_toBottomOf="@+id/revealLayout"
                app:layout_constraintTop_toTopOf="@+id/revealLayout">

            <CustomAttribute
                app:attributeName="backgroundTint"
                app:customColorValue="@color/map_fab_transform" />
        </Constraint>
    </ConstraintSet>
</MotionScene>
</code>```

When I run the scene the fab moves to its correct place but the color does not change nor does the icon get removed from it. It seems that any of the app properties do not get applied.

How do I change to color of the fab and remove the icon in the fab with MotionLayout?

答:
```<code> app:backgroundTint="@color/lightPurple"
 app:srcCompat="@drawable/ic_layers_24px"
 app:tint="@color/white"
</code>```

<p>Constraint does not take any of these tags.
It only takes a limited set of tags
You will have to set those with custom attributes.
If you want MotionLayout to interpolate the custom attributes you must set them on start and end ConstraintSet. </p>

Body:
I have a FloatingActionButton that I want to transition to another color with the use of MotionLayout and MotionScene.

This is my FAB in my layout file

<androidx.constraintlayout.motion.widget.MotionLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/motion_layout"
        app:layoutDescription="@xml/map_activity_scene"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="75dp"
            android:layout_marginEnd="32dp"
            android:id="@+id/fab"
            android:visibility="invisible"
            app:backgroundTint="@color/lightPurple"
            app:srcCompat="@drawable/ic_layers_24px"
            app:tint="@color/white"
            app:layout_constraintBottom_toBottomOf="@+id/map"
            app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.motion.widget.MotionLayout>

And this is my MotionScene

<MotionScene xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:android="http://schemas.android.com/apk/res/android">
    <Transition
            app:constraintSetStart="@+id/start"
            app:constraintSetEnd="@+id/end"
            app:duration="400">

    </Transition>

    <ConstraintSet android:id="@+id/start">
        <Constraint
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="75dp"
                    android:layout_marginEnd="32dp"
                    android:id="@+id/fab"
                    android:visibility="visible"
                    app:backgroundTint="@color/lightPurple"
                    app:srcCompat="@drawable/ic_layers_24px"
                    app:tint="@color/white"
                    app:layout_constraintBottom_toBottomOf="@+id/map"
                    app:layout_constraintEnd_toEndOf="parent">

            <CustomAttribute
                app:attributeName="backgroundTint"
                app:customColorValue="@color/lightPurple" />
        </Constraint>

    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint
                android:id="@+id/fab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:visibility="visible"
                app:backgroundTint="@color/map_fab_transform"
                app:layout_constraintEnd_toEndOf="@+id/revealLayout"
                app:layout_constraintStart_toStartOf="@+id/revealLayout"
                app:layout_constraintBottom_toBottomOf="@+id/revealLayout"
                app:layout_constraintTop_toTopOf="@+id/revealLayout">

            <CustomAttribute
                app:attributeName="backgroundTint"
                app:customColorValue="@color/map_fab_transform" />
        </Constraint>
    </ConstraintSet>
</MotionScene>

When I run the scene the fab moves to its correct place but the color does not change nor does the icon get removed from it. It seems that any of the app properties do not get applied.

How do I change to color of the fab and remove the icon in the fab with MotionLayout?

Body:
 app:backgroundTint="@color/lightPurple"
 app:srcCompat="@drawable/ic_layers_24px"
 app:tint="@color/white"

Constraint does not take any of these tags.
It only takes a limited set of tags
You will have to set those with custom attributes.
If you want MotionLayout to interpolate the custom attributes you must set them on start and end ConstraintSet.


问:
Notification from IntentService - NullPointerException while obtaining Context
I am unable to generate the notification (in the notification area) from an IntentService. I get a NullPointerException while obtaining NotificationManager. The problem is with Context.

```<code>06-01 16:46:05.910: ERROR/AndroidRuntime(14745): Caused by: java.lang.NullPointerException
06-01 16:46:05.910: ERROR/AndroidRuntime(14745):     at android.content.ContextWrapper.getSystemService(ContextWrapper.java:363)
06-01 16:46:05.910: ERROR/AndroidRuntime(14745):     at com.Android.Main1.FileUploaderService.<init>(FileUploaderService.java:71)
</code>```

The line of code is:

```<code>mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
</code>```

I have tried getApplicationContext(), getBaseContext(), but to no avail.

Could someone please let me know what is the problem here? How do I generate notifications from an IntentService?

Additional Info:

I also have a Service in my app, and notifications from there work properly. The IntentService is not started by an Activity; it is started by the Service.

答:
Move your call to getSystemService out of the constructor and into onCreate.

The base Context in the ContextWrapper has not been set yet, which is causing the NullPointerException.

Body:
I am unable to generate the notification (in the notification area) from an IntentService. I get a NullPointerException while obtaining NotificationManager. The problem is with Context.

06-01 16:46:05.910: ERROR/AndroidRuntime(14745): Caused by: java.lang.NullPointerException
06-01 16:46:05.910: ERROR/AndroidRuntime(14745):     at android.content.ContextWrapper.getSystemService(ContextWrapper.java:363)
06-01 16:46:05.910: ERROR/AndroidRuntime(14745):     at com.Android.Main1.FileUploaderService.<init>(FileUploaderService.java:71)

The line of code is:

mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

I have tried getApplicationContext(), getBaseContext(), but to no avail.

Could someone please let me know what is the problem here? How do I generate notifications from an IntentService?

Additional Info:

I also have a Service in my app, and notifications from there work properly. The IntentService is not started by an Activity; it is started by the Service.


问:
How to access csv file and insert data into csv
I am trying to insert data into csv file. I tried using XLWorkbook reference to access and insert data but I know that XLWorkbook can only support extension which are xlsx,xslm,xltx and xltm.

I am trying to find something similar to what I am trying to achieve through which I can insert data into specified column in csv file. I have used XLWorkbook for some other purpose but I am not aware to what I can use when I have to use csv.

```<code>//Accessing the csv file where I am trying to insert data.
string rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
string filelocation = @"\csv\TestData.csv";
string location = rootPath + filelocation;

XLWorkbook workbook = new XLWorkbook(pathfile);
IXLWorksheet worksheet = workbook.Worksheet("Sheet1");
//Insert data after first row as first row contains column header
int lastrow = worksheet.LastRowUsed().RowNumber() + 1;

//through previous function I am trying get data from database and insert those data into csv cells
worksheet.Cell(String.Format("B{0}", lastrow)).Value = dummydata.FirstName;
worksheet.Cell(String.Format("C{0}", lastrow)).Value = dummydata.LastName;
worksheet.Cell(String.Format("D{0}", lastrow)).Value = dummydata.Address1;
worksheet.Cell(String.Format("E{0}", lastrow)).Value = dummydata.Address2;
worksheet.Cell(String.Format("F{0}", lastrow)).Value = dummydata.City;
worksheet.Cell(String.Format("G{0}", lastrow)).Value = dummydata.StateProvinceCode;
worksheet.Cell(String.Format("H{0}", lastrow)).Value = dummydata.ZipCode;
worksheet.Cell(String.Format("I{0}", lastrow)).Value = dummydata.Country;
worksheet.Cell(String.Format("J{0}", lastrow)).Value = dummydata.HomePhone;
worksheet.Cell(String.Format("L{0}", lastrow)).Value = dummydata.HomePhone;
worksheet.Cell(String.Format("M{0}", lastrow)).Value = dummydata.CellPhone;
worksheet.Cell(String.Format("T{0}", lastrow)).Value = dummydata.Email;
worksheet.Cell(String.Format("U{0}", lastrow)).Value = dummydata.Country;

//After inserting save the file
workbook.Save();
</code>```

答:
You can simply copy and use this code as is. It should resolve your issues.

Here's the class I developed to replace and/or add csv cells:

```<code>using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CSVManager
{
    public class CSVWorker
    {
        private string m_FileName = string.Empty;

    public CSVWorker(string fileName)
    {
        m_FileName = fileName;
    }

    public void AddCells(int row, int column, string newValue)
    {
        var encoding = Encoding.GetEncoding("iso-8859-1");
        var csvLines = File.ReadAllLines(m_FileName, encoding);

        if (row < csvLines.Length)
        {
            ReplaceCells(row, column, newValue);
        }
        else
        {
            using (FileStream stream = new FileStream(m_FileName, FileMode.Create))
            {
                using (StreamWriter writer = new StreamWriter(stream, encoding))
                {
                    foreach (var line in csvLines)
                    {
                        writer.WriteLine(line);
                    }

                    int blankLines = row - csvLines.Length - 1;

                    for (int i =  0; i < blankLines; i++)
                    {
                        writer.WriteLine("");
                    }

                    string blankCols = string.Empty;

                    for (int i = 0; i < column-1; i++)
                    {
                        blankCols += ',';
                    }

                    writer.WriteLine(blankCols + newValue);
                }
            }
        }
    }

    public void ReplaceCells(int row, int column, string newValue)
    {
        var encoding = Encoding.GetEncoding("iso-8859-1");
        var csvLines = File.ReadAllLines(m_FileName, encoding);

        for (int i = 0; i < csvLines.Length; i++)
        {
            //var values = csvLines[i].Split(',');
            List <string> values = csvLines[i].Split(',').ToList();

            if (i == row)
            {
                if (column < values.Count)
                {
                    values[column] = newValue;
                }
                else
                {
                    while (values.Count < column - 1)
                    {
                        values.Append(",");
                    }

                    values.Append(newValue);
                }

                using (FileStream stream = new FileStream(m_FileName, FileMode.Create))
                {
                    using (StreamWriter writer = new StreamWriter(stream, encoding))
                    {
                        for (int currentLine = 0; currentLine < csvLines.Length; ++currentLine)
                        {
                            if (currentLine == i)
                            {
                                writer.WriteLine(string.Join(",", values));
                            }
                            else
                            {
                                writer.WriteLine(csvLines[currentLine]);
                            }
                        }

                        writer.Close();
                    }

                    stream.Close();
                    break;
                }
            }
        }
    }
  }
}
</code>```

Here's how I used it:

```<code>namespace CSVManager
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"C:\Users\mklig\Documents\TestCsv.csv";
            CSVWorker csvWorker = new CSVWorker(fileName);

            int row = 4;
            int col = 4;
            string newVal = "success";
            //csvWorker.ReplaceCells(row, col, newVal);
            csvWorker.AddCells(row, col, newVal);

         }
    }
}
</code>```

Body:
I am trying to insert data into csv file. I tried using XLWorkbook reference to access and insert data but I know that XLWorkbook can only support extension which are xlsx,xslm,xltx and xltm.

I am trying to find something similar to what I am trying to achieve through which I can insert data into specified column in csv file. I have used XLWorkbook for some other purpose but I am not aware to what I can use when I have to use csv.

//Accessing the csv file where I am trying to insert data.
string rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
string filelocation = @"\csv\TestData.csv";
string location = rootPath + filelocation;

XLWorkbook workbook = new XLWorkbook(pathfile);
IXLWorksheet worksheet = workbook.Worksheet("Sheet1");
//Insert data after first row as first row contains column header
int lastrow = worksheet.LastRowUsed().RowNumber() + 1;

//through previous function I am trying get data from database and insert those data into csv cells
worksheet.Cell(String.Format("B{0}", lastrow)).Value = dummydata.FirstName;
worksheet.Cell(String.Format("C{0}", lastrow)).Value = dummydata.LastName;
worksheet.Cell(String.Format("D{0}", lastrow)).Value = dummydata.Address1;
worksheet.Cell(String.Format("E{0}", lastrow)).Value = dummydata.Address2;
worksheet.Cell(String.Format("F{0}", lastrow)).Value = dummydata.City;
worksheet.Cell(String.Format("G{0}", lastrow)).Value = dummydata.StateProvinceCode;
worksheet.Cell(String.Format("H{0}", lastrow)).Value = dummydata.ZipCode;
worksheet.Cell(String.Format("I{0}", lastrow)).Value = dummydata.Country;
worksheet.Cell(String.Format("J{0}", lastrow)).Value = dummydata.HomePhone;
worksheet.Cell(String.Format("L{0}", lastrow)).Value = dummydata.HomePhone;
worksheet.Cell(String.Format("M{0}", lastrow)).Value = dummydata.CellPhone;
worksheet.Cell(String.Format("T{0}", lastrow)).Value = dummydata.Email;
worksheet.Cell(String.Format("U{0}", lastrow)).Value = dummydata.Country;

//After inserting save the file
workbook.Save();

Body:
You can simply copy and use this code as is. It should resolve your issues.

Here's the class I developed to replace and/or add csv cells:

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CSVManager
{
    public class CSVWorker
    {
        private string m_FileName = string.Empty;

    public CSVWorker(string fileName)
    {
        m_FileName = fileName;
    }

    public void AddCells(int row, int column, string newValue)
    {
        var encoding = Encoding.GetEncoding("iso-8859-1");
        var csvLines = File.ReadAllLines(m_FileName, encoding);

        if (row < csvLines.Length)
        {
            ReplaceCells(row, column, newValue);
        }
        else
        {
            using (FileStream stream = new FileStream(m_FileName, FileMode.Create))
            {
                using (StreamWriter writer = new StreamWriter(stream, encoding))
                {
                    foreach (var line in csvLines)
                    {
                        writer.WriteLine(line);
                    }

                    int blankLines = row - csvLines.Length - 1;

                    for (int i =  0; i < blankLines; i++)
                    {
                        writer.WriteLine("");
                    }

                    string blankCols = string.Empty;

                    for (int i = 0; i < column-1; i++)
                    {
                        blankCols += ',';
                    }

                    writer.WriteLine(blankCols + newValue);
                }
            }
        }
    }

    public void ReplaceCells(int row, int column, string newValue)
    {
        var encoding = Encoding.GetEncoding("iso-8859-1");
        var csvLines = File.ReadAllLines(m_FileName, encoding);

        for (int i = 0; i < csvLines.Length; i++)
        {
            //var values = csvLines[i].Split(',');
            List <string> values = csvLines[i].Split(',').ToList();

            if (i == row)
            {
                if (column < values.Count)
                {
                    values[column] = newValue;
                }
                else
                {
                    while (values.Count < column - 1)
                    {
                        values.Append(",");
                    }

                    values.Append(newValue);
                }

                using (FileStream stream = new FileStream(m_FileName, FileMode.Create))
                {
                    using (StreamWriter writer = new StreamWriter(stream, encoding))
                    {
                        for (int currentLine = 0; currentLine < csvLines.Length; ++currentLine)
                        {
                            if (currentLine == i)
                            {
                                writer.WriteLine(string.Join(",", values));
                            }
                            else
                            {
                                writer.WriteLine(csvLines[currentLine]);
                            }
                        }

                        writer.Close();
                    }

                    stream.Close();
                    break;
                }
            }
        }
    }
  }
}

Here's how I used it:

namespace CSVManager
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"C:\Users\mklig\Documents\TestCsv.csv";
            CSVWorker csvWorker = new CSVWorker(fileName);

            int row = 4;
            int col = 4;
            string newVal = "success";
            //csvWorker.ReplaceCells(row, col, newVal);
            csvWorker.AddCells(row, col, newVal);

         }
    }
}


问:
Error:Exception: You do not have permission to call Session.getActiveUser. Required permissions: https://www.googleapis.com/auth/userinfo.email
I recently migrated one of my projects to the new V8 engine of appscript.I am getting this exception

Exception: You do not have permission to call Session.getActiveUser.
  Required permissions:
  https://www.googleapis.com/auth/userinfo.email..Session.getActiveUser
  is not accessible without permission

Any ideas would be appreciated

答:
As stated by @Raserhin, there's an open issue with google and the problem seems to be with the new App Script runtime powered by Chrome v8.

A small workaround (until the issue is resolved) will be to disable the App Script runtime as follows: (Run -> Disable App Script runtime powered by Chrome V8). The project will now run with Apps Script Legacy which does not have this issue.