问:
Apache Drill Query Execution plan don't use MongoDB Index
The query plan was showing a collection scan which is going over all the rows in the mongo collection. Hence I created an index on the where clause columns, expecting Drill to choose the index based access plan. But drill continues to use the full table scan. Is there any thing else to be done to make drill use the index ?

The actual query, generated query plan and the mongo index are given below.

SQL:

```<code>    Select j.user as User, TO_DATE(j.created_at) as submitted_on
    from mongo.example.jobs j
    where j.user = 'john@example.ai' and j.created_at BETWEEN timestamp '2020-03-25 13:12:55' AND timestamp '2020-04-24 13:12:55'
</code>```

Physical Plan (from drill UI)

```<code>    00-00 Screen : rowType = RecordType(ANY User, ANY submitted_on): rowcount = 121.2375, cumulative cost = {6720.59875 rows, 23532.19875 cpu, 895541.0 io, 0.0 network, 0.0 memory}, id = 10468
    00-01 Project(User=[$0], submitted_on=[TO_DATE($1)]) : rowType = RecordType(ANY User, ANY submitted_on): rowcount = 121.2375, cumulative cost = {6708.475 rows, 23520.075 cpu, 895541.0 io, 0.0 network, 0.0 memory}, id = 10467
    00-02 SelectionVectorRemover : rowType = RecordType(ANY user, ANY created_at): rowcount = 121.2375, cumulative cost = {6587.2375 rows, 22913.8875 cpu, 895541.0 io, 0.0 network, 0.0 memory}, id = 10466
    00-03 Filter(condition=[AND(=($0, 'john@example.ai'), >=($1, 2020-03-25 13:12:55), <=($1, 2020-04-24 13:12:55))]) : rowType = RecordType(ANY user, ANY created_at): rowcount = 121.2375, cumulative cost = {6466.0 rows, 22792.65 cpu, 895541.0 io, 0.0 network, 0.0 memory}, id = 10465
    00-04 Scan(table=[[mongo, example, jobs]], groupscan=[MongoGroupScan [MongoScanSpec=MongoScanSpec [dbName=example, collectionName=jobs, filters=null], columns=[`user`, `created_at`]]]) : rowType = RecordType(ANY user, ANY created_at): rowcount = 3233.0, cumulative cost = {3233.0 rows, 6466.0 cpu, 895541.0 io, 0.0 network, 0.0 memory}, id = 10464
</code>```

Index created in MongoDB

```<code>{
"v" : 2,
"key" : { "user" : 1, "created_at" : 1, "method_map_id" : 1 },
"name" : "user_1_created_at_1_method_map_id_1",
"ns" : "example.jobs"
}
</code>```

Moreover, in a drill documentation, I see that drill supports indexes only for MapR DB. Does that mean Indexes of other data sources like mongo won't be used ?

https://drill.apache.org/docs/querying-indexes-introduction/

答:
The problem lies in the mongo-storage plugin dealing with Timestamp filter predicates.  The filter predicates are evaluated in the following modules in the given order.

MongoPushDownFilterForScan -> MongoFilterBuilder -> MongoCompareFunctionProcessor.process() -> MongoCompareFunctionProcessor.visitSchemaPath()

The visitSchemaPath method acts like a getter method for the value expression classes. I see that there is no handler for TimestampExpression. Added the piece of code below, rebuilt and tested it.

```<code>if (valueArg instanceof TimeStampExpression) {
 Long unixseconds = ((TimeStampExpression) valueArg).getTimeStamp();
 this.value = new Date(unixseconds);
 this.path = path;
 return true;
 }
</code>```

This makes the timestamp filters to be passed into the filter section of mongo queries.

Body:
The query plan was showing a collection scan which is going over all the rows in the mongo collection. Hence I created an index on the where clause columns, expecting Drill to choose the index based access plan. But drill continues to use the full table scan. Is there any thing else to be done to make drill use the index ?

The actual query, generated query plan and the mongo index are given below.

SQL:

    Select j.user as User, TO_DATE(j.created_at) as submitted_on
    from mongo.example.jobs j
    where j.user = 'john@example.ai' and j.created_at BETWEEN timestamp '2020-03-25 13:12:55' AND timestamp '2020-04-24 13:12:55'

Physical Plan (from drill UI)

    00-00 Screen : rowType = RecordType(ANY User, ANY submitted_on): rowcount = 121.2375, cumulative cost = {6720.59875 rows, 23532.19875 cpu, 895541.0 io, 0.0 network, 0.0 memory}, id = 10468
    00-01 Project(User=[$0], submitted_on=[TO_DATE($1)]) : rowType = RecordType(ANY User, ANY submitted_on): rowcount = 121.2375, cumulative cost = {6708.475 rows, 23520.075 cpu, 895541.0 io, 0.0 network, 0.0 memory}, id = 10467
    00-02 SelectionVectorRemover : rowType = RecordType(ANY user, ANY created_at): rowcount = 121.2375, cumulative cost = {6587.2375 rows, 22913.8875 cpu, 895541.0 io, 0.0 network, 0.0 memory}, id = 10466
    00-03 Filter(condition=[AND(=($0, 'john@example.ai'), >=($1, 2020-03-25 13:12:55), <=($1, 2020-04-24 13:12:55))]) : rowType = RecordType(ANY user, ANY created_at): rowcount = 121.2375, cumulative cost = {6466.0 rows, 22792.65 cpu, 895541.0 io, 0.0 network, 0.0 memory}, id = 10465
    00-04 Scan(table=[[mongo, example, jobs]], groupscan=[MongoGroupScan [MongoScanSpec=MongoScanSpec [dbName=example, collectionName=jobs, filters=null], columns=[`user`, `created_at`]]]) : rowType = RecordType(ANY user, ANY created_at): rowcount = 3233.0, cumulative cost = {3233.0 rows, 6466.0 cpu, 895541.0 io, 0.0 network, 0.0 memory}, id = 10464

Index created in MongoDB

{
"v" : 2,
"key" : { "user" : 1, "created_at" : 1, "method_map_id" : 1 },
"name" : "user_1_created_at_1_method_map_id_1",
"ns" : "example.jobs"
}

Moreover, in a drill documentation, I see that drill supports indexes only for MapR DB. Does that mean Indexes of other data sources like mongo won't be used ?

https://drill.apache.org/docs/querying-indexes-introduction/

Body:
The problem lies in the mongo-storage plugin dealing with Timestamp filter predicates.  The filter predicates are evaluated in the following modules in the given order.

MongoPushDownFilterForScan -> MongoFilterBuilder -> MongoCompareFunctionProcessor.process() -> MongoCompareFunctionProcessor.visitSchemaPath()

The visitSchemaPath method acts like a getter method for the value expression classes. I see that there is no handler for TimestampExpression. Added the piece of code below, rebuilt and tested it.

if (valueArg instanceof TimeStampExpression) {
 Long unixseconds = ((TimeStampExpression) valueArg).getTimeStamp();
 this.value = new Date(unixseconds);
 this.path = path;
 return true;
 }

This makes the timestamp filters to be passed into the filter section of mongo queries.


来源: stackexchange

问:
How to add a straight line y-axis over a dimple js scatterplot and assign colour to it
I would like to draw a horizontal average line on a dimple js scatterplot. I've tried to follow the solution from here
.But I can only get a point instead of a line and assignColor doesn't work either. I can't figure out what the problems are. Any suggestions? Your help would be appreciated.</p>

```<code>      var svg = dimple.newSvg("#ChartContainer", 800, 600);
      var myChart = new dimple.chart(svg, data);
      myChart.setBounds(60, 50, 600, 500)
      myChart.addMeasureAxis("x", "ESCIndex");
      myChart.addMeasureAxis("y", "Grade");
      var s=myChart.addSeries(["OECD"], dimple.plot.bubble);
      var myLegend=myChart.addLegend(10, 10, 400, 30, "right", s);

      var s1 = myChart.addSeries("Average", dimple.plot.line);
      s1.data = [
    { "Average" : "avg", "Grade" : 13.22, "ESCIndex" : -10.45 },
    { "Average" : "avg", "Grade" : 13.22, "ESCIndex" : 6.79 }
    ];
      myChart.assignColor("Average", "green");

      myChart.draw();
</code>```

答:
there is no direct way to add a average line in dimple charts , but we can add n number of series to it , so once u have added the required visualization bar,area,line etc . add another one like averageline series to ur code . this series should have only two data points , datapoint1 = {key:YourData[1].key , value : averageValue} , datapoint2 = {key:YourData[last].key, value : averageValue}

var svg = dimple.newSvg("#chartContainer", 600, 400),
    data = [
        { "Value" : 100, "Year" : 2009 , "sample": "0"},
        { "Value" : 40, "Year" : 2010 , "sample": "0"},
        { "Value" : 60, "Year" : 2011 , "sample": "0"},
        { "Value" : 10, "Year" : 2012 , "sample": "0"},
        { "Value" : 80, "Year" : 2013 , "sample": "0"},
        { "Value" : 20, "Year" : 2014 , "sample": "0"}
    ];

// Draw a standard chart using the aggregated data
var chart = new dimple.chart(svg, data);
var x = chart.addCategoryAxis("x", "Year");
var y = chart.addMeasureAxis("y", "Value");
y.hidden = true;
var s = chart.addSeries('channel', dimple.plot.bar);
let horizontalLine = chart.addSeries("Average", dimple.plot.line);
        chart.assignColor("Average","black");
        horizontalLine.data = [];
        for (let i = 0; i < 2; i++) {
            let obj = {};
            obj["Year"] = i ? data[0]["Year"] : data[data.length-1]["Year"];
            obj["Value"] =50;
            horizontalLine.data.push(obj);
        }

chart.draw();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dimple/2.2.0/dimple.latest.js"></script>
<div id="chartContainer"></div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to draw a horizontal average line on a dimple js scatterplot. I've tried to follow the solution from here
.But I can only get a point instead of a line and assignColor doesn't work either. I can't figure out what the problems are. Any suggestions? Your help would be appreciated.

      var svg = dimple.newSvg("#ChartContainer", 800, 600);
      var myChart = new dimple.chart(svg, data);
      myChart.setBounds(60, 50, 600, 500)
      myChart.addMeasureAxis("x", "ESCIndex");
      myChart.addMeasureAxis("y", "Grade");
      var s=myChart.addSeries(["OECD"], dimple.plot.bubble);
      var myLegend=myChart.addLegend(10, 10, 400, 30, "right", s);

      var s1 = myChart.addSeries("Average", dimple.plot.line);
      s1.data = [
    { "Average" : "avg", "Grade" : 13.22, "ESCIndex" : -10.45 },
    { "Average" : "avg", "Grade" : 13.22, "ESCIndex" : 6.79 }
    ];
      myChart.assignColor("Average", "green");

      myChart.draw();

Body:
there is no direct way to add a average line in dimple charts , but we can add n number of series to it , so once u have added the required visualization bar,area,line etc . add another one like averageline series to ur code . this series should have only two data points , datapoint1 = {key:YourData[1].key , value : averageValue} , datapoint2 = {key:YourData[last].key, value : averageValue}

var svg = dimple.newSvg("#chartContainer", 600, 400),
    data = [
        { "Value" : 100, "Year" : 2009 , "sample": "0"},
        { "Value" : 40, "Year" : 2010 , "sample": "0"},
        { "Value" : 60, "Year" : 2011 , "sample": "0"},
        { "Value" : 10, "Year" : 2012 , "sample": "0"},
        { "Value" : 80, "Year" : 2013 , "sample": "0"},
        { "Value" : 20, "Year" : 2014 , "sample": "0"}
    ];

// Draw a standard chart using the aggregated data
var chart = new dimple.chart(svg, data);
var x = chart.addCategoryAxis("x", "Year");
var y = chart.addMeasureAxis("y", "Value");
y.hidden = true;
var s = chart.addSeries('channel', dimple.plot.bar);
let horizontalLine = chart.addSeries("Average", dimple.plot.line);
        chart.assignColor("Average","black");
        horizontalLine.data = [];
        for (let i = 0; i < 2; i++) {
            let obj = {};
            obj["Year"] = i ? data[0]["Year"] : data[data.length-1]["Year"];
            obj["Value"] =50;
            horizontalLine.data.push(obj);
        }

chart.draw();

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.8/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dimple/2.2.0/dimple.latest.js"></script>
<div id="chartContainer"></div>

ContentLicense: CC BY-SA 4.0


问:
U-Boot add node to devicetree during startup
I work on a custom board with a Cyclone V SoC.

I need to add some informations to U-Boot device tree at startup and these informations are stored in an I2C device.

It appears that U-Boot device tree is read-only during its execution but before relocation. The function board_fix_fdt (void *rw_fdt_blob) can be used to make changes on the device tree before relocation.

The problem I have is that I cannot access the I2C device at this time. The driver doesn't seem to be loaded yet.

Can someone give me any hints on how I can enable the I2C at this stage ?

U-Boot version is 2018-05.

答:
The solution is to add in u-boot device tree the i2c driver and also the reset driver for pre-relocation states :</p>

```<code>&rst {
    status = "okay";
    u-boot,dm-pre-reloc;  // HERE
};

&i2c2 {
    status = "okay";
    u-boot,dm-pre-reloc;   // and HERE
}
</code>```

Body:
The solution is to add in u-boot device tree the i2c driver and also the reset driver for pre-relocation states :

&rst {
    status = "okay";
    u-boot,dm-pre-reloc;  // HERE
};

&i2c2 {
    status = "okay";
    u-boot,dm-pre-reloc;   // and HERE
}


问:
how do i convert dropdown list all values into Million/Billion in javascript?
How do I convert all the output numbers on the dropdown generated by the code  like in these examples ?
(Ex:if the output number is 100 0000 I want to show this as 1M(million)
Ex2:if the output number is  1000 000 000 I want to show this as 1B(billion) )

window.f = function(event) {
    var ddlArray = new Array();
    var onoffelem=event.target;
    var ddl = document.getElementById('ddl');
    var select = document.getElementById('combo2');
    var combo3 = document.getElementById('combo3');
    var selectedVal=onoffelem.options[onoffelem.selectedIndex].text ;

    if (selectedVal == "LKR") {
        document.getElementById("combo2").options.length = 0;
        for (i = 0; i < combo3.options.length; i++) {
            ddlArray[i] = combo3.options[i].value;
        }
        for (i = 0; i < ddlArray.length; i++) {
            var option = document.createElement("OPTION"),
            txt = document.createTextNode("Rs. " + ddlArray[i] * 185000000);
            option.appendChild(txt);
            option.setAttribute("value", ddlArray[i] * 185000000);
            select.insertBefore(option, select.lastChild);
        }
    }

    if (selectedVal == "USD") {
        document.getElementById("combo2").options.length = 0;
        for (i = 0; i < combo3.options.length; i++) {
            ddlArray[i] = combo3.options[i].value;
        }
        for (i = 0; i < ddlArray.length; i++) {
            var option = document.createElement("OPTION"),
            txt = document.createTextNode(ddlArray[i] * 20000);
            option.appendChild(txt);
            option.setAttribute("value",ddlArray[i] * 20000);
            select.insertBefore(option,select.lastChild);
        }
    }
}

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="ddl" onchange="f(event)" >
    <option value="185">USD</option>
    <option value="11">LKR</option>
    <option value="48">AED</option>
</select>
<select name="" id="combo2" >
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<select name="" id="combo3" hidden="">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select></code>```

答:
You can use a function similar to this one:</p>

```<code>formatNumber(num) {
    if (num >= 1000000000) {
      return (num / 1000000000).toFixed().replace(/\.0$/, '') + 'B';
    }
    if (num >= 1000000) {
      return (num / 1000000).toFixed().replace(/\.0$/, '') + 'M';
    }
    if (num >= 1000) {
      return (num / 1000).toFixed().replace(/\.0$/, '') + 'K';
    }
}
</code>```

Body:
How do I convert all the output numbers on the dropdown generated by the code  like in these examples ?
(Ex:if the output number is 100 0000 I want to show this as 1M(million)
Ex2:if the output number is  1000 000 000 I want to show this as 1B(billion) )

window.f = function(event) {
    var ddlArray = new Array();
    var onoffelem=event.target;
    var ddl = document.getElementById('ddl');
    var select = document.getElementById('combo2');
    var combo3 = document.getElementById('combo3');
    var selectedVal=onoffelem.options[onoffelem.selectedIndex].text ;

    if (selectedVal == "LKR") {
        document.getElementById("combo2").options.length = 0;
        for (i = 0; i < combo3.options.length; i++) {
            ddlArray[i] = combo3.options[i].value;
        }
        for (i = 0; i < ddlArray.length; i++) {
            var option = document.createElement("OPTION"),
            txt = document.createTextNode("Rs. " + ddlArray[i] * 185000000);
            option.appendChild(txt);
            option.setAttribute("value", ddlArray[i] * 185000000);
            select.insertBefore(option, select.lastChild);
        }
    }

    if (selectedVal == "USD") {
        document.getElementById("combo2").options.length = 0;
        for (i = 0; i < combo3.options.length; i++) {
            ddlArray[i] = combo3.options[i].value;
        }
        for (i = 0; i < ddlArray.length; i++) {
            var option = document.createElement("OPTION"),
            txt = document.createTextNode(ddlArray[i] * 20000);
            option.appendChild(txt);
            option.setAttribute("value",ddlArray[i] * 20000);
            select.insertBefore(option,select.lastChild);
        }
    }
}

<select id="ddl" onchange="f(event)" >
    <option value="185">USD</option>
    <option value="11">LKR</option>
    <option value="48">AED</option>
</select>
<select name="" id="combo2" >
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<select name="" id="combo3" hidden="">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

Body:
You can use a function similar to this one:

formatNumber(num) {
    if (num >= 1000000000) {
      return (num / 1000000000).toFixed().replace(/\.0$/, '') + 'B';
    }
    if (num >= 1000000) {
      return (num / 1000000).toFixed().replace(/\.0$/, '') + 'M';
    }
    if (num >= 1000) {
      return (num / 1000).toFixed().replace(/\.0$/, '') + 'K';
    }
}


问:
Subscribing to multiple observables sequentially with Rxjs
I am trying to make a http request only when my form is dirty. I tried using zip but it will still make the http request regardless as the pipe results will only apply on the subscribe block. Is there anyway for me to NOT nest the observables as I have to subscribe to another observable after the http call which will result is 3 nested layers of observable.

```<code>  @ViewChild('form')
  form: NgForm;

  // only take events when form is dirty
  const formValueChanges$ = this.form.valueChanges
    .pipe(
      debounceTime(500),
      filter(() => this.form.dirty),
      takeUntil(this._destroy$),
      distinctUntilChanged(),
      tap(result => {
        console.log(result);
      })
    );

  // http request returning an observable
  const updateForm$ = this.tempService.update();

  zip(formValueChanges$, updateForm$)
    .subscribe((response) => {
        console.log(response);
      }
    );
</code>```

Intended Behaviour

```<code>this.form.valueChanges
  .pipe(
     debounceTime(500),
     filter(() => this.form.dirty),
     takeUntil(this._destroy$),
     distinctUntilChanged(),
  ).subscribe(() => {
     console.log("SAVED");
     this.tempService.update().subscribe();
  });
</code>```

答: You can go for mergeMap Operator from rxjs.</p>

Body:
I am trying to make a http request only when my form is dirty. I tried using zip but it will still make the http request regardless as the pipe results will only apply on the subscribe block. Is there anyway for me to NOT nest the observables as I have to subscribe to another observable after the http call which will result is 3 nested layers of observable.

  @ViewChild('form')
  form: NgForm;

  // only take events when form is dirty
  const formValueChanges$ = this.form.valueChanges
    .pipe(
      debounceTime(500),
      filter(() => this.form.dirty),
      takeUntil(this._destroy$),
      distinctUntilChanged(),
      tap(result => {
        console.log(result);
      })
    );

  // http request returning an observable
  const updateForm$ = this.tempService.update();

  zip(formValueChanges$, updateForm$)
    .subscribe((response) => {
        console.log(response);
      }
    );

Intended Behaviour

this.form.valueChanges
  .pipe(
     debounceTime(500),
     filter(() => this.form.dirty),
     takeUntil(this._destroy$),
     distinctUntilChanged(),
  ).subscribe(() => {
     console.log("SAVED");
     this.tempService.update().subscribe();
  });


问:
more complicated label in checkbox - Vuetify
Here's my simple code:

```<code><v-checkbox
  v-model="rodo"
  label="I agree to Privacy Policy (show more)"
  :rules="policyRules"
  required
></v-checkbox>
</code>```

I want to have simple code inside the label, just something to show more on click. What's the best way to approach that? I want to have something like that in label:

```<code>I agree to Privacy Policy
<span @click="showMore=!showMore">(show more)</span>
<span v-show="showMore">Lorem ipsum...</span>
</code>```

答:
Since you are using vuetify I think you can easily append an icon and click on that:

```<code>      <v-checkbox
        v-model="rodo"
        label="I agree to Privacy Policy"
        append-icon="mdi-chevron-down"
        required
        @click:append="showMore = !showMore"
      ></v-checkbox>
      <span v-if="showMore">{{ policyRules }}</span>
</code>```

Body:
Here's my simple code:

<v-checkbox
  v-model="rodo"
  label="I agree to Privacy Policy (show more)"
  :rules="policyRules"
  required
></v-checkbox>

I want to have simple code inside the label, just something to show more on click. What's the best way to approach that? I want to have something like that in label:

I agree to Privacy Policy
(show more)
Lorem ipsum...

Body:
Since you are using vuetify I think you can easily append an icon and click on that:

      <v-checkbox
        v-model="rodo"
        label="I agree to Privacy Policy"
        append-icon="mdi-chevron-down"
        required
        @click:append="showMore = !showMore"
      ></v-checkbox>
      <span v-if="showMore">{{ policyRules }}</span>


问:
Mounting a configuration file structure in job pod
In our application we will have a Kubernetes job that will bootstrap microservices based on a set of (legacy) configuration files. These are in the legacy application packaged as a file structure, and we'd like to keep this so that we don't need to maintain different packaging of the configuration files for the Kubernetes variant and the legacy variant, and there is a lot of legacy code that we still want to use that expects this file structure.

My approach was that I wanted to mount a ConfigMap in the job pod since I naively assumed you could map a entire folder tree, but a ConfigMap is a flat key-value storage.

We're using Helm, so the idea is that the microservice will include the job and apply it with hooks. What would be a good way to map the configuration file structure into the job pod? Can you easily create a volume, populate it with the file strucutre, and then mount it in the job pod?

答:
There are many ways to achieve the result, some are better than the other so I am just going mention the better ones.

You could in theory use configmaps to do it but you also mentioned
"... there is a lot of legacy code" and because of that you need to aware that configmaps have 1MB limit (to be more specific I should mention that this limit is enforced by etcd and not configmap itself).
Now assuming this is not a problem you would need to hold each file as one key in configmap and then mount every file individually to its directory. Of cource you could automate this process byt its not ideal solution when having many files.

Now answering to your question:

Can you easily create a volume, populate it with the file strucutre, and then mount it in the job pod?

Probably the easiest way to achieve mentioned result would be by mounting emptyDir volume and populating it using initContainers. Init container could pull configuration folder (either from git repo or from some other file repository) and save it in emptyDit volume that would be later mounted to the actual container.
Here is an example of how it would look like.

What you are suggesting is also valid solution but it requires the use of persistent volumes and it may not always be necessary. But if you decide to use it, all you need to do is use the same volume name and use retain for persistentVolumeReclaimPolicy field.

You also need to remember that init(hook) container code should be idempotent. In particular, code that writes to EmptyDirs(persistent volume) should be prepared for the possibility that an output files already exist.


问:
Function to filter tibble with argument having same name as a column
A petty problem with an obvious solution to rename the parameter of the function. Yet I am interested whether there is a way how I can achieve the following where column name and argument name are the same?

library(dplyr)
d <- data.frame(x = 1:3)

f <- function(x) {
  list(
          ## returns all b/c always true
          d %>% filter(x == x),

          ## does not work either
          ## any way to tell dplyr to use the parameter x
          d %>% filter(.data$x == x)
       )
}
f(1)
```

答:
You can use {{}}

```<code>library(dplyr)
library(rlang)

f1 <- function(df, x) df %>% filter({{x}} == x)
f1(d, 1)

#  x
#1 1

f1(d, 2)
#  x
#1 2
</code>```

Body:
You can use {{}}

library(dplyr)
library(rlang)

f1 <- function(df, x) df %>% filter({{x}} == x)
f1(d, 1)

#  x
#1 1

f1(d, 2)
#  x
#1 2


问:
Why am I getting a "401 Unauthorized" error in Maven?
Why am I getting a "401 Unauthorized" error in Maven?

Here's the error I'm getting when calling mvn deploy (full logs at the bottom):

[INFO] BUILD FAILURE

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project xbnjava: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized. -> [Help 1]

According to this sonatype support page:

"If you are receiving a 401 it is because maven is sending the wrong login credentials, or no credentials at all."

Below are the steps I've taken, below that are my full settings.xml and pom.xml files, and below that are the full logs from mvn deploy and mvn deploy -e.

Any ideas would be appreciated. I am just hitting wall after wall with Maven.

I followed sonatype's checklist when receiving a 401 error:

Checklist item 1. Make sure your username/password is correct by logging into the Nexus UI. If curl is installed on your machine, you can try deploying an artifact with...

I successfully logged in and out of the sonatype.org website, using the user/pass in settings.xml.

I attempted to use curl to manually deploy an artifact, with the command

[C:\]curl -u MY_SONATYPE_DOT_COM_USERNAME:MY_SONATYPE_DOT_COM_PASSWORD https://oss.sonatype.org/content/repositories/snapshots/com/github/aliteralmind/xbnjava/0.1.2-SNAPSHOT/xbnjava-0.1.2-20140716.224928-1.pom --request PUT --data @pom.xml

but got this error:

```<code>Warning: Couldn't read data from file "pom.xml", this makes an empty POST.
curl: (60) SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.
</code>```

I ran it again with the -k option, and this time got only this:

```<code>Couldn't read data from file "pom.xml", this makes an empty POST.
</code>```

I've never used curl before, so I'm at a loss on what to do with this information.

Checklist item 2. If there is no error output, ensure your user privileges are correctly configured on the server.  Make sure to drop the repo you just created.

I don't know what "drop" means. I believe my privileges are properly installed, as I received this message from sonatype:

Configuration has been prepared, now you can:

Deploy snapshot artifacts into repository https://oss.sonatype.org/content/repositories/snapshots

Deploy release artifacts into the staging repository https://oss.sonatype.org/service/local/staging/deploy/maven2

Promote staged artifacts into repository 'Releases'

Download snapshot and release artifacts from group https://oss.sonatype.org/content/groups/public

Download snapshot, release and staged artifacts from staging group https://oss.sonatype.org/content/groups/staging

and I have successfully put these items onto the server via mvn deploy in the past couple days.

The project's settings:

Checklist item 3. Make sure you have configured a server in settings.xml and that the server id is identical to the distribution repository id in pom.xml.

In settings.xml, settings/servers/server/id equals ossrh

In pom.xml, distributionManagement/snapshotRepository/id equals ossrh

(full files are at the bottom)

Checklist item 4. Make sure your settings.xml is in the correct place (normally it’s _~/.m2/settings.xml).  You can check this by running mvn help:effective-settings.

According to Maven's settings reference, settings.xml must be in one of two locations:

The Maven install: $M2_HOME/conf/settings.xml

A user’s install: ${user.home}/.m2/settings.xml

Here's my setup:

settings.xml: C:\applications\programming\apache-maven-3.2.2\conf\settings.xml

M2_HOME is C:\applications\programming\apache-maven-3.2.2

Output for mvn help:effective-settings:

```<code>[C:\applications\utilities\curl]
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-help-plugin:2.2:effective-settings (default-cli) @ standalone-pom ---
[INFO]
Effective user-specific configuration settings:

<?xml version="1.0" encoding="UTF-8"?>
<!-- ====================================================================== -->
<!--                                                                        -->
<!-- Generated by Maven Help Plugin on 2014-07-18T12:48:19                  -->
<!-- See: http://maven.apache.org/plugins/maven-help-plugin/                -->
<!--                                                                        -->
<!-- ====================================================================== -->

<!-- ====================================================================== -->
<!--                                                                        -->
<!-- Effective Settings for 'jeffy' on 'kermit-the-frog'                    -->
<!--                                                                        -->
<!-- ====================================================================== -->

<settings xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:sc
hemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
  <localRepository xmlns="http://maven.apache.org/SETTINGS/1.1.0">C:\Users\jeffy\.m2\repository</localRepository
>
  <servers xmlns="http://maven.apache.org/SETTINGS/1.1.0">
    <server>
      <username>MY_SONATYPE_DOT_COM_USERNAME</username>
      <password>***</password>
      <id>ossrh</id>
    </server>
  </servers>
  <pluginGroups xmlns="http://maven.apache.org/SETTINGS/1.1.0">
    <pluginGroup>org.apache.maven.plugins</pluginGroup>
    <pluginGroup>org.codehaus.mojo</pluginGroup>
  </pluginGroups>
</settings>

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.310 s
[INFO] Finished at: 2014-07-18T12:48:19-04:00
[INFO] Final Memory: 7M/17M
[INFO] ------------------------------------------------------------------------
</code>```

Checklist item 5. If the server is using https but the URL in your POM is http, you might get 401 as well.

I don't understand which url it's referring to.

Checklist item 6. Use the latest version of Maven, as there is a known issue regarding 401: MNG-4469

I am using the latest version:

```<code>[C:\]mvn -version
Apache Maven 3.2.2 (45f7c06d68e745d05611f7fd14efb6594181933e; 2014-06-17T09:51:42-04:00)
Maven home: C:\applications\programming\apache-maven-3.2.2
Java version: 1.7.0_51, vendor: Oracle Corporation
Java home: C:\applications\programming\jdk_7_51\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "x86", family: "windows"
</code>```

------------------

Full settings.xml and pom.xml files

(Full logs for mvn deploy and mvn deploy -e below)

settings.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
   <servers>
     <server>
       <id>ossrh</id>
       <username>MY_SONATYPE_DOT_COM_USERNAME</username>
       <password>MY_SONATYPE_DOT_COM_PASSWORD</password>
     </server>
   </servers>

   <pluginGroups></pluginGroups>
   <proxies></proxies>
   <mirrors></mirrors>
   <profiles></profiles>
</settings>
</code>```

pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.github.aliteralmind</groupId>
   <artifactId>xbnjava</artifactId>
   <packaging>pom</packaging>
   <version>0.1.2</version>
   <name>XBN-Java</name>
   <url>https://github.com/aliteralmind/xbnjava</url>
   <inceptionYear>2014</inceptionYear>
   <organization>
      <name>Jeff Epstein</name>
   </organization>
   <description>XBN-Java is a collection of generically-useful backend (server side, non-GUI) programming utilities, featuring RegexReplacer and FilteredLineIterator. XBN-Java is the foundation of Codelet (http://codelet.aliteralmind.com).</description>

   <parent>
      <groupId>org.sonatype.oss</groupId>
      <artifactId>oss-parent</artifactId>
      <version>7</version>
   </parent>

   <licenses>
      <license>
         <name>Lesser General Public License (LGPL) version 3.0</name>
         <url>https://www.gnu.org/licenses/lgpl-3.0.txt</url>
      </license>
      <license>
         <name>Apache Software License (ASL) version 2.0</name>
         <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      </license>
   </licenses>

   <developers>
      <developer>
         <name>Jeff Epstein</name>
         <email>aliteralmind-github@yahoo.com</email>
         <roles>
            <role>Lead Developer</role>
         </roles>
      </developer>
   </developers>

   <issueManagement>
      <system>GitHub Issue Tracker</system>
      <url>https://github.com/aliteralmind/xbnjava/issues</url>
   </issueManagement>

   <distributionManagement>
      <snapshotRepository>
         <id>ossrh</id>
         <url>https://oss.sonatype.org/content/repositories/snapshots</url>
      </snapshotRepository>
   </distributionManagement>

   <scm>
      <connection>scm:git:git@github.com:aliteralmind/xbnjava.git</connection>
      <url>scm:git:git@github.com:aliteralmind/xbnjava.git</url>
      <developerConnection>scm:git:git@github.com:aliteralmind/xbnjava.git</developerConnection>
   </scm>

   <properties>
      <java.version>1.7</java.version>
      <jarprefix>R:\jeffy\programming\build\/${project.artifactId}-${project.version}/download/${project.artifactId}-${project.version}</jarprefix>
   </properties>
<!--
  <profiles>
    <profile>
      <id>default-tools.jar</id>
      <activation>
        <property>
          <name>java.vendor</name>
          <value>Sun Microsystems Inc.</value>
        </property>
      </activation>
      <dependencies>
        <dependency>
          <groupId>com.sun</groupId>
          <artifactId>tools</artifactId>
          <version>1.4.2</version>
          <scope>system</scope>
          <systemPath>${java.home}/../lib/tools.jar</systemPath>
        </dependency>
      </dependencies>
    </profile>
  </profiles>
 -->
   <build>
      <plugins>
         <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>build-helper-maven-plugin</artifactId>
            <version>1.8</version>
            <executions>
               <execution>
                  <id>attach-artifacts</id>
                  <phase>package</phase>
                  <goals>
                     <goal>attach-artifact</goal>
                  </goals>
                  <configuration>
                     <artifacts>
                        <artifact>
                           <file>${jarprefix}-all.jar</file>
                           <type>jar</type>
                        </artifact>
                     </artifacts>
                  </configuration>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </build>

   <profiles>
      <!--
      This profile will sign the JAR file, sources file, and javadocs file using the GPG key on the local machine.
      See: https://docs.sonatype.org/display/Repository/How+To+Generate+PGP+Signatures+With+Maven
      -->
      <profile>
         <id>release-sign-artifacts</id>
         <activation>
            <property>
               <name>release</name>
               <value>true</value>
            </property>
         </activation>
      </profile>
   </profiles>
</project>
</code>```

------------------

Full logs for mvn deploy and mvn deploy -e

mvn deploy output:

```<code>[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building XBN-Java 0.1.2
[INFO] ------------------------------------------------------------------------
[INFO] --- maven-enforcer-plugin:1.0:enforce (enforce-maven) @ xbnjava ---
[INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava ---
[INFO] --- maven-install-plugin:2.4:install (default-install) @ xbnjava ---
[INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\pom.xml to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.2\xbnjava-0.1.2.pom
[INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.2\download\xbnjava-0.1.2-all.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.2\xbnjava-0.1.2.jar
[INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ xbnjava ---
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom
2/6 KB
4/6 KB
6/6 KB
</code>```

(Failure section:)

```<code>[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.204 s
[INFO] Finished at: 2014-07-18T11:25:17-04:00
[INFO] Final Memory: 7M/17M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project xbnjava: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

mvn deploy -e output:

```<code>[INFO] Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building XBN-Java 0.1.2
[INFO] ------------------------------------------------------------------------
[INFO] --- maven-enforcer-plugin:1.0:enforce (enforce-maven) @ xbnjava ---
[INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava ---
[INFO] --- maven-install-plugin:2.4:install (default-install) @ xbnjava ---
[INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\pom.xml to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.2\xbnjava-0.1.2.pom
[INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.2\download\xbnjava-0.1.2-all.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.2\xbnjava-0.1.2.jar
[INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ xbnjava ---
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom
2/6 KB
4/6 KB
6/6 KB
</code>```

(Failure section:)

```<code>[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.492 s
[INFO] Finished at: 2014-07-18T11:25:37-04:00
[INFO] Final Memory: 7M/17M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project xbnjava: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized. -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project xbnjava: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)
   at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
   at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
   at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
   at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
   at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
   at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:120)
   at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:347)
   at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:154)
   at org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)
   at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:213)
   at org.apache.maven.cli.MavenCli.main(MavenCli.java:157)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
   at java.lang.reflect.Method.invoke(Method.java:606)
   at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
   at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
   at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
   at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.apache.maven.plugin.deploy.DeployMojo.execute(DeployMojo.java:193)
   at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:132)
   at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
   ... 19 more
Caused by: org.apache.maven.artifact.deployer.ArtifactDeploymentException: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.apache.maven.artifact.deployer.DefaultArtifactDeployer.deploy(DefaultArtifactDeployer.java:143)
   at org.apache.maven.plugin.deploy.AbstractDeployMojo.deploy(AbstractDeployMojo.java:167)
   at org.apache.maven.plugin.deploy.DeployMojo.execute(DeployMojo.java:149)
   ... 21 more
Caused by: org.eclipse.aether.deployment.DeploymentException: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.eclipse.aether.internal.impl.DefaultDeployer.deploy(DefaultDeployer.java:337)
   at org.eclipse.aether.internal.impl.DefaultDeployer.deploy(DefaultDeployer.java:268)
   at org.eclipse.aether.internal.impl.DefaultRepositorySystem.deploy(DefaultRepositorySystem.java:413)
   at org.apache.maven.artifact.deployer.DefaultArtifactDeployer.deploy(DefaultArtifactDeployer.java:139)
   ... 23 more
Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.eclipse.aether.connector.wagon.WagonRepositoryConnector$6.wrap(WagonRepositoryConnector.java:1016)
   at org.eclipse.aether.connector.wagon.WagonRepositoryConnector$6.wrap(WagonRepositoryConnector.java:1004)
   at org.eclipse.aether.connector.wagon.WagonRepositoryConnector$PutTask.run(WagonRepositoryConnector.java:895)
   at org.eclipse.aether.connector.wagon.WagonRepositoryConnector.put(WagonRepositoryConnector.java:522)
   at org.eclipse.aether.internal.impl.DefaultDeployer.deploy(DefaultDeployer.java:331)
   ... 26 more
Caused by: org.apache.maven.wagon.TransferFailedException: Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:573)
   at org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:493)
   at org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:474)
   at org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:454)
   at org.eclipse.aether.connector.wagon.WagonRepositoryConnector$PutTask.run(WagonRepositoryConnector.java:871)
   ... 28 more
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

答:
Failed to transfer file:

  http://mcpappxxxp.dev.chx.s.com:18080/artifactory/mcprepo-release-local/Shop/loyalty-telluride/01.16.03/loyalty-tell-01.16.03.jar.

  Return code is: 401, ReasonPhrase: Unauthorized. -> [Help 1]

Solution:

In this case you need to change the version in the pom file, and try to use a new version.

Here 01.16.03 already exist so it was failing and when i have tried with the 01.16.04 version the job went successful.

Body:
Why am I getting a "401 Unauthorized" error in Maven?

Here's the error I'm getting when calling mvn deploy (full logs at the bottom):

[INFO] BUILD FAILURE

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project xbnjava: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized. -> [Help 1]

According to this sonatype support page:

"If you are receiving a 401 it is because maven is sending the wrong login credentials, or no credentials at all."

Below are the steps I've taken, below that are my full settings.xml and pom.xml files, and below that are the full logs from mvn deploy and mvn deploy -e.

Any ideas would be appreciated. I am just hitting wall after wall with Maven.

I followed sonatype's checklist when receiving a 401 error:

Checklist item 1. Make sure your username/password is correct by logging into the Nexus UI. If curl is installed on your machine, you can try deploying an artifact with...

I successfully logged in and out of the sonatype.org website, using the user/pass in settings.xml.

I attempted to use curl to manually deploy an artifact, with the command

[C:\]curl -u MY_SONATYPE_DOT_COM_USERNAME:MY_SONATYPE_DOT_COM_PASSWORD https://oss.sonatype.org/content/repositories/snapshots/com/github/aliteralmind/xbnjava/0.1.2-SNAPSHOT/xbnjava-0.1.2-20140716.224928-1.pom --request PUT --data @pom.xml

but got this error:

Warning: Couldn't read data from file "pom.xml", this makes an empty POST.
curl: (60) SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.

I ran it again with the -k option, and this time got only this:

Couldn't read data from file "pom.xml", this makes an empty POST.

I've never used curl before, so I'm at a loss on what to do with this information.

Checklist item 2. If there is no error output, ensure your user privileges are correctly configured on the server.  Make sure to drop the repo you just created.

I don't know what "drop" means. I believe my privileges are properly installed, as I received this message from sonatype:

Configuration has been prepared, now you can:

Deploy snapshot artifacts into repository https://oss.sonatype.org/content/repositories/snapshots

Deploy release artifacts into the staging repository https://oss.sonatype.org/service/local/staging/deploy/maven2

Promote staged artifacts into repository 'Releases'

Download snapshot and release artifacts from group https://oss.sonatype.org/content/groups/public

Download snapshot, release and staged artifacts from staging group https://oss.sonatype.org/content/groups/staging

and I have successfully put these items onto the server via mvn deploy in the past couple days.

The project's settings:

Checklist item 3. Make sure you have configured a server in settings.xml and that the server id is identical to the distribution repository id in pom.xml.

In settings.xml, settings/servers/server/id equals ossrh

In pom.xml, distributionManagement/snapshotRepository/id equals ossrh

(full files are at the bottom)

Checklist item 4. Make sure your settings.xml is in the correct place (normally it’s _~/.m2/settings.xml).  You can check this by running mvn help:effective-settings.

According to Maven's settings reference, settings.xml must be in one of two locations:

The Maven install: $M2_HOME/conf/settings.xml

A user’s install: ${user.home}/.m2/settings.xml

Here's my setup:

settings.xml: C:\applications\programming\apache-maven-3.2.2\conf\settings.xml

M2_HOME is C:\applications\programming\apache-maven-3.2.2

Output for mvn help:effective-settings:

[C:\applications\utilities\curl]
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-help-plugin:2.2:effective-settings (default-cli) @ standalone-pom ---
[INFO]
Effective user-specific configuration settings:

<?xml version="1.0" encoding="UTF-8"?>

<settings xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:sc
hemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
  <localRepository xmlns="http://maven.apache.org/SETTINGS/1.1.0">C:\Users\jeffy\.m2\repository</localRepository
>
  <servers xmlns="http://maven.apache.org/SETTINGS/1.1.0">
    <server>
      <username>MY_SONATYPE_DOT_COM_USERNAME</username>
      <password>***</password>
      <id>ossrh</id>
    </server>
  </servers>
  <pluginGroups xmlns="http://maven.apache.org/SETTINGS/1.1.0">
    <pluginGroup>org.apache.maven.plugins</pluginGroup>
    <pluginGroup>org.codehaus.mojo</pluginGroup>
  </pluginGroups>
</settings>

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.310 s
[INFO] Finished at: 2014-07-18T12:48:19-04:00
[INFO] Final Memory: 7M/17M
[INFO] ------------------------------------------------------------------------

Checklist item 5. If the server is using https but the URL in your POM is http, you might get 401 as well.

I don't understand which url it's referring to.

Checklist item 6. Use the latest version of Maven, as there is a known issue regarding 401: MNG-4469

I am using the latest version:

[C:\]mvn -version
Apache Maven 3.2.2 (45f7c06d68e745d05611f7fd14efb6594181933e; 2014-06-17T09:51:42-04:00)
Maven home: C:\applications\programming\apache-maven-3.2.2
Java version: 1.7.0_51, vendor: Oracle Corporation
Java home: C:\applications\programming\jdk_7_51\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "x86", family: "windows"

------------------

Full settings.xml and pom.xml files

(Full logs for mvn deploy and mvn deploy -e below)

settings.xml:

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
   <servers>
     <server>
       <id>ossrh</id>
       <username>MY_SONATYPE_DOT_COM_USERNAME</username>
       <password>MY_SONATYPE_DOT_COM_PASSWORD</password>
     </server>
   </servers>

   <pluginGroups></pluginGroups>
   <proxies></proxies>
   <mirrors></mirrors>
   <profiles></profiles>
</settings>

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.github.aliteralmind</groupId>
   <artifactId>xbnjava</artifactId>
   <packaging>pom</packaging>
   <version>0.1.2</version>
   <name>XBN-Java</name>
   <url>https://github.com/aliteralmind/xbnjava</url>
   <inceptionYear>2014</inceptionYear>
   <organization>
      <name>Jeff Epstein</name>
   </organization>
   <description>XBN-Java is a collection of generically-useful backend (server side, non-GUI) programming utilities, featuring RegexReplacer and FilteredLineIterator. XBN-Java is the foundation of Codelet (http://codelet.aliteralmind.com).</description>

   <parent>
      <groupId>org.sonatype.oss</groupId>
      <artifactId>oss-parent</artifactId>
      <version>7</version>
   </parent>

   <licenses>
      <license>
         <name>Lesser General Public License (LGPL) version 3.0</name>
         <url>https://www.gnu.org/licenses/lgpl-3.0.txt</url>
      </license>
      <license>
         <name>Apache Software License (ASL) version 2.0</name>
         <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      </license>
   </licenses>

   <developers>
      <developer>
         <name>Jeff Epstein</name>
         <email>aliteralmind-github@yahoo.com</email>
         <roles>
            <role>Lead Developer</role>
         </roles>
      </developer>
   </developers>

   <issueManagement>
      <system>GitHub Issue Tracker</system>
      <url>https://github.com/aliteralmind/xbnjava/issues</url>
   </issueManagement>

   <distributionManagement>
      <snapshotRepository>
         <id>ossrh</id>
         <url>https://oss.sonatype.org/content/repositories/snapshots</url>
      </snapshotRepository>
   </distributionManagement>

   <scm>
      <connection>scm:git:git@github.com:aliteralmind/xbnjava.git</connection>
      <url>scm:git:git@github.com:aliteralmind/xbnjava.git</url>
      <developerConnection>scm:git:git@github.com:aliteralmind/xbnjava.git</developerConnection>
   </scm>

   <properties>
      <java.version>1.7</java.version>
      <jarprefix>R:\jeffy\programming\build\/${project.artifactId}-${project.version}/download/${project.artifactId}-${project.version}</jarprefix>
   </properties>

   <build>
      <plugins>
         <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>build-helper-maven-plugin</artifactId>
            <version>1.8</version>
            <executions>
               <execution>
                  <id>attach-artifacts</id>
                  <phase>package</phase>
                  <goals>
                     <goal>attach-artifact</goal>
                  </goals>
                  <configuration>
                     <artifacts>
                        <artifact>
                           <file>${jarprefix}-all.jar</file>
                           <type>jar</type>
                        </artifact>
                     </artifacts>
                  </configuration>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </build>

   <profiles>

      <profile>
         <id>release-sign-artifacts</id>
         <activation>
            <property>
               <name>release</name>
               <value>true</value>
            </property>
         </activation>
      </profile>
   </profiles>
</project>

------------------

Full logs for mvn deploy and mvn deploy -e

mvn deploy output:

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building XBN-Java 0.1.2
[INFO] ------------------------------------------------------------------------
[INFO] --- maven-enforcer-plugin:1.0:enforce (enforce-maven) @ xbnjava ---
[INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava ---
[INFO] --- maven-install-plugin:2.4:install (default-install) @ xbnjava ---
[INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\pom.xml to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.2\xbnjava-0.1.2.pom
[INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.2\download\xbnjava-0.1.2-all.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.2\xbnjava-0.1.2.jar
[INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ xbnjava ---
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom
2/6 KB
4/6 KB
6/6 KB

(Failure section:)

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.204 s
[INFO] Finished at: 2014-07-18T11:25:17-04:00
[INFO] Final Memory: 7M/17M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project xbnjava: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

mvn deploy -e output:

[INFO] Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building XBN-Java 0.1.2
[INFO] ------------------------------------------------------------------------
[INFO] --- maven-enforcer-plugin:1.0:enforce (enforce-maven) @ xbnjava ---
[INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava ---
[INFO] --- maven-install-plugin:2.4:install (default-install) @ xbnjava ---
[INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\pom.xml to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.2\xbnjava-0.1.2.pom
[INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.2\download\xbnjava-0.1.2-all.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.2\xbnjava-0.1.2.jar
[INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ xbnjava ---
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom
2/6 KB
4/6 KB
6/6 KB

(Failure section:)

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.492 s
[INFO] Finished at: 2014-07-18T11:25:37-04:00
[INFO] Final Memory: 7M/17M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project xbnjava: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized. -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on project xbnjava: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)
   at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
   at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
   at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
   at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
   at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
   at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:120)
   at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:347)
   at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:154)
   at org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)
   at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:213)
   at org.apache.maven.cli.MavenCli.main(MavenCli.java:157)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
   at java.lang.reflect.Method.invoke(Method.java:606)
   at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
   at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
   at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
   at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.apache.maven.plugin.deploy.DeployMojo.execute(DeployMojo.java:193)
   at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:132)
   at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
   ... 19 more
Caused by: org.apache.maven.artifact.deployer.ArtifactDeploymentException: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.apache.maven.artifact.deployer.DefaultArtifactDeployer.deploy(DefaultArtifactDeployer.java:143)
   at org.apache.maven.plugin.deploy.AbstractDeployMojo.deploy(AbstractDeployMojo.java:167)
   at org.apache.maven.plugin.deploy.DeployMojo.execute(DeployMojo.java:149)
   ... 21 more
Caused by: org.eclipse.aether.deployment.DeploymentException: Failed to deploy artifacts: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.eclipse.aether.internal.impl.DefaultDeployer.deploy(DefaultDeployer.java:337)
   at org.eclipse.aether.internal.impl.DefaultDeployer.deploy(DefaultDeployer.java:268)
   at org.eclipse.aether.internal.impl.DefaultRepositorySystem.deploy(DefaultRepositorySystem.java:413)
   at org.apache.maven.artifact.deployer.DefaultArtifactDeployer.deploy(DefaultArtifactDeployer.java:139)
   ... 23 more
Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Could not transfer artifact com.github.aliteralmind:xbnjava:pom:0.1.2 from/to sonatype-nexus-staging (https://oss.sonatype.org/service/local/staging/deploy/maven2/): Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.eclipse.aether.connector.wagon.WagonRepositoryConnector$6.wrap(WagonRepositoryConnector.java:1016)
   at org.eclipse.aether.connector.wagon.WagonRepositoryConnector$6.wrap(WagonRepositoryConnector.java:1004)
   at org.eclipse.aether.connector.wagon.WagonRepositoryConnector$PutTask.run(WagonRepositoryConnector.java:895)
   at org.eclipse.aether.connector.wagon.WagonRepositoryConnector.put(WagonRepositoryConnector.java:522)
   at org.eclipse.aether.internal.impl.DefaultDeployer.deploy(DefaultDeployer.java:331)
   ... 26 more
Caused by: org.apache.maven.wagon.TransferFailedException: Failed to transfer file: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.2/xbnjava-0.1.2.pom. Return code is: 401, ReasonPhrase: Unauthorized.
   at org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:573)
   at org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:493)
   at org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:474)
   at org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.put(AbstractHttpClientWagon.java:454)
   at org.eclipse.aether.connector.wagon.WagonRepositoryConnector$PutTask.run(WagonRepositoryConnector.java:871)
   ... 28 more
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException


问:
Django | HTML Render Issue | Querying Issue | Models | Views
In the html file I am trying to render the Remove button. If I just printout out the {{combo}} it renders out. But if I try to query it based on the cart model it doesn't render the button. I also tried querying it like this {% if combo in cart.combo_item.combo.all %} but it didn't work.

update-cart.html

```<code><form method="POST" action="{% url 'carts:combo_add_to_cart' %}" class="form">
    {% csrf_token %}
    <input type="hidden" name="combo_id" value="{{ combo.id }}">
    <button type="submit" class="btn btn-success">Add to Cart</button>
    {% if combo in cart.combo_item.all %}
        <button type="submit" class="btn btn-success">Remove?</button>
    {% endif %}
</form>
{{combo}}
</code>```

cart.models

```<code>class ComboCartItem(models.Model):
    user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    combo = models.ForeignKey(Combo, blank=True, null=True, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    ordered = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.quantity} of {self.combo.combo}"

class Cart(models.Model):
    user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    combo_item = models.ManyToManyField(ComboCartItem, blank=True, null=True)
    addon_item = models.ManyToManyField(AddonCartItem, blank=True, null=True)
    ordered = models.BooleanField(default=False)

    cart_total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)

    objects = CartManager()

    def __str__(self):
        return str(self.id)
</code>```

combo.models

```<code>class Combo(models.Model):
    title = models.CharField(max_length=120)
    combo_regular_price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00)
    combo_sale_price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00)
    timestamp = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(blank=True, null=True)
    active = models.BooleanField(default=True)

    objects = ComboManager()

    def __str__(self):
        return self.title
</code>```

views.py

```<code>class ComboList(ListView):
    template_name = 'products/list.html'

    def get_context_data(self, *args, **kwargs):
        context = super(ComboList, self).get_context_data(*args, **kwargs)
        cart_obj, new_obj = Cart.objects.new_or_get(self.request)
        context['cart'] = cart_obj
        return context

    def get_queryset(self, *args, **kwargs):
        request = self.request
        combo = Combo.objects.all()
        return combo
</code>```

答:
I think the problem is in the first part of the condition (the if combo in...). I would interpret it in the template as "is the value of my variable {{combo}} contained in this list?".

From what I understand, you want to check not only that the combo_list is not empty, but that at least one item of the list has the Combo property assigned. Maybe you could do this traversing the list and using a temporary variable, but Django best practices recommend that you keep all the logic away from the template.

The best option is to define a property in your cart model, and use that from your template. It will also make the template more readable. So you would do:

```<code>class Cart(models.Model):
    ...

    @property
    def is_empty(self):
         return self.combo_item.filter(combo__isnull=False).exists()
</code>```

And then, use this property in your template:

```<code>{% if not cart.is_empty %}
    <button type="submit" class="btn btn-success">Remove?</button>
{% endif %}
</code>```

Body:
In the html file I am trying to render the Remove button. If I just printout out the {{combo}} it renders out. But if I try to query it based on the cart model it doesn't render the button. I also tried querying it like this {% if combo in cart.combo_item.combo.all %} but it didn't work.

update-cart.html

<form method="POST" action="{% url 'carts:combo_add_to_cart' %}" class="form">
    {% csrf_token %}
    <input type="hidden" name="combo_id" value="{{ combo.id }}">
    <button type="submit" class="btn btn-success">Add to Cart</button>
    {% if combo in cart.combo_item.all %}
        <button type="submit" class="btn btn-success">Remove?</button>
    {% endif %}
</form>
{{combo}}

cart.models

class ComboCartItem(models.Model):
    user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    combo = models.ForeignKey(Combo, blank=True, null=True, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    ordered = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.quantity} of {self.combo.combo}"

class Cart(models.Model):
    user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    combo_item = models.ManyToManyField(ComboCartItem, blank=True, null=True)
    addon_item = models.ManyToManyField(AddonCartItem, blank=True, null=True)
    ordered = models.BooleanField(default=False)

    cart_total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)

    objects = CartManager()

    def __str__(self):
        return str(self.id)

combo.models

class Combo(models.Model):
    title = models.CharField(max_length=120)
    combo_regular_price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00)
    combo_sale_price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00)
    timestamp = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(blank=True, null=True)
    active = models.BooleanField(default=True)

    objects = ComboManager()

    def __str__(self):
        return self.title

views.py

class ComboList(ListView):
    template_name = 'products/list.html'

    def get_context_data(self, *args, **kwargs):
        context = super(ComboList, self).get_context_data(*args, **kwargs)
        cart_obj, new_obj = Cart.objects.new_or_get(self.request)
        context['cart'] = cart_obj
        return context

    def get_queryset(self, *args, **kwargs):
        request = self.request
        combo = Combo.objects.all()
        return combo

Body:
I think the problem is in the first part of the condition (the if combo in...). I would interpret it in the template as "is the value of my variable {{combo}} contained in this list?".

From what I understand, you want to check not only that the combo_list is not empty, but that at least one item of the list has the Combo property assigned. Maybe you could do this traversing the list and using a temporary variable, but Django best practices recommend that you keep all the logic away from the template.

The best option is to define a property in your cart model, and use that from your template. It will also make the template more readable. So you would do:

class Cart(models.Model):
    ...

    @property
    def is_empty(self):
         return self.combo_item.filter(combo__isnull=False).exists()

And then, use this property in your template:

{% if not cart.is_empty %}
    <button type="submit" class="btn btn-success">Remove?</button>
{% endif %}


问:
Show
 without JS
I have a very, very simple webpage, It consists of a large background image and a button in the centre of this image (the button is placed in a div to position it), I want this button to be clickable, and when clicked, replaced with ANOTHER div which will show a film trailer.

Every solution I come across implements JS and is to show/hide the div and does not replace the show/hide button.

I simply want to SHOW the div, it does not need to be hidden after (as the button will hopefully be replaced anyway).

Almost identical to this example on the Duke Nukem website : http://www.dukenukemforever.com/full/us/

When you click play trailer, it appears central. The only difference between this and what I want to do is I want my button to be central also, and show the trailer over the top of the button (with no ability to hide the trailer after it has begun)

If any one is wondering why I don't just put the trailer on the page and not bother with this is the reason for having it 'show' instead of just embedding the video in a div in the center of the page is that the webpage has a large background which I want to be visible first for impact, then show the trailer.

if this is possible in JS and someone can show me an example, I would be open to that too!

答:
Could you not use CSS with:

```<code>div.button:active {
   visibility:visible;
}
</code>```

You could also use CSS expressions I'm sure, expressions, however, are deprecated and hardly supported.

Title: Show <div> without JS

Body:
Could you not use CSS with:

div.button:active {
   visibility:visible;
}

You could also use CSS expressions I'm sure, expressions, however, are deprecated and hardly supported.


问:
How do you load array and object from Cloud Firestore in Flutter
I have a class that has several embedded arrays as well as a couple of objects. I'm using Flutter and can't figure out how to read/write to Cloud Firestore.

I can read/write data members that are default types like String and Int. Here is the constructor I'm trying to use to instantiate an object from a DocumentSnapshot:

```<code> class GameReview {
   String name;
   int howPopular;
   List<String> reviewers;
 }

 class ItemCount {
   int itemType;
   int count;

   ItemCount.fromMap(Map<dynamic, dynamic> data)
       : itemType = data['itemType'],
         count = data['count'];
 }

 class GameRecord {
   // Header members
   String documentID;
   String name;
   int creationTimestamp;
   List<int> ratings = new List<int>();
   List<String> players = new List<String>();
   GameReview gameReview;
   List<ItemCount> itemCounts = new List<ItemCount>();

   GameRecord.fromSnapshot(DocumentSnapshot snapshot)
       : documentID = snapshot.documentID,
         name = snapshot['name'],
         creationTimestamp = snapshot['creationTimestamp'],
         ratings = snapshot['ratings'], // ERROR on run
         players = snapshot['players'], // ERROR on run
         gameReview = snapshot['gameReview']; // ERROR on run
         itemCount = ????
 }
</code>```

It works until I add the last 3 members (ratings, players and gameReview). This should be obvious but none the less, it eludes me.

Help!

UPDATE:
Here is a sample of the document stored in Cloud Firestore. This is stored in a single document. In other words, I'm not using sub-collections for the embedded objects. I put it into a JSON format for clarity. I hope this helps.

```<code> {
   "documentID": "asd8didjeurkff3",
   "name": "My Game Record",
   "creationTimestamp": 1235434,
   "ratings": [
     4,
     2012,
     4
   ],
   "players": [
     "Fred",
     "Sue",
     "John"
   ],
   "gameReview": {
     "name": "Review 1",
     "howPopular": 5,
     "reviewers": [
       "Bob",
       "Hanna",
       "George"
     ]
   },
  "itemCounts": [
     {
       "itemType": 2,
       "count": 3
     },
     {
       "itemType": 1,
       "count": 2
     }
   ]
 }
</code>```

UPDATE 2:
I didn't put in the whole class definition because I thought it would be obvious to me how to do the rest but alas that was not the case.

I have a list of objects that I want to load.vbandrade's answer is BANG on but I can't quite figure out how I'm supposed to create the list of objects.  List.from(...) is looking for an iterator, not a created class. I'm sure it's some variation of creating a new object and then adding it to a list but I'm a little confused. (see edits in class above, specifically, the "itemCounts" member.

答:
If you came here because of List<dynamic> is not of type List<someType> error while reading data from firestore, you can just use List.castFrom

Example:
List<String> cards = List.castFrom(cardsListFromFirebase);

Checkout Flutter firebase, List<dynamic> is not of type List<String>

Body:
I have a class that has several embedded arrays as well as a couple of objects. I'm using Flutter and can't figure out how to read/write to Cloud Firestore.

I can read/write data members that are default types like String and Int. Here is the constructor I'm trying to use to instantiate an object from a DocumentSnapshot:

 class GameReview {
   String name;
   int howPopular;
   List<String> reviewers;
 }

 class ItemCount {
   int itemType;
   int count;

   ItemCount.fromMap(Map<dynamic, dynamic> data)
       : itemType = data['itemType'],
         count = data['count'];
 }

 class GameRecord {
   // Header members
   String documentID;
   String name;
   int creationTimestamp;
   List<int> ratings = new List<int>();
   List<String> players = new List<String>();
   GameReview gameReview;
   List<ItemCount> itemCounts = new List<ItemCount>();

   GameRecord.fromSnapshot(DocumentSnapshot snapshot)
       : documentID = snapshot.documentID,
         name = snapshot['name'],
         creationTimestamp = snapshot['creationTimestamp'],
         ratings = snapshot['ratings'], // ERROR on run
         players = snapshot['players'], // ERROR on run
         gameReview = snapshot['gameReview']; // ERROR on run
         itemCount = ????
 }

It works until I add the last 3 members (ratings, players and gameReview). This should be obvious but none the less, it eludes me.

Help!

UPDATE:
Here is a sample of the document stored in Cloud Firestore. This is stored in a single document. In other words, I'm not using sub-collections for the embedded objects. I put it into a JSON format for clarity. I hope this helps.

 {
   "documentID": "asd8didjeurkff3",
   "name": "My Game Record",
   "creationTimestamp": 1235434,
   "ratings": [
     4,
     2012,
     4
   ],
   "players": [
     "Fred",
     "Sue",
     "John"
   ],
   "gameReview": {
     "name": "Review 1",
     "howPopular": 5,
     "reviewers": [
       "Bob",
       "Hanna",
       "George"
     ]
   },
  "itemCounts": [
     {
       "itemType": 2,
       "count": 3
     },
     {
       "itemType": 1,
       "count": 2
     }
   ]
 }

UPDATE 2:
I didn't put in the whole class definition because I thought it would be obvious to me how to do the rest but alas that was not the case.

I have a list of objects that I want to load.vbandrade's answer is BANG on but I can't quite figure out how I'm supposed to create the list of objects.  List.from(...) is looking for an iterator, not a created class. I'm sure it's some variation of creating a new object and then adding it to a list but I'm a little confused. (see edits in class above, specifically, the "itemCounts" member.


问:
Centre of mass row-wise in a dataframe and multiply each column by different mass
I'm trying to calculate the centre of mass of 20 objects, where each object has it's own different mass.

These objects are represented in a dataframe cm_x, and their associated masses in a list. Below I show an example of just 3 of those 20 objects, for the sake of saving space. Each object has an x, y, z coordinate, but I'll just show the x and then I can apply the same technique to the rest. Below is the head of the dataframe.

```<code>bar_head_x  bar_hip_centre_x    bar_left_ankle_x
0   -203.3502   -195.4573   -293.262
1   -203.4280   -195.4720   -293.251
2   -203.4954   -195.4675   -293.248
3   -203.5022   -195.9193   -293.219
4   -203.5014   -195.9092   -293.328

m_head = 0.081
m_hipc = 0.139
m_lank = 0.0465
m = [m_head,m_hipc,m_lank]
</code>```

I saw in another similar question, someone has suggested this method, however this doesn't incorporate the masses, and that is where I'm having an issue:

```<code>def series_sum(pd_series):
    return np.sum(np.dot(pd_series.values, np.asarray(range(1, len(pd_series)+1)))/np.sum(pd_series))

cm_x.apply(series_sum, axis=1)
</code>```

Basically I want for each row, to have an associated centre of mass, using the formula for centre of mass which is sum(x_i * m_i) / sum(m_i).

The desired result would be a new column in the dataframe like so:

```<code>cm_x
0   -214.92
1   ...
2   ...
3   ...
4   ...
</code>```

Any help?

Body:
I'm trying to calculate the centre of mass of 20 objects, where each object has it's own different mass.

These objects are represented in a dataframe cm_x, and their associated masses in a list. Below I show an example of just 3 of those 20 objects, for the sake of saving space. Each object has an x, y, z coordinate, but I'll just show the x and then I can apply the same technique to the rest. Below is the head of the dataframe.

bar_head_x  bar_hip_centre_x    bar_left_ankle_x
0   -203.3502   -195.4573   -293.262
1   -203.4280   -195.4720   -293.251
2   -203.4954   -195.4675   -293.248
3   -203.5022   -195.9193   -293.219
4   -203.5014   -195.9092   -293.328

m_head = 0.081
m_hipc = 0.139
m_lank = 0.0465
m = [m_head,m_hipc,m_lank]

I saw in another similar question, someone has suggested this method, however this doesn't incorporate the masses, and that is where I'm having an issue:

def series_sum(pd_series):
    return np.sum(np.dot(pd_series.values, np.asarray(range(1, len(pd_series)+1)))/np.sum(pd_series))

cm_x.apply(series_sum, axis=1)

Basically I want for each row, to have an associated centre of mass, using the formula for centre of mass which is sum(x_i * m_i) / sum(m_i).

The desired result would be a new column in the dataframe like so:

cm_x
0   -214.92
1   ...
2   ...
3   ...
4   ...

Any help?

Body:
If I understand correctly, you can compute the desired column like this:

>>> df.mul(m).sum(axis=1)/sum(m)
0   -214.921628
1   -214.951023
2   -214.968638
3   -215.201292
4   -215.214800


问:
Check dict from Json output (urllib2)
I am trying to pull specific data from json output using urllib2.
From the code and output below, I am trying to pull out specific value but i didn't manage to do that.

This is the URL itself:

```<code>baseURIs: [
{
service: "true",
location: "alex",
URL: "barcelonat",
},
{
service: "false",
location: "daniel",
URL: "RealMadrid",
},
</code>```

This is the output from the json (using my code):

```<code>{u'URL': u'barcelona', u'location': u'alex', u'service': u'true'}
{u'URL': u'RealMadrid', u'location': u'daniel', u'service': u'false'}
</code>```

I am trying to search this dict and print "found it" if the string 'RealMadrid' is there.
Here is code:

```<code>#!/usr/bin/env python
import time
from datetime import datetime
import json
import urllib2
req = urllib2.Request('http://admin/alex/0.json')
response = urllib2.urlopen(req)
page = response.read()
user_dict = json.loads(page)
count = 0

for k in user_dict['baseURIs']:
    if 'RealMadrid' in k:
        print("Found it!")
</code>```

答:
You can access the values to compare them with your searchterm</p>

```<code>user_dict= {
    "baseURIs": [
    {
        "service": "true",
        "location": "alex",
        "URL": "barcelonat",
    },
    {
        "service": "false",
        "location": "daniel",
        "URL": "RealMadrid",
    }]
}

for key in user_dict['baseURIs']:
    if 'RealMadrid' in key.values():
        print("Found it!")
</code>```

Title: Check dict from Json output (urllib2)

Body:
I am trying to pull specific data from json output using urllib2.
From the code and output below, I am trying to pull out specific value but i didn't manage to do that.

This is the URL itself:

baseURIs: [
{
service: "true",
location: "alex",
URL: "barcelonat",
},
{
service: "false",
location: "daniel",
URL: "RealMadrid",
},

This is the output from the json (using my code):

{u'URL': u'barcelona', u'location': u'alex', u'service': u'true'}
{u'URL': u'RealMadrid', u'location': u'daniel', u'service': u'false'}

I am trying to search this dict and print "found it" if the string 'RealMadrid' is there.
Here is code:

#!/usr/bin/env python
import time
from datetime import datetime
import json
import urllib2
req = urllib2.Request('http://admin/alex/0.json')
response = urllib2.urlopen(req)
page = response.read()
user_dict = json.loads(page)
count = 0

for k in user_dict['baseURIs']:
    if 'RealMadrid' in k:
        print("Found it!")

Body:
You can access the values to compare them with your searchterm

user_dict= {
    "baseURIs": [
    {
        "service": "true",
        "location": "alex",
        "URL": "barcelonat",
    },
    {
        "service": "false",
        "location": "daniel",
        "URL": "RealMadrid",
    }]
}

for key in user_dict['baseURIs']:
    if 'RealMadrid' in key.values():
        print("Found it!")


问:
How to transform vue js html page into pdf
i was wondering if some of you experienced this problem, to generate pdf file from vue js or other js framework pdf file. I am not going to mention what libraries i tried, i am searching for a native way. Did some of you do something closer to this. The pdf needs to be generated from page that is is dropdowns and butons, so the functionality needs to remain in some way. Can you give me some proposals how to do it, with DOM or etc. </p>

答:
Where do you want to transform it into a pdf? On the server or in the browser?

In the browser, I'd recommend to simply allow the users to print it and use css to control what will be shown (using the print media query).
Then, instead of sending it to a printer, users can also choose to transform it into a pdf.

On the server you'll have to look for some libraries that offer this specific functionality and see which ones fit your usecase best.

Lastly, what do you mean with "the functionality needs to remain in some way"?
I'm not an expert in what PDFs can do, but they definitely cannot do enough to emulate a web-page – especially one that is complex enough to warrant using vue.js.
What exactly would you like to keep/have happen?


问:
Try to make PDF file with laravel-dompdf
when I will download the pdf, its just show 404 page and no file downloaded

view:

```<code><a href="/report/cetak_pdf" class="btn btn-primary" target="_blank">CETAK PDF</a>
        <div class="widget-title"> <span class="icon"><i class="icon-th"></i></span>
<?php
</code>```

controller :

```<code><?php

namespace App\Http\Controllers;

use App\Report_model;
use Illuminate\Support\Facades\Storage;
use Image;
use Illuminate\Http\Request;
use pdf;

class ReportController extends Controller
{
    public function index(){
        $menu_active=0;
        $order=Report_model::all();
        return view('backEnd.report.index',compact('menu_active','order'));
    }

    public function cetak_pdf()
    {
        $order=Report_model::all();
        $pdf = PDF::loadView('backEnd.report.pdf', $order);
        return $pdf->download('report.pdf');
    }

}
</code>```

route:

```<code>Route::resource('/report','ReportController');
Route::get('/report/cetak_pdf', 'PegawaiController@cetak_pdf');
</code>```

I tried Googling a lot but I am really lost at this point, can someone be so kind to point a lost developer in the right direction? :) Thank you for your time in advance!

答:
your route in using PegawaiController which probably must be ReportController

```<code>Route::get('/report/cetak_pdf', 'ReportController@cetak_pdf');
</code>```

and change the order of the routes:

```<code>Route::get('/report/cetak_pdf', 'ReportController@cetak_pdf');
Route::resource('/report','ReportController');
</code>```

Body:
when I will download the pdf, its just show 404 page and no file downloaded

view:

CETAK PDF

<?php

controller :

<?php

namespace App\Http\Controllers;

use App\Report_model;
use Illuminate\Support\Facades\Storage;
use Image;
use Illuminate\Http\Request;
use pdf;

class ReportController extends Controller
{
    public function index(){
        $menu_active=0;
        $order=Report_model::all();
        return view('backEnd.report.index',compact('menu_active','order'));
    }

    public function cetak_pdf()
    {
        $order=Report_model::all();
        $pdf = PDF::loadView('backEnd.report.pdf', $order);
        return $pdf->download('report.pdf');
    }

}

route:

Route::resource('/report','ReportController');
Route::get('/report/cetak_pdf', 'PegawaiController@cetak_pdf');

I tried Googling a lot but I am really lost at this point, can someone be so kind to point a lost developer in the right direction? :) Thank you for your time in advance!

Body:
your route in using PegawaiController which probably must be ReportController

Route::get('/report/cetak_pdf', 'ReportController@cetak_pdf');

and change the order of the routes:

Route::get('/report/cetak_pdf', 'ReportController@cetak_pdf');
Route::resource('/report','ReportController');


问:
Git clone a clone but only update remote from 1st clone
I have this situation where I have 2 home computers but only 1 is allowed access to a remote machine which hosts the remote repository and for various reasons I can't do my work on this machine.

What I want to do is this:
remote repo -> clone 1 -> clone 2 (do my work), then
clone 2 -> clone 1 -> remote repo.

I want to work on clone 2, push to clone 1 then push clone 1 back to the remote repository.

I can do the clone of the clone, but when I try to push back to clone 1, I get an error stating that the master is checkedout and I cannot push to it.

What is the cleanest way to do what I am trying achieve, I am relatively new to git (my current solution is just to copy clone 1, do my changes then copy it back and update - but this causes all sorts of issues).

I have been using sourcetree & tortoisegit, but don't mind some command line work

Cheers

ice

答:
When you create Clone 1, use git clone --bare to create a bare repository. As you don't modify and commit files in Clone 1, it's not necessary to checkout a branch in Clone 1. A bare repository is enough to work as a transfer station.

If you do need a non-bare repository for Clone 1, run git config receive.denyCurrentBranch false in Clone 1 so that it won't stop you from pushing to a checked out branch. false could also be warn or ignore.

I'm not familiar with any git GUI, but I guess they support a bare clone and git config.