How do I use For Loop twice to find datatable columns and rows?

Question: I want to use for loop to get average of datatable columns and rows. What I want to do is that what if there are 100 ~ 1000 columns and rows, I can't keep on adding them in the code. is there one simple code that can get average of automatically as I add columns and rows?
here is my code, I am stuck I don't know what to write in ?? area below and this code gets me error please help...
private void button1_Click(object sender, EventArgs e)
    {
        DataTable dtGrid = gridData.DataSource as DataTable;
        DataTable dtResult = new DataTable();
        Math columnIndex = new Math();

        List<double> avgList = new List<double>();

        for (int i = 0; i < dtGrid.Columns.Count; i++)
        {

            for (int k = 1; k < dtGrid.Rows.Count; k++)
            {
                // ??
                avgList.Add(Convert.ToDouble(dtGrid.Rows[i].ToString()));
            }

        }
        //this is from other class name Math
        /* public double getAverageValue(List<double> avgList)
        {
            double averageList = 0;

            averageList = MathNet.Numerics.Statistics.Statistics.Mean(avgList.ToList());

            return averageList;
        }*/
        double averageX1 = columnIndex.getAverageValue(avgList);

        List<Math> list = new List<Math>();

        //using get; set from other class
        list.Add(new Math { Result = "Average", X1 = averageX1.ToString() });

        gridData2.DataSource = list;
    }
}

}
Comment: It's unclear what you are asking. What is your question exactly? Do you want to calculate Average of values of a column? Or do you want to calculate Average of values of all cells together? Or something else?
Comment: I want to average up each columns not caulculate them into one. so if I have 10 columns I want to have them show individually. so 10 answer show be show up. I have checkboxes in each of first rows so I need to average up from row 1 instead of 0 thats why I need to use for loop not foreach loop
Answer: It looks like your loop is inside out.  Try this:
DataTable dtGrid = gridData.DataSource as DataTable;
DataTable dtResult = new DataTable();
Math columnIndex = new Math();

List<double> avgList = new List<double>();
for (int k = 1; k < dtGrid.Rows.Count; k++)
{
    for (int i = 0; i < dtGrid.Columns.Count; i++)
    {
        // ??
        avgList.Add(Convert.ToDouble(dtGrid.Rows[k].Columns[i].ToString()));
    }
}

This logic averages all columns in a row together.  If you need,, you can create a Dictionary and average each column separately.  Something like thisL
Dictionary<int, List<double>> AvgColumnList = new Dictionary<int, System.Collections.Generic.List<double>>();

This uses a dictionary that contains a list for each column in the row.  If there are 100 columns, then there will be 100 entries in the dictionary with index 0 - 99.  Each dictionary item will contain a list of doubles.
for (int k = 1; k < dtGrid.Rows.Count; k++)
{
    for (int i = 0; i < dtGrid.Columns.Count; i++)
    {
        if (!AvgColumnList.Keys.Contains(i))
            AvgColumnList.Add(i, new List<double>());

        AvgColumnList[i].Add(Convert.ToDouble(dtGrid.Rows[k].Columns[i].ToString()));
    }
}

Comment: Thank you for your answer, but I am trying to use for loop because I have check boxes in first rows, right below headers columns. so that I need to average up from the second rows instead of zero .
for example for(int i = 1; i < dtGrid.Rows.Count; i++ ) if I use foreach loop I can't control which rows to start. sorry that I didn't mentioned it earlier.. are you able to show me in for loop too?
Comment: Thank you!! it helps but my columns[i] get error so I used avgList.Add(Convert.ToDouble(dtGrid.Rows[k][i].ToString()));

um.. 1 more question. with this I only get 1 column result, what if I have 100 of columns to calculate? I can't keep on adding avglist1, avglist2, is there a way to calculate many columns individually? with 1 avgList in seperate columns?
Answer: DataTable is zero index based, in your code row count started from 1 it should be 0, also dtGrid.Rows[i] is a row not the cell value. Use below code to loop through each cell of a DataTable
Update : Code updated as OP want to save each column data separately and irrespective of column numbers.
 List<List<double>> perColumnAvg = new List<List<double>>();

 for (int i = 0; i < dtGrid.Columns.Count; i++)
 {
     avgList = new List<double>();
     for (int k = 0; k < dtGrid.Rows.Count; k++)
     {
         // ??
         avgList.Add(Convert.ToDouble(dtGrid.Rows[k][i].ToString()));
     }
     perColumnAvg.Add(avgList);
 }

Now you can compute individual column average as
foreach (var columnList in perColumnAvg)
{
    // place your logic here.
    columnIndex.getAverageValue(columnList);
}

And can compute avg across table using.
double tableAvg = columnIndex.getAverageValue(perColumnAvg.SelectMany(s=>s));

Comment: Thank you!! this help but I have 1 more question, with this I only get 1 column result, what if I have 100 of columns to calculate? I can't keep on adding avglist1, avglist2, is there a way to calculate many columns individually? with 1 avgList in seperate columns?
Comment: We can do that, it's very easy.
Comment: Define `List` and store individual column values.


How to recover keys

Question: I recently did a fresh installation of Ubuntu 20.04 on my workstation. I made a complete backup of my home directory, and have been pulling out the bits that I need. I had set up a signing key for my git commits, and failed to export it before the reinstallation. Of course, the file are still in ~/.gnupg. I'm not exactly sure of the structure in this directory, such as where the public and private keys are, and if just moving them over is sufficient. I'm worried about doing something stupid and messing up my existing installation.
Answer: First of all copying over ~/.gnupg to a new machine should be fine and working. See Moving/Copying your PGP Keys as reference.
Accordingly to the git documentation Git - Signing Your Work you should be able to see your existing key via:
gpg --list-keys

Your existing key should be listed there.
If it is check git repo or global configuration if and what key is currently set:

for "repo only" configuration (you have to be within your repo directory):
git config user.signingkey

global:
git config --global user.signingkey

If key from gpg --list-keys command and git config match you should be fine.
If git user.signingkey config is empty set it with
git config --global user.signingkey 0A46826A

where "0A46826A" should be your existing key hash.

How to recover keys


Laravel 8 vue 2 "npm run watch" giving `mix watch` error. Can anyone help please?

Question: node v 14.16.0
npm v 6.14.11

@ watch E:\xampp\htdocs
mix watch

E:\xampp\htdocs\node_modules\webpack\lib\NormalModule.js:181
throw new TypeError(
^
TypeError: The 'compilation' argument must be an instance of Compilation
at Function.getCompilationHooks (E:\xampp\htdocs\node_modules\webpack\lib\NormalModule.js:181:10)
at E:\xampp\htdocs\node_modules\vue-loader\lib\plugin-webpack5.js:36:70
at Hook.eval [as call] (eval at create (E:\XAMPP\htdocs\node_modules\tapable\lib\HookCodeFactory.js:19:10), :206:1)
at Hook.CALL_DELEGATE [as _call] (E:\XAMPP\htdocs\node_modules\tapable\lib\Hook.js:14:14)
at Compiler.newCompilation (E:\XAMPP\htdocs\node_modules\webpack\lib\Compiler.js:1017:26)
at E:\XAMPP\htdocs\node_modules\webpack\lib\Compiler.js:1059:29
at Hook.eval [as callAsync] (eval at create (E:\XAMPP\htdocs\node_modules\tapable\lib\HookCodeFactory.js:33:10), :22:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (E:\XAMPP\htdocs\node_modules\tapable\lib\Hook.js:18:14)
at Compiler.compile (E:\XAMPP\htdocs\node_modules\webpack\lib\Compiler.js:1054:28)
at E:\XAMPP\htdocs\node_modules\webpack\lib\Watching.js:134:19
at Hook.eval [as callAsync] (eval at create (E:\XAMPP\htdocs\node_modules\tapable\lib\HookCodeFactory.js:33:10), :22:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync]   (E:\XAMPP\htdocs\node_modules\tapable\lib\Hook.js:18:14)
at run (E:\XAMPP\htdocs\node_modules\webpack\lib\Watching.js:88:33)
at E:\XAMPP\htdocs\node_modules\webpack\lib\Watching.js:83:6
at Compiler.readRecords (E:\XAMPP\htdocs\node_modules\webpack\lib\Compiler.js:894:11)
at run (E:\XAMPP\htdocs\node_modules\webpack\lib\Watching.js:79:26)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ watch: mix watch
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ watch script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
package.json
{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "prod": "npm run production",
        "production": "mix --production"
    },
    "devDependencies": {
        "axios": "^0.21",
        "laravel-mix": "^6.0.18",
        "lodash": "^4.17.19",
        "postcss": "^8.2.12",
        "vue-loader": "^15.9.5",
        "vue-template-compiler": "^2.6.12"
    },
    "dependencies": {
        "vue": "^2.6.12",
        "vue-axios": "^3.2.4",
        "vue-router": "^3.5.1"
    }
}

PS E:\xampp\htdocs> npm install
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: firstname.lastname@example.com (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for firstname.lastname@example.com: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: email@example.com (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for firstname.lastname@example.com: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
It was working before when I tried
npm cache clean --force
but now giving same error. I also tried
npm install webpack
It updated 1 package but still not working. I'm using win 10 64bit.
Deleted node_modules folder, reinstalled nodejs and npm. Nothing worked.
Don't want to delete package-lock.json. Thanks.
Comment: It would be helpful if you pasted the error as text, instead of an image link, so that people can find this post by searching by the error.

(Rock over London, rock on Chicago)
Answer: I was facing this issue and was able to fix it by reinstalling node.js or run the node setup and choose repair, it seems that it's a problem related to npm itself


Allocate total amount to a column using cumulative sum, up to another column's limit

Question: Background: I am having a list of several hundred departments that I would like to allocate budget as follow:

Each DEPT has an AMT_TOTAL budget within given number of months. They also have a monthly limit LIMIT_MONTH that they cannot exceed.
As each DEPT plans to spend their budget as fast as possible, we assume they will spend up to their monthly limit until AMT_TOTAL runs out. The amount be forecast they will spend, given this assumption, is in AMT_ALLOC_MONTH

My objective is to calculate the AMT_ALLOC_MONTH column, given the LIMIT_MONTH and AMT_TOTAL column. Based on what I've read and searched, I believe a combination of fillna and cumsum() can do the job. So far, the Python dataframe I've managed to generate is as followed:

I planned to fill the NaN using the following line:
table['AMT_ALLOC_MONTH'] = min((table['AMT_TOTAL'] - table.groupby('DEPT')['AMT_ALLOC_MONTH'].cumsum()).ffill, table['LIMIT_MONTH'])

My objective is to have the AMT_TOTAL minus the cumulative sum of AMT_ALLOC_MONTH (excluding the NaN values), grouped by DEPT; the result is then compared with value in column LIMIT_MONTH, and the smaller value is filled in the NaN cells. The process is repeated till all NaN cells of each DEPT is filled.
Needless to say, the result did not come up as I expected; the code line only works with the 1st NaN after the cell with value; subsequent NaN cells just copy the value above it. If there is a way to fix the issue, or a new & more intuitive way to do this, please help. Truly appreciated!
Answer: Try this:
for department in table['DEPT'].unique():
    subset = table[table['DEPT'] == department]
    for index, row in subset.iterrows():
        subset = table[table['DEPT'] == department]
        cumsum = subset.loc[:index-1, 'AMT_ALLOC_MONTH'].sum()
        limit = row['LIMIT_MONTH']
        remaining = row['AMT_TOTAL'] - cumsum
        table.at[index, 'AMT_ALLOC_MONTH'] = min(remaining, limit)

It't not very elegant I guess, but it seems to work..
Comment: Thanks for your answer, although I was looking for a more panda/numpy-based, more efficient method than looping through rows, given data size of ~1 million rows.


IE < 9 CSS3 Transition Effect Cheats?

Question: Are there any "cheat" mechanisms similar to IE7.js available for browsers that do not support CSS3 transitions so that if you insert CSS3 transition elements into pages it will translate them to javascript methods?
Answer: Sure, there are a couple:

http://louisremi.github.com/jquery.transition.js/test/index.html
http://playground.benbarnett.net/jquery-animate-enhanced/

IE < 9 CSS3 Transition Effect Cheats?


Which foundation type for conservatory?

Question: I live in a new property where due to the underlying characteristics of the land, piling was required for the foundations.
Due to the additional cost, I'd like to explore what options for extension or conservatory I might have that do not require additional piling.
Does anyone know if there are regs relating to size, load or construction that might determine whether I have to pile or not?
Thanks
Comment: You've left out far too many factors to even hazard a guess.
Answer: The Code says the foundation need to be "adequate" for all loads.
Most people think of vertical loads, but there are horizontal loads, freeze/thaw loads, etc.
I too live where the ground is mush. Usually we install piling, caissons, etc. However, in certain situations we install a "floating slab".
This system is a structural slab (with reinforcing steel) with edges that turn down about 12" at the edges. (We don't have a frost freeze/thaw issue here. If you do, you may want to extend it somewhat.) We install about double the amount of reinforcing steel than we use in stem walls.
We use this system for small, simple, fairly symmetrical buildings...which sounds like your project.
You'll have one additional issue of where it connects into your existing house. Because your house is on piling, it will not move (settle) over time. Therefore, I'd recommend the structure be a few feet from your existing house where you can plan for a few inches of settlement. The connection space between the two structures can fasten (rest on) on both structures and flex when the conservatory settles slightly.
In fact, installing augured piling, hammered piling, etc. next to your home may cause significant damage (cracking plaster, cracking windows, etc.)
Any plumbing or electrical supply lines should have blockouts through the slab so it's flexible.
Because of all that glass in your conservatory and you don't want any differential settlement in the walls, I'd recommend you design the perimeter foundation as a concrete beam. You'll probably need an architect or structural engineer (not a civil engineer) to help you.
Comment: Lee Sam, thanks for the answer. There are clearly many factors involved and much to look into with the help of a structural engineer, but at least the details you've offered give me the confidence to pursue it. If the answer had been that if the house is piled, then you'll need to pile, then I might be deterred from doing the project. Thanks again.
Comment: Remember, all buildings settle. Just make sure it settles uniformly and allow for a little compared to your existing structure.

Which foundation type for conservatory?


Apply different css styling to words next to each other

Question: I want to put different words together in a
, and each word has a different font-size and a different CSS styling.
I can manage the different font-sizes, but somehow the words are ordered in a list with line-height. This I do not want.
This is my code:

more hungry?

want a drink too?

have it with natural flavour?

eat atleast 2 pieces of fruit?

a snack every hour?

Answer: They're on seperate lines because
 are block line elements.
One solution would be to change the style of those
 elements to inline-block:
p {
  display:inline-block;
}

(You should probably give all
 elements you want to target a common class and use that as the selector instead, as the above targets all
's).
Or just use  elements instead (they're inline by default):
more hungry?want a drink too?have it with natural flavour?eat atleast 2 pieces of fruit?a snack every hour?

Note though that inline CSS is generally not advised - you should use an external style sheet instead.
Answer: Why not wrap the whole section in a
 tag and then use a create a span for each different style you'd like to have? This would be a lot of spans with classes, though it seems to be a fairly common way that folks do this.
Here's a possibility (utilizing the "best practice" of separating content and style):

More hungry? want a drink too? have it with natural flavour? eat at least 2 pieces of fruit? a snack every hour?

I'd recommend naming the span classes to something that was a bit more descriptive. But this should do the trick, depending on the particular use you have in mind.


Azure Search - query within a specific field using the .Net SDK

Question: We are attempting to build our API for our Azure Search index using the .Net SDK for Azure Search.  We are trying to write the equivalent code for the searchFields parameter of the query found in the Rest API syntax for Azure Search (found via this thread: Azure Search; Search inside a specific field)
After lengthy research, there doesn't seem to be any such equivalent to use in the .Net SDK when we want to query on a specific field of our Azure Search index.  Could this possibly be the case?
Answer: I believe you're looking for this.
Comment: Bruce, you're always a great help.  Thanks.


Run time to Theta Notation

Question: After looking at the code:
for(i=n-1; i>=0; i-=2)
   for(j=15; j<100; j+=3)
      sum +=i+j

I would say that the run time for this in terms of Theta Notation to be Θ(n^2), as for there are two loops and const (i and j). Would this be correct?
Comment: Having two loops doesn't automatically mean that it is O(n^2). Look at the inner loop condition again - does it depend on anything else?
Answer: I'll put in another plug for that old asymptotic maxim of

"When in doubt, work inside-out!"

Let's take another look at that code:
for(i=n-1; i>=0; i-=2)
   for(j=15; j<100; j+=3)
      sum +=i+j;

Let's begin with the innermost statement, the one that adds into the variable sum. That statement's runtime is independent of any of the other variables here, so it does Θ(1) work. So let's rewrite the code like this:
for(i=n-1; i>=0; i-=2)
   for(j=15; j<100; j+=3)
      do Theta(1) work

Now, let's look at that inner for loop. Notice that this loop always runs the exact same number of times (around 30ish), regardless of the values of the other variables. That means that this loop runs a constant number of times and does a constant amount of work, and so the net effect of that loop is to do Θ(1) work. This is shown here:
for(i=n-1; i>=0; i-=2)
    do Theta(1) work

So now we're left this this final loop. Here, we see that the work done depends directly and linearly on n. Specifically, this loop does Θ(n) iterations and does Θ(1) work per iteration, and so the total work done is Θ(n).
Notice that it's not the number of for loops that determines the runtime, but rather what those loops are doing. Counting the number of loops is a good way to get a rough estimate for the runtime, but the approach I illustrated above of working from the inside outward is more precise.

Run time to Theta Notation


How to insert data in 4 tables with one form

Question: I am having trouble inserting into multiple tables using a single form in a news project.
insert into news JOIN news2 JOIN news3 JOIN news4(title,image,news,descn,category) values('$title','$image','$news','$descn','$category')

Comment: Please give us more details. Read: [How to ask](https://stackoverflow.com/help/how-to-ask)
Comment: why do you apparently have 4 news tables with the same structure? And you want to insert the same record into all of them? Why on earth would you copy the same data 4 times? It makes no sense (quite apart from the fact that this syntax is not allowed anyway).
Answer: That's not possible. INSERT statements always just use one table. If you want to insert into multiple tables and make sure that all inserts are considered as one atomic operation, use transactions. Like this:
START TRANSACTION;
INSERT INTO x VALUES ...
INSERT INTO y VALUES ...
INSERT INTO z VALUES ...
COMMIT;

When an error happens, you do ROLLBACK; instead of a commit and all statements of that transaction are undone.
On another note, when you have tables like news, news2, news3 and so on, this smells like bad database design. You should seriously reconsider that, as the goal of a relational database used for transactional workload usually is to avoid redundant data. To achieve this normalization is used. Here's a link to a tutorial. (I haven't read it, but after a quick glance after googling it looks promising)
Another note: When you join tables, provide a join condition. Otherwise you get every row of one table combined with every row from every other table, which can be a HUGE resultset. You usually don't want that. Consider reading a tutorial about SQL as well.


iOS Date Formatting without year, with correct localization

Question: Do you know how I could have the following date string Jun 28 on iOS?

Jun 28 in English
28 juin in French
etc

I want basically short month, day, without year. (in the localized order, so day, month in French for instance)
I tried the following:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd"
let dateStr = dateFormatter.string(from: Date())
print(dateStr) // --> Jun 28

It works in English but not in other languages.
For instance if you set
dateFormatter.locale = Locale(identifier: "fr")
It should output 28 juin but it returns juin 28.
I also tried to use:
let date = Date()
let customFormat = "MMM dd"
let frLocale = Locale(identifier: "fr_FR")
let frFormat = DateFormatter.dateFormat(fromTemplate: customFormat, options: 0, locale: frLocale)
let formatter = DateFormatter()
formatter.dateFormat = frFormat
let dateStr = formatter.string(from: date)
print(dateStr) // -> 28 Jun

^__ the order is correct but the month is in English.
What is the closest is:
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = .medium
let dateStr = dateFormatter.string(from: Date())
print(dateStr) // --> Jun 28, 2020

^__ but I don't want the year.
Answer: I believe this part of the documentation is the key (I mean if I was just to re-set the locale on the formatter without setting again the template, I would get what you describe in the first case):
func setLocalizedDateFormatFromTemplate(String)

Important: You should call this method only after setting the locale of
the receiver.

and sure enough, when you do this, you get correct formatting:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.setLocalizedDateFormatFromTemplate("MMM dd")
print(dateFormatter.string(from: Date())) // --> Jun 28

dateFormatter.locale = Locale(identifier: "fr_FR")
dateFormatter.setLocalizedDateFormatFromTemplate("MMM dd")
print(dateFormatter.string(from: Date())) // --> 28 juin

By the way, there is a really good session about formatters in WWDC'20


How to mapped my query for recieving the data?

Question: I send a Get Postman request and i am receiving status 200. The problem is that I don't get any data about it, it gives me only : [] .
Probably my error is that I don't map the constructor for the DTO class I made.
As another option I guess I have to make a projection or something similar to this, can anyone explain to me how to map the constructor and give me the data I want? I'm so messed up and dealing with this error for 2 hours and nothing.
Repository:
@Repository
public interface ManagementRepository extends JpaRepository<Management,Long>,ManagementRepositoryCustom {

    @Query(value = "SELECT wm.action_description " +
            "FROM testdb.warehouse_management wm " +
            "WHERE wm.action_description = :action_description ", nativeQuery = true)
    List<StockRecoveryDTO> findByDog(@Param("action_description") String action_description);

}

DTO:
package com.example.dto;

public class StockRecoveryDTO {

    private Long id_product;
    private String date;
    private int quantity_product;
    private String action_description;
    private Long id_action;
    private String quantity;

    public StockRecoveryDTO() {

    }

    public StockRecoveryDTO(Long id_product, String date, int quantity_product, String action_description, Long id_action, String quantity) {
        this.id_product = id_product;
        this.date = date;
        this.quantity_product = quantity_product;
        this.action_description = action_description;
        this.id_action = id_action;
        this.quantity = quantity;
    }
//GETTER SETTER

Console:
Hibernate: SELECT wm.action_description FROM testdb.warehouse_management wm WHERE wm.action_description = ?

Answer: That native query you are return only action_description so change the return type to List<String>.


Should I use SER or URD cable for a 100 amp sub-panel?

Question: I am running a new line from my main panel on the pole out to a sub panel in my shop. The sub panel will be 100amp. I have a 180' run and have buried 1-1/2" sch40 conduit. I'm planning on using 1/O alum wire, but can't figure out if I need to use "SER" cable ( looks like it comes with a ground) or "URD" and use a additional wire for the ground?
If I use the "URD"... what size & type of wire do I need to use for the ground?
Is THHN good enough or do I have to use XHHW ?
Comment: Neither of those is wires, they are cables.  Cables are multiple wires (usually) inside a sheath. They are a royal PITA to pull through conduit, for the same reason four 2x4's glue-laminated are much stiffer than four 2x4's unglued.
Answer: SER cable isn't legal underground, so cross that off the list.
URD also called Mobile Home feeder, comes in 3-wire or 4-wire, so it's an option.  It's legal for direct burial underground, but not for use indoors without conduit as if it was Romex or something.
So the real question is, what happens at the ends of the conduit?  Does the conduit go straight into the panels at both ends? Or does it just sorta end, and then ??? to get over to the panel?   I do not recommend the latter, as that ??? can get rather messy with wires this large.
If it's conduit all the way
Then don't use cable.  Because the wires are bound to each other, cable is excessively stiff and a real pain to "pull".   You can buy individual wires, either THWN or XHHW.  (All THWN is dual-rated THHN).  You simply buy three full-size wires for hots and neutral, and one appropriately ground-sized wire for the ground.
Note that URD is simply THHN or XHHW wires glued together.  If your conduit is continuous, then gluing the wires together is bad, and works against you.  Get the wires individually.
You need #1 Al. Do you need a wire size bump?
Voltage drop is proportional to actual load, and cannot see the number on the breaker handle. Therefore we do not calculate voltage drop based on breaker trip.  We calculate it based on the actual, expected, or permitted load on the wires.  For instance you're only allowed to plan for 80A on a 100A circuit, so you'd never, ever calculate voltage drop based on 100A. Never!
At less than 180', I don't even bother crunching the numbers to see if a wire size bump is worthwhile. It's not.  So you're right on the cusp. Anyway, we don't do wire size bumps for distance. We do them for distance and load. So let me ask - how much thinking did you do about loads?

Did you sort-of "arm-wave it" like "meh, everybody gets 100A, it's a common size"?  Or
was there a gory-details load calc like "47A compressor, 23A plasma cutter, blah blah, need to provision 93A" sort of thing?

In short, if it's the second one, and you're close, I'd do the bump to 1/0 Al wire.  Otherwise fuggedaboutit, just stick with #1 Al.
If you bump hots, bump ground too..   #1 Al maxes out at 100A, and that means a #8Cu / #6Al ground is sufficient.  However, if you do a wire size bump to 1/0, that maxes out at 125A, and that means you MUST have a #6Cu/#4Al ground.  When you bump the hots, bumping the ground also is mandatory per Code.  That's because ground wires have voltage drop too, and theirs is worse, because they only carry fault current!
Don't "Nanny Breaker" yourself.  If you decide on a wire size bump to 1/0 AL, you might as well use the 125A breaker that you are entitled to.  That way, you can the entire 125A of your feeder on the occasions when you do need it and are willing to "endure" the "scary, terrible" 3.7% voltage drop, woo woo.  You don't need a "100A nanny breaker" to protect yourself from voltage drop.  Unless you are in Canada, because they say you do.
Did we mention BIG panel?  Buying extra spaces at install time is extremely cheap. Adding spaces after you run out is extremely expensive.  As such, we really like to see people splurge on excessively sized panels (in terms of numbers of spaces).  If a 125A feed breaker seems like a buzzkill because your panel is only 100A, that implies a too-small panel. Take it out and swap it now, while it's still super easy to do.  That's one mistake NOT to double-down on.
Comment: If the 100 amp breaker is rated 100% like square d you could rate that at 100 amps , but it would be rare to use that much.
Comment: @EdBeal -- no, 100%-rated breakers are only really seen in industrial work
Answer: Much of what is sold as "THHN" is actually "XHHW2", but yes you need "XHHW" or "XHHW2" if it's going under the ground.
You'll need both a neutral and a ground conductior in addition to the phase conductors, so a service entrance cable is unsuited. you can use URD or SER (so long as you have enough conductors) but they will be harder to pull as they are designed for direct burial and so have a thicker sheath.
my research suggests that #6 aluminium is sufficient for your ground.
see also this question: What wire size for 100 Amp sub panel 100ft in length form 200 Amp main panel?
Comment: @jwh20  "#6 aluminium is sufficient for your ground", and "#6 AL ground would be legal" is not a VERY wide difference.
Comment: You recommend #6 AL without any explanation of this choice, while another answer recommends 1/0 AL or even 2/0 AL.  That's a VERY wide difference of OPINION!
Answer: If the cable is SER and not also USE or URD then it is not permitted underground. THHN is not wet location rated, underground is wet location even in conduit, but most THHN cable is also rated THWN, which is wet location rated. THWN or XHHW would be fine in conduit for all the circuit conductors. If you use a cable from the panel in 10' or longer conduit then the code requires the cable be secured in the cabinet, but a cabinet or connector Listed (UL or other NRTL) for that purpose seems to be as elusive as Bigfoot.
1/0 conductors and #6 AL ground would be legal in the US, but at that length the resistance of the wire may cause some voltage loss if operating at full load.  2/0 AL and #4 ground would fit in your 1.5" pvc and would alleviate the voltage loss issue.
Comment: You recommend 1/0 AL or even 2/0 AL without any explanation or references, while another answer recommends #6.  That's a VERY wide difference of OPINION!
Comment: @jwh20 The OP already stated in his answer that he planned on using 1/0 aluminum for the energized conductors,it appears he already researched the minimum size required, a reference for his research would be redundant. I will add the cause of voltage loss in my recommendation to upsize the wires.
Comment: Almost all thhn is dual rated thhn -thwn, the thhn I got yesterday south wire brand was thhn, thwn-2, MTW and possibly one other. I have not seen a single rated thhn for 20 years. But I agree SER is not allowed underground.
Comment: @EdBeal I understand probably all THHN is now THWN, but it's a lose/lose situation, if I say THHN is OK or not OK I still get kicked in the nads.


Multi-line JavaScript inside JSX?

Question: Is it possible to write a multiline js code in JSX?
return (
      {
      const a = props.users.find((user) => user.id === post.userId)
      console.log(a) // I want to console.log
      return a
      }
);

Comment: Look this post please: https://stackoverflow.com/questions/59375422/multiline-js-expressions-inside-jsx-are-forbidden
Answer: If you want to do multi-line JavaScript code, you can wrap your JS code with an IIFE, for example:
  <>
    {(() => {
      const a = [1, 2, 3].find((el) => el === 2)
      // as much code as you want ...
      // ...
      // ...
      console.log(a)
    })()}
  </>

Just in case you don't know, <> & </> are called React fragments, you can use any valid JSX element you want, for example, you can use instead
, ,
 or anything like that.
Comment: Thanks, man, you really helped me a lot!!
Comment: Please don't. How about you pull the code a few lines up, out of the markup and only `return {a}`.

Multi-line JavaScript inside JSX?


Proving that $H\cap K = \{e_G\}$ given $|H|=3$ and $|K|=5$

Question: I found the following question in an old test paper:

Suppose $H$ and $K$ are two subgroups of $G$ such that $|H|=3$ and $|K|=5$.
  Prove that $H\cap K = \{e_G\}$ where $e_G$ is the identity of $G$.

My attempt:
Every group of prime number order is isomorphic to $\Bbb Z_{p}$ ($p$ being the prime number) and thus they are necessarily cyclic. Thus, $H$ is isomorphic to $\Bbb Z_3$ and $G$ is isomorphic to $\Bbb Z_5$. After this I'm not sure how to proceed. I thought $\Bbb{Z_3}$ and $\Bbb{Z_5}$ have no element in common since the elements of $\Bbb{Z_3}$ are $\{\bar{0}_3,\bar{1}_3,\bar{2}_3\}$ while the elements of $\Bbb{Z_5}$ are $\{\bar{0}_5,\bar{1}_5,\bar{2}_5,\bar{3}_5,\bar{4}_5\}$. But again, I'm confused because since $H$ and $K$ are subgroups they must be sharing the identity element of $G$.
Questions:
So, could someone please clarify this problem of mine? Clearly $\Bbb Z_3$ and $\Bbb Z_5$ have no element in common, but then how do $H$ and $K$ have an element (the identity in common)?
Moreoever, what would the correct way to approach the quoted problem?
Comment: $H$ and $K$ occur in this question as subgroups of a group $G$, so they have the same identity.
Comment: Please note that one the main parts of the question is: $H$ is isomorphic to $\Bbb Z_{3}$ and $K$ is isomorphic to $\Bbb Z_{5}$. But then $\Bbb{Z_3}$ and $\Bbb {Z_5}$ do not share their identity element. So how can $H\cap K$ have the same identity (given that the groups they are isomorphic to do not share an identity)?
Answer: $H\cap{}K$ is a subgroup of both $H$ and $K$ and thus by Lagrange's theorem its order divides both 3 and 5 thus it has to be just the identity element. The identity element in both groups is the same as in G because they are subgroups and the identity element of a group is unique.
Answer: Any element of $H\cap K$ distinct from $e_G$ will have both order $3$ and $5$, but no such element of $g$ exists. To be more precise, if $g\in G$ is such that $g^3=g^5=e_G$, then $g=e_G$.
Comment: Thanks, but you missed a part of my question. $H$ is isomorphic to $\Bbb Z_{3}$ and $K$ is isomorphic to $\Bbb Z_{5}$. But then $\Bbb{Z_3}$ and $\Bbb {Z_5}$ do not share their identity element. So how can $H\cap K$ have the same identity (given that the groups they are isomorphic to do not share an identity)?
Comment: @Blue The groups $\mathbb{Z}_3$ and $\mathbb{Z}_5$ don't heve a common element indeed, but how do you deduce from that that $H$ and $K$ don't have a common element?
Comment: @Blue $H$ and $K$ are subgroups **of the same group**, so they do share a common identity, even if they are isomorphic to other groups that do not.
Comment: @Bungo I see. I was making a wrong assumption. Thanks


I crash whenever I open the first "loading" door

Question: On the PC version of Resident Evil 4, after going past the bridge in the first level where you start off in the house, I crash as soon as I enter the metal door.
Comment: What are your computers specs? Incapability might be the answer.
Comment: Are you playing the original PC version or the [remastered Steam release](http://store.steampowered.com/app/254700/resident_evil_4__biohazard_4/)?
Answer: Try to reinstall the game some files might be missing. If the problem persists lower down your graphical setting.
You can report the problem on Steam and they will help you.
Comment: "The Steam Beta Patch still won't fix it." Read the question - he's using an update, which doesn't work.
Comment: @Ben, it appears to me that the beta patch **did**, in fact, work.
Answer: Alright, I reinstalled the game and installed the Beta patch. It might be hit or miss, but it finally worked.
Comment: It appears you have simply commented on the fact that the other users answer worked. Instead, you should mark it as the accepted answer, and perhaps upvote it.


URL encoding a very long link and sending via email

Question: I'm sending a link via email, the link is rather long so after some Googling, it suggests sending a rich text email with the link as an actual link - I tested this solution but have come across something else:
Here's the link:
www.example.com/bridge/aHR0cDovL2QxbW8zdHp4dHRhYjNuLmNsb3VkZnJvbnQubmV0L3N0YXRpYy9yZW50YWxzLzcyMC9WSU5UMDA2Ni5tcDQ%2FaWQ9MTI3NSZFeHBpcmVzPTE0MTM0NTMyMjcmU2lnbmF0dXJlPUZvWDJvU2ZjVURwbjlIMzhWN3FCR0NqMWhMUTEyZGNaaXN%2BQ2lOTGZyVDVYWkNyeXZCejBNZEtQUjZFdHU2SmsySlI3OU04dldYeE1VRVRwNVhJNlgwVERLeHQyLWhUZUdQd0JPamZqLW9%2BaTBoM0hNb29pU0ZPZmE1MFhXMXhoLWZGNFlOMVFqdTY2UlhqU1oyODVSY2tpUkFxeU1zTFJDNlptdDI0ZEhNSmlITVI4Sld5QXhEOVlVcmxOOHc1OWxkVHkzNG5ySmFPazQySk1Ca2VQYnpUSVBxZWU5MXg0dmM3QVlsby1lampldzZodVBQVWx%2BWUxIbWhRYTJEdy12RFhqNFJ2blFYWVdUdnhkRmxBMXNTREgzRzdrRjg2N25tT240ZGNvTE53SW1VUWNoNH4xSTUtQ3ZudVQwQUh6UnZSc2FnbFY2US1IRmdKUUNTbzNCUV9fJktleS1QYWlyLUlkPUFQS0FJSTVPQlNRRUdZVzNSNVVB

The link is built by base 64 encoding a string (to make it look pretty, I did not like the look of the URL when it's just URL encoded) and then url encoding this:
$url = urlencode(base64_encode($string));

I then send this in an rich text email, but parts of the URL are being replaced, eg.
DQ%2Fa

becomes
DQ/a

Why is this happening and is there a way around it?
I'm just sending the link by OSX Mail, but in future it cold be send via Hotmail, Gmail etc.
Comment: Are you sending it via HTML mail? Seems it might be getting converted back. `%2F` is indeed a backslash. http://www.obkb.com/dcljr/charstxt.html
Comment: don't build long urls like that. browsers have a length limit on them and will silently truncate overly-long ones. you're risking ending up with corrupted data.
Comment: @MarcB He's safe up to the point of 2000 characters. The link he posted was around 600-700 characters so I think it's fine.
Comment: I need to build long URLs, it's a policy for S3. It's just being sent via OSX mail.
Comment: What kind of data are you passing along in the url?
Comment: @Oli a canned policy for S3
Answer: Digging up a dinosaur, but this issue is still present in 2021.
When I send long links via OSX Mail client using Rich Text, they will get decoded. Long links are very common in software like Sketch, Figma, etc.
The only solution that I was able to find is to send mail using Plain Text, but this may not work for some.
I'm on Big Sur and I never thought I'd run into such issue.
Is there any other workaroundf for this?
Comment: Does the link have to be *that* long? Can the long link be translated into a short link (256chrs URL) that when visited can be passed on to the original long link?
Comment: The links are generated automatically by the software and I have no control over it. The URL contains a hash, and a specific location of the shared design file, and that's why these URLs are usually long.
Comment: Same here with gmail url tracking in 2023. The link works just fine in Thunderbird, but when I click on it in gmail it gets urldecoded and I got garbage on my site. Not sure how to fix this.


Can Xcode include application resource files that are generated during the build process?

Question: I have a bunch of content files for my iPhone app that I generate via shell script. It takes way too long to be a part of the Xcode build process, so I run it periodically.
I don't want to have to continually add these files to my Xcode project in order to get them included my app resources folder. Is there a way to get Xcode to copy the contents of a folder   into the app resources at build time? (It'd be a bonus if I could specify other locations, such as the approot documents folder.)
I tried adding a new 'Copy Files Build Phase' to my target, but that didn't seem to work. This seems like a common problem, but I couldn't find anything about it here.
-- Edit (What I did)
Per Jasarien and cdespinosa's suggestions, I did the following in a build script. I decided not to copy to the destination, because that would only work when using the simulator, I don't think that'll work when deploying to a device.
<code>cp -rf "$PROJECT_DIR/mystuff" "$CONFIGURATION_BUILD_DIR/$CONTENTS_FOLDER_PATH/"
</code>
-- Edit 2
This doesn't appear to get files onto my iPhone. Any ideas?
Answer: You can setup a Run Script build phase in your app's target. Write the script so that it copies the resources into the app bundle.
Comment: Don't forget to add the generated files as the phase's Input Files, so that it depends on them, so that Xcode will not run the script until the files are ready to be copied. You may also want to add the copies' paths as the phase's Output Files.
Comment: Might as well copy them directly into the ${CONTENTS_FOLDER_PATH}/
Comment: That makes sense. I'm looking at the Xcode variables for where to copy my files. Do I want to copy them into a build directory, so that it gets installed at the end of the build process, or do I go directly to the install destination?
Answer: This is the path i use for output:
<code>${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}
</code>
Just copy your files in that directory, it's the bundle (simulator or device).
You can also take a look at my answer here : how to set up a Xcode build rule with a variable output file list?


ClamTK and Encrypted Home Directory

Question: I recently encrypted my home directory and since then I have realized Clam AV is not really scanning the file in my home directory. It is scanning the encrypted files. I am running the scan with the user who's home is encrypted (using ecryptfs-migrate-home).

How can I recursively scan my encrypted home directory now using ClamTK or freshclam?
Comment: You can't scan encrypted files, you have to decrypt them, then scan them
Comment: Agreed, but for all use other than the virus scan the contents of the home directory are automatically decrypted without me having to explicitly take any action to decrypt. Why won't that be the case while virus scanning?
Comment: You are asking why clamav or any virus scanner does not have decryption as a feature ? Really ? It would be poor encryption if clamav could decrypt the data.
Comment: No, the decryption is at the point when the user who's home is encrypted logs in. The user doesn't need to decrypt individual files to use. I am expecting the same from the antivirus for reading files during the scan.
Comment: user logs in  -> files are decrypted. Then step  run clamav. Exclude the encrypted files if you wish (.Private I think)
Answer: The point is that when setup as a cron job to run at 2AM, as daily scans should be, the application needs the smarts to decrypt a home folder. Many users now encrypt the home folder or the whole disk. From the login, scanning just ~/.mozilla, ~/.thunderbird, and ~/Downloads (4.1GB) took significant time, maybe an hour, running about 50% CPU on a dual core machine and Ubuntu 18.04. That is not an efficient use of resources when you are logged in trying to get other tasks accomplished.

ClamTK and Encrypted Home Directory


Maytag Dryer LD69806AAE Doesn't Start

Question: We have a Maytag Dryer Model # LDG9806AAE in our rental property. Our tenant said it stopped working so I checked it out today. When I pressed the "power" button. I hear a buzzing sound but the drum doesn't tumble. Any suggestions for investigating before I call an appliance expert come and fix it? Are there belts? or a motor needs to be replaced? Thanks in advance.
Mike
Comment: I'm voting to close this question because it's been abandoned
Comment: If the motor is buzzing, check if it has a startup capacitor, those go bad in time preventing motor from starting.
Comment: A broken belt would allow the motor to spin but may sound like buzzing with no load.
Comment: https://youtu.be/gJwYV8HkTbk
Answer: We had this problem and it turned out to be the thermal fuse. The thermal fuse helps prevent a dryer fire by shutting off power to the dryer if it gets too hot. If the clothes dryer will not start, examine this fuse. This is the most typical part to fail when the dryer won't work.
Comment: If the thermal fuse was blown/tripped, why would the dryer make a buzzing sound?
Answer: Old question but for others with the same problem...it can also be lint in the motor housing affecting the brushes and preventing it from starting up. Try pressing the door switch and rotating the drum by hand and see if it starts. If so, its probably lint in the motor.

Maytag Dryer LD69806AAE Doesn't Start


Very hot CPU on HP/Compaq 615

Question: I am using an HP Compaq 615 AMD dual-core laptop, and I just upgraded to Oneiric.
However, my CPU temperature has never been below 65 degrees C. When my laptop had Windows 7 Starter, the temperature would stay between 40-50 degrees C.
Obviously Ubuntu/Linux is using too much CPU power, even though the RAM usage is minimal. Is there any way to lighten the CPU load?
E
Comment: That's some sexy CPU you have there then ^^
Answer: You can start by removing any applications that you do not use through Ubuntu Software Center, and by stopping the automatic start-up of certain programs. You could switch to the Ubuntu classic environment, as well.
What is the CPU usage? Ubuntu is not generally going to use too many resources on a dual-core laptop especially compared to 7 Starter. This may just be a driver/fan control problem.
Answer: Apart from checking if the laptop has enough space underneath it (for the air to flow). you could try to control the fan speed:
Here is a nice link for Fan Control: How to control fan speed?
Also if you have a powerful video card. I think in your case is an Ati Radeon HD, then you might need to control the intensity with it. Change yourself to Unity 2D just to test out. Test how the temperature is when inside a terminal. Install the proprietary drivers just in case.
Check if you have a process running 100% of the time. The easiest way to test this is just by running the PC from a LiveCD. if the temperature stays low then maybe something that was installed recently made the CPU stay in heavy usage.
Answer: I would definetly check and see if you need to install any proprietary driver, which is not Open-Source. If the driver isn't installed, there is no way for the OS to communicate with the GPU. But Since the CPU is, the systems utilizies the CPU to calculate real-time image rendering (What you actually see on the screen). This causes the CPU to be busy all the time, while still being in the need to calculate different algorithms.
To check whether the GPU (Graphics Card) Driver is installed, the easiest way is (if you are using Ubuntu with Gnome, not Unity) to check your bar (where notifications and the menu, window manager,etc. is located), if it indicates a light shadow beneath it. This means, that Compiz is activated, producing a nicer appearance of mostly everything. Since this means higher Processing Consumption, the System needs a stand-alone Processing Unit, like a GPU (Which basically is a so called Co-Processor), to enable enough Processing Power.
If it doesn't happen to be, follow the very first step I mentioned.
Hopefully helped out
Answer: could be a cpu governor [performance]
<code> echo conservative | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
</code>
would lower the cpu mhz and temp

Very hot CPU on HP/Compaq 615


finding UMVUE for $\theta_x$/$\theta_y$

Question: Let Xi ~ Exp($\theta_x$), Yj ~ Exp($\theta_y$), i = 1; ... ; n1, j = 1;...;n2. Find UMVUE of $\theta_x$/$\theta_y$.
Since $\bar{X}$ and $\bar{Y}$ are compelete sufficient statistic, by using Lehmann-scheffe theorem, UMVUE should be found by solving E($\bar{X}$/$\bar{Y}$), but due to inverse of exponential family, is it possible to find it?
Comment: $\theta_x$/$\theta_x=1$
Comment: @tommik, sorry it is , $\theta_x$/ $\theta_y$
Comment: and what about independence or dependence between X and Y?
Comment: @tommik it didnt mentione, but I think it suppose to be independent
Answer: Assuming independence between $X_i $ and $Y_j$ the calculation of the following expectation
$$\mathbb{E}\left[\frac{\overline{X}_n}{\overline{Y}_m}  \right]$$
(I used $n,m$ instead of $n_1,n_2$ to simplify the notation...)
is very easy being
$$\mathbb{E}\left[\frac{\overline{X}_n}{\overline{Y}_m}  \right]=\frac{m}{n}\mathbb{E}\left[\frac{\Sigma_iX_i}{\Sigma_iY_i}  \right]=\frac{m}{n}\mathbb{E}\left[\Sigma_iX_i\cdot\frac{1}{\Sigma_iY_i}  \right]=\frac{m}{n}\mathbb{E}\left[\Sigma_iX_i\right]\cdot\mathbb{E}\left[\frac{1}{\Sigma_iY_i} \right]$$
and as known
$$\frac{1}{\Sigma_iY_i}\sim \text{Inverse Gamma}$$
Comment: thank you so much, E(1/$\sum Y_i$) = $\theta$ / m-1, if we put it in above formula by considering E[$\sum X_i$] = n$\theta_x$  then we will have m/m-1 [$\sum X_i$][$\sum Y_i$], this suppose to be our UMVUE?
Comment: yes, but  what about marking my answer as accepted? . It'll encourage others to answer your questions in the future
Comment: ya sure, how can I do that? I didn't know about this option, sorry
Comment: Be careful that I didn't check your calculations, but when you calculate the expectation and your estimator is biased...you have to correct the bias.... I think it shoud be $(m-1)/m...$

finding UMVUE for $\theta_x$/$\theta_y$


Parse a relative link in jQuery

Question: this is the output I am getting while retriving the data with Jquery
/content/apple/en_US/products/apple/phones/iphone6.html

I want to remove everthing after the last /
result should look like:
/content/apple/en_US/products/apple/phones/

how do I achive this task with jquery.
Comment: This is more a Javascript task.
Answer: could be like this:
var url = "/content/apple/en_US/products/apple/phones/iphone6.html"; // window.location.href;
var str = url.substr(0, url.lastIndexOf('/')+1);

You can use this with native javascript methods, there is no need to use jQuery.
Demo
Comment: I wanted /content/apple/en_US/products/apple/phones/   but I was getting /content/apple/en_US/products/apple/phones with your code. the last / was also trimmed out. :|
Comment: @Pratik This won't be possible as per current code. `url.lastIndexOf('/')+1` you can see the `+1` is for that last `"\"` use it and see will update you with a demo.
Comment: I take my previous comment back. THIS code works as well. thanks
Answer: You can use lastIndexOf to achieve what you need:
var teststr = "/content/apple/en_US/products/apple/phones/iphone6.html";
var result = teststr.substring(0, teststr.lastIndexOf('/'));

Comment: I wanted /content/apple/en_US/products/apple/phones/   but I was getting /content/apple/en_US/products/apple/phones with your code. the last / was also trimmed out. :|
Answer: Try this -

Parse a relative link in jQuery


Android rounded border color top-left only dinamically

Question: I need to set dynamically a GridView item, I am using LinearLayout with background drawable applying round corners but I can't figure out to set only top-left border color like this picture....

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gridview_item"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/btn_rounded_white"
        android:orientation="vertical">

        <TextView
            android:id="@+id/gridview_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clickable="true"
            android:text="@string/app_name"
            android:textSize="@dimen/gridview_text"
            android:textStyle="bold"
            android:layout_gravity="center"
            android:gravity="center">

        </TextView>

    </LinearLayout>

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid android:color="@color/griditem_cat" />
    <padding android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/>
    <corners android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/>
</shape>

Comment: you want to set that top left corner color dyanmically or you have this four color only?
Comment: @Aditya Vyas-Lakhan It need to be dynamically colored with hexadecimal colors, I AM trying with triangle custom views but I Lost the rounded top left corner like the image example attached
Comment: if dynamically, you need to call `Drawable#setColorFilter` on your "triangle" drawable
Comment: @pskink I will try setting triangle color...
Comment: As I said using triangle I can set color with a custom view (http://imgur.com/a/3i2JB) but I didn`t found how to make it rounded top-left
``
Answer: grid_item.xml
<RelativeLayout
android:id="@+id/gridview_item"
android:layout_width="match_parent"
android:layout_height="match_parent">
     <PinnedGridItemView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>
    <TextView android:id="@+id/gridview_text">
     </TextView>
</RelativeLayout>

CategoryAdapter
pin = (PinnedGridItemView) relativeLayout.findViewById(R.id.pinned_grid_item);
pin.setColorCode(Color.RED);// Here I set any color that I want dynamically, the problem now is to solve top-left rounded corner


How to combine one root level pom to child pom?

Question: Guys is that possible to combine two pom.xml files in my project one is root level pom and other is my child pom. I want to concatenate them in single pom. Is that possible ?
Answer: Possible, but not automatically.  You will need to manually merge, removing redundancies.
Comment: i have two artifacts id, one building the apk file and other running the tests. Root pom is with tests and child pom builds the apk file. Any idea about that ?
Comment: @DineshDhiman. Yes.  The current structure makes no sense and needs to be fixed.


Eclipse does not start on 14.04

Question:
I recently upgraded to Ubuntu 14.04 and have been trying to install and use Eclipse ever since. I tried using both open JDK as well as Oracle JDK installations(both Java 7 and Java8) and both Eclipse Juno as well Eclipse Luna.
I even tried installing Eclipse from aptitude installer. All of them stop on the flash screen that Eclipse loads and start and hangs there. If any of you have faced similar problems and were able to get around this, please let me know.
I tried running the eclipse -debug option to see if there are any errors on the console but nothing showed up.
Thanks & Regards,
Nachiketh
Answer: I add the follow line at the end of eclipse.ini file:
-Dorg.eclipse.swt.browser.DefaultType=mozilla
It worked for me, I hope you too.
Answer: I was having a similar problem, and found a solution in this post.
I just removed the old ~/workspace folder and, after starting 2 times (in the first time, Eclipse make a new ~/workspace folder and then close himself), the Eclipse works fine.

Eclipse does not start on 14.04


Firefox Group of Tabs: how to save and open as a group?

Question: Firefox 69.0.1 on Ubuntu:  How does one save a group of tabs as single line-item?  It would be very useful to be able to recall the saved group in a future browsing session.
Answer: You can specify they all open when you click on Home, or you can put them all in a folder on your Bookmark Bar, and when you want them all, right-click and choose Open All.
Answer:
Open all tabs (one by one) that you need to be able to close and open as a group.
Click on the first tab, hold down Shift key and click on the last one to select all of them.
Right click on one and choose "Bookmark tabs"
Choose a folder name
Now you can go to Bookmarks, choose your folder name which expands on the right to show the bookmarked tabs. At the very bottom there is an option, "Open all in tabs".

You can now open and close all tabs as a group.


X++ Update_recordset using MaxOf

Question: Is there anyway to use MaxOf on update_recordset on X++?
ttsbegin;
update_recordset asuRepairServiceProdDeviceInfo
    setting RepairCompletionDate = **maxof**(asuRepairOrderTrans.ScanEndDateTime)
    join asuRepairOrderTrans
    where asuRepairServiceProdDeviceInfo.RepairOrderID ==  asuRepairOrderTrans.RepairOrderId
       && asuRepairOrderTrans.RepairStepId == '7000';

info(strFmt("Repair Completion Date FG : Number of records updated is %1.",
            asuRepairServiceProdDeviceInfo.rowCount()));
ttscommit;

Or any different approach aside for While statement? as I'm working on over millions of records
Answer: The update_recordset does not allow aggregate functions. You can however use aggregates in views.
Create a view (ASURepairOrderMaxDate) on the the ASURepairOrderTrans containing the RepairOrderId, RepairStepId and max(ScanEndDateTime) fields.
Then the update is easy:
update_recordset asuRepairServiceProdDeviceInfo
    setting RepairCompletionDate = asuRepairOrderMaxDate.ScanEndDateTime
    join asuRepairOrderMaxDate
    where asuRepairOrderMaxDate.RepairOrderId ==  asuRepairServiceProdDeviceInfo.RepairOrderId
       && asuRepairOrderMaxDate.RepairStepId  == '7000';
info(strFmt("Repair Completion Date FG : Number of records updated is %1.",
            asuRepairServiceProdDeviceInfo.rowCount()));

X++ Update_recordset using MaxOf


something wrong when I exec a script with perl (ubuntu10.10)

Question: I got a perl script named test_perl.pl and try to exec it.
The first line of the scrpit is:
<code>#!/usr/bin/perl
</code>
When I try to exec this script, I get an error.
<code>$ type perl
perl is /usr/bin/perl

$ ll /usr/bin/perl test_perl.pl
-rwxr-xr-x 2 root        root        10352 2011-04-23 03:32 /usr/bin/perl*
-rwxr-xr-x 1 jim         jim         12121 2013-11-21 11:47 test_perl.pl*

$ test_perl.pl
test_perl.pl: line 1: #!/usr/bin/perl: No such file or directory
</code>
I don't no why this happens.
Answer: You have a BOM (see http://en.wikipedia.org/wiki/Byte_order_mark) at the beginning of your file.
try
<code> xxd test_perl.pl
</code>
to see it. Getting rid of the BOM will fix your script: Lots of ways to do this: Using awk to remove the Byte-order mark


Ubuntu Stuck on Black Screen After Fresh Installation

Question: I have an MSI GS63VR. It has an i7-7700HQ CPU, 16 GB of RAM, and an NVIDIA GeForce GTX 1060.
I just installed Ubuntu 16.04.4 LTS using the steps described on the site. I allocated 40 GBs to Ubuntu. Everything seemed to install correctly.
Once I saw the notification about the installation being successful, the machine said I'd need to restart. I press ok (or whatever the prompt said). It froze there. I left and came back a half hour later and saw it hadn't changed so I manually shut down the machine.
It restarted just fine. Instead of going straight to windows, it brought up the screen where I can choose ubuntu or windows. I chose ubuntu. After that, a black screen came up and nothing happened. It just froze there.
Is there something I can or should do to fix this?
Comment: So I followed the steps there (as far as changing the line to nomodeset) in the grub menu. After I reboot, it gets me to the log in screen (which is farther than I've been, so I think this is a step in the right direction).

After I enter my password, the system freezes. I read through that entire page but I didn't find anything that addresses that possibility. Any chance you might have a tip?

Thank you for the info so far!
Comment: Try booting with a different graphics card or without the NVIDIA GeForce GTX 1060 plugged in.
Comment: I have the exact same problem. But I just did a single change and then everything works --> click install updates and all other packages. install graph card driver as well. Then when you restart, do not remove the medium and press enter to restart. When restarting, remember to chang the order of your BOOT to make the HDD/SSD first. Then I can log into ubuntu.
Answer: Did you follow proper procedure, ie first disable windows fast boot and UEFI secure boot?
This should be done before attempting to install Ubuntu (or any other OS/Linux).
Secondly, upon installation and later upgrades, never do a hard-reset. It may seem the PC is doing nothing and is stuck - but allow it plenty of time.
Since it is a fresh install that have turned sour, I'd just as well go ahead and install from scratch. And maybe allow a bit more space for Ubuntu.
Some time ago I set up my ASUS N552VX with Ubuntu 16.04, allowing it 60Gb of the SSD. Which later turned out to be a mistake and increased it to 120Gb. Luckily did not have to do any reinstall, just some partition juggling and resizing.
Comment: Hi. Thank you for responding.

I disabled windows fast boot and uefi secure boot. Is there a page that you recommend with detailed installation instructions?

I used this page: https://tutorials.ubuntu.com/tutorial/tutorial-install-ubuntu-desktop#0 And I read on a few different pages that I had to disable fast boot and uefi secure boot. Not sure where I went wrong.

I'll also try allocating more space to the system.
Answer:
Escape from black screen
When you stuck on black screen, you can use Ctrl+Alt+F1 to select terminal. Then you can type your username and password to login.
edit /etc/default/grub
Modify the line of GRUB_CMDLINE_LINUX_DEFAULT to
GRUB_CMDLINE_LINUX_DEFAULT='pcie_port_pm=off acpi_backlight=none acpi_osi=Linux acpi_osi=! acpi_osi="Windows 2009"'

Then reboot again. You should be able to see login page.
Re-install nvidia driver (If step 1 & 2 cannot help)
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt-get update
sudo apt-get install nvidia-390 nvidia-settings


Time to get rid of Rust-Oleum Textured Stone spray paint finish on wood

Question: About 30 years ago I used Rust-Oleum spray paint to put a textured fake stone finish on a wooden nightstand for my young son's room. (It worked with this decor, trust me.) Now I want to be able to paint that nightstand for the guestroom using Benjamin Moore Advance Aklyd paint. But I need to get that surface smooth.
Do I try to sand it off? Will it even come off? It's been remarkable durable for 30 years with no visible wear - no chips, peeling, loss of little "stones".
Is there something to put over it to level it, fill in, and create a smooth surface to work from?
Janet
Comment: If this is the stuff I've used, there are no "stones" -- the paint is just designed to create blobs which provide stone-like texture when you spray it on. Remove it like any other paint.
Comment: @keshlam if it's spray, that must be true - anything solid in the can would clog the nozzle
Answer: Experiment. If testing reveals the "stone" bumps to be resistant to sanding, fill around them with something designed to be sanded smooth (like autobody putty.) If (as seems likely) they sand off without issue, just do that until the surface is smooth.
You can scrape or sand or use paint remover all the way to bare wood (but that is probably a great deal of needless work for a "more paint, just smooth" result.)
Comment: Yes—if it's real wood and not particleboard, you could hit it with a primer-filler, then wet-sand it smooth.
Answer: Sand it.
Benjamin Moore Advance is a self-leveling alkyd and will lay down exceptionally (I have sprayed hundreds of gallons of this product).
I would sand the surface as smooth as you can get it either by hand or with a random orbital sander using 220 grit sandpaper, vacuum and then paint it as usual.


How can I store a returned List in c#?

Question: This should be simple, but I keep running into problems with this. I have a generic class Csvs<T>with a method that returns a type List<T> through a Property called Dockets. (The method reads CSV files and returns the list of the records in that CSV file. T is the type of that CSV file, which is defined in a series of models, which contain the header row as Properties)
In my calling class (which I cannot make generic), I have a switch statement based on an enum that contains the names of the classes I use in T.
switch (_userInput.CsvType)
            {
                case CsvType.Type1:
                    var csvType1 = new Csvs<Type1>(_userInput);
                    _dockets  = csvType1.Dockets;
                    break;
                case CsvType.Type2:
                    var csvType2 = new Csvs<Type2>(_userInput);
                    _dockets  = csvType2.Dockets;
                    break;
                case CsvType.Type3:
                    var csvType3 = new Csvs<Type3>(_userInput);
                    _dockets  = csvType3.Dockets;
                    break;
                // more cases here [...]
                default:
                    throw new ArgumentOutOfRangeException();
            }

(It would be nice if I could find a better way than using this switch, too, but it works for now.)
What does not work, or what I do not know how to do is, how to declare _dockets? Since T could be any of the types. I've tried extracting an interface ICsvs and have the class inherit it, and then declare
var _dockets = new List<ICsvs>;

But this throws an error, that I can't implicitly convert the List<Type1> to a List<ICsvs>.
And I can't cast the List to a type List<ICsvs>. (Then I get the next exception)

Cannot convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

The same happens if I use an abstract class.
So, how do I store the returned List in the calling class? How do I declare a field or property that can hold any of the types?
Comment: you can't store cause you don't iknow the type beforehand. You are left with using another switch probably or using `dynamic`
Comment: Exactly my point. You can use a switch to instantiate the right generic class, but you cant consume it in any meaningful way as you dont know they type.
Comment: Generics always work best when you know the type at compiletime. If you only know they type at runtime, you *probably* dont want generics.
Comment: @Jamiec, The generic class works... I just don't know how to store the return type?
Comment: @Rahul. Thank you! I forgot about `dynamic`. That will work!
Comment: Why can't you just use `_dockets.AddRange(csvType1.Dockets)`? If `dockets` is `List` and `csvType1.Dockets` is a list of instances of some type that implements `ICsvs`, it will work perfectly.
Comment: Youve accepted an answer which *does not work* which will further confuse the next visitor to SO with this issue.
Answer: The simplest way to achieve this is to make all of your types implementing ICsv, like this:
interface ICsv { }

class CsvType1 : ICsv { }

class CsvType2 : ICsv { }

class Csvs<TCsvModel>
   where TCsvModel: ICsv
{
    public Csvs(IList<TCsvModel> csvModel)
    {
       this.Dockets = csvModel;
    }

    public IList<TCsvModel> Dockets { get; private set;}
}

So you can use this like:
IEnumerable<ICvs> dockets;

var cvsType1 = new Csvs<CsvType1>(_input);
dockets = cvsType1.Dockets

var cvsType2 = new Csvs<CsvType2>(_input);
dockets = cvsType2.Dockets

Comment: That's nice. Thank you.
Comment: This will not work for the same reason as the OP's code did not work. http://rextester.com/PRWX41261
Comment: No, close: It throws `Argument 1: cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'`
Comment: what's the type of _userInput ?
Comment: @vdefeo It's a custom class that has the type of csv and a few Properties, such as the date and time when the csv was written, etc
Comment: Ok you're right IList doesn't fit the return type, I've just changed to IEnumerable, I would prefer to work with IEnumerable instead of dynamics only because performance issues, dynamic will resolve the type in runtime and it's not good.
Answer: The most meaningful/polymorphic thing you can do is make the Dockets property return an interface describing what you do with them. Depending on your requirements, that may or may not be feasible - but you have little other option. As I commented, Generics really only works well when you know the type at compile-time.
By way of an example. An interface
public interface IDockets
{
    void DoSomethingWithRecords();
}

A generic implementation which will be returned from your Csvs class
public class Dockets<T> : IDockets
{
    private IEnumerable<T> dockets;
    public Dockets(IEnumerable<T> dockets)
    {
      this.dockets = dockets;
    }
    public void DoSomethingWithRecords()
    {
        foreach(var docket in dockets)
             Console.WriteLine(docket); // do whatever
    }
}

This class would then be returned from your Csvs class Dockets property
public class Csvs<T>
{
    private List<T> parsedDockets; // assume you have something like this:
    public IDockets Dockets{ get { return new Dockets(parsedDockets); } }
}

And your calling code
IDockets dockets = null;
switch (_userInput.CsvType)
{
    case CsvType.Type1:
        var csvType1 = new Csvs<Type1>(_userInput);
        dockets  = csvType1.Dockets;
        break;
   // Snip //
}
dockets.DoSomethingWithRecords();

Comment: The problem with the IEnumerable is that I need to add the values from the CSV, so a List would work much better.
Comment: @ToshiBoy whatever, List or enumerable makes no difference. Anyway, you're presumably adding them to a list in `Csvs` - by the time you spit them out to `Dockets` you probably dont need to add any more.
Answer: I think for what I was after, that is, storing the return value for later use, dynamic is the best answer (Thank you @Rahul). I can worry about the type later. Thank you all for your help.
dynamic _dockets;

then switch-case through the returns.

How can I store a returned List in c#?


How to traverse through the following loop in dart?

Question:  {"products": [
    {
        "prod_id": "prod-345",
        "name": "Something",
        "category": "Cloth",
        "thumbnail": "",
        "rating": 1,
    },
    {
        "prod_id": "prod-123",
        "name": "Something Else",
        "category": "Watch",
        "thumbnail": "",
        "rating": 1,
    },
 ]}

I want to traverse through the list using for each but am not able to do so. Please help.
Answer: Use following
ProductReply data = productReplyFromJson(jsonString);
for(int i=0;i<data.products.length;i++){
print(data.products[i]. name);
}

Define class to hold data as
// To parse this JSON data, do
//
//     final productReply = productReplyFromJson(jsonString);

import 'dart:convert';

ProductReply productReplyFromJson(String str) => ProductReply.fromJson(json.decode(str));

String productReplyToJson(ProductReply data) => json.encode(data.toJson());

class ProductReply {
    List<Product> products;

    ProductReply({
        this.products,
    });

    factory ProductReply.fromJson(Map<String, dynamic> json) => ProductReply(
        products: List<Product>.from(json["products"].map((x) => Product.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "products": List<dynamic>.from(products.map((x) => x.toJson())),
    };
}

class Product {
    String prodId;
    String name;
    String category;
    String thumbnail;
    int rating;

    Product({
        this.prodId,
        this.name,
        this.category,
        this.thumbnail,
        this.rating,
    });

    factory Product.fromJson(Map<String, dynamic> json) => Product(
        prodId: json["prod_id"],
        name: json["name"],
        category: json["category"],
        thumbnail: json["thumbnail"],
        rating: json["rating"],
    );

    Map<String, dynamic> toJson() => {
        "prod_id": prodId,
        "name": name,
        "category": category,
        "thumbnail": thumbnail,
        "rating": rating,
    };
}

Answer: List<Map> products = [];

 @override
  void initState(){
    super.initState();
    Map tmp = {"products": [
    {
        "prod_id": "prod-345",
        "name": "Something",
        "category": "Cloth",
        "thumbnail": "",
        "rating": 1,
    },
    {
        "prod_id": "prod-123",
        "name": "Something Else",
        "category": "Watch",
        "thumbnail": "",
        "rating": 1,
    },
 ]};
    products.addAll(tmp['products']);
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Let\'s parse some JSON'),
      ),
      body: Container(
      padding:EdgeInsets.fromLTRB(5,10,5,10),
      child:ListView.builder(
      itemCount:products.length,
      itemBuilder:(cc,ind){
        return ListTile(
        title:Text(products[ind]['name'])
        );
      }
      )
      )
    );
  }


PHP get previous array element knowing current array key

Question: I have an array with specific keys:
array(
    420 => array(...),
    430 => array(...),
    555 => array(...)
)

In my application I know current key (for example 555). And I want to get the previous array element. In this example it is array element with key 430. How can I do this in PHP? I tried to work with prev(), but for this function we should know current array element. I didn't find function, what set the current array element.
Comment: Are the keys in sorted order?
Comment: you can simple iterate over it.
Comment: As you can see from the explanation below, there is not a single reason to set any pointers in your case. They have another, very limited use.
Comment: @Gumbo. No, keys isn't sorted.
Answer: One option:
To set the internal pointer to a certain position, you have to forward it (using key and next, maybe do a reset before to make sure you start from the beginning of the array):
while(key($array) !== $key) next($array);

Then you can use prev():
$prev_val = prev($array);
// and to get the key
$prev_key = key($array);

Depending on what you are going to do with the array afterwards, you might want to reset the internal pointer.
If the key does not exist in the array, you have an infinite loop, but this could be solved with:
 while(key($array) !== null && key($array) !== $key)

of course prev would not give you the right value anymore but I assume the key you are searching for will be in the array anyway.
Comment: the fact that we would usually go over the array with foreach but he had a different approach that works well and it also uses internal pointers. +1
Comment: So, you just perfectly explained, why these pointers just shouldn't be used. as for `key($array)` - imagine we have a regular enumerated array... ;)
Comment: Cool non-foreach solution that actually works with the internal array pointer, +1
Comment: Shouldn't `key($array)` be `current($array)`
Comment: @RobertPitt: It's either way. `key` will return `null` if the internal pointer points outside of the array and `current` will return `false`. I think `key` is safer to use, because a value might be `false` but it is unlikely that a key will be `null`.
Comment: true, nice method either way.
Comment: @Eduard: Did you get an error? What happened? Did you reset the array before as I mentioned?
Comment: No error, but when accessing the array with the previous key, it threw a notice, that there's no such index in the array. I haven't used any array-specific functions on that array, so I don't think a reset was needed, or is it?
Comment: @Eduard: Are you sure you used the previous key and not the value?
Comment: @FelixKling well I used the previous key, to get the value :)
Answer: Solution with fast lookups: (if you have to do this more than once)
$keys = array_flip(array_keys($array));
$values = array_values($array);
return $values[$keys[555]-1];

array_flip(array_keys($array)); will return an array mapping keys to their position in the original array, e.g. array(420 => 0, 430 => 1, 555 => 2).
And array_values() returns an array mapping positions to values, e.g. array(0 => /* value of $array[420] */, ...).
So $values[$keys[555]-1] effectively returns the previous elements, given that the current one has key 555.
Alternative solution:
$keys = array_keys($array);
return $array[$keys[array_search(555, $keys)-1]];

Answer: I solved this issue in this way:
function getPrevKey($key, $hash = array()) {
    $keys = array_keys($hash);
    $found_index = array_search($key, $keys);
    if ($found_index === false || $found_index === 0)
        return false;
    return $keys[$found_index-1];
}

@return previous key or false if no previous key is available
Example:
$myhash = array(
    'foo' => 'foovalue',
    'goo' => 'goovalue',
    'moo' => 'moovalue',
    'zoo' => 'zoovalue'
);

echo "TEST: ". getPrevKey('zoo', $myhash); // prints moo

Answer: @Luca Borrione's solution was helpful.
If you want to find both previous and next keys, you may use the following function:
function getAdjascentKey( $key, $hash = array(), $increment ) {
    $keys = array_keys( $hash );
    $found_index = array_search( $key, $keys );
    if ( $found_index === false ) {
        return false;
    }
    $newindex = $found_index+$increment;
    // returns false if no result found
    return ($newindex > 0 && $newindex < sizeof($hash)) ? $keys[$newindex] : false;
}

Usage:
// previous key
getAdjascentKey( $key, $hash, -1 );

// next key
getAdjascentKey( $key, $hash, +1 );

Examples:
$myhash = array(
    'foo' => 'foovalue',
    'goo' => 'goovalue',
    'moo' => 'moovalue',
    'zoo' => 'zoovalue'
);

getAdjascentKey( 'goo', $myhash, +1 );
// moo

getAdjascentKey( 'zoo', $myhash, +1 );
// false

getAdjascentKey( 'foo', $myhash, -1 );
// false

Comment: The comments in the 'Usage' section are misleading. It returns false if the searched key is not found, but will throw an `Undefined offset` notice and return `null` if the result is at the first key and you're looking for the previous. Same for the last key with the next value.
Answer: You can iterate through the array in reverse and return the next iteration after finding the search value.
$found = false;
foreach(array_reverse($array, true) as $key=>$value) {
  if ($found) {
    print "$key => $value\n";
    break;
  } else if ($key == 555) {
    $found = true;
  }
}

http://ideone.com/2WqmC
Answer: Just iterate over the array
$_index = null;
foreach($myarray as $index => $value)
{
    if($key == $my_index) // if($key == 550)
    {
        break;
    }
    $_index = $index;
}

echo $_index; //the prev key from 550;

An alternative solution is to get the keys of your array within an enumerated array like so:
$keys = array_keys($my_array);

as the keys array is index you can move the the previous key like so:
$required_key = (array_search(550,$keys,true) - 1);

this will fine the value of 550, and return its index within the keys, remove one to get the previous index
key we have our previous key to get the value from the original array
$value = $my_array[$required_key];

Comment: +1 for the `array_keys` approach.  Compact, transparent and easily tweakable.
Answer: If your data is large then it might be a best practice to avoid looping. You could make your own custom function, like so:
$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');

function previous($key, $array) {
  $keysArray = array_keys($array);
  $keyNumber = array_search($key, $keysArray);
  if ($keyNumber === 0) {
    $keyNumber = count($array);
  }
  return $array[$keysArray[$keyNumber - 1]];
}
var_dump(previous("second", $array));

Note that if you provide first key then it will return the last value, like a cyclic array. You can handle it however you like.
With a bit tweak, you can also generalize it to return next values.
As for why prev isnt working is because it isnt used for that purpose. It just sets the internal pointer of the array to one behind, exact inverse of next
I hope it helps
Answer: This is a simple solution for taking previous and next items, even if we are at the ends of the array.
<?php

$current_key; // the key of the item we want to search from

if (isset($array[$current_key+1]))
{
  // get the next item if there is
  $array_next = $array[$current_key+1];
}
else
{
   // if not take the first (this means this is the end of the array)
  $array_next = $array[0];
}

if (isset($array[$current_key-1]))
{
   // get the previous item if there is
   $array_prev = $array[$current_key-1];
}
else
{
  // if not take the last item (this means this is the beginning of the array)
  $array_prev = $array[count($array)-1];
}

Comment: It will work only if the index is numerical and sequential(Ascending order).
Answer: Expanding further on the solution of Luca Borrione and cenk, so that you can wrap around the end of the array in either direction, you may use:
function getAdjascentKey($key, $hash = array(), $increment) {
    $keys = array_keys($hash);
    $found_index = array_search($key, $keys);
    if ($found_index === min(array_keys($keys)) && $increment === -1) {
        $found_index = max(array_keys($keys))+1;
    }
    if ($found_index === max(array_keys($keys)) && $increment === +1) {
        $found_index = min(array_keys($keys))-1;
    }
    return $keys[$found_index+$increment];
}

Answer: Here's a one-liner solution that accepts any type of keys and you can implement in a function or use as is:
$previousKey =
    array_keys($yourArray)[
        array_search(
            $currentKey,
            array_keys($yourArray)
        ) - 1
    ]
    ??
    null;

For example:
$yourArray = [
    30 => ['value1', 'value2', 'value3'],
    'keyA' => ['valueA', 'valueB', 'valueC'],
    8848 => ['valueX', 'valueY', 'valueZ']
];

echo
    array_keys($yourArray)[
        array_search(
                'keyA',
                array_keys($yourArray)
        ) - 1
    ]
    ??
    null;

Would echo 30
Here it is in the form of a function:
/**
 * Given an array and a key, returns the key that precedes it.
 * Works with hash arrays with any type of keys.
 * @param array $array The array to search the previous key in
 * @param mixed $pointerKey The key in the array that follows the key to be returned
 * @return mixed The key that precedes the specified $pointerKey in the $array, or null if the $pointerKey was not found or was the first key.
 */
function getPreviousKey(
    array $array,
    mixed $pointerKey
): mixed {
    return
        array_keys($array)[
            array_search(
                $pointerKey,
                array_keys($array)
            ) - 1
        ]
        ??
        null;
}

Please note:

This code will return null if the specified key was not found, or it was the first key on the array.
Since it makes use of PHP's null coalescing operator ??, this code needs PHP version >= 7.


how can i fix vercel path error when deploying

Question: My project works on local , but i try to deploy to vercel, i got this error Module not found: Can't resolve '../artifacts/contracts/Cartoonz.json' in '/vercel/path0/utils';
Here is my utils/interact.js
my path already exist on const contract, right ?
Comment: How you're deploying your application to Vercel? Have you tried vercel command with force flag? Like this `vercel --force`. Doing this will clear the build cache.
Comment: i am using vercel website , should i use to vercel CLI ? for write this command (vercel  --force)
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Please do not post images of code, anything text-based should be posted as text directly in the question itself and formatted properly as a [mre]. You can get more [formatting help here](https://stackoverflow.com/help/formatting). You can also read about [why you shouldn't post images/links of code](https://meta.stackoverflow.com/q/285551).
Answer: One possible cause for this issue is the fact that some filesystems are case-insensitive, however Vercel deployments use a case-sensitive filesystem. Because of this,  change the letter-casing in filenames on your local machine to match exactly the path
Answer: You have to run vercel from a directory that contains the assets folder, because the parent directories won't be uploaded to vercel.
Can you please post a screenshot of your folder structure, and tell us where you run the vercel command?


How do I programmatically connect to an AKS(Azure kubernetes service) cluster and create a K8 clientset in Golang?

Question: I am trying to fetch all the namespaces present in an AKS cluster programmatically using Golang for which I need to create a Kubernetes clientset for that particular AKS cluster, so that I can list the namespace as follows:
k8ClientSet.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})

I will need to this from outside the cluster so kube-config cannot be used and I will not be able to use the Kubelogin exec plugin since it requires it to be installed on the host system which is not possible. Even, the azure auth plugin has been deprecated.
I tried using the Azure auth plugin although it has been deprecated but it also required creating an apiserver app registration on host Azure AD which is not an ideal solution for me.
As of now, I am trying to use this API provided by Azure - https://learn.microsoft.com/en-us/rest/api/aks/managed-clusters/run-command?tabs=HTTP which I do not think is the best approach, but that's all I have got so far.
Pls help with the issue and share code sample, if possible.
Answer: I got this solution from Azure QnA forum and it worked!
import (
    "context"
    "fmt"
    "os"

    "github.com/Azure/azure-sdk-for-go/profiles/latest/containerservice/mgmt/containerservice"
    "github.com/Azure/go-autorest/autorest"
    "github.com/Azure/go-autorest/autorest/azure/auth"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
)

func main() {
    // Get the AKS cluster credentials using Azure Active Directory authentication
    authorizer, err := auth.NewAuthorizerFromEnvironment()
    if err != nil {
        panic(err.Error())
    }
    subscriptionID := "<your-subscription-id>"
    resourceGroupName := "<your-resource-group-name>"
    clusterName := "<your-aks-cluster-name>"
    client := containerservice.NewManagedClustersClient(subscriptionID)
    client.Authorizer = authorizer
    credentials, err := client.ListClusterAdminCredentials(context.Background(), resourceGroupName, clusterName)
    if err != nil {
        panic(err.Error())
    }
    kubeconfig := string(credentials.Kubeconfigs[0].Value)

    // Create a Kubernetes clientset
    config, err := rest.InClusterConfig()
    if err != nil {
        config, err = clientcmd.NewClientConfigFromBytes([]byte(kubeconfig)).ClientConfig()
        if err != nil {
            panic(err.Error())
        }
    }
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err.Error())
    }

    // List all the namespaces present in the AKS cluster[1](#doc-pos=0)
    namespaces, err := clientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{})
    if err != nil {
        panic(err.Error())
    }

    // Print the name of each namespace
    for _, ns := range namespaces.Items {
        fmt.Println(ns.Name)
    }
}

I had to make a few modifications like instead of auth, I used azidentity for authentication and since azure-sdk-for-go/profiles/latest/containerservice/mgmt/containerservice has been deprecated, I had to use azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v2 instead.


How to get value of node in firebase database in Cloud Function

Question: exports.respublished =
functions.database.ref('/Posts/{postid}').onWrite(event => {
  const snapshot = event.data;
  const postid = event.params.examid;
  const uid = snapshot.child('uid').val();
  const ispublic = snapshot.child('Public').val();
  firebase.database.ref('Users/' + uid).once(event => {
    const snapshot = event.data;
    const name = snapshot.child('name').val();
  });
});

The event is triggered by another node and i want to retrive data from another node of firebase database. I have tried the above code but it produces an error saying TypeError: firebase.database.ref(...).once is not a function.
Comment: Are you sure about that exact error message?  Do you mean `firebase.database.ref().once`?  If so, what is `firebase`?  Did you define it somewhere else?
Answer: yes i got the answer we can use this code
exports.respublished = functions.database.ref('/Posts/{postid}').onWrite(event => {
  const snapshot = event.data;
  const postid = event.params.examid;
  const uid = snapshot.child('uid').val();
  const ispublic = snapshot.child('Public').val();
  return admin.database().ref('Users/' + uid).once(event => {
    const snapshot = event.data;
    const name = snapshot.child('name').val();
  });
});


How to reattach the "head" of a ground wire?

Question: I just bought a new turntable and receiver
When I began using it, I noticed there was a loud buzzing sound coming from it.
Looking at the turntable's cables, there are the two Left and Right RCA cables as well as another cable with a missing head (not sure what the proper word is).
I realized this must be the ground cable and it just has uninsulated wire coming out of it.
Can I buy a new ground "head" and reattach it? How do I do this? Thanks
Comment: Can you provide a photo of where that cable connected to?
Answer: A crimp on eyelet or forked spade connector should do. There's nothing particular about a turntable ground wire like there might be for an antenna wire. I'd probably cut off the damaged end, re-strip with the appropriate size tool, and crimp to fresh wire. A locking pliers (Vice-Grip) works will in a pinch. So to speak.

It's also possible that the wire never had a connector. Some grounding lugs are designed to take a bare wire. Simply wrap the wire once around the lug, under any washer that's present, and snug it down lightly.
Comment: The receiver probably has a ground knob somewhere, probably close to any AM antenna connection. You can clamp it under there.
Comment: Thank you very much. When I reattach it, where do I connect the ground to? Is it okay to connect it to metal on the receiver, or does it have to be metal found elsewhere?
Comment: @Sam: the turntable ground wire *must* go to the receiver. You want the receiver and turntable to have the same ground. Any amp that is designed for a turntable will have a ground (might be marked GND or a [ground symbol](http://i52.tinypic.com/14o7gc5.png)). If it doesn't have one then you could try a random screw on the chassis.
Comment: I just found the ground knob, thanks very much for your help guys. :)


Marine Exterior Lights on Seaside Home

Question: On a residence located about 20 feet from the ocean in a severe weather climate. I am contemplating putting stainless steel well sealed marine lights on the house for some exterior deck lighting and flood lighting.
If I use a step down transformer for converting 120V to  24V, I'm wondering if there is a special junction box that would allow me to split the box and be able to fit transformers in the box at each light ?
Or would it be better to step down the power for the entire circuit near the panel?
I don't know if there's a voltage drop problem but farthest fixture might be 120 feet from the panel.
The lights I'm replacing had aluminum housings and completely degraded from the salt over 15 years. Hoping there is also a gasket-ed stainless box as well out there.
Am I crazy to pursue this ?
Comment: "*allow me to split the box*"  If the box is sealed from the elements what is the purpose of splitting it ? Or what do you mean by "*split the box*" ?
Comment: @AlaskaMan I think they're talking about putting a line voltage/low voltage barrier inside the box
Comment: What is the wattage of the lights in question?  Are they LED?
Comment: 100' - what voltage of lamps are you replacing?
Answer: Yes there are stainless fixtures but for the cost I would probably just purchase currently available led floods or wall packs. The fixtures I use are aluminum but are universal voltage rated 100-277vac.
These low wattage high lumen output fixtures are so much less than a stainless fixture you could replace them 1/2 a dozen times and wire them directly into your existing power.
Look at what is available at myledplace.com or 1000bulbs.com both have a good selection of DLC + UL approval  of LED fixtures I have used both and have had good customer service even on the few failures I have had. dlc is design light consortium and requires a 5 year warranty and you want UL for use in the USA.
The reason I suggest a less expensive aluminum fixture is because the electronics usually don't last as long as a stainless fixture and the non stainless parts inside usually fall apart requiring repair so all the big $ is kind of wasted where a good aluminum fixture will be much cheaper easier to wire so give them a look.
Comment: Based on OPs statement that the current fixtures are 15 years old, and looking at the changes in lighting tech in the last 15 years, this is a very reasonable response.

Marine Exterior Lights on Seaside Home


Find url and link text from string using php code

Question: I want to find url and hyper text  from a paragraph
eg:
$content = "Google The biggest
search engine is google .The lot of people are used google
GoogleThe google video
service is youtube. Youtube.
Google also provide Gmail.";

output like
Text        Url                         Count

Google      htp://google.com             2
Youtube     htp://youtube.com/ncvh/      1
Gmail       htp://gmail.com              1

please anyone help me
Comment: What have you tried so far? We're not going to write the code for you, but will help you fix whatever you've attempted.
Answer: preg_match("/<a\shref\=\"(.*)\"/",$content,$matches);

$matches is an array with all the matches on the regular expression to find links.
each capturing group is an index in $matches.
note that your  tags are not closed. If they were closed, you can also extract the text from the links:
preg_match("/(.*)<\/a>/",$content,$matches);

The regular expression that i used are not waterproof. It relies on the use of double quotes and expects href to be the last attribute in the  tag. You can find optimized regular expressions in online libraries like http://regexlib.com
Comment: If I'd get a dollar for every time I see someone attacking HTML with a RegEx here on SO, I'd be rich as hell. This **won't work**. Yes, it will given the input string, but what if an URI is formatted like `<a title="foo" href="bar"`?
Comment: as I said, 'The regular expressions that i used are not waterproof'. You can find way better ones for this purpose in regex libraries.
Answer: I created pretty much html parsers. Best way for me:
preg_match_all('_(.*?)</a_i', $html, &$matches); to get a attrs and anchor text
preg_match('_href[\s]*=[\s]*[\'"](.*?)[\'"]_', $attrs, &$href) to get href
Parsing href to proper url:
$url = str_replace(array(" ", "\n", "\r", "\t"), '', $url);
$url_components = parse_url(trim($url));


Angular Child Component is not being rendered as parent data changes

Question: Below code I have  method to select hero and it is updating selectedHero of app.component but after updating detail.component is not being rerendered.
please let me know how to notify child component when parent data changes.
app.component.ts
import { heroes } from './Hero.service';
import { Component, OnInit } from '@angular/core';
import {Hero} from './Hero'
import { heroes } from './Hero.service';
import { Component, OnInit } from '@angular/core';
import {Hero} from './Hero'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent  {
  title = 'tour-of-heroes';
  Heroes:Hero[]=heroes;
  selectedHero:Hero;

  constructor(){

  }

  selectHero(hero){
    this.selectedHero = hero;
    console.log(this.selectedHero)
  }
}

master.component.ts
import { Hero } from './../Hero';
import { Component, OnInit, Input, Output} from '@angular/core';
import { EventEmitter } from 'protractor';

@Component({
  selector: 'app-master',
  templateUrl: './master.component.html',
  styleUrls: ['./master.component.scss']
})
export class MasterComponent implements OnInit {
  @Input() Heroes:Hero[];
  @Input() selectHero;
  constructor() { }

  ngOnInit() {
    console.log(this.Heroes,'master Heroes')
  }

}

details.component.ts
import { Hero } from './../Hero';
import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.scss']
})
export class DetailComponent implements OnInit {
  @Input() selectedHero:Hero;
  constructor() { }

  ngOnInit() {
    console.log(this.selectedHero)
  }

}

app.component.html

Tour of Heroes

      <app-master [Heroes]="Heroes" [selectHero]="selectHero"></app-master>

        <app-detail [selectedHero]="selectedHero"></app-detail>

master.component.html

            Id : {{hero.id}}

            Name : {{hero.name}}

detail.component.html

Selected Hero is : {{selectedHero.name}}

Id : {{selectedHero.id}}

Name : {{selectedHero.name}}

In app.compponent selectedHero is being passed to details-component.
Answer: In DetailComponent, Data changes from parent component will be handled on ngOnChanges Life Cycle Hook.
export class DetailComponent implements OnInit, OnChanges {
      @Input() selectedHero:Hero;
      constructor() { }

        ngOnInit() {
           console.log(this.selectedHero)
        }

        ngOnChanges() {
           console.log(this.selectedHero)
        }

    }

Comment: this is not working for me, this.selectedHero is undefined
Comment: You can try using BehaviorSubject from Service. Emit from parent component using service.subject.next(); In Child Component, you can access using service.subject.subscribe() method.