问:
How to add columns into SQL database from another table
I have a table "names" which looks like
|name |
|-----|
|name1|
|name2|
|name3|
|.....|
From this table, I want to use the names as column names for another table "form"
|id|name1|name2|name3|...

The items under "names" are not fixed. I don't know exactly how many items are there.
How do I create this table "form" like this by using php and SQL?

答:
if I understand the question what you need is to have a reference of a table in another one. You can achieve this using foreign keys. They allow you to reference entries of table in another.
For example if I have a table "students" and another one "parents" and I want to know who are the parents of one student I can have in my table "students" a field "ID" that will identify my students uniquely (primary key) and then I will use this identifier in my table "parents" (as a foreign key).
Hence, I will not be able to add a parent with and invalid student ID (that will mean, the unknown student has 'parent_name' as parent which would make no sense).

Primary, and Foreign are SQL topics


来源: stackexchange

问:
How to delete a row in 2 tables which has the same id. How to use join
DELETE FROM tbl_usergroups,'tbl_group' WHERE (tbl_usergroups.tbl_group_GroupID='tbl_group.GroupID') AND(tbl_usergroups.tbl_group_GroupID=27)

GroupID is a foreign key to tbl_usergroups

答:
ITYM

```<code>DELETE FROM `tbl_usergroups` WHERE `tbl_usergroups`.`tbl_group_GroupID`=27
DELETE FROM `tbl_group` WHERE `tbl_group`.`GroupID`=27
</code>```

GroupIDis a foreign key to tbl_usergroups

Then the order of the DELETEs is important.

ContentLicense: CC BY-SA 3.0

Body:
ITYM

DELETE FROM `tbl_usergroups` WHERE `tbl_usergroups`.`tbl_group_GroupID`=27
DELETE FROM `tbl_group` WHERE `tbl_group`.`GroupID`=27

GroupIDis a foreign key to tbl_usergroups

Then the order of the DELETEs is important.


问:
Can someone explain to me the rule in JavaScript that applies here?
So I was playing around with JavaScript, and I ran into a problem. I was trying to make two buttons change the written text above them, with the change being different depending on what was already written. There were only 4 potential options. So what I thought was to just use an if and else ifs to make it work. But it didn’t work. Then over the next couple of hours I went over it again and again and couldn’t make it work. Finally I came up with an idea that made it work but I don’t know why.

The above is very long so you if you’d rather skip it, just read this:
Why does a) work and not b)?

First my HTML:

```<code><html>
    <head>
        <meta charset="utf-8">
        <title>Test</title>
        <link rel="stylesheet" type="text/css" href="stylesheets.css">
        <script rel="javascript" src="script.js"></script>
    </head>
    <body onload="boopFunction()">

        <h1 id="boop"></h1>

        <button onclick="ggFunction()">Leave
        </button>

        <button onclick="eeFunction()">Enter</button>

    </body>
</html>

</code>```

Then what worked, a):

```<code>

var Boop = document.getElementById("boop");

/* onload welcome */
function boopFunction() {
    document.getElementById("boop").innerHTML = Poob[4];
    Boop = Poob[4];
}

/* leave button */
function ggFunction() {

    if (Boop == Poob[0]) {
    document.getElementById("boop").innerHTML = Poob[1];
    Boop = Poob[1];
    }
    else if (Boop == Poob[2]) {

        document.getElementById("boop").innerHTML = Poob[1];
        Boop = Poob[1];
    }
    else if (Boop == Poob[1]) {

        document.getElementById("boop").innerHTML = Poob[3];
        Boop = Poob[3];
    }
    else if (Boop == Poob[4]) {

        document.getElementById("boop").innerHTML = Poob[1];
        Boop = Poob[1];
    }
}

/* enter button */
function eeFunction() {

    if (Boop == Poob[1]) {
    document.getElementById("boop").innerHTML = Poob[0];
    Boop = Poob[0];
    }
    else if (Boop == Poob[3]) {

    document.getElementById("boop").innerHTML = Poob[0];
    Boop = Poob[0];
    }
    else if (Boop == Poob[0]) {
    document.getElementById("boop").innerHTML = Poob[2];
    Boop = Poob[2];
    }
        else if (Boop == Poob[4]) {

        document.getElementById("boop").innerHTML = Poob[0];
        Boop = Poob[0];
    }
}

</code>```

Lastly what did not work, b):

```<code>
var Poob = ["Welcome!", "Goodbye!", "You're still here?", "You're still outside!", "Hello there!"];

var Boop = document.getElementById("boop");

/* onload welcome */
function boopFunction() {
    document.getElementById("boop").innerHTML = Poob[4];
}

/* leave button */
function ggFunction() {

    if (Boop == Poob[0]) {
    document.getElementById("boop").innerHTML = Poob[1];
    }
    else if (Boop == Poob[2]) {

        document.getElementById("boop").innerHTML = Poob[1];
    }
    else if (Boop == Poob[1]) {

        document.getElementById("boop").innerHTML = Poob[3];
    }
    else if (Boop == Poob[4]) {

        document.getElementById("boop").innerHTML = Poob[1];
    }
}

/* enter button */
function eeFunction() {

    if (Boop == Poob[1]) {
    document.getElementById("boop").innerHTML = Poob[0];
    }
    else if (Boop == Poob[3]) {

    document.getElementById("boop").innerHTML = Poob[0];
    }
    else if (Boop == Poob[0]) {
    document.getElementById("boop").innerHTML = Poob[2];
    }
        else if (Boop == Poob[4]) {

        document.getElementById("boop").innerHTML = Poob[0];
    }
}

</code>```

UPDATE: THANK YOU FOR YOUR HELP! This makes a lot more sense! Here is the code (though it’s really just for fun which is why it’s random) that I changed it to with the information you all gave me!

HTML:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Test</title>
        <link rel="stylesheet" type="text/css" href="stylesheets.css">
        <script rel="javascript" src="script.js"></script>
    </head>
    <body onload="olFunction()">

        <h1 id="banner"></h1>

        <button onclick="leaveFunction()">Leave
        </button>

        <button onclick="enterFunction()">Enter</button>

    </body>
</html>

</code>```

JavaScript:

```<code>
var Poof = ["Welcome!", "Goodbye!", "You're still here?", "You're still outside!", "Hello there!"];

var Crash = Poof[4];

/* onload */
function olFunction() {
    document.getElementById("banner").innerHTML = Crash;
}

/* leave button */
function leaveFunction() {

    if (Crash == Poof[0]) {

        Crash = Poof[1];
    }

    else if (Crash == Poof[2]) {

        Crash = Poof[1];
    }

    else if (Crash == Poof[1]) {

        Crash = Poof[3];
    }

    else if (Crash == Poof[4]) {

        Crash = Poof[1];
    }
    document.getElementById("banner").innerHTML = Crash;
}

/* enter button */
function enterFunction() {

    if (Crash == Poof[1]) {

        Crash = Poof[0];
    }

    else if (Crash == Poof[3]) {

        Crash = Poof[0];
    }

    else if (Crash == Poof[0]) {

        Crash = Poof[2];
    }
        else if (Crash == Poof[4]) {

        Crash = Poof[0];
    }

document.getElementById("banner").innerHTML = Crash;
}

</code>```

答:
Reason is easy. Because you have two function and each your function  doesn't include else condition. For initialize your data is html element

```<code>document.getElementById("boop");
</code>```

so u don't enter any of condition so nothing working. Here you should use

document.getElementById("boop").innerHTML;

As solution you will give initialize value like your working example or add else statement and inside it give expected value

ContentLicense: CC BY-SA 4.0

Body:
So I was playing around with JavaScript, and I ran into a problem. I was trying to make two buttons change the written text above them, with the change being different depending on what was already written. There were only 4 potential options. So what I thought was to just use an if and else ifs to make it work. But it didn’t work. Then over the next couple of hours I went over it again and again and couldn’t make it work. Finally I came up with an idea that made it work but I don’t know why.

The above is very long so you if you’d rather skip it, just read this:
Why does a) work and not b)?

First my HTML:

        <meta charset="utf-8">
        <title>Test</title>
        <link rel="stylesheet" type="text/css" href="stylesheets.css">

        <button onclick="ggFunction()">Leave
        </button>

        <button onclick="eeFunction()">Enter</button>

Then what worked, a):

var Boop = document.getElementById("boop");

/* onload welcome */
function boopFunction() {
    document.getElementById("boop").innerHTML = Poob[4];
    Boop = Poob[4];
}

/* leave button */
function ggFunction() {

    if (Boop == Poob[0]) {
    document.getElementById("boop").innerHTML = Poob[1];
    Boop = Poob[1];
    }
    else if (Boop == Poob[2]) {

        document.getElementById("boop").innerHTML = Poob[1];
        Boop = Poob[1];
    }
    else if (Boop == Poob[1]) {

        document.getElementById("boop").innerHTML = Poob[3];
        Boop = Poob[3];
    }
    else if (Boop == Poob[4]) {

        document.getElementById("boop").innerHTML = Poob[1];
        Boop = Poob[1];
    }
}

/* enter button */
function eeFunction() {

    if (Boop == Poob[1]) {
    document.getElementById("boop").innerHTML = Poob[0];
    Boop = Poob[0];
    }
    else if (Boop == Poob[3]) {

    document.getElementById("boop").innerHTML = Poob[0];
    Boop = Poob[0];
    }
    else if (Boop == Poob[0]) {
    document.getElementById("boop").innerHTML = Poob[2];
    Boop = Poob[2];
    }
        else if (Boop == Poob[4]) {

        document.getElementById("boop").innerHTML = Poob[0];
        Boop = Poob[0];
    }
}

Lastly what did not work, b):

var Poob = ["Welcome!", "Goodbye!", "You're still here?", "You're still outside!", "Hello there!"];

var Boop = document.getElementById("boop");

/* onload welcome */
function boopFunction() {
    document.getElementById("boop").innerHTML = Poob[4];
}

/* leave button */
function ggFunction() {

    if (Boop == Poob[0]) {
    document.getElementById("boop").innerHTML = Poob[1];
    }
    else if (Boop == Poob[2]) {

        document.getElementById("boop").innerHTML = Poob[1];
    }
    else if (Boop == Poob[1]) {

        document.getElementById("boop").innerHTML = Poob[3];
    }
    else if (Boop == Poob[4]) {

        document.getElementById("boop").innerHTML = Poob[1];
    }
}

/* enter button */
function eeFunction() {

    if (Boop == Poob[1]) {
    document.getElementById("boop").innerHTML = Poob[0];
    }
    else if (Boop == Poob[3]) {

    document.getElementById("boop").innerHTML = Poob[0];
    }
    else if (Boop == Poob[0]) {
    document.getElementById("boop").innerHTML = Poob[2];
    }
        else if (Boop == Poob[4]) {

        document.getElementById("boop").innerHTML = Poob[0];
    }
}

UPDATE: THANK YOU FOR YOUR HELP! This makes a lot more sense! Here is the code (though it’s really just for fun which is why it’s random) that I changed it to with the information you all gave me!

HTML:

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Test</title>
        <link rel="stylesheet" type="text/css" href="stylesheets.css">

        <button onclick="leaveFunction()">Leave
        </button>

        <button onclick="enterFunction()">Enter</button>

JavaScript:

var Poof = ["Welcome!", "Goodbye!", "You're still here?", "You're still outside!", "Hello there!"];

var Crash = Poof[4];

/* onload */
function olFunction() {
    document.getElementById("banner").innerHTML = Crash;
}

/* leave button */
function leaveFunction() {

    if (Crash == Poof[0]) {

        Crash = Poof[1];
    }

    else if (Crash == Poof[2]) {

        Crash = Poof[1];
    }

    else if (Crash == Poof[1]) {

        Crash = Poof[3];
    }

    else if (Crash == Poof[4]) {

        Crash = Poof[1];
    }
    document.getElementById("banner").innerHTML = Crash;
}

/* enter button */
function enterFunction() {

    if (Crash == Poof[1]) {

        Crash = Poof[0];
    }

    else if (Crash == Poof[3]) {

        Crash = Poof[0];
    }

    else if (Crash == Poof[0]) {

        Crash = Poof[2];
    }
        else if (Crash == Poof[4]) {

        Crash = Poof[0];
    }

document.getElementById("banner").innerHTML = Crash;
}

Body:
Reason is easy. Because you have two function and each your function  doesn't include else condition. For initialize your data is html element

document.getElementById("boop");

so u don't enter any of condition so nothing working. Here you should use

document.getElementById("boop").innerHTML;

As solution you will give initialize value like your working example or add else statement and inside it give expected value


问:
Laravel vue page is not loading and is pending in the network tab
I got question about Laravel and VueJS. I've built my Vue project with npm run watch and I started my Laravel application with php artisan serve to serve the app. When I went visit my website-page, the page would not load and is continuing in a infinite loop. In my network tab, I see an API request has been sent to /js/landing.js, but he seems to be pending for the whole time.

My application is at the moment running on WSL, but I do not know what problem caused this issue.

答:
I'm not sure but maybe if u re-install npm in VueJS?

another idea maybe is clear the cahe in vue and laravel terminal and test again!

php artisan cache:clear
php artisan config:clear

and try to check the log file for laravel and vuejs


问:
What is the limit number of GitLab CI/CD variables?
I am planning to store some of the key/values inside GitLab CI/CD variables? I found in the document that each value is limited to 1000 characters. I am wondering if there is any limitation for the number of keys/values as well?</p>

答:
It would be 25 according to the default plan but you can change it. Hope that answers your question!

https://docs.gitlab.com/ee/administration/instance_limits.html#number-of-instance-level-variables

Well, I see now that Tolis already clarified it but I will still post this :)


问:
Optaplanner: How to get solver instance in Quarkus
I am using Quarkus optaplanner, so instead of using SolverFactory to build a solver, I us ethe Quarkus way to inject a solverManager then let it solve the problem:

```<code>val solverJob: SolverJob<SolarDesign, UUID> = solverManager.solve(problemId, problem)
</code>```

But I want to still be able to addEventListener like:

```<code>solver.addEventListener(SolverEventListener<SolarDesign>() {
            fun bestSolutionChanged(event: BestSolutionChangedEvent<MyProblem>) {
                val solution = event.getNewBestSolution()
                if (solution.score.isFeasible()) {
                    println("found new best solution")
                    println(solution)
                }
            }
        })
</code>```

Question is how do I get a solver instance in Quarkus optaplanner so I can use it to addEventListener? It does not seem to be doable from solverManager.

Thanks

答:
Yes, that is possible with SolverManager and you don't need to obtain a Solver instance.

Use SolverManager.solverAndListen(problemId, problemFinder, bestSolutionConsumer). The third argument is a consumer where you can do whatever you want with each best solution that is found. It could look something like this in your case:

fun solve() {
    val solverJob: SolverJob<SolarDesign, UUID> = solverManager
        .solveAndListen(problemId, { problemId -> problem }, this::printSolution)
}

fun printSolution(solution: SolarDesign) {
    if (solution.score.isFeasible()) {
        println("found new best solution")
        println(solution)
    }
}
```

Find more details in this section about SolverManager.

Body:
I am using Quarkus optaplanner, so instead of using SolverFactory to build a solver, I us ethe Quarkus way to inject a solverManager then let it solve the problem:

val solverJob: SolverJob<SolarDesign, UUID> = solverManager.solve(problemId, problem)

But I want to still be able to addEventListener like:

solver.addEventListener(SolverEventListener<SolarDesign>() {
            fun bestSolutionChanged(event: BestSolutionChangedEvent<MyProblem>) {
                val solution = event.getNewBestSolution()
                if (solution.score.isFeasible()) {
                    println("found new best solution")
                    println(solution)
                }
            }
        })

Question is how do I get a solver instance in Quarkus optaplanner so I can use it to addEventListener? It does not seem to be doable from solverManager.

Thanks

Body:
Yes, that is possible with SolverManager and you don't need to obtain a Solver instance.

Use SolverManager.solverAndListen(problemId, problemFinder, bestSolutionConsumer). The third argument is a consumer where you can do whatever you want with each best solution that is found. It could look something like this in your case:

fun solve() {
    val solverJob: SolverJob<SolarDesign, UUID> = solverManager
        .solveAndListen(problemId, { problemId -> problem }, this::printSolution)
}

fun printSolution(solution: SolarDesign) {
    if (solution.score.isFeasible()) {
        println("found new best solution")
        println(solution)
    }
}

Find more details in this section about SolverManager.


问:
Cannot use ant layout slider collapsable with SSR with NextJs
I'm using antd within my NextJs app. I placed a Layout component at the top level of my app.

```<code>/* _app.tsx */
function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      <SideMenuLayout>
        <div>Patate</div>
      </SideMenuLayout>
    </Provider>
  );
}

/* sideMenuLayout.tsx */
const SideMenuLayout = ({ children }: SideMenuLayoutProps) => {
  const [collapsed, setCollapsed] = useState(false);
  const { Sider } = Layout;

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed}>
        <div className="logo" />
        <Menu theme="dark" defaultSelectedKeys={["1"]} mode="inline">
          <Menu.Item key="2" icon={<DesktopOutlined />}>
            Play
          </Menu.Item>
        </Menu>
      </Sider>
      <Layout className="site-layout">{children}</Layout>
    </Layout>
  );
};
</code>```

I get the error "Warning: useLayoutEffect does nothing on the server".

I understand <sider collapsible... use this useLayoutEffect. I don't understand why default mode is SSR in my case. I'm not sure how I should proceed if I wanna keep the sider collapsable.

Thanks!

答:
By default, Next.js attempts to pre-render your pages, useEffect is an indicator of client-side code.

However, is interesting how useLayoutEffect is notified as a warning without more details. Since it is omitted on the server pre-render as useEffect is, having this call skipped on the server-side may affect the pre-rendered version of the component. For example, the absolute positioning of an element in the center of a screen depends on screen size, and will not produce the desired result via pre-render.

Perhaps, indicating that your component is dynamic, and not to be considered during the pre-render phase from the get-go is the way-to-go:

import dynamic from "next/dynamic";
const NossrSider = dynamic(() => {
   const [collapsed, setCollapsed] = useState(false);
   const { Sider } = Layout;
   return <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed}>

        <Menu theme="dark" defaultSelectedKeys={["1"]} mode="inline">
          <Menu.Item key="2" icon={<DesktopOutlined />}>
            Play
          </Menu.Item>
        </Menu>
      </Sider>
},
 {ssr: false}
);
```

Body:
I'm using antd within my NextJs app. I placed a Layout component at the top level of my app.

/* _app.tsx */
function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      <SideMenuLayout>

Patate

      </SideMenuLayout>
    </Provider>
  );
}

/* sideMenuLayout.tsx */
const SideMenuLayout = ({ children }: SideMenuLayoutProps) => {
  const [collapsed, setCollapsed] = useState(false);
  const { Sider } = Layout;

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed}>

        <Menu theme="dark" defaultSelectedKeys={["1"]} mode="inline">
          <Menu.Item key="2" icon={<DesktopOutlined />}>
            Play
          </Menu.Item>
        </Menu>
      </Sider>
      <Layout className="site-layout">{children}</Layout>
    </Layout>
  );
};

I get the error "Warning: useLayoutEffect does nothing on the server".

I understand <sider collapsible... use this useLayoutEffect. I don't understand why default mode is SSR in my case. I'm not sure how I should proceed if I wanna keep the sider collapsable.

Thanks!

Body:
By default, Next.js attempts to pre-render your pages, useEffect is an indicator of client-side code.

However, is interesting how useLayoutEffect is notified as a warning without more details. Since it is omitted on the server pre-render as useEffect is, having this call skipped on the server-side may affect the pre-rendered version of the component. For example, the absolute positioning of an element in the center of a screen depends on screen size, and will not produce the desired result via pre-render.

Perhaps, indicating that your component is dynamic, and not to be considered during the pre-render phase from the get-go is the way-to-go:

import dynamic from "next/dynamic";
const NossrSider = dynamic(() => {
   const [collapsed, setCollapsed] = useState(false);
   const { Sider } = Layout;
   return <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed}>
        <div className="logo" />
        <Menu theme="dark" defaultSelectedKeys={["1"]} mode="inline">
          <Menu.Item key="2" icon={<DesktopOutlined />}>
            Play
          </Menu.Item>
        </Menu>
      </Sider>
},
 {ssr: false}
);


问:
MongoDB query to find text in third level array of objects
I have a Mongo collection that contains data on saved searches in a Vue/Laravel app, and it contains records like the following:

```<code>{
    "_id" : ObjectId("6202f3357a02e8740039f343"),
    "q" : null,
    "name" : "FCA last 3 years",
    "frequency" : "Daily",
    "scope" : "FederalContractAwardModel",
    "filters" : {
        "condition" : "AND",
        "rules" : [
            {
                "id" : "awardDate",
                "operator" : "between_relative_backward",
                "value" : [
                    "now-3.5y/d",
                    "now/d"
                ]
            },
            {
                "id" : "subtypes.extentCompeted",
                "operator" : "in",
                "value" : [
                    "Full and Open Competition"
                ]
            }
        ]
    },
</code>```

The problem is the value in the item in the rules array that has the decimal.

```<code>"value" : [
    "now-3.5y/d",
    "now/d"
]
</code>```

in particular the decimal. Because of a UI error, the user was allowed to enter a decimal value, and so this needs to be fixed to remove the decimal like so.

```<code>"value" : [
    "now-3y/d",
    "now/d"
]
</code>```

My problem is writing a Mongo query to identify these records (I'm a Mongo noob). What I need is to identify records in this collection that have an item in the filters.rules array with an item in the 'value` array that contains a decimal.

Piece of cake, right?

Here's as far as I've gotten.

```<code>myCollection.find({"filters.rules": })
</code>```

but I'm not sure where to go from here.

UPDATE: After running the regex provided by @R2D2, I found that it also brings up records with a valid date string , e.g.

```<code>        "rules" : [
            {
                "id" : "dueDate",
                "operator" : "between",
                "value" : [
                    "2018-09-10T19:04:00.000Z",
                    null
                ]
            },
</code>```

so what I need to do is filter out cases where the period has a double 0 on either side (i.e. 00.00). If I read the regex correctly, this part

```<code>[^\.]
</code>```

is excluding characters, so I would want something like

```<code>[^00\.00]
</code>```

but running this query

```<code>db.collection.find( {
         "filters.rules.value": { $regex:  /\.[^00\.00]*/ }
         } )
</code>```

still returns the same records, even though it works as expected in a regex tester. What am I missing?

答:
To find all documents containing at least one value string  with (.) , try:

```<code>    db.collection.find( {
         "filters.rules.value": { $regex:  /\.[^\.]*/ }
         } )
</code>```

Or you can filter only the fields that need fix via aggregation as follow:

```<code> [direct: mongos]> db.tes.aggregate([ {$unwind:"$filters.rules"}, {$unwind:"$filters.rules.value"}, {$match:{ "filters.rules.value": {$regex:  /\.[^\.]*/    } }}  ,{$project:{_id:1,oldValue:"$filters.rules.value"}}       ])
[
 { _id: ObjectId("6202f3357a02e8740039f343"), oldValue: 'now-3.5y/d' }
]
[direct: mongos]>
</code>```

Later to update those values:

```<code> db.collection.update({
   "filters.rules.value": "now-3.5y/d"
   },
   {
     $set: {
      "filters.rules.$[x].value.$": "now-3,5y/d-CORRECTED"
    }
   },
   {
     arrayFilters: [
   {
     "x.value": "now-3.5y/d"
   }
  ]
  })
</code>```

playground

Body:
I have a Mongo collection that contains data on saved searches in a Vue/Laravel app, and it contains records like the following:

{
    "_id" : ObjectId("6202f3357a02e8740039f343"),
    "q" : null,
    "name" : "FCA last 3 years",
    "frequency" : "Daily",
    "scope" : "FederalContractAwardModel",
    "filters" : {
        "condition" : "AND",
        "rules" : [
            {
                "id" : "awardDate",
                "operator" : "between_relative_backward",
                "value" : [
                    "now-3.5y/d",
                    "now/d"
                ]
            },
            {
                "id" : "subtypes.extentCompeted",
                "operator" : "in",
                "value" : [
                    "Full and Open Competition"
                ]
            }
        ]
    },

The problem is the value in the item in the rules array that has the decimal.

"value" : [
    "now-3.5y/d",
    "now/d"
]

in particular the decimal. Because of a UI error, the user was allowed to enter a decimal value, and so this needs to be fixed to remove the decimal like so.

"value" : [
    "now-3y/d",
    "now/d"
]

My problem is writing a Mongo query to identify these records (I'm a Mongo noob). What I need is to identify records in this collection that have an item in the filters.rules array with an item in the 'value` array that contains a decimal.

Piece of cake, right?

Here's as far as I've gotten.

myCollection.find({"filters.rules": })

but I'm not sure where to go from here.

UPDATE: After running the regex provided by @R2D2, I found that it also brings up records with a valid date string , e.g.

        "rules" : [
            {
                "id" : "dueDate",
                "operator" : "between",
                "value" : [
                    "2018-09-10T19:04:00.000Z",
                    null
                ]
            },

so what I need to do is filter out cases where the period has a double 0 on either side (i.e. 00.00). If I read the regex correctly, this part

[^\.]

is excluding characters, so I would want something like

[^00\.00]

but running this query

db.collection.find( {
         "filters.rules.value": { $regex:  /\.[^00\.00]*/ }
         } )

still returns the same records, even though it works as expected in a regex tester. What am I missing?

Body:
To find all documents containing at least one value string  with (.) , try:

    db.collection.find( {
         "filters.rules.value": { $regex:  /\.[^\.]*/ }
         } )

Or you can filter only the fields that need fix via aggregation as follow:

 [direct: mongos]> db.tes.aggregate([ {$unwind:"$filters.rules"}, {$unwind:"$filters.rules.value"}, {$match:{ "filters.rules.value": {$regex:  /\.[^\.]*/    } }}  ,{$project:{_id:1,oldValue:"$filters.rules.value"}}       ])
[
 { _id: ObjectId("6202f3357a02e8740039f343"), oldValue: 'now-3.5y/d' }
]
[direct: mongos]>

Later to update those values:

 db.collection.update({
   "filters.rules.value": "now-3.5y/d"
   },
   {
     $set: {
      "filters.rules.$[x].value.$": "now-3,5y/d-CORRECTED"
    }
   },
   {
     arrayFilters: [
   {
     "x.value": "now-3.5y/d"
   }
  ]
  })

playground


问:
In a Github Action, how to get diff of files from a Pull Request AFTER Closing/Merging?
I'm trying to run some code in a GitHub Action that depends on files that were merged in to our develop branch. I can't seem to find the right environment variables or event values to get the diff of the pull request after it has been merged. I have tried running this on push to the develop branch as well as on a pull request with type: closed and a conditional on whether the pull request was merged.

Here are two things I've tried:

closed pull request:

```<code>name: test_pr_action
on:
  pull_request:
    types:
      - closed

jobs:
  job1:
    if: github.event.pull_request.merged == 'true'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          ref: ${{ github.ref }}
      - name: one step
        run: |
          git fetch origin $GITHUB_BASE_REF --depth=1
          git diff --diff-filter=AM --name-only ${{ github.event.base.sha }} ${{ github.event.head.sha }}
</code>```

For the pull request, the step runs but does not pick up the SHAs so does not output anything.

push:

```<code>name: test_pr_action

on:
  push:
    branches:
      - main

jobs:
  job1:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          ref: ${{ github.ref }}
      - name: one step
        run: |
          git fetch origin $GITHUB_BASE_REF --depth=1
          git diff --diff-filter=AM --name-only ${{ github.event.before }} ${{ github.event.after }}
</code>```

For the push, the step fails because it doesn't like the first SHA.

I already have actions that run on push and on pull request BEFORE merge, so I have used these values before, but can't get it to work for this case.

Any advice helps! Thanks!

答:
Thanks to @GuiFalourd I was able to get this to work with the changed-files action.

My code ended up looking something like this:

```<code>name: action1
on:
  push:
    branches: [ develop ]

jobs:
  job1:
    runs-on: machine1
    steps:
      - uses: actions/checkout@v2
        with:
          ref: ${{ github.ref }}
      - name: Get changed files
        id: changed-files
        uses: tj-actions/changed-files@v14.4
        with:
          since_last_remote_commit: 'true'
      - name: get_modified_files
        id: diff
        working-directory: './diff_files'
        run: |
          git config diff.renameLimit 99000
          git fetch origin $GITHUB_BASE_REF --depth=1
          touch files.txt
          for file in ${{ steps.changed-files.outputs.all_changed_files }}; do
            echo $file >> files.txt
          done
          cat files.txt | split -l 100 -a 8
          rm files.txt
          export filename_string=""
          for i in `ls`; do export filename_string=$filename_string"file!"$i; done
          echo "::set-output name=filenames::$filename_string"
</code>```

For anyone wondering what all the extra stuff is, I'm reading each filename from the all_changed_files variable into a separate file, which I cat and split into several other files, which are left in the diff_files directory. This directory is then read by my python script that runs in subsequent steps. I break it up into separate files like this because the PRs in this repo tend to have thousands of file diffs.

Body:
I'm trying to run some code in a GitHub Action that depends on files that were merged in to our develop branch. I can't seem to find the right environment variables or event values to get the diff of the pull request after it has been merged. I have tried running this on push to the develop branch as well as on a pull request with type: closed and a conditional on whether the pull request was merged.

Here are two things I've tried:

closed pull request:

name: test_pr_action
on:
  pull_request:
    types:
      - closed

jobs:
  job1:
    if: github.event.pull_request.merged == 'true'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          ref: ${{ github.ref }}
      - name: one step
        run: |
          git fetch origin $GITHUB_BASE_REF --depth=1
          git diff --diff-filter=AM --name-only ${{ github.event.base.sha }} ${{ github.event.head.sha }}

For the pull request, the step runs but does not pick up the SHAs so does not output anything.

push:

name: test_pr_action

on:
  push:
    branches:
      - main

jobs:
  job1:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          ref: ${{ github.ref }}
      - name: one step
        run: |
          git fetch origin $GITHUB_BASE_REF --depth=1
          git diff --diff-filter=AM --name-only ${{ github.event.before }} ${{ github.event.after }}

For the push, the step fails because it doesn't like the first SHA.

I already have actions that run on push and on pull request BEFORE merge, so I have used these values before, but can't get it to work for this case.

Any advice helps! Thanks!

Body:
Thanks to @GuiFalourd I was able to get this to work with the changed-files action.

My code ended up looking something like this:

name: action1
on:
  push:
    branches: [ develop ]

jobs:
  job1:
    runs-on: machine1
    steps:
      - uses: actions/checkout@v2
        with:
          ref: ${{ github.ref }}
      - name: Get changed files
        id: changed-files
        uses: tj-actions/changed-files@v14.4
        with:
          since_last_remote_commit: 'true'
      - name: get_modified_files
        id: diff
        working-directory: './diff_files'
        run: |
          git config diff.renameLimit 99000
          git fetch origin $GITHUB_BASE_REF --depth=1
          touch files.txt
          for file in ${{ steps.changed-files.outputs.all_changed_files }}; do
            echo $file >> files.txt
          done
          cat files.txt | split -l 100 -a 8
          rm files.txt
          export filename_string=""
          for i in `ls`; do export filename_string=$filename_string"file!"$i; done
          echo "::set-output name=filenames::$filename_string"

For anyone wondering what all the extra stuff is, I'm reading each filename from the all_changed_files variable into a separate file, which I cat and split into several other files, which are left in the diff_files directory. This directory is then read by my python script that runs in subsequent steps. I break it up into separate files like this because the PRs in this repo tend to have thousands of file diffs.


问:
How to parse and convert string list to JSON string array in shell command?
How to parse and convert string list to JSON string array in shell command?

```<code>'["test1","test2","test3"]'
</code>```

to

```<code>test1
test2
test3
</code>```

I tried like below:

```<code>string=$1
array=${string#"["}
array=${array%"]"}

IFS=',' read -a array <<< $array;

echo "${array[@]}"
</code>```

Any other optimized way?

答:
As bash and jq are tagged, this solution relies on both (without summoning eval). The input string is expected to be in $string, the output array is generated into ${array[@]}. It is robust wrt spaces, newlines, quotes, etc. as it uses NUL as delimiter.

mapfile -d '' array < <(jq -j '.[] + "\u0000"' <<< "$string")
```
<h5>Testing</h5>
<pre class="lang-sh prettyprint-override"><code>string='["has spaces\tand tabs","has a\nnewline","has \"quotes\""]'
mapfile -d '' array < <(jq -j '.[] + "\u0000"' <<< "$string")
printf '==>%s<==\n' "${array[@]}"
</code>```
```<code>==>has spaces   and tabs<==
==>has a
newline<==
==>has "quotes"<==
</code>```

Body:
How to parse and convert string list to JSON string array in shell command?

'["test1","test2","test3"]'

to

test1
test2
test3

I tried like below:

string=$1
array=${string#"["}
array=${array%"]"}

IFS=',' read -a array <<< $array;

echo "${array[@]}"

Any other optimized way?

Body:
As bash and jq are tagged, this solution relies on both (without summoning eval). The input string is expected to be in $string, the output array is generated into ${array[@]}. It is robust wrt spaces, newlines, quotes, etc. as it uses NUL as delimiter.

mapfile -d '' array < <(jq -j '.[] + "\u0000"' <<< "$string")

Testing

string='["has spaces\tand tabs","has a\nnewline","has \"quotes\""]'
mapfile -d '' array < <(jq -j '.[] + "\u0000"' <<< "$string")
printf '==>%s<==\n' "${array[@]}"

==>has spaces   and tabs<==
==>has a
newline<==
==>has "quotes"<==


问:
How to group values in a column (R)
I'm creating a summary table that groups my records by country of destination:

```<code>SummarybyLocation <- PSTNRecords %>%
                           group_by(Destination) %>%
                                summarize(
                                  Calls = n(),
                                  Minutes = sum(durationMinutes),
                                  MaxDuration = max(durationMinutes),
                                  AverageDuration = mean(durationMinutes),
                                  Charges = sum(charge),
                                  Fees = sum(connectionCharge)
                                )

SummarybyLocation
</code>```

The resulting table is as follows:

I realized that the Destination values are inconsistent (for example,  "France" and "FR" both refer to the same area, and then I have a "North America" that I presume gathers USA and Canada.

I was wondering if there's a way of creating custom groups for these values, so that the aggregation would make more sense. I tried to use the countrycode package to add an iso2c column, but that doesn't resolve the problem of managing other area aggregations like "North America".

I would really appreciate some suggestions on how to handle this.

Thanks in advance!

答:
Here is one possibility for cleaning up the data with a very minimal example. First, I get a list of country names and the 2 and 3 letter abbreviations, and put into a dataframe, countries. Then, I left_join countries to df for the two letter code, which in this case matches FR. Then, I repeat the left_join but with the 3 letter code, which has no matches in this case. Then, I coalesce the two new columns together, i.e., Country.x and Country.y. Then, I use case_when to multiple if-else statements. First, if Country is not an NA, then I replace Destination with the full country name. This is where you can add in other arguments if you have other items (e.g., Europe) that you might also need to fix. Next, I replace North America with "United States-Canada-Mexico". Finally, I remove the columns that start with "Country".

```<code>library(XML)
library(RCurl)
library(rlist)
library(tidyverse)

theurl <-
  getURL("https://www.iban.com/country-codes",
         .opts = list(ssl.verifypeer = FALSE))
countries <- readHTMLTable(theurl)
countries <-
  list.clean(countries, fun = is.null, recursive = FALSE)[[1]]

df %>%
  left_join(.,
            countries %>% select(Country, `Alpha-2 code`),
            by = c("Destination" = "Alpha-2 code")) %>%
  left_join(.,
            countries %>% select(Country, `Alpha-3 code`),
            by = c("Destination" = "Alpha-3 code")) %>%
  mutate(
    Country = coalesce(Country.x, Country.y),
    Destination = case_when(!is.na(Country) ~ Country,
                            Destination == "North America" ~ "United States-Canada-Mexico",
                            TRUE ~ Destination
  )) %>%
select(-c(starts_with("Country")))
</code>```

Output

```<code>                  Destination durationMinutes charge connectionCharge
1                      France            6.57   0.00                0
2                      France            3.34   1.94                0
3               United States          234.40   3.00                0
4 United States-Canada-Mexico           23.40   2.00                0
</code>```

However, if you have a lot of different variations, then you probably just want to create a simple dataframe with the substitutions, as then you can just do one left_join.

Another option is to also add in a Continent column, which you could get from countrycode.

```<code>library(countrycode)

countrycode(sourcevar = df$Destination,
            origin = "country.name",
            destination = "continent")

[1] NA         "Europe"   "Americas" NA
</code>```

Data

```<code>df <- structure(list(Destination = c("FR", "France", "United States",
"North America"), durationMinutes = c(6.57, 3.34, 234.4, 23.4
), charge = c(0, 1.94, 3, 2), connectionCharge = c(0, 0, 0, 0
)), class = "data.frame", row.names = c(NA, -4L))
</code>```

Title: How to group values in a column (R)

Body:
I'm creating a summary table that groups my records by country of destination:

SummarybyLocation <- PSTNRecords %>%
                           group_by(Destination) %>%
                                summarize(
                                  Calls = n(),
                                  Minutes = sum(durationMinutes),
                                  MaxDuration = max(durationMinutes),
                                  AverageDuration = mean(durationMinutes),
                                  Charges = sum(charge),
                                  Fees = sum(connectionCharge)
                                )

SummarybyLocation

The resulting table is as follows:

I realized that the Destination values are inconsistent (for example,  "France" and "FR" both refer to the same area, and then I have a "North America" that I presume gathers USA and Canada.

I was wondering if there's a way of creating custom groups for these values, so that the aggregation would make more sense. I tried to use the countrycode package to add an iso2c column, but that doesn't resolve the problem of managing other area aggregations like "North America".

I would really appreciate some suggestions on how to handle this.

Thanks in advance!

Body:
Here is one possibility for cleaning up the data with a very minimal example. First, I get a list of country names and the 2 and 3 letter abbreviations, and put into a dataframe, countries. Then, I left_join countries to df for the two letter code, which in this case matches FR. Then, I repeat the left_join but with the 3 letter code, which has no matches in this case. Then, I coalesce the two new columns together, i.e., Country.x and Country.y. Then, I use case_when to multiple if-else statements. First, if Country is not an NA, then I replace Destination with the full country name. This is where you can add in other arguments if you have other items (e.g., Europe) that you might also need to fix. Next, I replace North America with "United States-Canada-Mexico". Finally, I remove the columns that start with "Country".

library(XML)
library(RCurl)
library(rlist)
library(tidyverse)

theurl <-
  getURL("https://www.iban.com/country-codes",
         .opts = list(ssl.verifypeer = FALSE))
countries <- readHTMLTable(theurl)
countries <-
  list.clean(countries, fun = is.null, recursive = FALSE)[[1]]

df %>%
  left_join(.,
            countries %>% select(Country, `Alpha-2 code`),
            by = c("Destination" = "Alpha-2 code")) %>%
  left_join(.,
            countries %>% select(Country, `Alpha-3 code`),
            by = c("Destination" = "Alpha-3 code")) %>%
  mutate(
    Country = coalesce(Country.x, Country.y),
    Destination = case_when(!is.na(Country) ~ Country,
                            Destination == "North America" ~ "United States-Canada-Mexico",
                            TRUE ~ Destination
  )) %>%
select(-c(starts_with("Country")))

Output

                  Destination durationMinutes charge connectionCharge
1                      France            6.57   0.00                0
2                      France            3.34   1.94                0
3               United States          234.40   3.00                0
4 United States-Canada-Mexico           23.40   2.00                0

However, if you have a lot of different variations, then you probably just want to create a simple dataframe with the substitutions, as then you can just do one left_join.

Another option is to also add in a Continent column, which you could get from countrycode.

library(countrycode)

countrycode(sourcevar = df$Destination,
            origin = "country.name",
            destination = "continent")

[1] NA         "Europe"   "Americas" NA

Data

df <- structure(list(Destination = c("FR", "France", "United States",
"North America"), durationMinutes = c(6.57, 3.34, 234.4, 23.4
), charge = c(0, 1.94, 3, 2), connectionCharge = c(0, 0, 0, 0
)), class = "data.frame", row.names = c(NA, -4L))


问:
Find row where values for column is maximal in a pandas DataFrame
How can I find the row for which the value of a specific column is maximal?

df.max() will give me the maximal value for each column, I don't know how to get the corresponding row.

答:
If there are ties in the maximum values, then idxmax returns the index of only the first max value. For example, in the following DataFrame:

```<code>   A  B  C
0  1  0  1
1  0  0  1
2  0  0  0
3  0  1  1
4  1  0  0
</code>```

idxmax returns

```<code>A    0
B    3
C    0
dtype: int64
</code>```

Now, if we want all indices corresponding to max values, then we could use max + eq to create a boolean DataFrame, then use it on df.index to filter out indexes:

```<code>out = df.eq(df.max()).apply(lambda x: df.index[x].tolist())
</code>```

Output:

```<code>A       [0, 4]
B          [3]
C    [0, 1, 3]
dtype: object
</code>```

Body:
If there are ties in the maximum values, then idxmax returns the index of only the first max value. For example, in the following DataFrame:

   A  B  C
0  1  0  1
1  0  0  1
2  0  0  0
3  0  1  1
4  1  0  0

idxmax returns

A    0
B    3
C    0
dtype: int64

Now, if we want all indices corresponding to max values, then we could use max + eq to create a boolean DataFrame, then use it on df.index to filter out indexes:

out = df.eq(df.max()).apply(lambda x: df.index[x].tolist())

Output:

A       [0, 4]
B          [3]
C    [0, 1, 3]
dtype: object


问:
define 32bit on 64bit
i have some C files here (you don't need to know what's inside), it's in stable 32bit mode (with gcc -m32), now i want to do more 64bit (gcc -m64) it has some minor bugs\

question:

so how to use a 32bit C number (how 32bit works), on 64bit\

more understandable explanation:
i want to use 32bit in 64bit mode (-m64, there is some way works 32bit C cannot work in 64bit C)

The most common error about this problem:

"Cast to pointer from integer of different size"

I really need help!\

答:
"Cast to pointer from integer of different size"

Oh no. Go through your code and get rid of all casts between pointer and integer that don't convert from or to intptr_t, uintptr_t, or ptrdiff_t. If you convert between pointer and other-sized integer it won't work no matter how many layers of indirection you use.

Once you've done that and you still need certain-sized integers for I/O reasons use the definitions from stdint.h:

int16_t: signed 16 bit integer

uint16_t: unsigned 16 bit integer

int32_t: signed 32 bit integer

uint32_t: unsigned 32 bit integer

int64_t: signed 64 bit integer

uint64_t: unsigned 64 bit integer

Keep size_t for array sizes, don't use it in on-disk formats. It changes.

Title: define 32bit on 64bit


问:
How to change font color of the title in grouped type UITableView?
I have a grouped type table view and it looks pretty cool.

But, if I change the background color of the table to black, the titles becomes unclear.

Is it possible to change the font color and its styles so that I can make it more readable? Should I implement the tableView:viewForHeaderInSection: method?

答:
From apple documentation

The table view uses a fixed font style for section header titles. If you want a different font style, return a custom view (for example, a UILabel object) in the delegate method tableView:viewForHeaderInSection: instead.

So use the below method and return your custom view (UILabel) with your choice of font.

```<code>- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
</code>```

Read from apple documentation

Body:
From apple documentation

The table view uses a fixed font style for section header titles. If you want a different font style, return a custom view (for example, a UILabel object) in the delegate method tableView:viewForHeaderInSection: instead.

So use the below method and return your custom view (UILabel) with your choice of font.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

Read from apple documentation


问:
App Immediatley crashes once app runs with error ClassNotFoundException: Didn't find class application on path: DexPathList
Starting a new project and I am experiencing the following error... I have tried other solutions but seem to be dated

Steps I have tried:

Double checked plugins (listed below)

Instance Run (not listed)

tried using kapt in-place of annotationProccessor (produces a different error)

```<code>    Process: com.example.transfer_tracker, PID: 28953
    java.lang.RuntimeException: Unable to instantiate application com.example.transfer_tracker.CoreApplication package com.example.transfer_tracker: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1364)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:76)
        at androidx.core.app.CoreComponentFactory.instantiateApplication(CoreComponentFactory.java:52)
        at android.app.Instrumentation.newApplication(Instrumentation.java:1177)
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1356)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
        Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
                ... 15 more
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.Hilt_CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                ... 18 more
        [CIRCULAR REFERENCE:java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;]
</code>```

Android Manifest

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.transfer_tracker">

    <application
        android:name=".CoreApplication"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TransferTracker">
        <activity
            android:name=".login.LauncherActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

</code>```

Project build.gradle

```<code>buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20"
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.40.5'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Module project.gradle

```<code>plugins {
    id 'com.android.application'
    id 'kotlin-kapt'
    id 'kotlin-android'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.transfer_tracker"
        minSdk 22
        targetSdk 31
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'com.google.dagger:hilt-android:2.40.5'
    annotationProcessor 'com.google.dagger:hilt-compiler:2.40.5'
}
</code>```

Application Class

```<code>package com.example.transfer_tracker

import android.app.Application
import androidx.multidex.MultiDexApplication
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class CoreApplication : Application()
</code>```

when using kapt instead of annotationProccessor

```<code>public final class CoreApplication extends android.app.Application {
             ^
  Expected @HiltAndroidApp to have a value. Did you forget to apply the Gradle Plugin? (dagger.hilt.android.plugin)
  See https://dagger.dev/hilt/gradle-setup.html
  [Hilt] Processing did not complete. See error above for details.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
   > java.lang.reflect.InvocationTargetException (no error message)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
</code>```

UPDATE

Implemented with Dagger2 error is gone... maybe this is due to a bug within the Hilt library

答:
After adding these dependencies everything works fine</p>
```<code>implementation 'com.google.dagger:hilt-android:2.40.5'
implementation 'androidx.navigation:navigation-fragment-ktx:2.4.0'
implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03'
annotationProcessor 'androidx.hilt:hilt-compiler:1.0.0'
annotationProcessor 'com.google.dagger:hilt-android-compiler:2.38.1'
</code>```

Body:
Starting a new project and I am experiencing the following error... I have tried other solutions but seem to be dated

Steps I have tried:

Double checked plugins (listed below)

Instance Run (not listed)

tried using kapt in-place of annotationProccessor (produces a different error)

    Process: com.example.transfer_tracker, PID: 28953
    java.lang.RuntimeException: Unable to instantiate application com.example.transfer_tracker.CoreApplication package com.example.transfer_tracker: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1364)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:76)
        at androidx.core.app.CoreComponentFactory.instantiateApplication(CoreComponentFactory.java:52)
        at android.app.Instrumentation.newApplication(Instrumentation.java:1177)
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1356)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
        Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
                ... 15 more
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.Hilt_CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                ... 18 more
        [CIRCULAR REFERENCE:java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;]

Android Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.transfer_tracker">

    <application
        android:name=".CoreApplication"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TransferTracker">
        <activity
            android:name=".login.LauncherActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Project build.gradle

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20"
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.40.5'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module project.gradle

plugins {
    id 'com.android.application'
    id 'kotlin-kapt'
    id 'kotlin-android'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.transfer_tracker"
        minSdk 22
        targetSdk 31
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'com.google.dagger:hilt-android:2.40.5'
    annotationProcessor 'com.google.dagger:hilt-compiler:2.40.5'
}

Application Class

package com.example.transfer_tracker

import android.app.Application
import androidx.multidex.MultiDexApplication
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class CoreApplication : Application()

when using kapt instead of annotationProccessor

public final class CoreApplication extends android.app.Application {
             ^
  Expected @HiltAndroidApp to have a value. Did you forget to apply the Gradle Plugin? (dagger.hilt.android.plugin)
  See https://dagger.dev/hilt/gradle-setup.html
  [Hilt] Processing did not complete. See error above for details.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
   > java.lang.reflect.InvocationTargetException (no error message)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

UPDATE

Implemented with Dagger2 error is gone... maybe this is due to a bug within the Hilt library

Body:
After adding these dependencies everything works fine

implementation 'com.google.dagger:hilt-android:2.40.5'
implementation 'androidx.navigation:navigation-fragment-ktx:2.4.0'
implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03'
annotationProcessor 'androidx.hilt:hilt-compiler:1.0.0'
annotationProcessor 'com.google.dagger:hilt-android-compiler:2.38.1'


问:
How to draw dynamically draw units out of an array and pair them with a predefined number value?
So I'm working on a homework assignment where I'm supposed track the "how many points a sports team has earned in a season" by writing a function called getTotalPoints that accepts a string of letters and returns the total points earned. These letters would be any series of "w" (wins) "d" (draws) and/or "l"(losses).

The assignment includes a pre-defined number value to each letter (w = 3, d = 1, and l =0), a helper function to draw out these values getPointsFromResult, and the function with a string param passed, getTotalPoints('wwdl') to test the getTotalPoints function I wrote works properly.

I got as a far as turning the string into an array and then tried to iterate on that array. The correct answer should be 7, but I am getting a result of 16, because it seems that forEach loop is iterating everything x's 4 (4 being the length of the array) As a result of 4 sets of 3+1+0 (essentially 4 x 4).

I have no idea how to move forward from here and am completely stuck.

const RESULT_VALUES = {
  w: 3,
  d: 1,
  l: 0
}

/**
 * Takes a single result string and (one of 'w', 'l', or 'd')
 * and returns the point value
 *
 * @param {string} result
 * @returns {number} point value
 */

function getPointsFromResult(result) {
  return RESULT_VALUES[result];
}

// Create getTotalPoints function which accepts a string of results
// including wins, draws, and losses i.e. 'wwdlw'
// Returns total number of points won

let getTotalPoints = function(pointsString) {
  let pointsArray = Array.from(pointsString);
  console.log(pointsArray);

  let sum = 0

  pointsArray.forEach(function(result) {
    console.log(result)
    let wins = getPointsFromResult('w');
    let draws = getPointsFromResult('d');
    let losses = getPointsFromResult('l');

    console.log(wins);
    console.log(draws);
    console.log(losses);

    sum += wins;
    sum += draws;
    sum += losses;
  })

  return sum;

};

// Check getTotalPoints
console.log(getTotalPoints('wwdl')); // should equal 7```

答:
How about something like this:

const RESULT_VALUES = {
  w: 3,
  d: 1,
  l: 0
}

function getPointsFromResult(result) {
  return RESULT_VALUES[result];
}

let getTotalPoints = function(pointsString) {
  let pointsArray = Array.from(pointsString);
  // Put value of each letter into a results array:
  let results = pointsArray.map(result => getPointsFromResult(result));
  // Sum all values in above results array to get total.
  let sum = results.reduce((a, b) => a + b, 0);

  return sum;
};

console.log(getTotalPoints('wwdl')); // should equal 7```


问:
Including header file in assembly file
I am trying to include a header file containing a macro into my main assembly file, but the compilation fails.

Below is my main.S file

#include "common.h"
BEGIN
    mov $0x0E40, %ax
    int $0x10
    hlt
```

<p>Below is my <code>common.h</code> file :</p>

<pre class="lang-none prettyprint-override"><code>.macro BEGIN
    LOCAL after_locals
    .code16
    cli
    ljmp $0, $1f
    1:
    xor %ax, %ax
    /* We must zero %ds for any data access. */
    mov %ax, %ds
    mov %ax, %es
    mov %ax, %fs
    mov %ax, %gs
    mov %ax, %bp
    /* Automatically disables interrupts until the end of the next instruction. */
    mov %ax, %ss
    /* We should set SP because BIOS calls may depend on that. TODO confirm. */
    mov %bp, %sp
    /* Store the initial dl to load stage 2 later on. */
    mov %dl, initial_dl
    jmp after_locals
    initial_dl: .byte 0
after_locals:
.endm
</code>```

Both files are in same directory. When I do the compilation :

$ as --32 -o main.o main.S
main.S: Assembler messages:
main.S:2: Error: no such instruction: `begin'
```

What am I missing? I did a little research and got this answer in SO, but its not helpful. Please help.

答: If your header file is just assembly then include with .include "file" directive in main.S. But this way of doing would insert the code the location where its included.

Title: Including header file in assembly file

Body:
I am trying to include a header file containing a macro into my main assembly file, but the compilation fails.

Below is my main.S file

#include "common.h"
BEGIN
    mov $0x0E40, %ax
    int $0x10
    hlt

Below is my common.h file :

.macro BEGIN
    LOCAL after_locals
    .code16
    cli
    ljmp $0, $1f
    1:
    xor %ax, %ax
    /* We must zero %ds for any data access. */
    mov %ax, %ds
    mov %ax, %es
    mov %ax, %fs
    mov %ax, %gs
    mov %ax, %bp
    /* Automatically disables interrupts until the end of the next instruction. */
    mov %ax, %ss
    /* We should set SP because BIOS calls may depend on that. TODO confirm. */
    mov %bp, %sp
    /* Store the initial dl to load stage 2 later on. */
    mov %dl, initial_dl
    jmp after_locals
    initial_dl: .byte 0
after_locals:
.endm

Both files are in same directory. When I do the compilation :

$ as --32 -o main.o main.S
main.S: Assembler messages:
main.S:2: Error: no such instruction: `begin'

What am I missing? I did a little research and got this answer in SO, but its not helpful. Please help.


问:
CURL testing many ip addresses of a url in the same time: Response PROBLEM
Am making a curl request on an URL. this URL is hosted by many servers ==> many ip addresses.
Imagine  "www.example.com" is hosted by

192.168.60.31

198.166.15.15

217.15.74.1

here is the test that i did:

```<code>public function curlInfosMulti($ips,$url, $timeout, $method, $params) {

        $count= count($ips);
        $container = array ();
        $tab = array('Host:'.$url);
// set URL and other appropriate options
        for ($i=0; $i<$count; $i++)
        {
            $container[$i] = curl_init();
            curl_setopt($container[$i], CURLOPT_URL, $ips[$i]);
            curl_setopt($container[$i], CURLOPT_HTTPHEADER, $tab);
            curl_setopt($container[$i], CURLOPT_HEADER, 1);
            curl_setopt($container[$i], CURLOPT_RETURNTRANSFER, true);
        }

//create the multiple cURL handle
        $mh = curl_multi_init();

        for ($i=0; $i<$count; $i++)
        {
            curl_multi_add_handle($mh, $container[$i]);
        }

        $running = null;
//execute the handles
        do {
            curl_multi_exec($mh, $running);
        } while ($running > 0);

        $response_1 = curl_multi_getcontent($container[1]);
        //$response_2 = curl_multi_getcontent($ch2);
       $infos0 = curl_getinfo($container[0]);
       $infos1 = curl_getinfo($container[1]);
        $infos2 = curl_getinfo($container[2]);
        $infos3 = curl_getinfo($container[3]);
        $infos4 = curl_getinfo($container[4]);
        $infos5 = curl_getinfo($container[5]);

        print_r($infos0);
                echo '</br></br></br>';
        print_r($infos1);
                echo '</br></br></br>';
        print_r($infos2);
         echo '</br></br></br>';
        print_r($infos3);
         echo '</br></br></br>';
        print_r($infos4);
         echo '</br></br></br>';
        print_r($infos5);

//close the handles

          for ($i=0; $i<$count; $i++)
        {

        curl_multi_remove_handle($mh, $container[$i]);
        }
        curl_multi_close($mh);
    }
</code>```

The PROBLEM here is that when i visualise the infos i get this :

```<code>**Array ( [url] => HTTP://195.81.228.5 [content_type] => text/html; charset=utf-8 [http_code] => 200 [header_size] => 354 [request_size]
=> 53 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 1.138 [namelookup_time] => 0.998 [connect_time] =>
1.045 [pretransfer_time] => 1.045 [size_upload] => 0 [size_download]
=> 8387 [speed_download] => 7369 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => 0 [starttransfer_time] => 1.092 [redirect_time] => 0 [certinfo] => Array ( ) )

Array ( [url] => HTTP://195.81.228.17 [content_type] => text/html; charset=utf-8 [http_code] => 200 [header_size] => 354 [request_size]
=> 53 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 1.138 [namelookup_time] => 0.998 [connect_time] =>
1.045 [pretransfer_time] => 1.045 [size_upload] => 0 [size_download]
=> 8387 [speed_download] => 7369 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => 0 [starttransfer_time] => 1.092 [redirect_time] => 0 [certinfo] => Array ( ) )

Array ( [url] => HTTP://195.81.228.37 [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 22.136 [namelookup_time] => 0.998 [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [certinfo] => Array ( ) )

Array ( [url] => HTTP://195.81.228.39 [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 22.136 [namelookup_time] => 0.998 [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [certinfo] => Array ( ) )

Array ( [url] => HTTP://195.81.228.40 [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 22.136 [namelookup_time] => 0.998 [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [certinfo] => Array ( ) )

Array ( [url] => HTTP://195.81.228.41 [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 22.136 [namelookup_time] => 0.998 [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [certinfo] => Array ( ) )**
</code>```

as you see: in some servers i DON'T GET Time informations (everything is set to 0)
is there any problem with this code?

答: Try setting CURLOPT_CONNECTTIMEOUT to 0 (wait indefinitely) and see if it helps.

Body:
Am making a curl request on an URL. this URL is hosted by many servers ==> many ip addresses.
Imagine  "www.example.com" is hosted by

192.168.60.31

198.166.15.15

217.15.74.1

here is the test that i did:

public function curlInfosMulti($ips,$url, $timeout, $method, $params) {

        $count= count($ips);
        $container = array ();
        $tab = array('Host:'.$url);
// set URL and other appropriate options
        for ($i=0; $i<$count; $i++)
        {
            $container[$i] = curl_init();
            curl_setopt($container[$i], CURLOPT_URL, $ips[$i]);
            curl_setopt($container[$i], CURLOPT_HTTPHEADER, $tab);
            curl_setopt($container[$i], CURLOPT_HEADER, 1);
            curl_setopt($container[$i], CURLOPT_RETURNTRANSFER, true);
        }

//create the multiple cURL handle
        $mh = curl_multi_init();

        for ($i=0; $i<$count; $i++)
        {
            curl_multi_add_handle($mh, $container[$i]);
        }

        $running = null;
//execute the handles
        do {
            curl_multi_exec($mh, $running);
        } while ($running > 0);

        $response_1 = curl_multi_getcontent($container[1]);
        //$response_2 = curl_multi_getcontent($ch2);
       $infos0 = curl_getinfo($container[0]);
       $infos1 = curl_getinfo($container[1]);
        $infos2 = curl_getinfo($container[2]);
        $infos3 = curl_getinfo($container[3]);
        $infos4 = curl_getinfo($container[4]);
        $infos5 = curl_getinfo($container[5]);

        print_r($infos0);
                echo '

';
        print_r($infos1);
                echo '

';
        print_r($infos2);
         echo '

';
        print_r($infos3);
         echo '

';
        print_r($infos4);
         echo '

';
        print_r($infos5);

//close the handles

          for ($i=0; $i<$count; $i++)
        {

        curl_multi_remove_handle($mh, $container[$i]);
        }
        curl_multi_close($mh);
    }

The PROBLEM here is that when i visualise the infos i get this :

**Array ( [url] => HTTP://195.81.228.5 [content_type] => text/html; charset=utf-8 [http_code] => 200 [header_size] => 354 [request_size]
=> 53 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 1.138 [namelookup_time] => 0.998 [connect_time] =>
1.045 [pretransfer_time] => 1.045 [size_upload] => 0 [size_download]
=> 8387 [speed_download] => 7369 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => 0 [starttransfer_time] => 1.092 [redirect_time] => 0 [certinfo] => Array ( ) )

Array ( [url] => HTTP://195.81.228.17 [content_type] => text/html; charset=utf-8 [http_code] => 200 [header_size] => 354 [request_size]
=> 53 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 1.138 [namelookup_time] => 0.998 [connect_time] =>
1.045 [pretransfer_time] => 1.045 [size_upload] => 0 [size_download]
=> 8387 [speed_download] => 7369 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => 0 [starttransfer_time] => 1.092 [redirect_time] => 0 [certinfo] => Array ( ) )

Array ( [url] => HTTP://195.81.228.37 [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 22.136 [namelookup_time] => 0.998 [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [certinfo] => Array ( ) )

Array ( [url] => HTTP://195.81.228.39 [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 22.136 [namelookup_time] => 0.998 [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [certinfo] => Array ( ) )

Array ( [url] => HTTP://195.81.228.40 [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 22.136 [namelookup_time] => 0.998 [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [certinfo] => Array ( ) )

Array ( [url] => HTTP://195.81.228.41 [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 22.136 [namelookup_time] => 0.998 [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [certinfo] => Array ( ) )**

as you see: in some servers i DON'T GET Time informations (everything is set to 0)
is there any problem with this code?


问:
how to get specific nested values inside of XML using Linq to XML C# in .Net 5.0
I'm working with a massive XML file that is exported from Confluence to represent the current state of a given Confluence space. For those familiar with Confluence this is used for backing up and restoring or migrating Confluence spaces in or across environments.

I'm trying to automate some basic analysis on the XML so I can output some useful information for determining if our export data is "OK" based on a set of rules we have defined.

Given the size of some of these exports and the structure of the XML it can be a pain and very time consuming to analyze this manually.

Essentially I've whittled down the XML to a IEnumerable of "object" XElements.

```<code>var filename = "export.xml";
var currentDirectory = Directory.GetCurrentDirectory();
var confluenceExportFilePath = Path.Combine(currentDirectory, filename);
XDocument confluenceExport = XDocument.Load(confluenceExportFilePath);
var objects = confluenceExport.Descendants("object");
</code>```

Then I've taken that further and only selected objects that contain a class attribute equal to "Page" as I only care about the "objects" that are Page "objects". Up to this point I've returned some basic "header" information about each Page.

```<code>var pages =
from page in objects
where (string)page.Attribute("class") == "Page"
select new Page
{
    Id = (string)page.Element("id"),
    Title = (string)page.Elements("property").FirstOrDefault(property =>
        property.Attribute("name").Value == "title"),
    Version = (int)page.Elements("property").FirstOrDefault(property =>
        property.Attribute("name").Value == "version"),
};
</code>```

An example page "object" may look like this:

```<code><object class="Page" package="com.atlassian.confluence.pages">
    <id name="id">001</id>
    <property name="title"><![CDATA[Test Page]]></property>
    <property name="lowerTitle"><![CDATA[test page]]></property>
    <property name="version">022</property>
    <property name="creationDate">2020-06-15 20:13:00.195</property>
    <property name="lastModificationDate">2020-06-18 12:01:04.482</property>
    <property name="versionComment"><![CDATA[]]></property>
    <collection name="bodyContents" class="java.util.Collection">
        <element class="BodyContent" package="com.atlassian.confluence.core">
            <id name="id">011</id>
        </element>
    </collection>
    <collection name="historicalVersions" class="java.util.Collection">
        <element class="Page" package="com.atlassian.confluence.pages">
            <id name="id">021</id>
        </element>
        <element class="Page" package="com.atlassian.confluence.pages">
            <id name="id">022</id>
        </element>
    </collection>
    <property name="contentStatus"><![CDATA[current]]></property>
    <collection name="attachments" class="java.util.Collection">
        <element class="Attachment" package="com.atlassian.confluence.pages">
            <id name="id">031</id>
        </element>
        <element class="Attachment" package="com.atlassian.confluence.pages">
            <id name="id">032</id>
        </element>
    </collection>
</object>
</code>```

However, I wanted to dig a little deeper into the XML and get some more specific data and I'm struggling to do that. For example, I would like to select the "id" value that is nested inside the BodyContent collection.

```<code>    <collection name="bodyContents" class="java.util.Collection">
        <element class="BodyContent" package="com.atlassian.confluence.core">
            <id name="id">011</id>
        </element>
    </collection>
</code>```

Ultimately what I would like is to be able to output:

```<code>Page ID: 001
Page Title: Test Page
Page Version: 022
Page Body Content ID: 011
</code>```

How can I go about getting this?

答:
If you want to dig deep, then you can directly use XPath to retrieve the required values.

Code snippet:

```<code>var docNav = new XPathDocument(FILE_PATH);
var navigator = docNav.CreateNavigator();
var nodeIterator = navigator.Select("//object");
while (nodeIterator.MoveNext())
{
    Console.WriteLine("Page ID: {0}", nodeIterator.Current.SelectSingleNode("id")?.Value);
    Console.WriteLine("Page Title: {0}", nodeIterator.Current.SelectSingleNode("property[@name='title']")?.Value);
    Console.WriteLine("Page Version: {0}", nodeIterator.Current.SelectSingleNode("property[@name='version']")?.Value);
    Console.WriteLine("Page Body Content ID: {0}", nodeIterator.Current.SelectSingleNode("collection[@name='bodyContents']//id")?.Value);
};
</code>```

Body:
I'm working with a massive XML file that is exported from Confluence to represent the current state of a given Confluence space. For those familiar with Confluence this is used for backing up and restoring or migrating Confluence spaces in or across environments.

I'm trying to automate some basic analysis on the XML so I can output some useful information for determining if our export data is "OK" based on a set of rules we have defined.

Given the size of some of these exports and the structure of the XML it can be a pain and very time consuming to analyze this manually.

Essentially I've whittled down the XML to a IEnumerable of "object" XElements.

var filename = "export.xml";
var currentDirectory = Directory.GetCurrentDirectory();
var confluenceExportFilePath = Path.Combine(currentDirectory, filename);
XDocument confluenceExport = XDocument.Load(confluenceExportFilePath);
var objects = confluenceExport.Descendants("object");

Then I've taken that further and only selected objects that contain a class attribute equal to "Page" as I only care about the "objects" that are Page "objects". Up to this point I've returned some basic "header" information about each Page.

var pages =
from page in objects
where (string)page.Attribute("class") == "Page"
select new Page
{
    Id = (string)page.Element("id"),
    Title = (string)page.Elements("property").FirstOrDefault(property =>
        property.Attribute("name").Value == "title"),
    Version = (int)page.Elements("property").FirstOrDefault(property =>
        property.Attribute("name").Value == "version"),
};

An example page "object" may look like this:

<object class="Page" package="com.atlassian.confluence.pages">
    <id name="id">001</id>
    <property name="title"><![CDATA[Test Page]]></property>
    <property name="lowerTitle"><![CDATA[test page]]></property>
    <property name="version">022</property>
    <property name="creationDate">2020-06-15 20:13:00.195</property>
    <property name="lastModificationDate">2020-06-18 12:01:04.482</property>
    <property name="versionComment"><![CDATA[]]></property>
    <collection name="bodyContents" class="java.util.Collection">
        <element class="BodyContent" package="com.atlassian.confluence.core">
            <id name="id">011</id>
        </element>
    </collection>
    <collection name="historicalVersions" class="java.util.Collection">
        <element class="Page" package="com.atlassian.confluence.pages">
            <id name="id">021</id>
        </element>
        <element class="Page" package="com.atlassian.confluence.pages">
            <id name="id">022</id>
        </element>
    </collection>
    <property name="contentStatus"><![CDATA[current]]></property>
    <collection name="attachments" class="java.util.Collection">
        <element class="Attachment" package="com.atlassian.confluence.pages">
            <id name="id">031</id>
        </element>
        <element class="Attachment" package="com.atlassian.confluence.pages">
            <id name="id">032</id>
        </element>
    </collection>
</object>

However, I wanted to dig a little deeper into the XML and get some more specific data and I'm struggling to do that. For example, I would like to select the "id" value that is nested inside the BodyContent collection.

    <collection name="bodyContents" class="java.util.Collection">
        <element class="BodyContent" package="com.atlassian.confluence.core">
            <id name="id">011</id>
        </element>
    </collection>

Ultimately what I would like is to be able to output:

Page ID: 001
Page Title: Test Page
Page Version: 022
Page Body Content ID: 011

How can I go about getting this?

Body:
If you want to dig deep, then you can directly use XPath to retrieve the required values.

Code snippet:

var docNav = new XPathDocument(FILE_PATH);
var navigator = docNav.CreateNavigator();
var nodeIterator = navigator.Select("//object");
while (nodeIterator.MoveNext())
{
    Console.WriteLine("Page ID: {0}", nodeIterator.Current.SelectSingleNode("id")?.Value);
    Console.WriteLine("Page Title: {0}", nodeIterator.Current.SelectSingleNode("property[@name='title']")?.Value);
    Console.WriteLine("Page Version: {0}", nodeIterator.Current.SelectSingleNode("property[@name='version']")?.Value);
    Console.WriteLine("Page Body Content ID: {0}", nodeIterator.Current.SelectSingleNode("collection[@name='bodyContents']//id")?.Value);
};


问:
Why are calculations included in a GROUP BY in SQL?
Is there ever a reason to include a function in the GROUP BY?

I see in in code and even in some instructions but have never been explained why, outside of it's easier to copy from the SELECT then typing it again.

Example:

```<code>SELECT
    ProductName,
    IFF (UnitsInStock > 0, 'true', 'false) AS InStock
    COUNT(ProductID)
FROM Products
GROUP BY ProductName, IFF (UnitsInStock > 0, 'true', 'false)
</code>```

I have started removing the functions in all my coding:

```<code>GROUP BY ProductName, UnitsInStock
</code>```

Is there a reason to keep the full expression?

答:
There are many articles out there (and training material to boot) about this subject, but the explanation is fairly straightforward really.

Keep in mind that (T-) SQL is not Turing-proof, it does not actually compiles to code - it transcribes your input - and therefor what comes in must go out - so if you input something SQL cannot "find" by itself, you need to reproduce it.

You can not GROUP BY InStock, because there is no InStock to use : you use a temporary "variable"  created by the function (it is not a variable, that's a lie, but for sake of argument keep that metaphor in mind).

EDIT: I want to point out @userMT has a good point, when you actually remove that code there is a good chance you might get more problems then you're bargaining for

Body:
Is there ever a reason to include a function in the GROUP BY?

I see in in code and even in some instructions but have never been explained why, outside of it's easier to copy from the SELECT then typing it again.

Example:

SELECT
    ProductName,
    IFF (UnitsInStock > 0, 'true', 'false) AS InStock
    COUNT(ProductID)
FROM Products
GROUP BY ProductName, IFF (UnitsInStock > 0, 'true', 'false)

I have started removing the functions in all my coding:

GROUP BY ProductName, UnitsInStock

Is there a reason to keep the full expression?


问:
CSS BEM, nest child elements or create new block?
I love the BEM concept, but I get extremely confused when an element has multiple child components, should I keep nesting elements or transform them into new blocks? or something else?

Real example:

<form class="darpi-form">

      <input type="text" />

  <button class="darpi-form__button"></button>
</form>

```
<p>or</p>
<pre class="lang-html prettyprint-override"><code><form class="darpi-form">
  <div class="field">
    <label class="field__label"></label>
    <div class="field__content">
      <input type="text" />
      <!-- .. -->
    </div>
    <span class="field__error-message"></span>
  </div>

  <button class="darpi-form__button"></button>
</form>

<style>
  .darpi-form {}
  .darpi-form__button {}

  .field {}
  .field__error-message {}
  .field__content {}
</style>
</code>```

答:
“BEM methodology doesn’t recommend to use elements within elements in class names. You don’t need to resemble DOM structure in naming. Having one level structure makes refactoring much easier.” -Vladimir Grinenko, Yandex

Refer to the Grandchild Solution:

Instead of darpi-form__field__label you should just use darpi-form__label.

Body:
I love the BEM concept, but I get extremely confused when an element has multiple child components, should I keep nesting elements or transform them into new blocks? or something else?

Real example:

<form class="darpi-form">

      <input type="text" />

  <button class="darpi-form__button"></button>
</form>

or

<form class="darpi-form">

      <input type="text" />

  <button class="darpi-form__button"></button>
</form>


答: grouping by  IFF (UnitsInStock > 0, 'true', 'false) produces -at most- two rows per product, grouping by `UnitsInStock ' produces row per unique value of the UnitsInStock.

Title: Why are calculations included in a GROUP BY in SQL?