问:
Bootstrap not working without Visual Studio Code live-server plugin
I am using visual code IDE for coding and a plugin "live server" which is very handy for quick checks of the changes made in code and everything with bootstrap worked excellently.

But when I tried to open a .html file just by double-clicking on it (without live server from Visual Code IDE), it opened like there was totally no css or bootstrap's js.

Looking forward for any help.

A really small snippet of code with necessary parts here:

```<code><html lang="en">
  <head>

    <!-- Bootstrap core CSS -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">

    <!-- Main css -->
    <link rel="stylesheet" href="/css/style.css">
</head>
  <body>

    <header>
      <!-- Fixed navbar -->
      <nav class="navbar navbar-light navbar-expand-md fixed-top bg-light border-bottom">
        <a class="navbar-brand text-info" href="#">AirFly</a>

        <!-- Hamburger menu -->
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>

        <div style="position:relative;" class="collapse navbar-collapse" id="navbarCollapse">
            <div class="float-right">
            <ul class="navbar-nav">
              <li class="nav-item active">
                <a class="nav-link text-uppercase text-info" href="index.html">Home <span class="sr-only">(current)</span></a>
              </li>
              <li class="nav-item">
                <a class="nav-link text-uppercase text-dark" href="about.html">About us</a>
              </li>
              <li class="nav-item">
                <a class="nav-link text-uppercase text-dark" href="contact.html">Contact</a>
              </li>
            </ul>
          </div>
          </div>
      </nav>
    </header>

<script src="/js/popper.min.js"></script>
    <script src="/js/bootstrap.min.js"></script>
    <script src="js/weather.js"></script>
    <script src="js/ui.js"></script>
    <script src="js/main.js"></script>
  </body>
</html>
</code>```

答:
Remove this attribute from links,

```<code>integrity="sha384AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p"
crossorigin="anonymous"
</code>```

then your page design will be working perfectly.

Body:
I am using visual code IDE for coding and a plugin "live server" which is very handy for quick checks of the changes made in code and everything with bootstrap worked excellently.

But when I tried to open a .html file just by double-clicking on it (without live server from Visual Code IDE), it opened like there was totally no css or bootstrap's js.

Looking forward for any help.

A really small snippet of code with necessary parts here:

    <link href="/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="/css/style.css">

        AirFly

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                Home (current)

                About us

                Contact

Body:
Remove this attribute from links,

integrity="sha384AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p"
crossorigin="anonymous"

then your page design will be working perfectly.


来源: stackexchange

问:
React/node => image display not allowed to load local ressource
I'm on a react/node website project. Pretty simple website with a crud.
My crud worked but my pictures doesn't appears (they are upload on a folder public/uploads/news/ and their path is save in mongoDb) For my news I can see the title, message, date but the picture is broken and I've only the alt.
When I go to the console and go on the element, the patch is OK "c:/users/......... /public/uploads/news/nameofmypicture.jpg".
I just got an error message "not allowed to load local resources"

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { dateParser, isEmpty } from "../../../general/utils/Utils";
import { updateNews } from "../../../../store/actions/news.actions";
import DeleteCard from "./DeleteCard";
import Loader from "../../../general/utils/Loading";

const Card = ({ news }) => {
    const [isLoading, setIsLoading] = useState(true);
    const [isUpdated, setIsUpdated] = useState(false);
    const [textUpdate, setTextUpdate] = useState(null);
    const newsData = useSelector((state) => state.newsReducer);
    const dispatch = useDispatch();

    const updateItem = () => {
        if (textUpdate) {
            dispatch(updateNews(news._id, textUpdate));
        }
        setIsUpdated(false);
    };

    useEffect(() => {
        !isEmpty(newsData[0]) && setIsLoading(false);
    }, [newsData]);

    return (

            {isLoading ? (
                <Loader />
            ) : (
                <>

                        {isUpdated === false &&
{news.title}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.title}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                        )}
                            {dateParser(news.createdAt)}

                        {isUpdated === false &&
{news.message}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.message}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                                    <button className="btn btn-success" onClick={updateItem}>
                                        Valider modification
                                    </button>

                        )}
                        {news.picture && (

                        )}
                        {news.video && (

                        )}

                            <button className="btn btn-primary" onClick={() => setIsUpdated(!isUpdated)}>Edit</button>
                            <DeleteCard id={news._id} />

                </>
            )}

    );
};

export default Card;```

If someone wants the full code
https://github.com/macath/AJC-modelism
If you have more questions, ask me. I'm on this problem since 4 days, I really don't understand why it's don't work.
I specify that this project will be put online so I need a valid solution on a server and not only local

Ps : sorry for my English I'm French

答:
The problem is solve. In my news.controller i replace

```<code>picture: req.file.path
</code>```

by

```<code>picture: req.file.filename
</code>```

In my card.js i replace

```<code>img src={news.picture}
</code>```

by

```<code><img src={`${window.location.origin}/uploads/${news.picture}`}
</code>```

thanks for your help

ContentLicense: CC BY-SA 4.0

Body:
I'm on a react/node website project. Pretty simple website with a crud.
My crud worked but my pictures doesn't appears (they are upload on a folder public/uploads/news/ and their path is save in mongoDb) For my news I can see the title, message, date but the picture is broken and I've only the alt.
When I go to the console and go on the element, the patch is OK "c:/users/......... /public/uploads/news/nameofmypicture.jpg".
I just got an error message "not allowed to load local resources"

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { dateParser, isEmpty } from "../../../general/utils/Utils";
import { updateNews } from "../../../../store/actions/news.actions";
import DeleteCard from "./DeleteCard";
import Loader from "../../../general/utils/Loading";

const Card = ({ news }) => {
    const [isLoading, setIsLoading] = useState(true);
    const [isUpdated, setIsUpdated] = useState(false);
    const [textUpdate, setTextUpdate] = useState(null);
    const newsData = useSelector((state) => state.newsReducer);
    const dispatch = useDispatch();

    const updateItem = () => {
        if (textUpdate) {
            dispatch(updateNews(news._id, textUpdate));
        }
        setIsUpdated(false);
    };

    useEffect(() => {
        !isEmpty(newsData[0]) && setIsLoading(false);
    }, [newsData]);

    return (

            {isLoading ? (
                <Loader />
            ) : (
                <>

                        {isUpdated === false &&
{news.title}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.title}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                        )}
                            {dateParser(news.createdAt)}

                        {isUpdated === false &&
{news.message}
}
                        {isUpdated && (

                                <textarea
                                    defaultValue={news.message}
                                    onChange={(e) => setTextUpdate(e.target.value)}
                                />

                                    <button className="btn btn-success" onClick={updateItem}>
                                        Valider modification
                                    </button>

                        )}
                        {news.picture && (

                        )}
                        {news.video && (

                        )}

                            <button className="btn btn-primary" onClick={() => setIsUpdated(!isUpdated)}>Edit</button>
                            <DeleteCard id={news._id} />

                </>
            )}

    );
};

export default Card;

If someone wants the full code
https://github.com/macath/AJC-modelism
If you have more questions, ask me. I'm on this problem since 4 days, I really don't understand why it's don't work.
I specify that this project will be put online so I need a valid solution on a server and not only local

Ps : sorry for my English I'm French

Body:
The problem is solve. In my news.controller i replace

picture: req.file.path

by

picture: req.file.filename

In my card.js i replace

img src={news.picture}

by

<img src={`${window.location.origin}/uploads/${news.picture}`}

thanks for your help


问:
Match Operator prettier syntax in Groovy
I'm very new to groovy (here working on Jenkinsfile)

One of my coworkers uses a Match Operator to check a condition. But I find it not readable and hard to maintain.

Original Match Operator:

```<code>PROJECT_NAME = 'projectA' // User Input from Jenkins params normaly
if ( "${PROJECT_NAME}" ==~ /projectA|projectB|projectC|projectD/) { // The real line is 300 Char long
    // Do stuff
}
</code>```

There is 15 projects in total, i've shorten up the line because it was too long. So every time he needs to add a project name, he appends at the start or end of his regex.

Also, those project name are in a list before.

```<code>projects = ['projectA',
    'projectB',
    'projectC',
    'projectD']
</code>```

Could there be a way to use this list to build the regex?

Here is what I tried:

```<code>string_regex = "/"
for (project in projects) {
    string_regex = string_regex + project + "|"
}
string_regex = string_regex.substring(0, string_regex.length() - 1)
string_regex = string_regex + "/"

print "${string_regex}\n"

if ("${PROJECT_NAME}" ==~ string_regex) {
    print "Well Done you did it\n"
    // Do stuff
}
</code>```

But saddly it doesn't seems to work, since I'm using a string?

EDIT: I found out that I could use the contains method from a list in Groovy. In my case, it fixes my original problem. But I'm still curious on how to build such regex with strings.

```<code>if (projects.contains(PROJECT_NAME)) {
    // Do stuff
}
</code>```

答:
If you have already an collection, you should nearly always use an collection operator; E.g. replace

```<code>if ( "${PROJECT_NAME}" ==~ /projectA|projectB|projectC|projectD/) {
</code>```

with:

```<code>if (PROJECT_NAME in projects) {
</code>```

Much easier to read and understand, no?

Body:
I'm very new to groovy (here working on Jenkinsfile)

One of my coworkers uses a Match Operator to check a condition. But I find it not readable and hard to maintain.

Original Match Operator:

PROJECT_NAME = 'projectA' // User Input from Jenkins params normaly
if ( "${PROJECT_NAME}" ==~ /projectA|projectB|projectC|projectD/) { // The real line is 300 Char long
    // Do stuff
}

There is 15 projects in total, i've shorten up the line because it was too long. So every time he needs to add a project name, he appends at the start or end of his regex.

Also, those project name are in a list before.

projects = ['projectA',
    'projectB',
    'projectC',
    'projectD']

Could there be a way to use this list to build the regex?

Here is what I tried:

string_regex = "/"
for (project in projects) {
    string_regex = string_regex + project + "|"
}
string_regex = string_regex.substring(0, string_regex.length() - 1)
string_regex = string_regex + "/"

print "${string_regex}\n"

if ("${PROJECT_NAME}" ==~ string_regex) {
    print "Well Done you did it\n"
    // Do stuff
}

But saddly it doesn't seems to work, since I'm using a string?

EDIT: I found out that I could use the contains method from a list in Groovy. In my case, it fixes my original problem. But I'm still curious on how to build such regex with strings.

if (projects.contains(PROJECT_NAME)) {
    // Do stuff
}

Body:
If you have already an collection, you should nearly always use an collection operator; E.g. replace

if ( "${PROJECT_NAME}" ==~ /projectA|projectB|projectC|projectD/) {

with:

if (PROJECT_NAME in projects) {

Much easier to read and understand, no?


问:
XMLHttpRequest - a problem with event.loaded and event.total values
I use XMLHttpRequest for file upload and in the browser I've a progress bar that show, how big part of image is already uploaded.

```<code>  xhr.upload.addEventListener('progress', onprogressHandler, false);

  function onprogressHandler(event) {
    resp.innerHTML = event.loaded +' and '+ event.total;

    var percent = Math.round((event.loaded / event.total) * 100);
    var calc_display = document.getElementById('calc');
    calc_display.innerHTML = percent;
  };
</code>```

If I choose an image for upload and send a form, so I see always the same values of event.loaded and event.total.
I think the value event.total is the size of file.

I am a newbie so I haven't so much of experience, but how is possible I have always the same  values? (usually about 2.700.000 kB)

Where could be a problem?

答: Values might be same if your uploaded video/image size is small. You can check by uploading video of size more than 70MB and check your loaded and total values, it should give you different values in total and loaded</p>

Body:
I use XMLHttpRequest for file upload and in the browser I've a progress bar that show, how big part of image is already uploaded.

  xhr.upload.addEventListener('progress', onprogressHandler, false);

  function onprogressHandler(event) {
    resp.innerHTML = event.loaded +' and '+ event.total;

    var percent = Math.round((event.loaded / event.total) * 100);
    var calc_display = document.getElementById('calc');
    calc_display.innerHTML = percent;
  };

If I choose an image for upload and send a form, so I see always the same values of event.loaded and event.total.
I think the value event.total is the size of file.

I am a newbie so I haven't so much of experience, but how is possible I have always the same  values? (usually about 2.700.000 kB)

Where could be a problem?


问:
Cannot attach project in DataSpell
On the welcome screen of DataSpell I chose to open a project with Get from Version Control to get a project from GitHub, although in the left pane I didn't choose GitHub, so it created an empty .git repository.

After that, I git cloned elsewhere the git repository or tried to clone it correctly from GitHub but in every occasion I get

```<code>Error
Cannot attach project Module name 'project name' already exists.
Trying to load module: /path/to/project name.iml
</code>```

Where does DataSpell save the imported projects, to detach the empty project that I imported initially?

答:
I managed to open the project following the instructions of Open your project from disk section of the DataSpell site.

For avoiding further trouble, I opened the project in a new window. After the configuration in step 2 Reopen projects on startup --> Ask, Dataspell will ask how to open the project.

Title: Cannot attach project in DataSpell

Body:
On the welcome screen of DataSpell I chose to open a project with Get from Version Control to get a project from GitHub, although in the left pane I didn't choose GitHub, so it created an empty .git repository.

After that, I git cloned elsewhere the git repository or tried to clone it correctly from GitHub but in every occasion I get

Error
Cannot attach project Module name 'project name' already exists.
Trying to load module: /path/to/project name.iml

Where does DataSpell save the imported projects, to detach the empty project that I imported initially?


问:
What is the difference between Live IP and STATIC IP?
I came across the terms LIVE IP and STATIC IP and did research on them but couldn't find useful info about the differences between them.

Can anyone please explain the difference to me?

答:
The term live IP address could mean an address that is accessible on the internet. Another usage of the term could also mean if the machine with that given IP address is on the network and responding. See what is a live ip address

A static IP address indicates that the IP address for that network interface has been assigned through configuration on the system as opposed to getting an IP address dynamically from a DHCP server.

ContentLicense: CC BY-SA 3.0


问:
why the JAXRSIntegration can't lookup JNDI
i need some help here!

I'm using javaEE 7,  javax-ws-rs 2.0.1 and Weblogic 12.2.1.4.0.

Im getting following error on my Manage Server log:

```<code><04.01.2022 16:51 Uhr MEZ> <Warning> <JAXRSIntegration> <BEA-2192505> <An instance of EJB class com.my.company.rest.MyExchangeServer could not be looked up using a simple form name.
Attempting to look up using the fully-qualified form name.
javax.naming.NameNotFoundException: While trying to look up /app/my-company-web-1.7.0.2/MyExchangeServer in /app/webapp/my-company-web/1607311341.; remaining name '/app/my-company-web-1/7/0/2/MyExchangeServer'
</code>```

this happend after the Migration from Weblogic 12.1 to Weblogic 12.2.
The Application runs without problem tough.
Only the ms_logs bothering us, because it take so much memory.

```<code>@ApplicationPath("rest")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> restClasses = new HashSet<>();
        restClasses.add(MyExchangeServer.class);
        return restClasses;
    }
}
</code>```
```<code></web-app>
    ...
    <servlet>
        <servlet-name>Jersey-Servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.my.company.rest.ApplicationConfig</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.spi.container.ContainerResponseFilter</param-name>
            <param-value>com.sun.jersey.server.linking.LinkFiler</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey-Servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>
</code>```
```<code>@Stateless
@LocalBean
@Path("serviceInterface")
public class MyExchangeServer {
    ...
}
</code>```

Under JNDI tree i find:
java:global.my-int-ear.my-company-web.MyExchangeServer!com.my.company.rest.MyExchangeServer

It seems that the MyExchangeServer class are instantiated by jersey and not from EJB.
Why would JAXRSIntegration trying to look up under /app/my-company-web-1.7.0.2/MyExchangeServer ?

The Application works prefectly tough

答:
now i have found the solution. The porblem was i'm still using JAX-RS 1.0 on my project. Since on WLS 12.2.* JAX-RS 1.0 deprecated. I have to use the JAX-RS 2.*.

So far i only need to change the Jersey configuration on my web.xml. And i'm good to go.

```<code><web-app>
    <servlet>
        <servlet-name>Jersey-Servlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <!-- Register resources and providers under my.package. -->
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>my.company.rest.ApplicationConfig</param-value>
        </init-param>
        <!-- Enable Tracing support. -->
        <init-param>
            <param-name>jersey.config.server.tracing</param-name>
            <param-value>ALL</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey-Servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

Body:
i need some help here!

I'm using javaEE 7,  javax-ws-rs 2.0.1 and Weblogic 12.2.1.4.0.

Im getting following error on my Manage Server log:

<04.01.2022 16:51 Uhr MEZ> <Warning> <JAXRSIntegration> <BEA-2192505> <An instance of EJB class com.my.company.rest.MyExchangeServer could not be looked up using a simple form name.
Attempting to look up using the fully-qualified form name.
javax.naming.NameNotFoundException: While trying to look up /app/my-company-web-1.7.0.2/MyExchangeServer in /app/webapp/my-company-web/1607311341.; remaining name '/app/my-company-web-1/7/0/2/MyExchangeServer'

this happend after the Migration from Weblogic 12.1 to Weblogic 12.2.
The Application runs without problem tough.
Only the ms_logs bothering us, because it take so much memory.

@ApplicationPath("rest")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> restClasses = new HashSet<>();
        restClasses.add(MyExchangeServer.class);
        return restClasses;
    }
}

</web-app>
    ...
    <servlet>
        <servlet-name>Jersey-Servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.my.company.rest.ApplicationConfig</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.spi.container.ContainerResponseFilter</param-name>
            <param-value>com.sun.jersey.server.linking.LinkFiler</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey-Servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

@Stateless
@LocalBean
@Path("serviceInterface")
public class MyExchangeServer {
    ...
}

Under JNDI tree i find:
java:global.my-int-ear.my-company-web.MyExchangeServer!com.my.company.rest.MyExchangeServer

It seems that the MyExchangeServer class are instantiated by jersey and not from EJB.
Why would JAXRSIntegration trying to look up under /app/my-company-web-1.7.0.2/MyExchangeServer ?

The Application works prefectly tough

Body:
now i have found the solution. The porblem was i'm still using JAX-RS 1.0 on my project. Since on WLS 12.2.* JAX-RS 1.0 deprecated. I have to use the JAX-RS 2.*.

So far i only need to change the Jersey configuration on my web.xml. And i'm good to go.

<web-app>
    <servlet>
        <servlet-name>Jersey-Servlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <!-- Register resources and providers under my.package. -->
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>my.company.rest.ApplicationConfig</param-value>
        </init-param>
        <!-- Enable Tracing support. -->
        <init-param>
            <param-name>jersey.config.server.tracing</param-name>
            <param-value>ALL</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey-Servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>


问:
ld -v leads to segmentation fault in WSL2
I am getting segmentation faults while compiling a project with gcc on a WSL2 Ubuntu 20.04 installation.

I narrowed the problem down to the linker in my opinion:

```<code>> ld -v
Segmentation fault
</code>```

The system information from uname -a is Linux Spectre 5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

The install is fresh for this project.

What could cause this problem?
Thanks in advance.

答:
You always find the solution just after you ask.

If you just reinstall build-essentials it wont work.

Thus remove binutils and make. Then install again. Ie:

```<code>sudo apt purge binutils
sudo apt remove make
sudo apt autoremove
sudo apt install build-essential
</code>```

Body:
I am getting segmentation faults while compiling a project with gcc on a WSL2 Ubuntu 20.04 installation.

I narrowed the problem down to the linker in my opinion:

> ld -v
Segmentation fault

The system information from uname -a is Linux Spectre 5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

The install is fresh for this project.

What could cause this problem?
Thanks in advance.

Body:
You always find the solution just after you ask.

If you just reinstall build-essentials it wont work.

Thus remove binutils and make. Then install again. Ie:

sudo apt purge binutils
sudo apt remove make
sudo apt autoremove
sudo apt install build-essential


问:
not able to set replication for "docker" repository on replica server
I have replica and master Artifactory server. I have set replication successfully for many different packages (maven, npm, bower etc.).
I am having difficulties to set pull replication for docker repository on my replica server.

I am able to list the URL with repository structure and its folders in web browser:

```<code>http://af.domain:8081/artifactory/front-docker
</code>```

This lists a folders which I have in that repo. I am using the admin user to access.
However if I try to set this URL in JFROG Artifactory UI I am getting the message:

```<code>Connection failed: Error 404: Not Found
</code>```

I have found this link as well:
https://www.jfrog.com/confluence/display/JFROG/Smart+Remote+Repositories#SmartRemoteRepositories-Configuration
which implies that I should use /api/docker as prefix before the repository key.

```<code>http://af.domain:8081/artifactory/api/docker/front-docker
</code>```

with this URL I am getting:

```<code>Connection failed: Error 403: Forbidden
</code>```

I tried also:

http://af.domain:8081/api/docker/front-docker
but again I get error 404.
I have set admin credentials on Advanced tab. That is the admin user on master server which I am using for all other replications so the permissions should not be the issue.

In logs I do not see anything.

What else can I try?

答: The needed URL for pull replication is "http://af.domain:8081/artifactory/api/docker/front-docker" and the reason you are getting 403 is the forbidden issue, so add the admin to confirm if 403 is indeed a forbidden/permission issue.</p>

Body:
I have replica and master Artifactory server. I have set replication successfully for many different packages (maven, npm, bower etc.).
I am having difficulties to set pull replication for docker repository on my replica server.

I am able to list the URL with repository structure and its folders in web browser:

http://af.domain:8081/artifactory/front-docker

This lists a folders which I have in that repo. I am using the admin user to access.
However if I try to set this URL in JFROG Artifactory UI I am getting the message:

Connection failed: Error 404: Not Found

I have found this link as well:
https://www.jfrog.com/confluence/display/JFROG/Smart+Remote+Repositories#SmartRemoteRepositories-Configuration
which implies that I should use /api/docker as prefix before the repository key.

http://af.domain:8081/artifactory/api/docker/front-docker

with this URL I am getting:

Connection failed: Error 403: Forbidden

I tried also:

http://af.domain:8081/api/docker/front-docker
but again I get error 404.
I have set admin credentials on Advanced tab. That is the admin user on master server which I am using for all other replications so the permissions should not be the issue.

In logs I do not see anything.

What else can I try?


问:
@PostConstruct method runs before flyway
I know this kind of question has been asked before.
I have a method which is annotated with @PostConstruct.
The methods assumes that all Flyway scripts have been executed before invocation.
It seems that Flyway also uses @PostConstruct annotated methods and that these methods are called after my method.
I tried to annotate my method with @DependOn and different flyway beennames.
Unfortunately without success. Can anybody help me.

答:
For new Flyway this work (use Flyway callbacks)</p>
```<code>    @Configuration
    class FlywayConfig(env: Environment) {
    private val env: Environment

    init {
        this.env = env
    }

    @Bean(initMethod = "migrate")
    fun flyway(dbLoadService: DbLoadService): Flyway {
        return Flyway(
            Flyway.configure()
                .baselineOnMigrate(true)
                .dataSource(
                    env.getRequiredProperty("spring.datasource.url"),
                    env.getRequiredProperty("spring.datasource.username"),
                    env.getRequiredProperty("spring.datasource.password")
                )
                //запуск загрузки из базы после окончания миграции
                .callbacks(FlywayMigrationsCompleteCallback {
                    dbLoadService.loadAllCertificateInformation()
                })
        )
    }

    class FlywayMigrationsCompleteCallback(private val callback: () -> Unit) : Callback {

    override fun supports(event: Event?, context: Context?): Boolean {
        return event == Event.AFTER_MIGRATE
    }

    override fun canHandleInTransaction(event: Event?, context: Context?): Boolean {
        return true
    }

    override fun handle(event: Event?, context: Context?) {
        callback()
    }

    override fun getCallbackName(): String {
        return FlywayMigrationsCompleteCallback::class.simpleName!!
     }
  }

  @Component
  class DbLoadService(private val certificateRepository:CertificateRepository) {
    @Volatile var  certificate: List<Certificate>?=null
    fun loadAllCertificateInformation(){
        val findAll = certificateRepository.findAll()
        runBlocking {
            certificate = findAll.toList()
        }
    }
}
</code>```

Body:
For new Flyway this work (use Flyway callbacks)

    @Configuration
    class FlywayConfig(env: Environment) {
    private val env: Environment

    init {
        this.env = env
    }

    @Bean(initMethod = "migrate")
    fun flyway(dbLoadService: DbLoadService): Flyway {
        return Flyway(
            Flyway.configure()
                .baselineOnMigrate(true)
                .dataSource(
                    env.getRequiredProperty("spring.datasource.url"),
                    env.getRequiredProperty("spring.datasource.username"),
                    env.getRequiredProperty("spring.datasource.password")
                )
                //запуск загрузки из базы после окончания миграции
                .callbacks(FlywayMigrationsCompleteCallback {
                    dbLoadService.loadAllCertificateInformation()
                })
        )
    }

    class FlywayMigrationsCompleteCallback(private val callback: () -> Unit) : Callback {

    override fun supports(event: Event?, context: Context?): Boolean {
        return event == Event.AFTER_MIGRATE
    }

    override fun canHandleInTransaction(event: Event?, context: Context?): Boolean {
        return true
    }

    override fun handle(event: Event?, context: Context?) {
        callback()
    }

    override fun getCallbackName(): String {
        return FlywayMigrationsCompleteCallback::class.simpleName!!
     }
  }

  @Component
  class DbLoadService(private val certificateRepository:CertificateRepository) {
    @Volatile var  certificate: List<Certificate>?=null
    fun loadAllCertificateInformation(){
        val findAll = certificateRepository.findAll()
        runBlocking {
            certificate = findAll.toList()
        }
    }
}


问:
Reading from Socket
I am having issues getting this simple class to work. It basically connects to an IMAP server and reads the banner. But after reading all chars, it is somewhat hanging. In the debugger I can step through the while loop and see all chars are being read and eventually it is coming out of the loop. But the last System.out.println statement is never reached.</p>

```<code>import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class TestClient
{

    /**

        @param args

     */
    public static void main( String[] args ) throws Exception
    {

        Socket socket = new Socket( "imap.1and1.com", 143 );

        DataOutputStream os = new DataOutputStream( socket.getOutputStream() );
        BufferedReader reader = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );

        StringBuilder sb = new StringBuilder();
        char ch = (char) reader.read();
        while ( ch != -1 ) {
            sb.append( ch );
            ch = (char) reader.read();

        }

        System.out.println( sb.toString() ); /// <--- never prints anything and program just hangs..
    }

}
</code>```

答:
read function blocks if there is no data to read, only comes out when readStream is closed or socket connection got disconnected. What you should do is to create a protocol which disconnect the connection after data has been read fully. ie you should come out of the loop

either by somehow disconnecting the connection after all data has
been read (for that you must identify all data has been read)

or get out of the loop yourself if you have read some previously agreed
"end of message" string..

One more thing, since read() blocks, waiting for more data, it is advised you should read in a background thread..

Title: Reading from Socket

Body:
I am having issues getting this simple class to work. It basically connects to an IMAP server and reads the banner. But after reading all chars, it is somewhat hanging. In the debugger I can step through the while loop and see all chars are being read and eventually it is coming out of the loop. But the last System.out.println statement is never reached.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class TestClient
{

    /**

        @param args

     */
    public static void main( String[] args ) throws Exception
    {

        Socket socket = new Socket( "imap.1and1.com", 143 );

        DataOutputStream os = new DataOutputStream( socket.getOutputStream() );
        BufferedReader reader = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );

        StringBuilder sb = new StringBuilder();
        char ch = (char) reader.read();
        while ( ch != -1 ) {
            sb.append( ch );
            ch = (char) reader.read();

        }

        System.out.println( sb.toString() ); /// <--- never prints anything and program just hangs..
    }

}


问:
updateCheckboxGroupInput behaves differently depending on previous added/deleted updateRadioButtons
In short, the issue I have is the following: Depending on whether I update or leave empty Radio buttons "previously" shown to users of my Shiny App, the CheckboxGroup will update correctly or not.
I added a reproducible example below.

My goal is to allow our research assistants to enter data for specific parties. We have the data set stored in the background, and it might be that RAs have already started working on some of the parties. So they can, at first, choose the country, the party and indicate whether they have already worked on the party previously. In the latter case, their previous codings shall be updated and shown on the "next pages". What is shown on the "next pages" (hiding and showing parts of the shiny app) in our online version is shown below the vertical line.

However, the following issue puzzles me to great extent: When ignoring the lines 69-71 as it is now done, the CheckboxGroupInput behaves as expected; once all relevant meta data is selected, it shows a list of ethnic groups to choose from for the respective country chosen. If RAs have already started coding these parties, the previously selected choices are again selected. But, of course, the previously added data for religious claims are not shown, because they are not (yet) updated.

When I run all lines, including lines 69-71, the Shiny App updates the information on the religious claims correctly, but only shows all possible choices for ethnic groups per country if and only if the party data is sub-setted to the ones previously coded. If RAs choose "No" and then any combination of party ids and countries, they only see the choice selections "Other..." and "Don't know". However, if they choose "Yes" and any combination of party ids and countries, they do get the full list of ethnic groups plus their previous entered data.

Obviously, I would like my app to update both the religious claims and the ethnic groups selection, irrespective of any of the selections made regarding previously coded data, party id and country.

```<code>library(shiny)
library(dplyr)
library(stringr)

party_data <- data.frame(country_name=c("Austria","Austria","Belgium","Belgium","Austria","Austria","Belgium","Belgium"),
                         party_id=c(100,101,100,101,100,101,100,101),
                         rel_claim_flag=c(rep(NA,4), rep("Yes",4)),
                         eth_base_group=c(rep(NA,4), rep("Germans|Czech",2), rep("French|Flemings",2)),
                         coded=c(rep("No",4),rep("Yes",4)),
                         stringsAsFactors = F)
party_data$eth_base_group <- str_split(string=party_data$eth_base_group, pattern="\\|")
ethnicgroups <- data.frame(country_name=c(rep("Austria",3), rep("Belgium",3)),
                           groupname=c("Germans","Czech","French","French","Flemings","Dutch"),
                           stringsAsFactors = F)

ui <- fluidPage(

  ############## Country /party selection #####
  div(id="choose_country_and_party",
      div(id="preselect",
          selectInput("coded", "Has the data already been coded?",
                      choices=c("Yes","No",""),
                      selected=""),
          selectInput("country_name", "Select country",
                      choices=c(party_data$country_name,""),
                      selected=""),
          selectInput("party_id", "Select party ID",
                      choices=c(party_data$party_id,0),
                      selected=0)),
  ),
  hr(),

  ############## Ethnic page #####
  div(id="data_entry_ethnic",

      h3("Religious claims and base"),
      radioButtons("rel_claim_flag", "Religious claim and base:", choices=c("Yes","No","Don't know"),
                   selected=character(0)),

      h3("Ethnic base group"),
      checkboxGroupInput("eth_base_group", "Please select:",
                         choices=c(unique(ethnicgroups$groupname),"Other (please specify below)","Don't know"),
                         selected=character(0))
  )
)

server <- function(input, output, session) {

  selectedData <- reactive({
    if (input$coded=="Yes") {
      selected <- party_data %>%
        filter(coded=="Yes" &
                 country_name==input$country_name &
                 party_id==input$party_id)
    } else {
      selected <- party_data %>%
        filter(coded=="No" &
                 country_name==input$country_name &
                 party_id==input$party_id)
    }
  })

  # 3.4 Religion, language and ethnicity ####
  observe({
    selected <- selectedData()
#    updateRadioButtons(session,
#                        inputId="rel_claim_flag",
#                        selected=selected$rel_claim_flag)
    updateCheckboxGroupInput(session,
                             inputId="eth_base_group",
                             choices=c(ethnicgroups$groupname[ethnicgroups$country_name%in%selected$country_name],
                                       "Other (please specify below)","Don't know"),
                             selected = unlist(selected$eth_base_group))
  })

}

shinyApp(ui=ui, server=server)
</code>```

I am especially confused here because from my understanding, updating the radio buttons should neither affect the data in the background, nor is it in any way linked to the checkboxGroupInput element. Any suggestions on how to move forward here so that I can update both input elements would be highly appreciated.

Thank you!

P.S. I do not care for the following issues with this minimal reproducible example, because in the final version, they will not be problematic / solved: Sometimes, the input objects only get updated, once.

答:
Try this</p>
```<code>server <- function(input, output, session) {

  selectedData <- reactive({
    req(input$coded,input$country_name,input$party_id)
    party_data %>% dplyr::filter(coded %in% input$coded &
                          country_name==input$country_name &
                          party_id==input$party_id)

  })

  # 3.4 Religion, language and ethnicity ####
  observeEvent(c(input$coded,input$country_name,input$party_id), {
    selected <- selectedData()
    updateRadioButtons(session,
                           inputId="rel_claim_flag",
                           selected=selected$rel_claim_flag)

  })

  observeEvent(input$country_name, {
    updateCheckboxGroupInput(session,
                             inputId="eth_base_group",
                             choices=c( ethnicgroups$groupname[ethnicgroups$country_name %in% input$country_name],
                                        "Other (please specify below)","Don't know"),
                             selected = selectedData()$eth_base_group)
  })

}
</code>```

Body:
In short, the issue I have is the following: Depending on whether I update or leave empty Radio buttons "previously" shown to users of my Shiny App, the CheckboxGroup will update correctly or not.
I added a reproducible example below.

My goal is to allow our research assistants to enter data for specific parties. We have the data set stored in the background, and it might be that RAs have already started working on some of the parties. So they can, at first, choose the country, the party and indicate whether they have already worked on the party previously. In the latter case, their previous codings shall be updated and shown on the "next pages". What is shown on the "next pages" (hiding and showing parts of the shiny app) in our online version is shown below the vertical line.

However, the following issue puzzles me to great extent: When ignoring the lines 69-71 as it is now done, the CheckboxGroupInput behaves as expected; once all relevant meta data is selected, it shows a list of ethnic groups to choose from for the respective country chosen. If RAs have already started coding these parties, the previously selected choices are again selected. But, of course, the previously added data for religious claims are not shown, because they are not (yet) updated.

When I run all lines, including lines 69-71, the Shiny App updates the information on the religious claims correctly, but only shows all possible choices for ethnic groups per country if and only if the party data is sub-setted to the ones previously coded. If RAs choose "No" and then any combination of party ids and countries, they only see the choice selections "Other..." and "Don't know". However, if they choose "Yes" and any combination of party ids and countries, they do get the full list of ethnic groups plus their previous entered data.

Obviously, I would like my app to update both the religious claims and the ethnic groups selection, irrespective of any of the selections made regarding previously coded data, party id and country.

library(shiny)
library(dplyr)
library(stringr)

party_data <- data.frame(country_name=c("Austria","Austria","Belgium","Belgium","Austria","Austria","Belgium","Belgium"),
                         party_id=c(100,101,100,101,100,101,100,101),
                         rel_claim_flag=c(rep(NA,4), rep("Yes",4)),
                         eth_base_group=c(rep(NA,4), rep("Germans|Czech",2), rep("French|Flemings",2)),
                         coded=c(rep("No",4),rep("Yes",4)),
                         stringsAsFactors = F)
party_data$eth_base_group <- str_split(string=party_data$eth_base_group, pattern="\\|")
ethnicgroups <- data.frame(country_name=c(rep("Austria",3), rep("Belgium",3)),
                           groupname=c("Germans","Czech","French","French","Flemings","Dutch"),
                           stringsAsFactors = F)

ui <- fluidPage(

  ############## Country /party selection #####
  div(id="choose_country_and_party",
      div(id="preselect",
          selectInput("coded", "Has the data already been coded?",
                      choices=c("Yes","No",""),
                      selected=""),
          selectInput("country_name", "Select country",
                      choices=c(party_data$country_name,""),
                      selected=""),
          selectInput("party_id", "Select party ID",
                      choices=c(party_data$party_id,0),
                      selected=0)),
  ),
  hr(),

  ############## Ethnic page #####
  div(id="data_entry_ethnic",

      h3("Religious claims and base"),
      radioButtons("rel_claim_flag", "Religious claim and base:", choices=c("Yes","No","Don't know"),
                   selected=character(0)),

      h3("Ethnic base group"),
      checkboxGroupInput("eth_base_group", "Please select:",
                         choices=c(unique(ethnicgroups$groupname),"Other (please specify below)","Don't know"),
                         selected=character(0))
  )
)

server <- function(input, output, session) {

  selectedData <- reactive({
    if (input$coded=="Yes") {
      selected <- party_data %>%
        filter(coded=="Yes" &
                 country_name==input$country_name &
                 party_id==input$party_id)
    } else {
      selected <- party_data %>%
        filter(coded=="No" &
                 country_name==input$country_name &
                 party_id==input$party_id)
    }
  })

  # 3.4 Religion, language and ethnicity ####
  observe({
    selected <- selectedData()
#    updateRadioButtons(session,
#                        inputId="rel_claim_flag",
#                        selected=selected$rel_claim_flag)
    updateCheckboxGroupInput(session,
                             inputId="eth_base_group",
                             choices=c(ethnicgroups$groupname[ethnicgroups$country_name%in%selected$country_name],
                                       "Other (please specify below)","Don't know"),
                             selected = unlist(selected$eth_base_group))
  })

}

shinyApp(ui=ui, server=server)

I am especially confused here because from my understanding, updating the radio buttons should neither affect the data in the background, nor is it in any way linked to the checkboxGroupInput element. Any suggestions on how to move forward here so that I can update both input elements would be highly appreciated.

Thank you!

P.S. I do not care for the following issues with this minimal reproducible example, because in the final version, they will not be problematic / solved: Sometimes, the input objects only get updated, once.

Body:
Try this

server <- function(input, output, session) {

  selectedData <- reactive({
    req(input$coded,input$country_name,input$party_id)
    party_data %>% dplyr::filter(coded %in% input$coded &
                          country_name==input$country_name &
                          party_id==input$party_id)

  })

  # 3.4 Religion, language and ethnicity ####
  observeEvent(c(input$coded,input$country_name,input$party_id), {
    selected <- selectedData()
    updateRadioButtons(session,
                           inputId="rel_claim_flag",
                           selected=selected$rel_claim_flag)

  })

  observeEvent(input$country_name, {
    updateCheckboxGroupInput(session,
                             inputId="eth_base_group",
                             choices=c( ethnicgroups$groupname[ethnicgroups$country_name %in% input$country_name],
                                        "Other (please specify below)","Don't know"),
                             selected = selectedData()$eth_base_group)
  })

}


问:
SharedPreferences.Editor vs onSharedPreferenceChanged listener
I have an activity that implements SharedPreferences.OnSharedPreferenceChangeListener

```<code>    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_visualizer);
    mVisualizerView = (VisualizerView) findViewById(R.id.activity_visualizer);
    setupSharedPreferences();
    setupPermissions();
}

private void setupSharedPreferences() {

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mVisualizerView.setShowBass(sharedPreferences.getBoolean(getString(R.string.pref_show_bass_key), getResources().getBoolean(R.bool.pref_show_bass_default)));

    mVisualizerView.setShowMid(true);
    mVisualizerView.setShowTreble(true);
    mVisualizerView.setMinSizeScale(1);
    mVisualizerView.setColor(getString(R.string.pref_color_red_value));

    sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
</code>```

I have an override method that listens to a preference change

```<code>    @Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    if(key.equals(getString(R.string.pref_show_bass_key))){
        mVisualizerView.setShowBass(sharedPreferences.getBoolean(key, getResources().getBoolean(R.bool.pref_show_bass_default)));
    }

}
</code>```

I wonder what  mVisualizerView.setShowBass(sharedPreferences.getBoolean(key, getResources().getBoolean(R.bool.pref_show_bass_default))); inside the override method does because what I know is that if we want to put values inside preference object is that we should use SharedPreferences.Editor just like

```<code>    editor.putBoolean(key, value);
</code>```

setShowBass is a setter method for the mVisualizerView not the method used for storing values that we want to save

if we want to retrieve the data we use

```<code>    sharedPreferences.getBoolean(key, value);
</code>```

why my code works without using the editor object for storing and retrieving of data?

答:
Yes everything you assuming is correct, and the code you shared is also correct.

```<code>mVisualizerView.setShowBass(sharedPreferences.getBoolean(key, getResources().getBoolean(R.bool.pref_show_bass_default)));
</code>```

This code is retrieving a boolean from sharedPreferences WHICH MIGHT BE SETTING IN from some change visualiser settings screen.

```<code>onSharedPreferenceChanged
</code>```

is just an observer which is listening if any of visualiser/player setting is changed then update the view accordingly.

Body:
I have an activity that implements SharedPreferences.OnSharedPreferenceChangeListener

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_visualizer);
    mVisualizerView = (VisualizerView) findViewById(R.id.activity_visualizer);
    setupSharedPreferences();
    setupPermissions();
}

private void setupSharedPreferences() {

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mVisualizerView.setShowBass(sharedPreferences.getBoolean(getString(R.string.pref_show_bass_key), getResources().getBoolean(R.bool.pref_show_bass_default)));

    mVisualizerView.setShowMid(true);
    mVisualizerView.setShowTreble(true);
    mVisualizerView.setMinSizeScale(1);
    mVisualizerView.setColor(getString(R.string.pref_color_red_value));

    sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}

I have an override method that listens to a preference change

    @Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    if(key.equals(getString(R.string.pref_show_bass_key))){
        mVisualizerView.setShowBass(sharedPreferences.getBoolean(key, getResources().getBoolean(R.bool.pref_show_bass_default)));
    }

}

I wonder what  mVisualizerView.setShowBass(sharedPreferences.getBoolean(key, getResources().getBoolean(R.bool.pref_show_bass_default))); inside the override method does because what I know is that if we want to put values inside preference object is that we should use SharedPreferences.Editor just like

    editor.putBoolean(key, value);

setShowBass is a setter method for the mVisualizerView not the method used for storing values that we want to save

if we want to retrieve the data we use

    sharedPreferences.getBoolean(key, value);

why my code works without using the editor object for storing and retrieving of data?

Body:
Yes everything you assuming is correct, and the code you shared is also correct.

mVisualizerView.setShowBass(sharedPreferences.getBoolean(key, getResources().getBoolean(R.bool.pref_show_bass_default)));

This code is retrieving a boolean from sharedPreferences WHICH MIGHT BE SETTING IN from some change visualiser settings screen.

onSharedPreferenceChanged

is just an observer which is listening if any of visualiser/player setting is changed then update the view accordingly.


问:
Excel formula where certain combinations of cells would return a value
I'm creating a stakeholder map and I have two columns with two possible entries for each

```<code>Power | Interest | Strategy
</code>```

Power and Interest can be either High or Low

So I am trying to get a strategy to return a value based on whether Power or Interest is one of those two combinations as an example:

```<code>Power = High, Interest = High, Strategy = Manage Closely
Power = Low, Interest = High, Strategy = Keep Informed
Power = Low, Interest = Low, Strategy = Monitor
Power = High, Interest = Low, Strategy = Meet Their Needs
</code>```

Can someone help me with this formula?

答:
Another solution:
You can use built-in function below after saving your file as an .xlsm file and saving the code in a new module in file:

```<code>    Function myStrategy(power As String, Interest As String) As String

    If LCase(power) = "high" And LCase(Interest) = "high" Then
    myStrategy = "Manage Closely"
    ElseIf LCase(power) = "low" And LCase(Interest) = "high" Then
    myStrategy = "Keep Informed"
    ElseIf LCase(power) = "low" And LCase(Interest) = "low" Then
    myStrategy = "Monitor"
    ElseIf LCase(power) = "high" And LCase(Interest) = "low" Then
    myStrategy = "Meet Their Needs"
    End If

    End Function
</code>```

Body:
I'm creating a stakeholder map and I have two columns with two possible entries for each

Power | Interest | Strategy

Power and Interest can be either High or Low

So I am trying to get a strategy to return a value based on whether Power or Interest is one of those two combinations as an example:

Power = High, Interest = High, Strategy = Manage Closely
Power = Low, Interest = High, Strategy = Keep Informed
Power = Low, Interest = Low, Strategy = Monitor
Power = High, Interest = Low, Strategy = Meet Their Needs

Can someone help me with this formula?

Body:
Another solution:
You can use built-in function below after saving your file as an .xlsm file and saving the code in a new module in file:

    Function myStrategy(power As String, Interest As String) As String

    If LCase(power) = "high" And LCase(Interest) = "high" Then
    myStrategy = "Manage Closely"
    ElseIf LCase(power) = "low" And LCase(Interest) = "high" Then
    myStrategy = "Keep Informed"
    ElseIf LCase(power) = "low" And LCase(Interest) = "low" Then
    myStrategy = "Monitor"
    ElseIf LCase(power) = "high" And LCase(Interest) = "low" Then
    myStrategy = "Meet Their Needs"
    End If

    End Function


问:
I have a code for CircularLinkedList but the `printList` function here behaves weird
Following is the code for a CircularLinkedList. I noticed that whenever I call theprintList function in my code, nothing after the function call gets executed. Why is it so?

```<code>typedef struct Node
{
    int data;
    struct Node *next;//this is called self-referential structure
} Node;

Node *head = NULL;//global head pointer
Node *tail = NULL;

void insertAtBeginning(int num){
    Node *newNode = (Node*)(malloc(sizeof(Node)));
    newNode->data = num;
    newNode->next = NULL;
    if(head == NULL){
        head = newNode;
        tail = newNode;
        return;
    }
    newNode->next = head;
    head = newNode;
    tail->next = head;
}
void printList(Node *head){
    if(head == NULL){
        cout<<"List is empty"<<endl;
        return;
    }

    Node* temp;
    temp = head;
    do{
        cout<<temp->data<<" ";
        temp = temp->next;
    }while(temp != head);

}

int main(){
    insertAtBeginning(1);
    printList(head);
    insertAtBeginning(2);
    printList(head);
    return 0;

}
</code>```

The above code results in the following output:
Output: 1
Image: Code output
Can anyone explain why is this happening?

答:
For starters in C++ you should use the operator new instead of the standard C function malloc.

Nevertheless, after this code snippet

```<code>Node *newNode = (Node*)(malloc(sizeof(Node)));
newNode->data = num;
newNode->next = NULL;
if(head == NULL){
    head = newNode;
    tail = newNode;
    return;
}
</code>```

pointers head->next and tail->next are equal to NULL.

As a result this code snippet

```<code>Node* temp;
temp = head;
do{
    cout<<temp->data<<" ";
    temp = temp->next;
}while(temp != head);
</code>```

invokes undefined behavior.

It seems you need to add one more statement to the body of the if statement

```<code>if(head == NULL){
    head = newNode;
    tail = newNode;
    tail->next = head;
    return;
}
</code>```

Body:
Following is the code for a CircularLinkedList. I noticed that whenever I call theprintList function in my code, nothing after the function call gets executed. Why is it so?

typedef struct Node
{
    int data;
    struct Node *next;//this is called self-referential structure
} Node;

Node *head = NULL;//global head pointer
Node *tail = NULL;

void insertAtBeginning(int num){
    Node *newNode = (Node*)(malloc(sizeof(Node)));
    newNode->data = num;
    newNode->next = NULL;
    if(head == NULL){
        head = newNode;
        tail = newNode;
        return;
    }
    newNode->next = head;
    head = newNode;
    tail->next = head;
}
void printList(Node *head){
    if(head == NULL){
        cout<<"List is empty"<<endl;
        return;
    }

    Node* temp;
    temp = head;
    do{
        cout<<temp->data<<" ";
        temp = temp->next;
    }while(temp != head);

}

int main(){
    insertAtBeginning(1);
    printList(head);
    insertAtBeginning(2);
    printList(head);
    return 0;

}

The above code results in the following output:
Output: 1
Image: Code output
Can anyone explain why is this happening?

Body:
For starters in C++ you should use the operator new instead of the standard C function malloc.

Nevertheless, after this code snippet

Node *newNode = (Node*)(malloc(sizeof(Node)));
newNode->data = num;
newNode->next = NULL;
if(head == NULL){
    head = newNode;
    tail = newNode;
    return;
}

pointers head->next and tail->next are equal to NULL.

As a result this code snippet

Node* temp;
temp = head;
do{
    cout<<temp->data<<" ";
    temp = temp->next;
}while(temp != head);

invokes undefined behavior.

It seems you need to add one more statement to the body of the if statement

if(head == NULL){
    head = newNode;
    tail = newNode;
    tail->next = head;
    return;
}


问:
How to add/update an attribute to an HTML element using JavaScript?
I'm trying to find a way that will add / update attribute using JavaScript.  I know I can do it with setAttribute() function but that doesn't work in IE.

答:
You can read here about the behaviour of attributes in many different browsers, including IE.

element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn't work, then maybe
element.attributeName = 'value' might work.

OwnerDisplayName: andi


问:
Entity Framework & MVC Models
Our team is currently developing a web application, in that we have a class library with Entity Framework .edmx added and have generated the POCO classes.

Our Web Application is based on MVC, we have defined our classes in models with the same name and attributes (copy paste of the POCO classes from the .edmx). The .edmx class library is refrenced to MVC web application.

The Views are strongly typed of MVC Model classes. We have used MVC Models for Display, StringLength & Required.

In our controller when there is a CRUD operation we are accepting the POCO Classes Type such as

```<code>     public ActionResult Create(EFModels.User user)    {    }
</code>```

EFModels.User is a class from the .edmx (POCO generated class) and the MVC View is strongly typed to the model which is MvcWebApplication.Models.User.

Question is how are we getting data from the MvcWebApplication.Models.User (from Model) to EFModels.User (EF class) in the ActionResult Create ??

I am able to get the data, I know it is coz of the same property name. I tried changing the class name but still it works, but if we change the property name it does not work. I cannot understand the logic behind it.

Initially we never knew it didn`t work and we were using AutoMapper to convert the Model Class to Edmx POCO class.

Any ideas, Thanks.

The question is how are we getting the values of the Model Class to the EF class with any mapping. I don`t need to use AutoMapper, without using that I am getting the values.

Have a look at the code, hope that explains better...

//POCO CLASS

```<code>namespace EFModels
{
    using System;
    using System.Collections.Generic;

    public partial class User
    {
        public int Id { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
    }
}
</code>```

//MVC Model Class

```<code>namespace MvcWebSamp.Models
{
    public class User
    {
        public int Id { get; set; }

        [Display(ResourceType = typeof(BasicTags), Name = "Type")]
        [StringLength(15, ErrorMessageResourceName = "TypeLength", ErrorMessageResourceType = typeof(BasicTags))]
        [Required(ErrorMessageResourceName = "TypeRequired", ErrorMessageResourceType = typeof(BasicTags))]
        public string TypeName { get; set; }
        public string Name { get; set; }

        public Address Address { get; set; }
    }
}
</code>```

//MVC VIEW PAGE

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcWebSamp.Models.User>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    User
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>User</h2>
  <% using (Html.BeginForm("Create", "User", FormMethod.Post))
       {
    %>
     <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>User</legend>
        <div class="editor-field">
            <%: Html.LabelFor(model => model.TypeName) %>
            <%: Html.EditorFor(model => model.TypeName)%>
            <%: Html.ValidationMessageFor(model => model.TypeName)%>
        </div>
        <div class="editor-field">
            <%: Html.LabelFor(model => model.Name) %>
            <%: Html.EditorFor(model => model.Name)%>
             <%: Html.EditorFor(model => model.Address.street)%>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
    <% } %>
</asp:Content>
</code>```

//Controller Method

```<code> public ActionResult Create(EFModels.User user)
    {
        Model1Container con = new Model1Container();
        con.Users.Add(user);
        con.SaveChanges();
        return View("User");
    }
</code>```

When I hit the Create Button, I am posting data of the type MvcWebSamp.Models.User and in the Create Action I am able to get the data of the type EFModels.User user without using any AutoMapper. I want to know how this works???

答:
You aren't using your MvcWebSamp at all - as you can see, the controller takes the EFModel

```<code>public ActionResult Create(EFModels.User user)
</code>```

It works because the properties are the same. You just need to modify the controller method signatures to take the MvcWebSamp objects instead, and then transform those objects to the EFModel objects.

Title: Entity Framework & MVC Models

Body:
Our team is currently developing a web application, in that we have a class library with Entity Framework .edmx added and have generated the POCO classes.

Our Web Application is based on MVC, we have defined our classes in models with the same name and attributes (copy paste of the POCO classes from the .edmx). The .edmx class library is refrenced to MVC web application.

The Views are strongly typed of MVC Model classes. We have used MVC Models for Display, StringLength & Required.

In our controller when there is a CRUD operation we are accepting the POCO Classes Type such as

     public ActionResult Create(EFModels.User user)    {    }

EFModels.User is a class from the .edmx (POCO generated class) and the MVC View is strongly typed to the model which is MvcWebApplication.Models.User.

Question is how are we getting data from the MvcWebApplication.Models.User (from Model) to EFModels.User (EF class) in the ActionResult Create ??

I am able to get the data, I know it is coz of the same property name. I tried changing the class name but still it works, but if we change the property name it does not work. I cannot understand the logic behind it.

Initially we never knew it didn`t work and we were using AutoMapper to convert the Model Class to Edmx POCO class.

Any ideas, Thanks.

The question is how are we getting the values of the Model Class to the EF class with any mapping. I don`t need to use AutoMapper, without using that I am getting the values.

Have a look at the code, hope that explains better...

//POCO CLASS

namespace EFModels
{
    using System;
    using System.Collections.Generic;

    public partial class User
    {
        public int Id { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
    }
}

//MVC Model Class

namespace MvcWebSamp.Models
{
    public class User
    {
        public int Id { get; set; }

        [Display(ResourceType = typeof(BasicTags), Name = "Type")]
        [StringLength(15, ErrorMessageResourceName = "TypeLength", ErrorMessageResourceType = typeof(BasicTags))]
        [Required(ErrorMessageResourceName = "TypeRequired", ErrorMessageResourceType = typeof(BasicTags))]
        public string TypeName { get; set; }
        public string Name { get; set; }

        public Address Address { get; set; }
    }
}

//MVC VIEW PAGE

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcWebSamp.Models.User>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    User
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

User

  <% using (Html.BeginForm("Create", "User", FormMethod.Post))
       {
    %>
     <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>User</legend>

            <%: Html.LabelFor(model => model.TypeName) %>
            <%: Html.EditorFor(model => model.TypeName)%>
            <%: Html.ValidationMessageFor(model => model.TypeName)%>

            <%: Html.LabelFor(model => model.Name) %>
            <%: Html.EditorFor(model => model.Name)%>
             <%: Html.EditorFor(model => model.Address.street)%>

            <input type="submit" value="Create" />

    </fieldset>
    <% } %>
</asp:Content>

//Controller Method

 public ActionResult Create(EFModels.User user)
    {
        Model1Container con = new Model1Container();
        con.Users.Add(user);
        con.SaveChanges();
        return View("User");
    }

When I hit the Create Button, I am posting data of the type MvcWebSamp.Models.User and in the Create Action I am able to get the data of the type EFModels.User user without using any AutoMapper. I want to know how this works???

Body:
You aren't using your MvcWebSamp at all - as you can see, the controller takes the EFModel

public ActionResult Create(EFModels.User user)

It works because the properties are the same. You just need to modify the controller method signatures to take the MvcWebSamp objects instead, and then transform those objects to the EFModel objects.


问:
How to get unexported types with reflect?
Imagine someone has initialized a rpc client with client, _ := rpc.Dial('tcp', 'example.com:port') and provides you only the rpc client instance. For some reason, you'd like to get the address example.com from the client instance. However, as the client type is highly abstracted, you cannot directly get the net.Conn instance which serves a RemoteAddr() method. In this case, the reflect package might be helpful.

Lets start with the following attempt:

```<code>func getRemoteAddr(client *rpc.Client) net.Addr {
  codec := reflect.Indirect(rpclient).FieldByName("codec")
  connV := codec.FieldByName("rwc")
  conn := connV.Interface().(net.Conn)
  return conn.RemoteAddr()
}
</code>```

However, an error jumped out immediately from the second line:

```<code>panic: reflect: call of reflect.Value.FieldByName on interface Value
</code>```

This is reasonable as codec is declared as type ClientCodec which is just an interface with four methods' signatures. However, from the code, we know that the detailed type of codec might be the unexported struct gobClientCodec. Unfortunately, the Go compiler is not smart enough to trace down that deep and figure out the actual type. Therefore, is there a way with the reflect package to tell the compiler that I'm confident with the type of codec to be the unexported gobClientCodec? If this is not possible, I'll probably have to calculate the address offset and play with the unsafe pointers, which is the last choice.

P.S. The default Type() method from the reflect method won't work as codec is declared as ClientCodec and initialized by passing the address of a gobClientCodec struct in the NewClient method as follow:

```<code>func NewClient(conn io.ReadWriteCloser) *Client {
    encBuf := bufio.NewWriter(conn)
    client := &gobClientCodec{conn, gob.NewDecoder(conn), gob.NewEncoder(encBuf), encBuf}
    return NewClientWithCodec(client)
}
</code>```

Also, reflect.TypeOf(rpc.gobClientCodec) won't work as well as the compiler refuses unexported type usages.

答:
Use .Elem() to get the value contained in the interface.

Elem returns the value that the interface v contains or that the
pointer v points to. It panics if v's Kind is not Interface or Ptr. It
returns the zero Value if v is nil.

And for your specific use-case you'll also need to use the unsafe package to get access to unexported fields. Make sure to read unsafe's documentation before you use it.

func getRemoteAddr(client *rpc.Client) net.Addr {
  rv := reflect.ValueOf(client)
  rv = rv.Elem()               // deref *rpc.Client
  rv = rv.FieldByName("codec") // get "codec" field from rpc.Client
  rv = rv.Elem()               // get the value that ClientCodec contains
  rv = rv.Elem()               // deref *gobClientCodec
  rv = rv.FieldByName("rwc")   // get "rwc" field from gobClientCodec

  conn := *(*net.Conn)(unsafe.Pointer(rv.UnsafeAddr()))
  return conn.RemoteAddr()
}
```

https://go.dev/play/p/cHHdwQJ7DE7

Body:
Imagine someone has initialized a rpc client with client, _ := rpc.Dial('tcp', 'example.com:port') and provides you only the rpc client instance. For some reason, you'd like to get the address example.com from the client instance. However, as the client type is highly abstracted, you cannot directly get the net.Conn instance which serves a RemoteAddr() method. In this case, the reflect package might be helpful.

Lets start with the following attempt:

func getRemoteAddr(client *rpc.Client) net.Addr {
  codec := reflect.Indirect(rpclient).FieldByName("codec")
  connV := codec.FieldByName("rwc")
  conn := connV.Interface().(net.Conn)
  return conn.RemoteAddr()
}

However, an error jumped out immediately from the second line:

panic: reflect: call of reflect.Value.FieldByName on interface Value

This is reasonable as codec is declared as type ClientCodec which is just an interface with four methods' signatures. However, from the code, we know that the detailed type of codec might be the unexported struct gobClientCodec. Unfortunately, the Go compiler is not smart enough to trace down that deep and figure out the actual type. Therefore, is there a way with the reflect package to tell the compiler that I'm confident with the type of codec to be the unexported gobClientCodec? If this is not possible, I'll probably have to calculate the address offset and play with the unsafe pointers, which is the last choice.

P.S. The default Type() method from the reflect method won't work as codec is declared as ClientCodec and initialized by passing the address of a gobClientCodec struct in the NewClient method as follow:

func NewClient(conn io.ReadWriteCloser) *Client {
    encBuf := bufio.NewWriter(conn)
    client := &gobClientCodec{conn, gob.NewDecoder(conn), gob.NewEncoder(encBuf), encBuf}
    return NewClientWithCodec(client)
}

Also, reflect.TypeOf(rpc.gobClientCodec) won't work as well as the compiler refuses unexported type usages.

Body:
Use .Elem() to get the value contained in the interface.

Elem returns the value that the interface v contains or that the
pointer v points to. It panics if v's Kind is not Interface or Ptr. It
returns the zero Value if v is nil.

And for your specific use-case you'll also need to use the unsafe package to get access to unexported fields. Make sure to read unsafe's documentation before you use it.

func getRemoteAddr(client *rpc.Client) net.Addr {
  rv := reflect.ValueOf(client)
  rv = rv.Elem()               // deref *rpc.Client
  rv = rv.FieldByName("codec") // get "codec" field from rpc.Client
  rv = rv.Elem()               // get the value that ClientCodec contains
  rv = rv.Elem()               // deref *gobClientCodec
  rv = rv.FieldByName("rwc")   // get "rwc" field from gobClientCodec

  conn := *(*net.Conn)(unsafe.Pointer(rv.UnsafeAddr()))
  return conn.RemoteAddr()
}

https://go.dev/play/p/cHHdwQJ7DE7


问:
Stack Overflow 64 characters limit
I'm creating a Database from excel files scraped from the web, the problem is that the source lacks a pattern, the name of the columns vary a lot and sometimes it exceeds the 64 characters limitation from MySQL. My solution by now is running the script and replace each word I find to a reduced version. The problem is that there is too much data and the replace library is getting huge.

Here's an example of one table being created after replaces:

CREATE TABLE `ecorodovias_concessões_e_serviços__bal_at` (
    `index` TEXT,
    `ATIVO TOTAL` FLOAT(53),
    `ATIVO CIRCULANTE` FLOAT(53),
    `CAIXA E EQS CAIXA` FLOAT(53),
    `CAIXA E BANCOS` FLOAT(53),
    `APL FINS` FLOAT(53),
    `APL FINS AV VAL` FLOAT(53),
    `TIT NEG` FLOAT(53),
    `TIT DISP VENDA` FLOAT(53),
    `APL FINS AV CUSTO AMORTIZADO` FLOAT(53),
    `TIT MANTIDOS ATÉ O VENCIMENTO` FLOAT(53),
    `CONTAS RECEBER` FLOAT(53),
    `CLIENTES` FLOAT(53),
    `OUTRAS CONTAS RECEBER` FLOAT(53),
    `ESTOQUES` FLOAT(53),
    `ATIVOS BIOLÓGICOS` FLOAT(53),
    `TRIB REC` FLOAT(53),
    `TRIB CORRENTES REC` FLOAT(53),
    `DSP ANTECIPADAS` FLOAT(53),
    `PRÊMIOS E SEGUROS APROPRIAR` FLOAT(53),
    `OUTROS ATIVOS CIRCULANTES` FLOAT(53),
    `ATIVOS NCO VENDA` FLOAT(53),
    `ATIVOS OP DESCS` FLOAT(53),
    `OUTROS` FLOAT(53),
    `TIT E VAL MOB` FLOAT(53),
    `DIV E JUROS CAPITAL` FLOAT(53),
    `OUTROS CRED` FLOAT(53),
    `EMPRESAS LIGADAS` FLOAT(53),
    `ATIVO NCI` FLOAT(53),
    `ATIVO REALIZÁVEL LONGO PRAZO` FLOAT(53),
    `TRIB DIFERIDOS` FLOAT(53),
    `IR E CS DIFERIDOS` FLOAT(53),
    `CRED PT RELS` FLOAT(53),
    `CRED COLIGADAS` FLOAT(53),
    `CRED CONTROLADORES` FLOAT(53),
    `CRED OUTRAS PT RELS` FLOAT(53),
    `OUTROS ATIVOS NCIS` FLOAT(53),
    `DPST JDC` FLOAT(53),
    `INV` FLOAT(53),
    `PART SOCIETÁRIAS` FLOAT(53),
    `PART COLIGADAS` FLOAT(53),
    `OUTRAS PART SOCIETÁRIAS` FLOAT(53),
    `PROPRIEDADES INV` FLOAT(53),
    `IMOB` FLOAT(53),
    `IMOB OP` FLOAT(53),
    `IMOB ARRADO` FLOAT(53),
    `IMOB ANDAMENTO` FLOAT(53),
    `INTA` FLOAT(53),
    `CONT CSS` FLOAT(53),
    `OBRAS ANDAMENTO` FLOAT(53),
    `GOODWILL` FLOAT(53)
)
```
<p>Before replaces one column might be like "ATIVOS REALIZADOS APÓS COMPRA DE RODOVIA E LIQUIDAÇÃO DE LUCROS", which would result in the 64 characters error.</p>
<p>My replace library are following this pattern:</p>
<pre class="lang-py prettyprint-override"><code>balativo = balativo.replace(regex=['IMPOSTO DE RENDA'], value='IR')
balativo = balativo.replace(regex=['REDUÇÃO'], value='VAR')
balativo = balativo.replace(regex=['AUMENTO'], value='VAR')
balativo = balativo.replace(regex=['EFEITO'], value='VAR')
balativo = balativo.replace(regex=['PERDA'], value='VAR')
balativo = balativo.replace(regex=['GANHO'], value='VAR')
balativo = balativo.replace(regex=['CONSTITUIÇÃO'], value='VAR')
balativo = balativo.replace(regex=['REVERSÃO'], value='VAR')
balativo = balativo.replace(regex=['CAIXA DESPENDIDO'], value='DESPESA')
...
</code>```

So I was wondering if there is a different and more efficient approach to automatically match the 64 characters limit, the column names doesn't have to perfectly match the source.

答:
I've found an alternative that worked for me, truncating the data, for my database the most important information are in the first words, so truncating works for me, heres the partial code:

```<code>columnslist = []
columns = list(balativo.columns)
for column in columns:
    if len(column) >= 64:
        column = column[0:63]
        columnslist.append(column)
    else:
        columnslist.append(column)
balativo = balativo.set_axis(columnslist, axis=1)
</code>```

This worked for uploading ~4000 sheets to my database with no errors, so I will mark this as the answer if someone goes through the same.

Title: Stack Overflow 64 characters limit

Body:
I'm creating a Database from excel files scraped from the web, the problem is that the source lacks a pattern, the name of the columns vary a lot and sometimes it exceeds the 64 characters limitation from MySQL. My solution by now is running the script and replace each word I find to a reduced version. The problem is that there is too much data and the replace library is getting huge.

Here's an example of one table being created after replaces:

CREATE TABLE `ecorodovias_concessões_e_serviços__bal_at` (
    `index` TEXT,
    `ATIVO TOTAL` FLOAT(53),
    `ATIVO CIRCULANTE` FLOAT(53),
    `CAIXA E EQS CAIXA` FLOAT(53),
    `CAIXA E BANCOS` FLOAT(53),
    `APL FINS` FLOAT(53),
    `APL FINS AV VAL` FLOAT(53),
    `TIT NEG` FLOAT(53),
    `TIT DISP VENDA` FLOAT(53),
    `APL FINS AV CUSTO AMORTIZADO` FLOAT(53),
    `TIT MANTIDOS ATÉ O VENCIMENTO` FLOAT(53),
    `CONTAS RECEBER` FLOAT(53),
    `CLIENTES` FLOAT(53),
    `OUTRAS CONTAS RECEBER` FLOAT(53),
    `ESTOQUES` FLOAT(53),
    `ATIVOS BIOLÓGICOS` FLOAT(53),
    `TRIB REC` FLOAT(53),
    `TRIB CORRENTES REC` FLOAT(53),
    `DSP ANTECIPADAS` FLOAT(53),
    `PRÊMIOS E SEGUROS APROPRIAR` FLOAT(53),
    `OUTROS ATIVOS CIRCULANTES` FLOAT(53),
    `ATIVOS NCO VENDA` FLOAT(53),
    `ATIVOS OP DESCS` FLOAT(53),
    `OUTROS` FLOAT(53),
    `TIT E VAL MOB` FLOAT(53),
    `DIV E JUROS CAPITAL` FLOAT(53),
    `OUTROS CRED` FLOAT(53),
    `EMPRESAS LIGADAS` FLOAT(53),
    `ATIVO NCI` FLOAT(53),
    `ATIVO REALIZÁVEL LONGO PRAZO` FLOAT(53),
    `TRIB DIFERIDOS` FLOAT(53),
    `IR E CS DIFERIDOS` FLOAT(53),
    `CRED PT RELS` FLOAT(53),
    `CRED COLIGADAS` FLOAT(53),
    `CRED CONTROLADORES` FLOAT(53),
    `CRED OUTRAS PT RELS` FLOAT(53),
    `OUTROS ATIVOS NCIS` FLOAT(53),
    `DPST JDC` FLOAT(53),
    `INV` FLOAT(53),
    `PART SOCIETÁRIAS` FLOAT(53),
    `PART COLIGADAS` FLOAT(53),
    `OUTRAS PART SOCIETÁRIAS` FLOAT(53),
    `PROPRIEDADES INV` FLOAT(53),
    `IMOB` FLOAT(53),
    `IMOB OP` FLOAT(53),
    `IMOB ARRADO` FLOAT(53),
    `IMOB ANDAMENTO` FLOAT(53),
    `INTA` FLOAT(53),
    `CONT CSS` FLOAT(53),
    `OBRAS ANDAMENTO` FLOAT(53),
    `GOODWILL` FLOAT(53)
)

Before replaces one column might be like "ATIVOS REALIZADOS APÓS COMPRA DE RODOVIA E LIQUIDAÇÃO DE LUCROS", which would result in the 64 characters error.

My replace library are following this pattern:

balativo = balativo.replace(regex=['IMPOSTO DE RENDA'], value='IR')
balativo = balativo.replace(regex=['REDUÇÃO'], value='VAR')
balativo = balativo.replace(regex=['AUMENTO'], value='VAR')
balativo = balativo.replace(regex=['EFEITO'], value='VAR')
balativo = balativo.replace(regex=['PERDA'], value='VAR')
balativo = balativo.replace(regex=['GANHO'], value='VAR')
balativo = balativo.replace(regex=['CONSTITUIÇÃO'], value='VAR')
balativo = balativo.replace(regex=['REVERSÃO'], value='VAR')
balativo = balativo.replace(regex=['CAIXA DESPENDIDO'], value='DESPESA')
...

So I was wondering if there is a different and more efficient approach to automatically match the 64 characters limit, the column names doesn't have to perfectly match the source.

Body:
I've found an alternative that worked for me, truncating the data, for my database the most important information are in the first words, so truncating works for me, heres the partial code:

columnslist = []
columns = list(balativo.columns)
for column in columns:
    if len(column) >= 64:
        column = column[0:63]
        columnslist.append(column)
    else:
        columnslist.append(column)
balativo = balativo.set_axis(columnslist, axis=1)

This worked for uploading ~4000 sheets to my database with no errors, so I will mark this as the answer if someone goes through the same.


问:
How to group columns and sum them, in a large CSV?
I have a large CSV (hundreds of millions of rows) and I need to sum the Value column based on the grouping of the ID, Location, and Date columns.

My CSV is similar to:

    ID Location        Date  Value
 1   1     Loc1  2022-01-27      5
 2   1     Loc1  2022-01-27      4
 3   1     Loc1  2022-01-28      7
 4   1     Loc2  2022-01-29      8
 5   2     Loc1  2022-01-27     11
 6   2     Loc2  2022-01-28      4
 7   2     Loc2  2022-01-29      6
 8   3     Loc1  2022-01-28      9
 9   3     Loc1  2022-01-28      9
10   3     Loc2  2022-01-29      1
```
<ul>
<li><code>{ID: 1, Location: Loc1, Date: 2022-01-27}</code> is one such group, and its sub values <code>5</code> and <code>4</code> should be summed to <code>9</code></li>
<li><code>{ID: 3, Location: Loc1, Date: 2022-01-28}</code> is another group and its sum should be <code>18</code></li>
</ul>
<p>Here's what that sample input should look like, processed/summed, and written to a new CSV:</p>
<pre class="lang-none prettyprint-override"><code>ID Location        Date  Value
1     Loc1  2022-01-27      9
1     Loc1  2022-01-28      7
1     Loc2  2022-01-29      8
2     Loc1  2022-01-27     11
2     Loc2  2022-01-28      4
2     Loc2  2022-01-29      6
3     Loc1  2022-01-28     18
3     Loc2  2022-01-29      1
</code>```

I know using df.groupby([columns]).sum() would give the desired result, but the CSV is so big I keep getting memory errors. I've tried looking at other ways to read/manipulate CSV data but have still not been successful, so if anyone knows a way I can do this in python without maxing out my memory that would be great!

NB: I know there is a unnamed first column in my initial csv, this is irrelevant and doesn't need to be in the outputted, but doesn't matter if it is :)

答:
Have you tried:

```<code>output = []
for key, group in df.groupby([columns]):
    output.append((key, group['a'].sum()))

pd.DataFrame(output).to_csv("....csv")
</code>```

source:
https://stackoverflow.com/a/54244289/7132906

Body:
I have a large CSV (hundreds of millions of rows) and I need to sum the Value column based on the grouping of the ID, Location, and Date columns.

My CSV is similar to:

    ID Location        Date  Value
 1   1     Loc1  2022-01-27      5
 2   1     Loc1  2022-01-27      4
 3   1     Loc1  2022-01-28      7
 4   1     Loc2  2022-01-29      8
 5   2     Loc1  2022-01-27     11
 6   2     Loc2  2022-01-28      4
 7   2     Loc2  2022-01-29      6
 8   3     Loc1  2022-01-28      9
 9   3     Loc1  2022-01-28      9
10   3     Loc2  2022-01-29      1

{ID: 1, Location: Loc1, Date: 2022-01-27} is one such group, and its sub values 5 and 4 should be summed to 9

{ID: 3, Location: Loc1, Date: 2022-01-28} is another group and its sum should be 18

Here's what that sample input should look like, processed/summed, and written to a new CSV:

ID Location        Date  Value
1     Loc1  2022-01-27      9
1     Loc1  2022-01-28      7
1     Loc2  2022-01-29      8
2     Loc1  2022-01-27     11
2     Loc2  2022-01-28      4
2     Loc2  2022-01-29      6
3     Loc1  2022-01-28     18
3     Loc2  2022-01-29      1

I know using df.groupby([columns]).sum() would give the desired result, but the CSV is so big I keep getting memory errors. I've tried looking at other ways to read/manipulate CSV data but have still not been successful, so if anyone knows a way I can do this in python without maxing out my memory that would be great!

NB: I know there is a unnamed first column in my initial csv, this is irrelevant and doesn't need to be in the outputted, but doesn't matter if it is :)

Body:
Have you tried:

output = []
for key, group in df.groupby([columns]):
    output.append((key, group['a'].sum()))

pd.DataFrame(output).to_csv("....csv")

source:
https://stackoverflow.com/a/54244289/7132906


问:
How to read property of control defined inside style in silverlight.?
I am using NumericUpDown control in my silver-light application. Code is as follows

```<code> <StackPanel Style="{StaticResource StackPanelStyle_LableValue}">
                        <TextBlock Text="{Binding Path=ViewItem.Strength, Source={StaticResource LocalizedStrings }}" Style="{StaticResource TextBlockStyle}" />
                        <inputToolkit:NumericUpDown Style="{StaticResource NumericUpdownStyle_Strength}"
                                                    Value="{Binding RightSpecGlassStrength, Mode=TwoWay, ValidatesOnNotifyDataErrors=True, NotifyOnValidationError=True}"
                                                    TabIndex="5" />
                    </StackPanel>
</code>```

and Style that i bind to NumericUpDown control as follows

```<code> <Style x:Key="NumericUpdownStyle_Strength" TargetType="inputToolkit:NumericUpDown">
    <Setter Property="Width" Value="Auto"></Setter>
    <Setter Property="MinWidth" Value="50"></Setter>
    <Setter Property="Height" Value="20"></Setter>
    <Setter Property="Minimum" Value="-28"></Setter>
    <Setter Property="Maximum" Value="28"></Setter>
    <Setter Property="BorderThickness" Value="0"></Setter>
    <Setter Property="BorderBrush" Value="White"></Setter>
    <Setter Property="DecimalPlaces" Value="2"></Setter>
    <Setter Property="Increment" Value="0.25"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="inputToolkit:NumericUpDown">
                <Grid>
                    <VisualStateManager.VisualStateGroups>

                        <VisualStateGroup x:Name="CommonStates">
                            <VisualStateGroup.Transitions>
                                <VisualTransition GeneratedDuration="0"/>
                            </VisualStateGroup.Transitions>
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="DisabledVisualElement" Storyboard.TargetProperty="(UIElement.Opacity)" To="1"/>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                        <VisualStateGroup x:Name="FocusStates">
                            <VisualState x:Name="Focused">
                                <Storyboard>
                                    <DoubleAnimationUsingKeyFrames Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity">
                                        <SplineDoubleKeyFrame KeyTime="0" Value="1"/>
                                    </DoubleAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Unfocused"/>
                        </VisualStateGroup>

                        <VisualStateGroup x:Name="ValidationStates">
                            <VisualState x:Name="Valid"/>
                            <VisualState x:Name="InvalidUnfocused">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="InvalidFocused">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsOpen">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <sys:Boolean>True</sys:Boolean>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>

                    </VisualStateManager.VisualStateGroups>
                    <inputToolkit:ButtonSpinner x:Name="Spinner" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" MinWidth="35">
                        <StackPanel Background="White" Orientation="Horizontal" HorizontalAlignment="Right" Width="Auto">
                            <TextBox x:Name="Text"  Style="{StaticResource TextBoxStyle}" TabIndex="0"
                                 BorderThickness="0" FontFamily="{TemplateBinding FontFamily}" FontSize="{TemplateBinding FontSize}" FontStretch="{TemplateBinding FontStretch}" FontStyle="{TemplateBinding FontStyle}" FontWeight="{TemplateBinding FontWeight}" Foreground="{TemplateBinding Foreground}" MinWidth="50" Width="Auto"  AcceptsReturn="False" Text="{TemplateBinding Value}" TextAlignment="Left" TextWrapping="NoWrap"/>
                        </StackPanel>
                    </inputToolkit:ButtonSpinner>
                    <Border x:Name="DisabledVisualElement" IsHitTestVisible="false" Opacity="0" Background="#A5FFFFFF" CornerRadius="2.5,2.5,2.5,2.5"/>
                    <Border x:Name="FocusVisualElement" IsHitTestVisible="False" Opacity="0" BorderBrush="#FF45D6FA" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1,1,1,1"/>
                    <Border x:Name="ValidationErrorElement" Visibility="Collapsed" BorderBrush="#FFDB000C" BorderThickness="1" CornerRadius="1">
                        <ToolTipService.ToolTip>
                            <ToolTip x:Name="validationTooltip" Height="Auto" Width="Auto" Template="{StaticResource ValidationToolTipTemplate}" DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" Placement="Right" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}">
                                <ToolTip.Triggers>
                                    <EventTrigger RoutedEvent="Canvas.Loaded">
                                        <BeginStoryboard>
                                            <Storyboard>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsHitTestVisible">
                                                    <DiscreteObjectKeyFrame KeyTime="0">
                                                        <DiscreteObjectKeyFrame.Value>
                                                            <sys:Boolean>true</sys:Boolean>
                                                        </DiscreteObjectKeyFrame.Value>
                                                    </DiscreteObjectKeyFrame>
                                                </ObjectAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </BeginStoryboard>
                                    </EventTrigger>
                                </ToolTip.Triggers>
                            </ToolTip>
                        </ToolTipService.ToolTip>
                        <Grid Height="12" HorizontalAlignment="Right" Margin="1,-4,-4,0" VerticalAlignment="Top" Width="12" Background="Transparent">
                            <Path Fill="#FFDC000C" Margin="1,3,0,0" Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z"/>
                            <Path Fill="#ffffff" Margin="1,3,0,0" Data="M 0,0 L2,0 L 8,6 L8,8"/>
                        </Grid>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

I found bug while running appliction build using above code.

To solve that bug I want read value that entered TextBox defined inside <inputToolkit:ButtonSpinner > </inputToolkit:ButtonSpinner >  "Text" defined in the style of  App.xaml  for the NumericUpDown control.

How do i read value from textBox at run time on ValueChainging/ValueChanged/GotFocus/LostFocust or any other event of NumericUpDown control.

答:
You can add event handler to your inner TextBox template. I don't remember, can you add it on template, but I'm sure, that you can create style like this

```<code><Style x:Key="MyTextBoxStyle" TargetType="{x:Type TextBox}">
    <EventSetter Event="ValueChainging" Handler="PathName_KeyDown" />
    <EventSetter Event="LostFocust" Handler="GiveFocusToMe" />
    ....
</Style>
</code>```

and than apply it to your TextBox, put BreakPoints and see all details you need

Body:
I am using NumericUpDown control in my silver-light application. Code is as follows

 <StackPanel Style="{StaticResource StackPanelStyle_LableValue}">
                        <TextBlock Text="{Binding Path=ViewItem.Strength, Source={StaticResource LocalizedStrings }}" Style="{StaticResource TextBlockStyle}" />
                        <inputToolkit:NumericUpDown Style="{StaticResource NumericUpdownStyle_Strength}"
                                                    Value="{Binding RightSpecGlassStrength, Mode=TwoWay, ValidatesOnNotifyDataErrors=True, NotifyOnValidationError=True}"
                                                    TabIndex="5" />
                    </StackPanel>

and Style that i bind to NumericUpDown control as follows

I found bug while running appliction build using above code.

To solve that bug I want read value that entered TextBox defined inside <inputToolkit:ButtonSpinner > </inputToolkit:ButtonSpinner >  "Text" defined in the style of  App.xaml  for the NumericUpDown control.

How do i read value from textBox at run time on ValueChainging/ValueChanged/GotFocus/LostFocust or any other event of NumericUpDown control.

Body:
You can add event handler to your inner TextBox template. I don't remember, can you add it on template, but I'm sure, that you can create style like this

<Style x:Key="MyTextBoxStyle" TargetType="{x:Type TextBox}">
    <EventSetter Event="ValueChainging" Handler="PathName_KeyDown" />
    <EventSetter Event="LostFocust" Handler="GiveFocusToMe" />
    ....
</Style>

and than apply it to your TextBox, put BreakPoints and see all details you need