问:
Docker-compose Nginx multiple containers flask issue
I have a Flask app with a Nginx reverse proxy setup with docker-compose. I can get everything to work in a single container without problems, but I need to launch the staging and production servers on the same machine, so I am trying to migrate my setup to multiple containers with a separate nginx-proxy container. The reverse proxy setup seems to be ok, but when I access the app using the proxy Flask has some issue with the request. I detail below the docker-compose files and the server outputs.

NGINX-PROXY docker-compose.yml

```<code>version: "3.5"
services:
  nginx-proxy:
    image: jwilder/nginx-proxy
    ports:
      - 80:80
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
    networks:
      - proxy

networks:
  proxy:
</code>```

Flask docker-compose.yml

```<code>version: '3.5'

services:
  # other services defined, not relevant for the issue

  data-api:
    environment:
      FLASK_ENV: development
      VIRTUAL_HOST: app.local
    build: ./dataAPI
    expose:
      - 5000
    ports:
      - 5000:5000
    volumes:
     - ./dataAPI:/dataAPI
    networks:
      - nginx_proxy

networks:
  nginx_proxy:
    external: true
</code>```

I added a line in /etc/hosts for app.local.
I spin up first nginx then the app. If I try to access it directly with 0.0.0.0:5000/staging/data the request is served without problems, but if I try to use the proxy with  app.local/staging/data the Flask  app throws a 404:

Flask log

```<code>data-api_1  | 172.20.0.1 - - [30/May/2019 14:13:29] "GET /staging/data/ HTTP/1.1" 200 -
data-api_1  | 172.20.0.2 - - [30/May/2019 14:13:31] "GET /staging/data/ HTTP/1.1" 404 -
</code>```

答:
It doesn't look like you put the containers on the same network.  The nginx_proxy is using a network named proxy while the flask container is using an network named nginx_proxy.

By the way, docker-compose is useful for composing applications requiring multiple containers.  Rather than use a separate docker-compose file for each container, this setup might be easier if you put both services in the same docker-compose file.  Then you don't even need to setup a separate network as compose creates a default network for the services.

Another note, since you are using an nginx reverse proxy, you probably wouldn't want to map the flask port to the host machine.

Body:
I have a Flask app with a Nginx reverse proxy setup with docker-compose. I can get everything to work in a single container without problems, but I need to launch the staging and production servers on the same machine, so I am trying to migrate my setup to multiple containers with a separate nginx-proxy container. The reverse proxy setup seems to be ok, but when I access the app using the proxy Flask has some issue with the request. I detail below the docker-compose files and the server outputs.

NGINX-PROXY docker-compose.yml

version: "3.5"
services:
  nginx-proxy:
    image: jwilder/nginx-proxy
    ports:
      - 80:80
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
    networks:
      - proxy

networks:
  proxy:

Flask docker-compose.yml

version: '3.5'

services:
  # other services defined, not relevant for the issue

  data-api:
    environment:
      FLASK_ENV: development
      VIRTUAL_HOST: app.local
    build: ./dataAPI
    expose:
      - 5000
    ports:
      - 5000:5000
    volumes:
     - ./dataAPI:/dataAPI
    networks:
      - nginx_proxy

networks:
  nginx_proxy:
    external: true

I added a line in /etc/hosts for app.local.
I spin up first nginx then the app. If I try to access it directly with 0.0.0.0:5000/staging/data the request is served without problems, but if I try to use the proxy with  app.local/staging/data the Flask  app throws a 404:

Flask log

data-api_1  | 172.20.0.1 - - [30/May/2019 14:13:29] "GET /staging/data/ HTTP/1.1" 200 -
data-api_1  | 172.20.0.2 - - [30/May/2019 14:13:31] "GET /staging/data/ HTTP/1.1" 404 -


来源: stackexchange

问:
How to use @XmlIDREF and @XmlID
I don't quite understand how @XmlIDREF and @XmlID work together. By using XmlIDREF I only create a reference to the actual element. However what is the use case for XmlID.

I want to create a reference to the class Publication. Is it enough to annotate the publication List with @XmlIDREF?

```<code>public class Author {

    private String id;
    private String name;
    private List<Publication> publications = new LinkedList<>();

    public Author() {
        super();
    }
    @XmlElement
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElement
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    @XmlIDREF
    public List<Publication> getPublications() {
        return publications;
    }
</code>```

答:
I want to create a reference to the class Publication.
    Is it enough to annotate the publication List with @XmlIDREF?

No, that's only one half of what you need.

You already have this:
With @XmlIDREF you mark the referencing side of the relation
(pointing from Author to Publication).

```<code>public class Author {

    ...

    @XmlIDREF
    @XmlElement(name = "publication")
    public List<Publication> getPublications() {
        return publications;
    }

    ...

}
</code>```

You also need to mark the referenced side (the Publication itself)
by annotating one of its properties with @XmlID, for example like this:

```<code>public class Publication {

    ...

    @XmlID
    @XmlElement
    public String getId() {
        return id;
    }

    ...
}
</code>```

Then you are able to process XML content like this example:

```<code><root>
    <publication>
       <id>p-101</id>
       <title>Death on the Nile</title>
    </publication>
    <publication>
       <id>p-102</id>
       <title>The murder of Roger Ackroyd</title>
    </publication>
    ...
    <author>
       <id>a-42</id>
       <name>Agatha Christie</name>
       <publication>p-101</publication>
       <publication>p-102</publication>
    </author>
    ...
</root>
</code>```

You see, the XML references (like <publication>p-101</publication>)
are mapped to Java object references (in List<Publication> publications).

ContentLicense: CC BY-SA 4.0

Title: How to use @XmlIDREF and @XmlID

Body:
I don't quite understand how @XmlIDREF and @XmlID work together. By using XmlIDREF I only create a reference to the actual element. However what is the use case for XmlID.

I want to create a reference to the class Publication. Is it enough to annotate the publication List with @XmlIDREF?

public class Author {

    private String id;
    private String name;
    private List<Publication> publications = new LinkedList<>();

    public Author() {
        super();
    }
    @XmlElement
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElement
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    @XmlIDREF
    public List<Publication> getPublications() {
        return publications;
    }

Body:
I want to create a reference to the class Publication.
    Is it enough to annotate the publication List with @XmlIDREF?

No, that's only one half of what you need.

You already have this:
With @XmlIDREF you mark the referencing side of the relation
(pointing from Author to Publication).

public class Author {

    ...

    @XmlIDREF
    @XmlElement(name = "publication")
    public List<Publication> getPublications() {
        return publications;
    }

    ...

}

You also need to mark the referenced side (the Publication itself)
by annotating one of its properties with @XmlID, for example like this:

public class Publication {

    ...

    @XmlID
    @XmlElement
    public String getId() {
        return id;
    }

    ...
}

Then you are able to process XML content like this example:

<root>
    <publication>
       <id>p-101</id>
       <title>Death on the Nile</title>
    </publication>
    <publication>
       <id>p-102</id>
       <title>The murder of Roger Ackroyd</title>
    </publication>
    ...
    <author>
       <id>a-42</id>
       <name>Agatha Christie</name>
       <publication>p-101</publication>
       <publication>p-102</publication>
    </author>
    ...
</root>

You see, the XML references (like <publication>p-101</publication>)
are mapped to Java object references (in List<Publication> publications).


问:
Java - wrapper classes and hashCode()
is there any difference b/w value returned by Integer's hashCode() and intValue()? Can hashcode be negative?

答:
Integer.hashCode() just returns the value, yes... although it's not a good idea to rely on that. The return value of a hash code should really just be used as an opaque value without attaching any particular meaning to it - only equality should really be taken into account. Even if Integer.hashCode() is documented to just return the value (EDIT: it is; see other answer), I'd be very wary of any code which would break if the implementation changed to return (say) value + 1.

The return value of hashCode() is certainly allowed to be negative - both here and in general.

ContentLicense: CC BY-SA 3.0

Title: Java - wrapper classes and hashCode()


问:
Is it possible to build Apache HtmlEmail from string representation?
I'm building a ImageHtmlEmail in order to download and embed all the images from given HTML into a multipart email. I need to store that email for sending later.

Problem is, I can get the resulting email text and content-type, but I see no means to construct an ImageHtmlEmail back from a text and a content-type. Is it possible at all? Or should I go with raw javax.mail for actual sending?

答:
I was able to create javax.mail.internet.MimeMessage out of String representation of an email (ASCII dump as one one get on downloading original email from gmail). However not been very successful in constructing Email subclasses like HtmlEmail from it yet.

```<code>MimeMessage mimeMessage  =  MimeMessageUtils.createMimeMessage(Session.getDefaultInstance(new Properties()), new ByteArrayInputStream(oneEmail.toString().getBytes()));
</code>```

It does give me most of the things I can think of as useful using its getter methods.

Body:
I was able to create javax.mail.internet.MimeMessage out of String representation of an email (ASCII dump as one one get on downloading original email from gmail). However not been very successful in constructing Email subclasses like HtmlEmail from it yet.

MimeMessage mimeMessage  =  MimeMessageUtils.createMimeMessage(Session.getDefaultInstance(new Properties()), new ByteArrayInputStream(oneEmail.toString().getBytes()));

It does give me most of the things I can think of as useful using its getter methods.


问:
How to use reduce to return an object in Javascript?
I'm trying to count the number of odd and even numbers in an array by using the Array.reduce() method. When I run the below code, I get the error "odd is not defined." How/where do I define odd to get this code to work?</p>

```<code>var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
var oddEvenCounts = numbers.reduce(function(counts, number) {
   if (number % 2 === 1) {
     counts[odd]++
   } else {
     counts[even]++;
   }
   return counts;
 }, {});
</code>```

答:
This is a function that can do it for you.

function oddEvenCounts(arr) {
  const counts = {
    even: 0,
    odd: 0
  };
  arr.forEach(n => {
    if(n % 2 === 0) {
      counts.even++;
    } else {
      counts.odd++
    }
  });
  return counts;
}

const array = [5, 3, 8, 6, 9, 1, 0, 2, 2];
console.log(oddEvenCounts(array));```

Body:
I'm trying to count the number of odd and even numbers in an array by using the Array.reduce() method. When I run the below code, I get the error "odd is not defined." How/where do I define odd to get this code to work?

var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
var oddEvenCounts = numbers.reduce(function(counts, number) {
   if (number % 2 === 1) {
     counts[odd]++
   } else {
     counts[even]++;
   }
   return counts;
 }, {});


问:
Material-UI checkbox backrground color
I am using material ui checkbox, i wanted it to have its own background color over my div which has colored background. I have set the root to have a backgroundColor as white but the svgicon is a round shape which is not the look i intend to have. Can i shape the checkbox ?

Already have tried many things but not able to figure out how to change the icon

```<code>const styles = {
    root : {
        padding : '0px',
        display : 'inline-block',
        backgroundColor : 'white'
    },
    formLabelRoot : {
        margin : '0'
    }
}
.
.
.
render () {
        const { classes } = this.props
        return(
            <div style={customStyles.divStyle}>
                <div style={customStyles.div1}>
                    <FormControlLabel
                        classes={{root: classes.formLabelRoot}}
                        control={
                            <Checkbox
                                classes={{root : classes.root }}
                                color='primary'
                            />
                            }
                        label={''}
                    />
                </div>
</code>```

The background white is making a spherical rounded checkbox apparent

Image of what is happening now

答:
You can override the icons used for the checked and unchecked states. The props you're looking for are icon for the unchecked state and checkedIcon for the checked state. Both of which take a component to be used as the icon.

Documentation here

Title: Material-UI checkbox backrground color

Body:
I am using material ui checkbox, i wanted it to have its own background color over my div which has colored background. I have set the root to have a backgroundColor as white but the svgicon is a round shape which is not the look i intend to have. Can i shape the checkbox ?

Already have tried many things but not able to figure out how to change the icon

const styles = {
    root : {
        padding : '0px',
        display : 'inline-block',
        backgroundColor : 'white'
    },
    formLabelRoot : {
        margin : '0'
    }
}
.
.
.
render () {
        const { classes } = this.props
        return(

                    <FormControlLabel
                        classes={{root: classes.formLabelRoot}}
                        control={
                            <Checkbox
                                classes={{root : classes.root }}
                                color='primary'
                            />
                            }
                        label={''}
                    />

The background white is making a spherical rounded checkbox apparent

Image of what is happening now


问:
User IsInRole only works after signing in and out from the website
I am adding and removing users from roles in my controller code and in my shared _Layout view, I am using User.IsInRole to check and remove links accordingly but it  only works if user signs out of the website then User.IsInRole returns correct result?

Is there a way to reload the _Layout page so it grabs the data correctly?

Controller Code to change roles

```<code>  _userManager.RemoveFromRole(obj.strUserID, "Consumer");
  _userManager.AddToRole(obj.strUserID, "Provider");
  _context.SaveChanges();
  return View("Success");
</code>```

Shared _Layout View which is used by multiple pages

```<code>  if (!User.IsInRole("Provider"))
      {
       <li>@Html.ActionLink("Become a Member", "Memmber", "CustProfile")</li>
      }
</code>```

Once, I remove and add new roles to User, I want _Layout.cstml to show correct links but it does not. It works fine, if I sign out and sign back in.

Is there a way to fix this behavior?

答:
User is cached until log out so you will have to sign them again. Please use the following code to sign them again. Also, make sure to redirect them instead of View so page is reloaded.

```<code> private ApplicationSignInManager _signInManager;

 public ApplicationSignInManager SignInManager
        {
            get
            {
                return _signInManager ??
                HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
            }
            private set
            {
                _signInManager = value;
            }
        }
</code>```

Add the following code after changing the roles:

```<code>  var userinDb = _context.Users.Find(UserID);
  await SignInManager.SignInAsync(userinDb, true,false);
  return RedirectToAction("Success");

</code>```

Body:
I am adding and removing users from roles in my controller code and in my shared _Layout view, I am using User.IsInRole to check and remove links accordingly but it  only works if user signs out of the website then User.IsInRole returns correct result?

Is there a way to reload the _Layout page so it grabs the data correctly?

Controller Code to change roles

  _userManager.RemoveFromRole(obj.strUserID, "Consumer");
  _userManager.AddToRole(obj.strUserID, "Provider");
  _context.SaveChanges();
  return View("Success");

Shared _Layout View which is used by multiple pages

  if (!User.IsInRole("Provider"))
      {

@Html.ActionLink("Become a Member", "Memmber", "CustProfile")

      }

Once, I remove and add new roles to User, I want _Layout.cstml to show correct links but it does not. It works fine, if I sign out and sign back in.

Is there a way to fix this behavior?

Body:
User is cached until log out so you will have to sign them again. Please use the following code to sign them again. Also, make sure to redirect them instead of View so page is reloaded.

 private ApplicationSignInManager _signInManager;

 public ApplicationSignInManager SignInManager
        {
            get
            {
                return _signInManager ??
                HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
            }
            private set
            {
                _signInManager = value;
            }
        }

Add the following code after changing the roles:

  var userinDb = _context.Users.Find(UserID);
  await SignInManager.SignInAsync(userinDb, true,false);
  return RedirectToAction("Success");


问:
Django SESSION_COOKIE_DOMAIN error
I'm trying to using SESSION_COOKIE_DOMAIN, but I get an error in any browser I try when I try to log into the admin:

```<code>Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.
</code>```

Any idea?

答:
This usually indicates that you have misconfigured your SESSION_COOKIE_DOMAIN setting. Can you provide more info?

What domain are you running your app on?
What is the current value of SESSION_COOKIE_DOMAIN?

ContentLicense: CC BY-SA 2.5

Title: Django SESSION_COOKIE_DOMAIN error

Body:
I'm trying to using SESSION_COOKIE_DOMAIN, but I get an error in any browser I try when I try to log into the admin:

Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.

Any idea?


问:
How to recode negative values in a set of variables based on if conditional statement in R?
R newbie here. I am currently trying to recode a set of variables in R, such that all negative values within them are recoded as positive values.

Please find simulated data below:

```<code>df <- data.frame(ID = c(1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011),
                 measure1 = rnorm(11, mean = 0, sd = 1),
                 measure2 = rnorm(11, mean = 0, sd = 1),
                 measure3 = rnorm(11, mean = 0, sd = 1),
                 measure4 = rnorm(11, mean = 0, sd = 1))
</code>```

This is the function I've written so far:

```<code>df[2:5] <- sapply(df[2:5], function(x) {
  if(x<0) {
  return(x*-1)
}  else {
   return(x)
    }
  })
</code>```

although I recieve the following errors:

```<code>Warning messages:
1: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
2: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
3: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
4: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
</code>```

Any ideas on how to make this work?

Thanks!

Body:
R newbie here. I am currently trying to recode a set of variables in R, such that all negative values within them are recoded as positive values.

Please find simulated data below:

df <- data.frame(ID = c(1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011),
                 measure1 = rnorm(11, mean = 0, sd = 1),
                 measure2 = rnorm(11, mean = 0, sd = 1),
                 measure3 = rnorm(11, mean = 0, sd = 1),
                 measure4 = rnorm(11, mean = 0, sd = 1))

This is the function I've written so far:

df[2:5] <- sapply(df[2:5], function(x) {
  if(x<0) {
  return(x*-1)
}  else {
   return(x)
    }
  })

although I recieve the following errors:

Warning messages:
1: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
2: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
3: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used
4: In if (x < 0) { :
  the condition has length > 1 and only the first element will be used

Any ideas on how to make this work?

Thanks!

Body:
You can use

df[, 2:5] <- abs(df[, 2:5])


问:
Jekyll - Evaluate a string before assignment
I need to capture a string into a variable tag, then use this variable in site.tags.tag. The code is:

```<code>{% capture tag %}programming{% endcapture %}
{{ tag }}
{%- assign titles = site.tags.tag | map: "title" -%}
{{ titles }}
</code>```

This code only prints prints:

```<code>programming
</code>```

But if I replace site.tags.tag with either site.tags.programming or site.tags.'programming' I get the desired output:

```<code>programming
title1 title2
</code>```

Is there a way to evaluate the variable tag before the assignment? After reading a similar question I tried site.tags.{{tag}} but it didn't work.

答: site.tags[tag] might be what you're looking for.

Body:
I need to capture a string into a variable tag, then use this variable in site.tags.tag. The code is:

{% capture tag %}programming{% endcapture %}
{{ tag }}
{%- assign titles = site.tags.tag | map: "title" -%}
{{ titles }}

This code only prints prints:

programming

But if I replace site.tags.tag with either site.tags.programming or site.tags.'programming' I get the desired output:

programming
title1 title2

Is there a way to evaluate the variable tag before the assignment? After reading a similar question I tried site.tags.{{tag}} but it didn't work.


问:
Sorting an object with object.entries
I have an object of data which I'd like to sort. I'm running the following object through Object.entries(data).map() to display it on my Front-End, but I'd like to maintain a specific order. Right now it seems that the order is somewhat random. I'm using .map to display a number of React components so sorting after the map doesn't seem to be possible.

```<code>const data = {
  rent: {
   value: '100'
    },
  },
  legal: {
    value: '300'
  },
  misc: {
    value: '300'
    },
 horse: {
   value: '400'
   }
  },
};
</code>```

Ideally rent should be the first item when it's mapped out, and misc should be the last one. I've tried using .sort() but I don't seem to be having any luck.

What is the right way to achieve this? I assume some combination of Object.entries(data).sort().map() but I can't seem to figure it out.

答:
If you need to maintain a consistent order, use an array of objects instead of a single object.  The property order of an object is not guaranteed.

const data = [
  { name: 'rent', value: '100' },
  { name: 'legal', value: '300' },
  { name: 'misc', value: '300' },
  { name: 'horse', value:'400' }
];

const sortedData = data.sort((a, b) => {
    return a.name  b.name ? 1 : 0;
});

console.log(sortedData);```

Title: Sorting an object with object.entries

Body:
I have an object of data which I'd like to sort. I'm running the following object through Object.entries(data).map() to display it on my Front-End, but I'd like to maintain a specific order. Right now it seems that the order is somewhat random. I'm using .map to display a number of React components so sorting after the map doesn't seem to be possible.

const data = {
  rent: {
   value: '100'
    },
  },
  legal: {
    value: '300'
  },
  misc: {
    value: '300'
    },
 horse: {
   value: '400'
   }
  },
};

Ideally rent should be the first item when it's mapped out, and misc should be the last one. I've tried using .sort() but I don't seem to be having any luck.

What is the right way to achieve this? I assume some combination of Object.entries(data).sort().map() but I can't seem to figure it out.

Body:
If you need to maintain a consistent order, use an array of objects instead of a single object.  The property order of an object is not guaranteed.

const data = [
  { name: 'rent', value: '100' },
  { name: 'legal', value: '300' },
  { name: 'misc', value: '300' },
  { name: 'horse', value:'400' }
];

const sortedData = data.sort((a, b) => {
    return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});

console.log(sortedData);


问:
Unable to resolve valid table in PhpStorm
I'm getting unable to resolve table errors appear in php files containing SQL querying valid tables.

If I Ctrl + Enter over the query, then I get expected results in the DB console, and if I expand the database in the DB explorer tab then I can see the tables.

It's not affecting code execution, but it's annoying because it catches my eye when writing code, and it masks real SQL errors.

I've tried refreshing the database connection, and I've verified that the php tab is connecting to the correct database.

答:
Although this answer is specifically for phpstorm, I had this same issue in IntelliJ and none of the above fixes worked for me. I had my scope added, everything was active. I could query the database in the console window perfectly fine, and I was totally stumped.

Eventually, I noticed some text in the database panel that said 0 of 4 in tiny text. It looked like this:

Upon clicking on the 0 of 4 text, I discovered there were no schemas added to the connection, even though a default database was set upon making the connection originally. Going to that page allows you to add schemas. Be sure to either select "All schemas", "Current schema", or the specific database that you want to use with your connection.


问:
spark-submit is throwing java.lang.ClassNotFoundException: SparkPIIDetector
I have a simple java spark application (SimpleApp.jar) that I am trying to run using the below command in Windows environment

```<code>spark-submit.cmd --class SimpleJar --master local SimpleApp.jar
</code>```

which keeps throwing

```<code>java.lang.ClassNotFoundException: SimpleApp
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at org.apache.spark.util.Utils$.classForName(Utils.scala:225)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:686)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

The directory structure of my project is like this

```<code>SimpleApp
- infrastructure (AN ANSIBLE MODULE)
- SimpleApp (A MAVEN MODULE)
- - src
- - - main
- - - - java
- - - - - SimpleApp.java
- - - - resources
- - pom.xml
</code>```

And inside the POM I am using the shade plugin to build my uber jar like so

```<code><plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <!-- Run shade goal on package phase -->
                    <execution>
                        <id>SimpleAppId</id>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <!-- add Main-Class to manifest file -->
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>SimpleApp</mainClass>
                                </transformer>
                            </transformers>
                            <shadedClassifierName>SimpleApp</shadedClassifierName>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
</code>```

Could someone please advise what is being missconfigured here.
Is this something that has to do with the environment being windows?
I am able to deploy this on AWS EMR with no issues.
In addition, this may also be useful

```<code>unzip -p SimpleApp.jar META-INF/MANIFEST.MF

Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Built-By: <author>
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_191
Main-Class: SimpleApp
</code>```

答: There was a version mismatch between the spark running on my machine and the dependency I was using in my application. Once I have changed to the newest version of spark everything worked smoothly.</p>

Body:
I have a simple java spark application (SimpleApp.jar) that I am trying to run using the below command in Windows environment

spark-submit.cmd --class SimpleJar --master local SimpleApp.jar

which keeps throwing

java.lang.ClassNotFoundException: SimpleApp
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at org.apache.spark.util.Utils$.classForName(Utils.scala:225)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:686)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

The directory structure of my project is like this

SimpleApp
- infrastructure (AN ANSIBLE MODULE)
- SimpleApp (A MAVEN MODULE)
- - src
- - - main
- - - - java
- - - - - SimpleApp.java
- - - - resources
- - pom.xml

And inside the POM I am using the shade plugin to build my uber jar like so

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>

                    <execution>
                        <id>SimpleAppId</id>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>

                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>SimpleApp</mainClass>
                                </transformer>
                            </transformers>
                            <shadedClassifierName>SimpleApp</shadedClassifierName>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

Could someone please advise what is being missconfigured here.
Is this something that has to do with the environment being windows?
I am able to deploy this on AWS EMR with no issues.
In addition, this may also be useful

unzip -p SimpleApp.jar META-INF/MANIFEST.MF

Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Built-By: <author>
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_191
Main-Class: SimpleApp


问:
Is there a way to make a makefile autodownload another makefile?
i know it is possible to execute standard rules on a makefile by simply including them like

```<code>hi:; echo hello

include hi
</code>```

but there is some way, by doing this, to fetch an external input like a ftp server or, lets say, the aws s3 to fetch a "newborn" makefile and then include it to the project? in runtime?
like

```<code>include https://s3.bucket.domain.com/newmk.mk
</code>```

答:
As mentioned there's no way to include a URL.  However, you can do something almost as good with GNU make's auto-re-make feature.

To do this, include a local file you download and create a rule that knows how to download it:

```<code>include newmk.mk

newmk.mk:
        wget https://s3.bucket.domain.com/newmk.mk -O $@
</code>```

In this situation, if (and only if) newmk.mk doesn't exist, then the recipe will be invoked, the file will be downloaded, then make will re-exec itself to read that file.

Body:
i know it is possible to execute standard rules on a makefile by simply including them like

hi:; echo hello

include hi

but there is some way, by doing this, to fetch an external input like a ftp server or, lets say, the aws s3 to fetch a "newborn" makefile and then include it to the project? in runtime?
like

include https://s3.bucket.domain.com/newmk.mk

Body:
As mentioned there's no way to include a URL.  However, you can do something almost as good with GNU make's auto-re-make feature.

To do this, include a local file you download and create a rule that knows how to download it:

include newmk.mk

newmk.mk:
        wget https://s3.bucket.domain.com/newmk.mk -O $@

In this situation, if (and only if) newmk.mk doesn't exist, then the recipe will be invoked, the file will be downloaded, then make will re-exec itself to read that file.


问:
CakePHP and referential integrity
My DB server doesn't support innodb engine, so I can't use Foreign key
costraints at DB level.
How can I assure referential intergrity? Can I do this using cakephp model,
how?</p>

答:
As long as you define your model associations properly, you should be ok. If you're worried about orphan records when deleting records, you can set 'dependent'=> true in your associations.

http://book.cakephp.org/view/1039/Associations-Linking-Models-Together#hasMany-1043

Title: CakePHP and referential integrity


问:
Dealing with time data, how do I convert this AS3 line to Javascript?
I have an old line of code for an AS3 application:

```<code>return Math.Round((DateTime.Now - new DateTime(1970, 1,1)).TotalMilliseconds);
</code>```

However, I'm currently working in Javascript / Typescript. I tried to write what felt like a conversion, but it's just producing NaN.

```<code>getTime() {
    return Math.round((new Date().Now - new Date().getTime()) / 1000);
}
</code>```

How can I fix this small snippet so that it produces the same results?

答:
If I'm understanding what you want to do, it's as simple as this:

```<code>new Date().getTime() // For Milliseconds

Math.round(new Date().getTime() / 1000) // For Seconds
</code>```

.getTime() returns the milliseconds since the epoch of January 1, 1970 UTC.  To convert that to seconds, divide by 1,000.  And, the Math.round() to get you seconds instead of milliseconds.

So, you were almost there, it's just that new Date().Now isn't a thing.  :-)

Body:
I have an old line of code for an AS3 application:

return Math.Round((DateTime.Now - new DateTime(1970, 1,1)).TotalMilliseconds);

However, I'm currently working in Javascript / Typescript. I tried to write what felt like a conversion, but it's just producing NaN.

getTime() {
    return Math.round((new Date().Now - new Date().getTime()) / 1000);
}

How can I fix this small snippet so that it produces the same results?

Body:
If I'm understanding what you want to do, it's as simple as this:

new Date().getTime() // For Milliseconds

Math.round(new Date().getTime() / 1000) // For Seconds

.getTime() returns the milliseconds since the epoch of January 1, 1970 UTC.  To convert that to seconds, divide by 1,000.  And, the Math.round() to get you seconds instead of milliseconds.

So, you were almost there, it's just that new Date().Now isn't a thing.  :-)


问:
Clojure returning simple true or false from a function
I am new to Clojure and i am having trouble with the basics of it. I am trying to write a simple if else program and use it in recursion but i am having trouble with the syntax. The code in Java is :

```<code>if(a > 0 && b >0){
   return true;
}else{
  return false;
}
</code>```

The code in clojure should be :

```<code>(defn checkPositiveNumber
    [x y]
    (if (and (> x 0) (> y 0))
            (do
                (def val true)
            )
            (do
                (def val false)
    )
)

(println (checkPositiveNumber 2 3))
</code>```

returns #'user/val instead of false.
What am i doing wrong ? This function should return true or false as i will be using it to either terminate my recursion or to check further.

Edit:
Thanks to Lee i was able to achieve the thing i asked... But my real purpose is :

```<code>if(a > 0 && b >0){
       System.out.println("Values are Positive");
       return true;
    }else{
      System.out.println("Some Values are Negative");
      return false;
    }
</code>```

答:
To further Lee's answer, you could also make use of the every? function to make your function more general:

```<code>(defn every-pos? [& values]
  (every? pos? values))
</code>```

This function has the advantage in that you don't have to specify the evaluation of each argument and it takes an unlimited number of parameters:

```<code>=> (every-pos? 1 7)
true
=> (every-pos? 3 -1 13 2)
false
</code>```

Learning to metaprogram with sequences rather than individual values really demonstrates the strengths of functional programming.

To check the value and include side-effects, something like the following would do the job:

```<code>(defn check-positive-numbers [x y]
  (let [pos-values? (every-pos? x y)
        msg (if pos-values?
              "all numbers positive"
              "one or more numbers non-positive")]
    (println msg)
    pos-values?))
</code>```

Body:
I am new to Clojure and i am having trouble with the basics of it. I am trying to write a simple if else program and use it in recursion but i am having trouble with the syntax. The code in Java is :

if(a > 0 && b >0){
   return true;
}else{
  return false;
}

The code in clojure should be :

(defn checkPositiveNumber
    [x y]
    (if (and (> x 0) (> y 0))
            (do
                (def val true)
            )
            (do
                (def val false)
    )
)

(println (checkPositiveNumber 2 3))

returns #'user/val instead of false.
What am i doing wrong ? This function should return true or false as i will be using it to either terminate my recursion or to check further.

Edit:
Thanks to Lee i was able to achieve the thing i asked... But my real purpose is :

if(a > 0 && b >0){
       System.out.println("Values are Positive");
       return true;
    }else{
      System.out.println("Some Values are Negative");
      return false;
    }

Body:
To further Lee's answer, you could also make use of the every? function to make your function more general:

(defn every-pos? [& values]
  (every? pos? values))

This function has the advantage in that you don't have to specify the evaluation of each argument and it takes an unlimited number of parameters:

=> (every-pos? 1 7)
true
=> (every-pos? 3 -1 13 2)
false

Learning to metaprogram with sequences rather than individual values really demonstrates the strengths of functional programming.

To check the value and include side-effects, something like the following would do the job:

(defn check-positive-numbers [x y]
  (let [pos-values? (every-pos? x y)
        msg (if pos-values?
              "all numbers positive"
              "one or more numbers non-positive")]
    (println msg)
    pos-values?))


问:
Wiremock Request Pattern Matching with Request Parameters
I am using spock and wiremock for functional testing in a Spring Boot 2.1.5 application. The incoming url is:

```<code>/mockedserver/v1/Items('1010873195')/Products?$format=json
</code>```

yes, its a pretty weird url, but I can't do anything about that.

I have set up a path matcher in JSON with:

```<code>{
  "request": {
    "method": "GET",
    "url": "/mockedserver/v1/Items('1010873195')/Products.*",
    "queryParams" : {
      "$format": "json"
    },
    "headers": {
      "x-csrf-token": "",
      "Accept": "application/json",
      "Content-Type": "application/json"
    }
  },
  "response": {
    "headers": {
      "Content-Type": "application/json"
    },
    "status": 200,
    "bodyFileName": "/../responses/mockedserver/get-products/1010873195-success-200.json"
  }
}
</code>```

As you might be able to see, I modelled the strange looking request parameter in the "queryParams" block. This didn't work, so I then put the regex, .*, on the end of the url.

Both gave me the result:

                                               Request was not matched
                                               =======================

-----------------------------------------------------------------------------------------------------------------------
| Closest stub                                             | Request                                                  |
-----------------------------------------------------------------------------------------------------------------------
                                                           |
GET                                                        | GET
/mockedserver/v1/Items('1010873195')/Produ                 | /mockedserver/v1/Items('1010873195')/Produ<<<<< URL does not match
cts                                                        | cts?$format=json
                                                           |
                                                           |
-----------------------------------------------------------------------------------------------------------------------

```

<p>As you can see, it matches, except the param part at the end, basically, I don't care about the param, so I was hoping to just wildcard it out.</p>

<p>One possibility is that the <code>$</code> sign is making a mess of things, should I be escaping it instead? if so, how?</p>

<p>The other is that its the question mark, <code>?</code>. I have tried escapting that with <code>\?</code> and <code>\\?</code>, both of which were unsuccessful.</p>

<p>Just concerning the part of the request block that looks important here:</p>

```    "method": "GET",
    "url": "/mockedserver/v1/Items('1010873195')/Products.*",
    "queryParams" : {
      "$format": "json"
    },
```

<p>I have seen it said elsewhere that if you use <code>urlPath</code> in place of <code>url</code> that WireMock treats extra headers or query parameters without match parameters as "don't care, match anyway". But this doesn't seem to be the case here as the error output shows.</p>

<p><strong>FURTHER DISCUSSION</strong>
I have since tried various combinations putting <code>urlPath</code>, <code>urlPattern</code> and even <code>urlPathPattern</code> as suggested, in place of <code>url</code>. All of these result in:</p>

<pre class="lang-sh prettyprint-override"><code>                                               Request was not matched
                                               =======================

-----------------------------------------------------------------------------------------------------------------------
| Closest stub                                             | Request                                                  |
-----------------------------------------------------------------------------------------------------------------------
                                                           |
GET                                                        | GET
                                                           | /mockedserver/v1/Items('1010873195')/Produ<<<<< URL does not match. URLs must start with a /
                                                           | cts?$format=json
                                                           |
                                                           |
-----------------------------------------------------------------------------------------------------------------------

</code>```

I have also tried this with and without the queryParams block, just in case this contributed to the matching, but it does not seem to have any effect.
I am beginning to wonder if there is some other flag i need to set in the stubFor call?

答:
Fixed: Basically, you need urlPath, no queryParams, and a string-based regex pattern, which I solved with:

/^\\/mockedserver\\/v1\\/Items\('[0-9]{10}'\)\\/Products/
```

Basically, it came down to the right combination of things.

Body:
I am using spock and wiremock for functional testing in a Spring Boot 2.1.5 application. The incoming url is:

/mockedserver/v1/Items('1010873195')/Products?$format=json

yes, its a pretty weird url, but I can't do anything about that.

I have set up a path matcher in JSON with:

{
  "request": {
    "method": "GET",
    "url": "/mockedserver/v1/Items('1010873195')/Products.*",
    "queryParams" : {
      "$format": "json"
    },
    "headers": {
      "x-csrf-token": "",
      "Accept": "application/json",
      "Content-Type": "application/json"
    }
  },
  "response": {
    "headers": {
      "Content-Type": "application/json"
    },
    "status": 200,
    "bodyFileName": "/../responses/mockedserver/get-products/1010873195-success-200.json"
  }
}

As you might be able to see, I modelled the strange looking request parameter in the "queryParams" block. This didn't work, so I then put the regex, .*, on the end of the url.

Both gave me the result:

                                               Request was not matched
                                               =======================

-----------------------------------------------------------------------------------------------------------------------
| Closest stub                                             | Request                                                  |
-----------------------------------------------------------------------------------------------------------------------
                                                           |
GET                                                        | GET
/mockedserver/v1/Items('1010873195')/Produ                 | /mockedserver/v1/Items('1010873195')/Produ<<<<< URL does not match
cts                                                        | cts?$format=json
                                                           |
                                                           |
-----------------------------------------------------------------------------------------------------------------------

As you can see, it matches, except the param part at the end, basically, I don't care about the param, so I was hoping to just wildcard it out.

One possibility is that the $ sign is making a mess of things, should I be escaping it instead? if so, how?

The other is that its the question mark, ?. I have tried escapting that with \? and \\?, both of which were unsuccessful.

Just concerning the part of the request block that looks important here:

    "method": "GET",
    "url": "/mockedserver/v1/Items('1010873195')/Products.*",
    "queryParams" : {
      "$format": "json"
    },

I have seen it said elsewhere that if you use urlPath in place of url that WireMock treats extra headers or query parameters without match parameters as "don't care, match anyway". But this doesn't seem to be the case here as the error output shows.

FURTHER DISCUSSION
I have since tried various combinations putting urlPath, urlPattern and even urlPathPattern as suggested, in place of url. All of these result in:

                                               Request was not matched
                                               =======================

-----------------------------------------------------------------------------------------------------------------------
| Closest stub                                             | Request                                                  |
-----------------------------------------------------------------------------------------------------------------------
                                                           |
GET                                                        | GET
                                                           | /mockedserver/v1/Items('1010873195')/Produ<<<<< URL does not match. URLs must start with a /
                                                           | cts?$format=json
                                                           |
                                                           |
-----------------------------------------------------------------------------------------------------------------------

I have also tried this with and without the queryParams block, just in case this contributed to the matching, but it does not seem to have any effect.
I am beginning to wonder if there is some other flag i need to set in the stubFor call?

Body:
Fixed: Basically, you need urlPath, no queryParams, and a string-based regex pattern, which I solved with:

/^\\/mockedserver\\/v1\\/Items\('[0-9]{10}'\)\\/Products/

Basically, it came down to the right combination of things.


问:
Duplicate entries in the list
Having to enter 8 unique entries, logic should detect if any entry is duplicate otherwise continue until all 8 entries are entered.

I've played around with the For loop but it seems to not give me desired output, i want to go back to last entry if duplicate entry is scanned instead it will give a message "Duplicate SCAN, please rescan" but also the counter moves on.

sorry, i'm new to this i thought i've included code. Hoping it goes through this time.

```<code>x=1
mac_list = []
while (x <=8):
    MAC1 = input("SCAN MAC"+str(x)+":")

for place in mac_list:

    print (mac_list)
    if place==MAC1:
        print ("place"+place)
        print ("Duplicate SCAN, please rescan")
else:
    mac_list.append(MAC1)
    x+=1
</code>```

答:
Python's in comparison should do what you need:

values = []

while True:
    value = input('Input value: ')

    if value in values:
        print('Duplicate, please try again')

    else:
        values.append(value)

    if len(values) > 7:
        break

print(values)
```

Title: Duplicate entries in the list

Body:
Having to enter 8 unique entries, logic should detect if any entry is duplicate otherwise continue until all 8 entries are entered.

I've played around with the For loop but it seems to not give me desired output, i want to go back to last entry if duplicate entry is scanned instead it will give a message "Duplicate SCAN, please rescan" but also the counter moves on.

sorry, i'm new to this i thought i've included code. Hoping it goes through this time.

x=1
mac_list = []
while (x <=8):
    MAC1 = input("SCAN MAC"+str(x)+":")

for place in mac_list:

    print (mac_list)
    if place==MAC1:
        print ("place"+place)
        print ("Duplicate SCAN, please rescan")
else:
    mac_list.append(MAC1)
    x+=1


问:
Method chaining - why is it a good practice, or not?
Method chaining is the practice of object methods returning the object itself in order for the result to be called for another method. Like this:

```<code>participant.addSchedule(events[1]).addSchedule(events[2]).setStatus('attending').save()
</code>```

This seems to be considered a good practice, since it produces readable code, or a "fluent interface". However, to me it instead seems to break the object calling notation implied by the object orientation itself - the resulting code does not represent performing actions to the result of a previous method, which is how object oriented code is generally expected to work:

```<code>participant.getSchedule('monday').saveTo('monnday.file')
</code>```

This difference manages to create two different meanings for the dot-notation of "calling the resulting object": In the context of chaining, the above example would read as saving the participant object, even though the example is in fact intended to save the schedule object received by getSchedule.

I understand that the difference here is whether the called method should be expected to return something or not (in which case it would return the called object itself for chaining). But these two cases are not distinguishable from the notation itself, only from the semantics of the methods being called. When method chaining is not used, I can always know that a method call operates on something related to the result of the previous call - with chaining, this assumption breaks, and I have to semantically process the whole chain to understand what the actual object being called really is. For example:

```<code>participant.attend(event).setNotifications('silent').getSocialStream('twitter').postStatus('Joining '+event.name).follow(event.getSocialId('twitter'))
</code>```

There the last two method calls refer to the result of getSocialStream, whereas the ones before refer to the participant. Maybe it's bad practice to actually write chains where the context changes (is it?), but even then you'll have to constantly check whether dot-chains that look similar are in fact keep within the same context, or only work on the result.

To me it appears that while method chaining superficially does produce readable code, overloading the meaning of the dot-notation only results in more confusion. As I don't consider myself a programming guru, I assume the fault is mine. So: What am I missing? Do I understand method chaining somehow wrong? Are there some cases where method chaining is especially good, or some where it's especially bad?

Sidenote: I understand this question could be read as a statement of opinion masked as a question. It, however, isn't - I genuinely want to understand why chaining is considered good practice, and where do I go wrong in thinking it breaks the inherent object-oriented notation.

答:
Opinionated Answer

The biggest drawback of chaining is that it can be hard for the reader to understand how each method affects the original object, if it does, and what type does every method return.

Some questions:

Do methods in the chain return a new object, or the same object mutated?

Do all methods in the chain return the same type?

If not, how is indicated when a type in the chain changes?

Can the value returned by the last method be safely discarded?

Debugging, in most languages, can indeed be harder with chaining. Even if each step in the chain is on its own line (which kind of defeats the purpose of chaining), it can be hard to inspect the value returned after each step, specially for non-mutating methods.

Compile times can be slower depending on the language and compiler, as expressions can be much more complex to resolve.

I believe that like with everything, chaining is a good solution that can be handy in some scenario. It should be used with caution, understanding the implications, and limiting the number of chain elements to a few.

Body:
Method chaining is the practice of object methods returning the object itself in order for the result to be called for another method. Like this:

participant.addSchedule(events[1]).addSchedule(events[2]).setStatus('attending').save()

This seems to be considered a good practice, since it produces readable code, or a "fluent interface". However, to me it instead seems to break the object calling notation implied by the object orientation itself - the resulting code does not represent performing actions to the result of a previous method, which is how object oriented code is generally expected to work:

participant.getSchedule('monday').saveTo('monnday.file')

This difference manages to create two different meanings for the dot-notation of "calling the resulting object": In the context of chaining, the above example would read as saving the participant object, even though the example is in fact intended to save the schedule object received by getSchedule.

I understand that the difference here is whether the called method should be expected to return something or not (in which case it would return the called object itself for chaining). But these two cases are not distinguishable from the notation itself, only from the semantics of the methods being called. When method chaining is not used, I can always know that a method call operates on something related to the result of the previous call - with chaining, this assumption breaks, and I have to semantically process the whole chain to understand what the actual object being called really is. For example:

participant.attend(event).setNotifications('silent').getSocialStream('twitter').postStatus('Joining '+event.name).follow(event.getSocialId('twitter'))

There the last two method calls refer to the result of getSocialStream, whereas the ones before refer to the participant. Maybe it's bad practice to actually write chains where the context changes (is it?), but even then you'll have to constantly check whether dot-chains that look similar are in fact keep within the same context, or only work on the result.

To me it appears that while method chaining superficially does produce readable code, overloading the meaning of the dot-notation only results in more confusion. As I don't consider myself a programming guru, I assume the fault is mine. So: What am I missing? Do I understand method chaining somehow wrong? Are there some cases where method chaining is especially good, or some where it's especially bad?

Sidenote: I understand this question could be read as a statement of opinion masked as a question. It, however, isn't - I genuinely want to understand why chaining is considered good practice, and where do I go wrong in thinking it breaks the inherent object-oriented notation.


问:
Is there a way to automatically add a whitespace upon completion in company-mode?
I use company-mode a lot on natural language completion with the local dictionary. I am wondering if there is a way to automatically add a whitespace upon completion.

For example, currently when I type abili and select the first candidate ability, my insert point is right after y|. Is there a way that the company-mode can add a space so my insert point is after y |?

I could not find any related information on this but this issue mentioned  a space is added after completion in the Eshell mode. Apparently this is exactly what I want.

The issue mentioned the function completion-at-point. Is there a way that I can change or have a function that I can override the current completion mechanism?

Thanks! I’d really appreciate any suggestions.

答:
You could add a hook to company-after-completion-hook that would be called after completion with any of your company backends, eg.

```<code>(defun my-company-after-completion-hook (&rest _ignored)
  ;; this would be called with the completion candidate, so you could
  ;; modify it to insert spaces based on the candidate
  (just-one-space))

;; or setq-local in a mode hook, eg. for text-mode/org-mode or wherever you are
;; completing with dictionary words
(setq company-after-completion-hook #'my-company-after-completion-hook)
</code>```

If you only wanted to add space after completing with a specific backend you could see if the backend already implements a post-completion action, otherwise you could probably advise it.

Body:
You could add a hook to company-after-completion-hook that would be called after completion with any of your company backends, eg.

(defun my-company-after-completion-hook (&rest _ignored)
  ;; this would be called with the completion candidate, so you could
  ;; modify it to insert spaces based on the candidate
  (just-one-space))

;; or setq-local in a mode hook, eg. for text-mode/org-mode or wherever you are
;; completing with dictionary words
(setq company-after-completion-hook #'my-company-after-completion-hook)

If you only wanted to add space after completing with a specific backend you could see if the backend already implements a post-completion action, otherwise you could probably advise it.


问:
Does Google Dataproc support Apache Impala?
I am new to using cloud services and navigating Google's Cloud Platform is quite intimidating. When it comes to Google Dataproc, they do advertise Hadoop, Spark and Hive.

My question is, is Impala available at all?

I would like to do some benchmarking projects using all four of these tools and I require Apache Impala along side Spark/Hive.

答:
No, DataProc is a cluster that supports Hadoop, Spark, Hive and pig; using default images.

Check this link for more information about native image list for DataProc

https://cloud.google.com/dataproc/docs/concepts/versioning/dataproc-versions


问:
How to update cell data without previous value clearing in NodeJS(google-sheets-api)
I working on NodeJS, Google Sheets API
I try to add some logs to a cell on a sheet, the logs are created each time that my code has executed a function (creating logs). Each time code updates the cell, my previous logs are erased. How I can get rid of overwrite in a cell? I want that my new logs are kept with old

I tried to change sheets.spreadsheets.values.batchUpdate({}) to
sheets.spreadsheets.batchUpdate({}), but can't find related parameter there

async regressionMapBatchUpdateSheet(auth, cellsRange = "", ...restValues) {
        return new Promise((resolve, reject) => {
            const sheets = google.sheets({ version: 'v4', auth });
            sheets.spreadsheets.values.batchUpdate({
                spreadsheetId: 'spreadsheetId',
                requestBody: {
                    data: [
                        {
                            range: cellsRange,
                            values: [
                                restValues
                            ]
                        }
                    ],
                    valueInputOption: "USER_ENTERED",
                    includeValuesInResponse: true
                }
            }, (err, response) => {
                if (err) {
                    console.log(err);
                    return reject(err);
                } else {
                    console.log(`The sheet were updated, cells were updated: "${response.data.responses.map(res => res.updatedData.values)}"`);
                    resolve(response);
                }
            })
        });
```

values: [restValues] = my entered logs

I want to keep my logs in a cell. There would be great if logs will be started from new line each time.

答:
You want to append a value to new row using Sheets API with Node.js.

If my understanding is correct, how about this modification?

Modification point:

I think that using the method of values.append is suitable for your situation.

Modified script:

Please modify as follows.

From:

```<code>sheets.spreadsheets.values.batchUpdate({
    spreadsheetId: 'spreadsheetid',
    requestBody: {
            data: [
                {
                    range: dateCell,
                    values: [
                        [date]
                    ]
                },
                {
                    range: resultCell,
                    values: [
                        [result]
                    ]
                },
                {
                    range: commentCell,
                    values: [
                        [comment]
                    ]
                }
            ],
            valueInputOption: "RAW",
            includeValuesInResponse: true
        }
}, (err, response) => {
</code>```

To:

When you use this, please set the range and values. By this script, the values are append to new row.

```<code>sheets.spreadsheets.values.append(
  {
    spreadsheetId: 'spreadsheetid',
    range: "Sheet1!A:A", // This is a sample range.
    valueInputOption: "RAW",
    resource: { values: [["date", "result", "comment"]] } // This is a sample value.
  }, (err, response) => {
</code>```

Note:

From your question, I could confirm that you have already been able to use Sheets API.

In this case, the value can be set like { values: [["date", "result", "comment"]] }.

References:

spreadsheets.values.append

If I misunderstood your question and this was not the result you want, I apologize.

Edit:

You want to add the value to the same cells without overwriting. For example, the cells A1:B1 have sample1 and sample2. When the values of sample3 and sample4 are added to A1 and B1, respectively, the cells become sample1sample3 and sample2sample4.

From your reply comment, I could understand like this. For this situation, unfortunately, in the current stage, this cannot be directly achieved by one API call. So it is required to do the following flow.

Get values from A1:B1.

Put values to A1:B1 by updating the values.

In order to do this, for example, how about using the method of spreadsheets.values.get and spreadsheets.values.update?

Modified script:

From:

```<code>sheets.spreadsheets.values.batchUpdate({
    spreadsheetId: 'spreadsheetid',
    requestBody: {
            data: [
                {
                    range: dateCell,
                    values: [
                        [date]
                    ]
                },
                {
                    range: resultCell,
                    values: [
                        [result]
                    ]
                },
                {
                    range: commentCell,
                    values: [
                        [comment]
                    ]
                }
            ],
            valueInputOption: "RAW",
            includeValuesInResponse: true
        }
}, (err, response) => {
</code>```

To:

In this case, the cells of Sheet1!A1:B1 are updated by adding the additional values to the existing values. For example, when the cells Sheet1!A1:B1 have sample1 and sample2, by running this script, the cells are updated to sample1sample3 and sample2sample4.

```<code>const spreadsheetId = "###";
const range = "Sheet1!A1:B1";
const additionalValue = [["sample3", "sample4"]];
sheets.spreadsheets.values.get(
  {
    spreadsheetId: spreadsheetId,
    range: range
  },
  (err1, result1) => {
    if (err1) {
      console.log(err1.errors);
      return;
    }
    const newValue = result1.data.values.map((row, i) =>
      row.map((col, j) => col + additionalValue[i][j])
    );
    sheets.spreadsheets.values.update(
      {
        spreadsheetId: spreadsheetId,
        range: range,
        valueInputOption: "USER_ENTERED",
        resource: { values: newValue }
      },
      (err2, result2) => {
        if (err2) {
          console.log(err2.errors);
          return;
        }
        console.log(result2.data);
      }
    );
  }
);
</code>```

References:

spreadsheets.values.get

spreadsheets.values.update

Body:
I working on NodeJS, Google Sheets API
I try to add some logs to a cell on a sheet, the logs are created each time that my code has executed a function (creating logs). Each time code updates the cell, my previous logs are erased. How I can get rid of overwrite in a cell? I want that my new logs are kept with old

I tried to change sheets.spreadsheets.values.batchUpdate({}) to
sheets.spreadsheets.batchUpdate({}), but can't find related parameter there

async regressionMapBatchUpdateSheet(auth, cellsRange = "", ...restValues) {
        return new Promise((resolve, reject) => {
            const sheets = google.sheets({ version: 'v4', auth });
            sheets.spreadsheets.values.batchUpdate({
                spreadsheetId: 'spreadsheetId',
                requestBody: {
                    data: [
                        {
                            range: cellsRange,
                            values: [
                                restValues
                            ]
                        }
                    ],
                    valueInputOption: "USER_ENTERED",
                    includeValuesInResponse: true
                }
            }, (err, response) => {
                if (err) {
                    console.log(err);
                    return reject(err);
                } else {
                    console.log(`The sheet were updated, cells were updated: "${response.data.responses.map(res => res.updatedData.values)}"`);
                    resolve(response);
                }
            })
        });

values: [restValues] = my entered logs

I want to keep my logs in a cell. There would be great if logs will be started from new line each time.

Body:
You want to append a value to new row using Sheets API with Node.js.

If my understanding is correct, how about this modification?

Modification point:

I think that using the method of values.append is suitable for your situation.

Modified script:

Please modify as follows.

From:

sheets.spreadsheets.values.batchUpdate({
    spreadsheetId: 'spreadsheetid',
    requestBody: {
            data: [
                {
                    range: dateCell,
                    values: [
                        [date]
                    ]
                },
                {
                    range: resultCell,
                    values: [
                        [result]
                    ]
                },
                {
                    range: commentCell,
                    values: [
                        [comment]
                    ]
                }
            ],
            valueInputOption: "RAW",
            includeValuesInResponse: true
        }
}, (err, response) => {

To:

When you use this, please set the range and values. By this script, the values are append to new row.

sheets.spreadsheets.values.append(
  {
    spreadsheetId: 'spreadsheetid',
    range: "Sheet1!A:A", // This is a sample range.
    valueInputOption: "RAW",
    resource: { values: [["date", "result", "comment"]] } // This is a sample value.
  }, (err, response) => {

Note:

From your question, I could confirm that you have already been able to use Sheets API.

In this case, the value can be set like { values: [["date", "result", "comment"]] }.

References:

spreadsheets.values.append

If I misunderstood your question and this was not the result you want, I apologize.

Edit:

You want to add the value to the same cells without overwriting. For example, the cells A1:B1 have sample1 and sample2. When the values of sample3 and sample4 are added to A1 and B1, respectively, the cells become sample1sample3 and sample2sample4.

From your reply comment, I could understand like this. For this situation, unfortunately, in the current stage, this cannot be directly achieved by one API call. So it is required to do the following flow.

Get values from A1:B1.

Put values to A1:B1 by updating the values.

In order to do this, for example, how about using the method of spreadsheets.values.get and spreadsheets.values.update?

Modified script:

From:

sheets.spreadsheets.values.batchUpdate({
    spreadsheetId: 'spreadsheetid',
    requestBody: {
            data: [
                {
                    range: dateCell,
                    values: [
                        [date]
                    ]
                },
                {
                    range: resultCell,
                    values: [
                        [result]
                    ]
                },
                {
                    range: commentCell,
                    values: [
                        [comment]
                    ]
                }
            ],
            valueInputOption: "RAW",
            includeValuesInResponse: true
        }
}, (err, response) => {

To:

In this case, the cells of Sheet1!A1:B1 are updated by adding the additional values to the existing values. For example, when the cells Sheet1!A1:B1 have sample1 and sample2, by running this script, the cells are updated to sample1sample3 and sample2sample4.

const spreadsheetId = "###";
const range = "Sheet1!A1:B1";
const additionalValue = [["sample3", "sample4"]];
sheets.spreadsheets.values.get(
  {
    spreadsheetId: spreadsheetId,
    range: range
  },
  (err1, result1) => {
    if (err1) {
      console.log(err1.errors);
      return;
    }
    const newValue = result1.data.values.map((row, i) =>
      row.map((col, j) => col + additionalValue[i][j])
    );
    sheets.spreadsheets.values.update(
      {
        spreadsheetId: spreadsheetId,
        range: range,
        valueInputOption: "USER_ENTERED",
        resource: { values: newValue }
      },
      (err2, result2) => {
        if (err2) {
          console.log(err2.errors);
          return;
        }
        console.log(result2.data);
      }
    );
  }
);

References:

spreadsheets.values.get

spreadsheets.values.update


问:
How to save figures to pdf as raster images in matplotlib
I have some complex graphs made using matplotlib. Saving them to a pdf using the savefig command uses a vector format, and the pdf takes ages to open. Is there any way to save the figure to pdf as a raster image to get around this problem?</p>

答:
You can force individual figure elements to be rasterized like this:</p>

```<code>text(1,1,'foobar',rasterized=True)
</code>```

Body:
You can force individual figure elements to be rasterized like this:

text(1,1,'foobar',rasterized=True)


问:
media folder images are not displaying in Template Page
I'm new to Django. Medial folder images are not displaying in Template file. please help me in that.

models.py

```<code>class Images(models.Model):
    image = models. ImageField(upload_to='images', blank=True, null=True)
</code>```

settings.py

```<code>STATIC_URL = '/static/'

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'
</code>```

urls.py

```<code>urlpatterns = [
......
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

views.py

```<code>def image_display(request):
    image_obj = Images.objects.all()
    return render(request, 'index.html', {'image_obj': image_obj})
</code>```

index.html

```<code><body>

    {% for item in myoffers_objs %}
    <div>
        <img src="{{ item.image.url }}" alt="Images"/>
    </div>
    {% endfor %}

</body>
</code>```

Project details where i did mistake. why its displaying like this.
Image displaying like this

答:
correct static_root:

```<code>STATIC_ROOT = os.path.join(BASE_DIR, 'static')
</code>```

you have to add this to your html file if you use statics in that html:

```<code>{% load staticfiles %}
</code>```

also you have to run this command to collect static files in your project:

```<code>python manage.py collectstatic
</code>```

Body:
I'm new to Django. Medial folder images are not displaying in Template file. please help me in that.

models.py

class Images(models.Model):
    image = models. ImageField(upload_to='images', blank=True, null=True)

settings.py

STATIC_URL = '/static/'

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'

urls.py

urlpatterns = [
......
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

def image_display(request):
    image_obj = Images.objects.all()
    return render(request, 'index.html', {'image_obj': image_obj})

index.html

    {% for item in myoffers_objs %}

    {% endfor %}

Project details where i did mistake. why its displaying like this.
Image displaying like this

Body:
correct static_root:

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

you have to add this to your html file if you use statics in that html:

{% load staticfiles %}

also you have to run this command to collect static files in your project:

python manage.py collectstatic


答:
the following will sort them so that rent is first misc is last and the rest are alphabetically

const data = {
  rent: {
    value: '100'
  },
  legal: {
    value: '300'
  },
  misc: {
    value: '300'
  },
  horse: {
    value: '400'
  }
};

function rent_ab_misc(obj=[]){
  return Object.entries(obj).sort(([key1], [key2]) => {
    if (key1 === 'misc' || key2==='rent') return 1;
    if (key1 === 'rent' || key2 === 'misc') return -1;
    return key1 > key2
  })
}

// useage
const output = rent_ab_misc(data).map(([key,item])=>`<div>${key}:${item.value}</div>`)

console.log(output);```

Title: Sorting an object with object.entries

Body:
I have an object of data which I'd like to sort. I'm running the following object through Object.entries(data).map() to display it on my Front-End, but I'd like to maintain a specific order. Right now it seems that the order is somewhat random. I'm using .map to display a number of React components so sorting after the map doesn't seem to be possible.

const data = {
  rent: {
   value: '100'
    },
  },
  legal: {
    value: '300'
  },
  misc: {
    value: '300'
    },
 horse: {
   value: '400'
   }
  },
};

Ideally rent should be the first item when it's mapped out, and misc should be the last one. I've tried using .sort() but I don't seem to be having any luck.

What is the right way to achieve this? I assume some combination of Object.entries(data).sort().map() but I can't seem to figure it out.


问:
Starting an embedded Cassandra instance for Unit tests
I need to start a Embedded cassandra instance to perform some operations on a Cassandra keyspace via Unit tests. Programming Language is Java. What are the options to start an embedded cassandra?

I used the mojo maven plugin, however after starting the instance using following command, I do not see the cassandra instance started at default port 9042 on localhost.
Plugin:http://www.mojohaus.org/cassandra-maven-plugin/usage.html
Command to start: mvn cassandra:run  -Dcassandra.nativeTransportPort=9042

Is there something missing in terms of usage or do I need to use something different?

Thanks
Jyothi

答:
It depends on what you are trying to test. Cassandra Maven Plugin (of which I was one of the original authors) and Cassandra Unit both do something very similar in that they start an in-JVM instance of Cassandra.

This works great if you just want to do some CRUD stuff in you integration tests, but really does not help if you want to test scenarios like consistency level failures and retries in the face of various failure cases, particularly for multiple datacenters. And Cassandra is just a beast at this point so it means you need a lot of memory for you tests to run.

To really verify things like the above, I recommend using Simulacron:
https://github.com/datastax/simulacron/blob/master/doc/java_api/README.md

And an example integration:
https://github.com/datastax/java-driver/blob/9f0d89799a8a1e4cd1022dd7c43333924c36a648/integration-tests/src/test/java/com/datastax/oss/driver/api/core/ProtocolVersionMixedClusterIT.java

This is what the driver teams use to test behavior scenarios, though they still rely on a CCM test bridge (also an option) for a lot of block and tackle stuff. For both, the way it's plumbed into maven in that project should be used as an example of best practices:

https://github.com/datastax/java-driver/blob/3.x/pom.xml#L749-L816

And profile switching for such:
https://github.com/datastax/java-driver/blob/3.x/pom.xml#L925-L947

And using the profiles:
https://github.com/datastax/java-driver/blob/3.x/driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java#L146

To really get your head around it, I recommend pulling down the driver project and picking it apart to see how this is all put together. Probably the biggest win is that this whole project does not have any dependency on Cassandra code.


问:
Get attachment as string from multipart/ALTERNATIVE message
I have a routine where I have to download an attachment from an e-mail that is multipart/ALTERNATIVE. The attachment come as string and I'm having trouble trying to save it correctly to my hard drive.

I'm able to download the e-mail content, but unable to open it, saying the archive is corrupted and it looks like there are parts missing.

When I print contentType and Encoding I get the following results:

```<code>content type of email: multipart/ALTERNATIVEboundary=000000000000b1955e0589a4192e

Content type of the part of message: TEXT/PLAIN; charset=UTF-8

Encode: QUOTED-PRINTABLE
</code>```

Here's part of the e-mail I'm trying to get the attachment:

```<code>begin 600 INTFOCOA.ZIP
M4$L#!!0````(`-I[MTX@BC)`.UI$`(Y71``5````4$%$4D%/,#%?1D]#3RY4
M6%0N0U-"`%"`KW\Y[::&9%]=.4>H(KX):(05"[CW`%*7_+:QH
--------------------end
</code>```

for (Message message : messages) {
            Multipart multiPart = (Multipart) message.getContent();
            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(0);
            String destFilePath = "C:\\Users\\fribeiro\\Desktop\\arquivo_santander\\testname";
            FileOutputStream output = new FileOutputStream(destFilePath);
            InputStream input = part.getInputStream();
            byte[] buffer = new byte[4096];
            int byteRead;
            while ((byteRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, byteRead);
            }
            output.close();

        }
```

I'm trying to get the INTFOCOA.ZIP file. thanks in advance.

答:
The content of that part is uuencoding if a zip file.

You need to apply a uudecode algorithm on it to get the zip file.

E.g. see Does Java has any standard mechanism for uudecoding?

Body:
I have a routine where I have to download an attachment from an e-mail that is multipart/ALTERNATIVE. The attachment come as string and I'm having trouble trying to save it correctly to my hard drive.

I'm able to download the e-mail content, but unable to open it, saying the archive is corrupted and it looks like there are parts missing.

When I print contentType and Encoding I get the following results:

content type of email: multipart/ALTERNATIVEboundary=000000000000b1955e0589a4192e

Content type of the part of message: TEXT/PLAIN; charset=UTF-8

Encode: QUOTED-PRINTABLE

Here's part of the e-mail I'm trying to get the attachment:

begin 600 INTFOCOA.ZIP
M4$L#!!0````(`-I[MTX@BC)`.UI$`(Y71``5````4$%$4D%/,#%?1D]#3RY4
M6%0N0U-"`%"`KW\Y[::&9%]=.4>H(KX):(05"[CW`%*7_+:QH
--------------------end

for (Message message : messages) {
            Multipart multiPart = (Multipart) message.getContent();
            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(0);
            String destFilePath = "C:\\Users\\fribeiro\\Desktop\\arquivo_santander\\testname";
            FileOutputStream output = new FileOutputStream(destFilePath);
            InputStream input = part.getInputStream();
            byte[] buffer = new byte[4096];
            int byteRead;
            while ((byteRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, byteRead);
            }
            output.close();

        }

I'm trying to get the INTFOCOA.ZIP file. thanks in advance.


问:
How to use an existing column as index in Spark's Dataframe
I am 'translating' a python code to pyspark. I would like to use an existing column as index for a dataframe. I did this in python using pandas. The small piece of code below explains what I did. Thanks for helping.

df.set_index('colx',drop=False,inplace=True)
# Ordena index
df.sort_index(inplace=True)
```

I expect the result to be a dataframe with 'colx' as index.

答:
This is not how it works with Spark. No such concept exists.

One can add a column to an RDD zipWithIndex by convert DF to RDD and back, but that is a new column, so not the same thing.

Body:
I am 'translating' a python code to pyspark. I would like to use an existing column as index for a dataframe. I did this in python using pandas. The small piece of code below explains what I did. Thanks for helping.

df.set_index('colx',drop=False,inplace=True)
# Ordena index
df.sort_index(inplace=True)

I expect the result to be a dataframe with 'colx' as index.


问:
Use awk, or sed commands to remove the letters and parenthesis from the rows of a file
I have an input file as below,

```<code>group_velocity: [     0.0000000      0.0000000      0.0000000 ]
group_velocity: [     6.8213667      5.2673206      0.0002496 ]
group_velocity: [    19.0751734     29.0686833      0.0006979 ]
</code>```

Now, I want to use the awk/sed command, such that the output file would look as:

```<code>   0.0000000      0.0000000      0.0000000
   6.8213667      5.2673206      0.0002496
   19.0751734     29.0686833     0.0006979
</code>```

Any help would be appreciated.

Body:
I have an input file as below,

group_velocity: [     0.0000000      0.0000000      0.0000000 ]
group_velocity: [     6.8213667      5.2673206      0.0002496 ]
group_velocity: [    19.0751734     29.0686833      0.0006979 ]

Now, I want to use the awk/sed command, such that the output file would look as:

   0.0000000      0.0000000      0.0000000
   6.8213667      5.2673206      0.0002496
   19.0751734     29.0686833     0.0006979

Any help would be appreciated.

Body:
$ tr -dc '0-9. \n' < file
      0.0000000      0.0000000      0.0000000
      6.8213667      5.2673206      0.0002496
     19.0751734     29.0686833      0.0006979


问:
Issues with function output using if/else if
I am (new to c++) trying to create a power function manually and came across the issue where if the power inputted is negative, the result is always being printed out as 0. I suspect that one of the variables might not be declared properly, can you help please</p>

```<code>#include <iostream>

using namespace std;

int power;
float result = 1, base;

int firs();
void pow(int base, int power);

int main()
{
    firs();
    pow(base, power);

    return 0;
}

int firs()
{
    cout << "Enter a base input: ";
    cin >> base;

    cout << "Enter a power input: ";
    cin >> power;

    return base, power;
}

void pow(int base, int power)
{
    cout << "With a given base of " << base << " and a given power of " << power << endl;

    if (power > 0)
    {
        for (int i = 0; i < power; i++)
        {
            result = result*base;
        }

    cout << "The final answer is: " << result;

    }
    else if (power < 0)
    {
        for (int i = 0; i > power; i--)
        {
            result = result*(1/base);
        }

    cout << "The final answer is: " << result;
    }
    else
    {
        cout << "The final answer is: " << 1;
    }
}
</code>```

答:
Just change this line

```<code>        result = result*(1/base);
</code>```

to

```<code>        result = result*(1.0/base);
</code>```

And you will get the correct result.

Body:
I am (new to c++) trying to create a power function manually and came across the issue where if the power inputted is negative, the result is always being printed out as 0. I suspect that one of the variables might not be declared properly, can you help please

#include <iostream>

using namespace std;

int power;
float result = 1, base;

int firs();
void pow(int base, int power);

int main()
{
    firs();
    pow(base, power);

    return 0;
}

int firs()
{
    cout << "Enter a base input: ";
    cin >> base;

    cout << "Enter a power input: ";
    cin >> power;

    return base, power;
}

void pow(int base, int power)
{
    cout << "With a given base of " << base << " and a given power of " << power << endl;

    if (power > 0)
    {
        for (int i = 0; i < power; i++)
        {
            result = result*base;
        }

    cout << "The final answer is: " << result;

    }
    else if (power < 0)
    {
        for (int i = 0; i > power; i--)
        {
            result = result*(1/base);
        }

    cout << "The final answer is: " << result;
    }
    else
    {
        cout << "The final answer is: " << 1;
    }
}

Body:
Just change this line

        result = result*(1/base);

to

        result = result*(1.0/base);

And you will get the correct result.


问:
JQuery Mobile Detected if there's internet Connection
What is the best way to detect if there's internet connection or not on my mobile via my web app?</p>

答:
There's no code necessary for this -- it's part of the HTML5 API.  Check the value of window.navigator.onLine -- it will be false if the user is offline.

http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#browser-state


问:
How to include additional CSS files in Aurelia?
Ihave a app that opens a new window with content. I need special CSS for that window.

Code for opening the window is this:

```<code>var Printwindow = window.open("","","width=360,height=188");
    var cssFile = Printwindow.document.createElement("link");
    cssFile.rel = "stylesheet";
    cssFile.type = "text/css";
    cssFile.href = "../../content/label.css";

    Printwindow.document.write("<head>" + cssFile.outerHTML + "</head><body onload='window.print();'>" + this.label.innerHTML + "</body>");
    Printwindow.document.close();
    Printwindow.focus();
</code>```

the label.css is there when i just run it in localhost. But when i build it and eploy it to server it is missing. How can i include this label.css in the bundle so that it can find it?

答:
Personally, I would recommend that you create a component and compose that within a dialog or new window. This will allow you to avoid building your presentation layer within JS. If you created a custom-component, you could do the following:

```<code><template>
 <require from="label.css"></require>
 {Content Here}
</template>
</code>```

You could then compose this into a dialog.

Alternatively, if you're unable to make structural changes, then you should import PLATFORM from aurelia-pal and use it as such:

```<code>import {PLATFORM} from 'aurelia-pal';
// .. other code here ..
cssFile.href = PLATFORM.moduleName("../../content/label.css");
</code>```

If you are still having issues, then it may be because you need to resolve your production server's base URL.

Body:
Ihave a app that opens a new window with content. I need special CSS for that window.

Code for opening the window is this:

var Printwindow = window.open("","","width=360,height=188");
    var cssFile = Printwindow.document.createElement("link");
    cssFile.rel = "stylesheet";
    cssFile.type = "text/css";
    cssFile.href = "../../content/label.css";

    Printwindow.document.write("" + cssFile.outerHTML + "" + this.label.innerHTML + "");
    Printwindow.document.close();
    Printwindow.focus();

the label.css is there when i just run it in localhost. But when i build it and eploy it to server it is missing. How can i include this label.css in the bundle so that it can find it?

Body:
Personally, I would recommend that you create a component and compose that within a dialog or new window. This will allow you to avoid building your presentation layer within JS. If you created a custom-component, you could do the following:

<template>
 <require from="label.css"></require>
 {Content Here}
</template>

You could then compose this into a dialog.

Alternatively, if you're unable to make structural changes, then you should import PLATFORM from aurelia-pal and use it as such:

import {PLATFORM} from 'aurelia-pal';
// .. other code here ..
cssFile.href = PLATFORM.moduleName("../../content/label.css");

If you are still having issues, then it may be because you need to resolve your production server's base URL.


问:
Writing the results in html file by passing the values in java - any help would be greatly appreciated
Placed the reports have overrided all the resultsi would like to print in a table with results but when i printed it overriding the results and it is printing only one line

am passing the values form other class file to print the results

i have tried using Buffered  writer for writing the code

public void createTestSummaryHTMLTable(String sample,String samp[le,String sample,String passedText,String status) throws IOException {

    File file=new File("C:\\AutomationResults\\Forms\\",foldername);
    if(!file.exists()){
        file.mkdir();}

    final String FILE_PATH =(file+"/"+formname);

    //final String FILE_PATH = "C:\\AutomationResults\\Forms\\"+formname;
    final String FILE_EXTENSION = "html";
    DateFormat df = new SimpleDateFormat("yyyyMMdd"); // add S if you need milliseconds
    String filename = FILE_PATH + "_"+ df.format(new Date()) + "." + FILE_EXTENSION;

    File file2 = new File(filename);

    // if file doesnt exists, then create it
    if (!file2.exists()) {
        file2.createNewFile();
    }
    BufferedWriter html = new BufferedWriter(new FileWriter(file2));
    html.write("
");
    html.write("<title>Automation Summary report </title>");
    html.write("
");
    html.write("Batch report heading");
    html.write(""+new Date().toString()+"");
    html.write("
");
    addlabel1(html,"Test Step Name");
    addlabel1(html,"Test Step Description");
    addlabel1(html,"Status");
    addlabel1(html,"Screenshot");
    html.write("
");

    html.write("
");
    html.newLine();
    addlabel(html,sample);

    addlabel(html,sample);

    String status1 = "Passed";
    if (status1.equals(status))
    {
        html.write(""+status+"	");
    } else {
        html.write(""+status+"	");
    }

    addlabel(html,"Screenshot");

    html.write("
");
    html.write("
");
    html.close();
}
```

答:
Oh, I think i guessed your problem. The file written is a single long line.

That is because write only writes what you give it. You need to put a \n at the end of all your strings.

Alternatively, use Printwriter's println method to output to your file.


问:
Database design for UserConsent
I am trying to create a table where I will be storing if we have user's consent to send emails. Those things can be weeklyEmails, monthylEmails, passwordChangesEmails, profileChangesEmails and so on.

This is what I have thought of making for now:

```<code>*********************** UserConsent Table ***************************

   |columns|                      |datatype|
    ID                              uuid
    User_id(Foreign_key)            uuid
    weeklyEmails                    boolean
    monthlyEmai                     boolean
    passwordChangeEmails            boolean
</code>```

The downside of this is let's say in the future I want to add another consent like profileChangeEmails or dailyDigestEmails, I will have to write database migrations and add a new column.

Is there a better way to do this where there is no need to create a new column?

It's for a relational database.

答:
Your solution seems adequate.

One thing to think about is whether it is worth it to separate into a 1:1 model like you have specified, rather than just add columns to the user table. If you have a reasonably small user table, it would probably be simpler to add the columns so you don't have to deal with relationship management.

Title: Database design for UserConsent

Body:
I am trying to create a table where I will be storing if we have user's consent to send emails. Those things can be weeklyEmails, monthylEmails, passwordChangesEmails, profileChangesEmails and so on.

This is what I have thought of making for now:

*********************** UserConsent Table ***************************

   |columns|                      |datatype|
    ID                              uuid
    User_id(Foreign_key)            uuid
    weeklyEmails                    boolean
    monthlyEmai                     boolean
    passwordChangeEmails            boolean

The downside of this is let's say in the future I want to add another consent like profileChangeEmails or dailyDigestEmails, I will have to write database migrations and add a new column.

Is there a better way to do this where there is no need to create a new column?

It's for a relational database.