问:
.htaccess rules being overriden
I am currently having an issue with a website I am working on. I am forwarding one URL to another URL.

In my root folder, I have the following code:

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domaina.com
RewriteRule ^(.*) http://www.domainb.com/$1 [R=301,L]
</code>```

It's redirecting traffic as it is supposed to, except in one directory on the website > /shop

In the /shop directory, there is also an .htaccess file and it seems to be cancelling out what I have set in the root. Here are the contents of the .htaccess in the /shop directory:

```<code>RewriteEngine On
RewriteBase /shop/

RewriteRule ^enclosures-enclosure-guidelines-c-229_675.html$
/resources#nema-guidelines [L,R=301,NE]

#RewriteRule ^category/(.*)$ index.php?$cPath=$2
RewriteRule ^mc/(.*)$ mc.php?keywords=$1

RewriteRule ^(.*)-c-(.*)-p-(.*)$ product_info.php?cPath=$2&products_id=$3&%{QUERY_STRING}
RewriteRule ^(.*)-p-(.*)$ product_info.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-c-(.*)$ index.php?cPath=$2&%{QUERY_STRING}
RewriteRule ^(.*)-c2-(.*)$ index2.php?cPath=$2&%{QUERY_STRING}

RewriteRule ^(.*)-c-(.*)-p-(.*).html$ product_info.php?cPath=$2&products_id=$3&%{QUERY_STRING}
RewriteRule ^(.*)-p-(.*).html$ product_info.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-c-(.*).html$ index.php?cPath=$2&%{QUERY_STRING}
RewriteRule ^(.*)-m-(.*).html$ index.php?manufacturers_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-pi-(.*).html$ popup_image.php?pID=$2&%{QUERY_STRING}
RewriteRule ^(.*)-t-(.*).html$ articles.php?tPath=$2&%{QUERY_STRING}
RewriteRule ^(.*)-a-(.*).html$ article_info.php?articles_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-pr-(.*).html$ product_reviews.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-pri-(.*).html$ product_reviews_info.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-i-(.*).html$ information.php?info_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-links-(.*).html$ links.php?lPath=$2&%{QUERY_STRING}
</code>```

Any help would be appreciated.

答:
it seems to be cancelling out what I have set in the root"

That's how .htaccess files work. From the docs:

The configuration directives found in a .htaccess file are applied to
  the directory in which the .htaccess file is found, and to all
  subdirectories thereof. However, it is important to also remember that
  there may have been .htaccess files in directories higher up.
  Directives are applied in the order that they are found. Therefore, a
  .htaccess file in a particular directory may override directives found
  in .htaccess files found higher up in the directory tree. And those,
  in turn, may have overridden directives found yet higher up, or in the
  main server configuration file itself.

Title: .htaccess rules being overriden

Body:
I am currently having an issue with a website I am working on. I am forwarding one URL to another URL.

In my root folder, I have the following code:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domaina.com
RewriteRule ^(.*) http://www.domainb.com/$1 [R=301,L]

It's redirecting traffic as it is supposed to, except in one directory on the website > /shop

In the /shop directory, there is also an .htaccess file and it seems to be cancelling out what I have set in the root. Here are the contents of the .htaccess in the /shop directory:

RewriteEngine On
RewriteBase /shop/

RewriteRule ^enclosures-enclosure-guidelines-c-229_675.html$
/resources#nema-guidelines [L,R=301,NE]

#RewriteRule ^category/(.*)$ index.php?$cPath=$2
RewriteRule ^mc/(.*)$ mc.php?keywords=$1

RewriteRule ^(.*)-c-(.*)-p-(.*)$ product_info.php?cPath=$2&products_id=$3&%{QUERY_STRING}
RewriteRule ^(.*)-p-(.*)$ product_info.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-c-(.*)$ index.php?cPath=$2&%{QUERY_STRING}
RewriteRule ^(.*)-c2-(.*)$ index2.php?cPath=$2&%{QUERY_STRING}

RewriteRule ^(.*)-c-(.*)-p-(.*).html$ product_info.php?cPath=$2&products_id=$3&%{QUERY_STRING}
RewriteRule ^(.*)-p-(.*).html$ product_info.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-c-(.*).html$ index.php?cPath=$2&%{QUERY_STRING}
RewriteRule ^(.*)-m-(.*).html$ index.php?manufacturers_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-pi-(.*).html$ popup_image.php?pID=$2&%{QUERY_STRING}
RewriteRule ^(.*)-t-(.*).html$ articles.php?tPath=$2&%{QUERY_STRING}
RewriteRule ^(.*)-a-(.*).html$ article_info.php?articles_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-pr-(.*).html$ product_reviews.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-pri-(.*).html$ product_reviews_info.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-i-(.*).html$ information.php?info_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-links-(.*).html$ links.php?lPath=$2&%{QUERY_STRING}

Any help would be appreciated.


来源: stackexchange

问:
How to show an elements value in a vue modal?
I have several elements that are displayed as
 elements in a loop. For each element I want behavior such that when the element is clicked a modal box opens up. Inside the modal box I want contents that are specific to the element that was clicked.

The data below shows all the elements:

```<code>              {value: 10, name: "foo"},
              {value: 12, name: "bar"},
              {value: 14, name: "foobar"},
              {value: 22, name: "test"},
              {value: 1, name: "testtooo"},
              {value: 8, name: "something"}
</code>```

When I click on an element, I want to see the value property for it inside the modal box.

I've created a fiddle for this: https://jsfiddle.net/hvb9hvog/14/

Question

I've gotten the modal working, however, how can I show each elements value property inside the modal?

答:
I am sure there are multiple ways to go about this, but one way would be to create a new data property, let's call it value. When you @click the li you get it's value, set it to the value property and display that value property in the body of the modal ({{this.value}}).

You can have two @click methods, so create another one that updates the data property you just created, called value.

Here's a fiddle

Relevant code changes:

In your li element:

```<code><li v-for="request in filteredRequests">
    <a href="#" @click="showModal = true; setVal(request.value)">{{request.name}}</a>
</li>
</code>```

In your modal markup:

```<code><modal v-if="showModal" @close="showModal = false">
    <!--
    you can use custom content here to overwrite
    default content
    -->
    <h3 slot="header">custom header</h3>
    <div slot="body">
        {{this.value}}
    </div>
</modal>
</code>```

In vue data:

```<code>data: {
    requests:   [
        {value: 10, name: "foo"},
        {value: 12, name: "bar"},
        {value: 14, name: "foobar"},
        {value: 22, name: "test"},
        {value: 1, name: "testtooo"},
        {value: 8, name: "something"}
    ],
    num: 0,
    showModal: false,
    value: 9999999999
},
</code>```

In vue methods:

```<code>methods: {
    setVal(val) {
        this.value = val;
    }
},
</code>```

Vue.component('modal', {
  template: '#modal-template'
})
var vm = new Vue({
  el: "#app",
  data: {
    requests: [{
        value: 10,
        name: "foo"
      },
      {
        value: 12,
        name: "bar"
      },
      {
        value: 14,
        name: "foobar"
      },
      {
        value: 22,
        name: "test"
      },
      {
        value: 1,
        name: "testtooo"
      },
      {
        value: 8,
        name: "something"
      }

    ],
    num: 0,
    showModal: false,
    value: 9999999999
  },
  methods: {
    setVal(val) {
      this.value = val;
    }
  },
  computed: {
    c: function() {
      return `Slider Number: (${this.num})`
    },
    filteredRequests() {
      return this.requests.filter(r => r.value > this.num)
    }
  },
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal-mask {
  position: fixed;
  z-index: 9998;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .5);
  display: table;
  transition: opacity .3s ease;
}

.modal-wrapper {
  display: table-cell;
  vertical-align: middle;
}

.modal-container {
  width: 300px;
  margin: 0px auto;
  padding: 20px 30px;
  background-color: #fff;
  border-radius: 2px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, .33);
  transition: all .3s ease;
  font-family: Helvetica, Arial, sans-serif;
}

.modal-header h3 {
  margin-top: 0;
  color: #42b983;
}

.modal-body {
  margin: 20px 0;
}

.modal-default-button {
  float: right;
}

/*
 * The following styles are auto-applied to elements with
 * transition="modal" when their visibility is toggled
 * by Vue.js.
 *
 * You can easily play with the modal transition by editing
 * these styles.
 */

.modal-enter {
  opacity: 0;
}

.modal-leave-active {
  opacity: 0;
}

.modal-enter .modal-container,
.modal-leave-active .modal-container {
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

      色

        <input class="form-control" v-model="c" :style="{backgroundColor: c}" />

          <input type="range" min="0" max="360" v-model.number="num" />

              {{request.name}}

          <modal v-if="showModal" @close="showModal = false">

custom header

              {{this.value}}

          </modal>

```

ContentLicense: CC BY-SA 3.0

Body:
I have several elements that are displayed as
 elements in a loop. For each element I want behavior such that when the element is clicked a modal box opens up. Inside the modal box I want contents that are specific to the element that was clicked.

The data below shows all the elements:

              {value: 10, name: "foo"},
              {value: 12, name: "bar"},
              {value: 14, name: "foobar"},
              {value: 22, name: "test"},
              {value: 1, name: "testtooo"},
              {value: 8, name: "something"}

When I click on an element, I want to see the value property for it inside the modal box.

I've created a fiddle for this: https://jsfiddle.net/hvb9hvog/14/

Question

I've gotten the modal working, however, how can I show each elements value property inside the modal?

Body:
I am sure there are multiple ways to go about this, but one way would be to create a new data property, let's call it value. When you @click the li you get it's value, set it to the value property and display that value property in the body of the modal ({{this.value}}).

You can have two @click methods, so create another one that updates the data property you just created, called value.

Here's a fiddle

Relevant code changes:

In your li element:

<li v-for="request in filteredRequests">
    <a href="#" @click="showModal = true; setVal(request.value)">{{request.name}}</a>
</li>

In your modal markup:

<modal v-if="showModal" @close="showModal = false">
    <!--
    you can use custom content here to overwrite
    default content
    -->
    <h3 slot="header">custom header</h3>
    <div slot="body">
        {{this.value}}
    </div>
</modal>

In vue data:

data: {
    requests:   [
        {value: 10, name: "foo"},
        {value: 12, name: "bar"},
        {value: 14, name: "foobar"},
        {value: 22, name: "test"},
        {value: 1, name: "testtooo"},
        {value: 8, name: "something"}
    ],
    num: 0,
    showModal: false,
    value: 9999999999
},

In vue methods:

methods: {
    setVal(val) {
        this.value = val;
    }
},

Vue.component('modal', {
  template: '#modal-template'
})
var vm = new Vue({
  el: "#app",
  data: {
    requests: [{
        value: 10,
        name: "foo"
      },
      {
        value: 12,
        name: "bar"
      },
      {
        value: 14,
        name: "foobar"
      },
      {
        value: 22,
        name: "test"
      },
      {
        value: 1,
        name: "testtooo"
      },
      {
        value: 8,
        name: "something"
      }

    ],
    num: 0,
    showModal: false,
    value: 9999999999
  },
  methods: {
    setVal(val) {
      this.value = val;
    }
  },
  computed: {
    c: function() {
      return `Slider Number: (${this.num})`
    },
    filteredRequests() {
      return this.requests.filter(r => r.value > this.num)
    }
  },
});

.modal-mask {
  position: fixed;
  z-index: 9998;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .5);
  display: table;
  transition: opacity .3s ease;
}

.modal-wrapper {
  display: table-cell;
  vertical-align: middle;
}

.modal-container {
  width: 300px;
  margin: 0px auto;
  padding: 20px 30px;
  background-color: #fff;
  border-radius: 2px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, .33);
  transition: all .3s ease;
  font-family: Helvetica, Arial, sans-serif;
}

.modal-header h3 {
  margin-top: 0;
  color: #42b983;
}

.modal-body {
  margin: 20px 0;
}

.modal-default-button {
  float: right;
}

/*
 * The following styles are auto-applied to elements with
 * transition="modal" when their visibility is toggled
 * by Vue.js.
 *
 * You can easily play with the modal transition by editing
 * these styles.
 */

.modal-enter {
  opacity: 0;
}

.modal-leave-active {
  opacity: 0;
}

.modal-enter .modal-container,
.modal-leave-active .modal-container {
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://unpkg.com/vue@2.3.4/dist/vue.js"></script>
<script type="text/x-template" id="modal-template">
  <transition name="modal">
    <div class="modal-mask">
      <div class="modal-wrapper">
        <div class="modal-container">

          <div class="modal-header">
            <slot name="header">
              default header
            </slot>
          </div>

          <div class="modal-body">
            <slot name="body">
              default body
            </slot>
          </div>

          <div class="modal-footer">
            <slot name="footer">
              default footer
              <button class="modal-default-button" @click="$emit('close')">
                OK
              </button>
            </slot>
          </div>
        </div>
      </div>
    </div>
  </transition>
</script>
<div id="app">
  <div class="form-horizontal">
    <div class="form-group">
      <label class="col-md-2 control-label">色</label>
      <div class="col-md-10">
        <input class="form-control" v-model="c" :style="{backgroundColor: c}" />
        <div class="help-block">
          <input type="range" min="0" max="360" v-model.number="num" />
          <ul class="ml-thumbs">
            <li v-for="request in filteredRequests">
              <a href="#" @click="showModal = true; setVal(request.value)">{{request.name}}</a>
            </li>
          </ul>
          <modal v-if="showModal" @close="showModal = false">
            <!--
            you can use custom content here to overwrite
            default content
          -->
            <h3 slot="header">custom header</h3>
            <div slot="body">
              {{this.value}}
            </div>
          </modal>
        </div>
      </div>
    </div>
  </div>
</div>


问:
Break <option> items in loop
I am trying to loop 100 values from an API into a dropdown list. When the function runs the page loads all 100 values but inserts them into the list on 1 line, rather than on 100 separate lines. I have tried adding a break tag to the loop but that didn't work.
How do you separate each item onto its own line?

// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
    // var xhr = new XMLHttpRequest();
    // xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
    // xhr.onreadystatechange = function() {
    //      if (xhr.readyState == 4 && xhr.status == 200) {
    //          var items = JSON.parse(xhr.responseText);
                var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
                var output = '<select>'
                for (var i in items) {
                    output += '<option>' + items[i].address + '</option>
'
                }
                output += '</select>'
                document.getElementById("replaceOption").innerHTML = output
    //      }
    // }
    // xhr.send();
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <script src="stations.js"></script>
    <title></title>
</head>
<body onload="addressList()">
    <div>
        <div id="addressDropdown">
            <form>
                <select>
                    <option id="addressList" value="select station" selected="selected">Select Station..</option>
                    <option id="replaceOption">0</option>
                </select>
                <br>
                <input type="submit" value="Go" id="sumbit" href="#">
            </form>
        </div>
    </div>
</body>
</html></code>```

答:
Append your options to the select element it's self. The reason why it's all on one line is because you're adding the new options inside an existing option rather than appending them after the existing option.

// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
    var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
    for (var i in items) {
        document.getElementById("mySelect").innerHTML += '<option>' + items[i].address + '</option>';
    }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <script src="stations.js"></script>
    <title></title>
</head>
<body onload="addressList()">
    <div>
        <div id="addressDropdown">
            <form>
                <select id="mySelect">
                    <option id="addressList" value="select station" selected="selected">Select Station..</option>
                    <option id="replaceOption">0</option>
                </select>
                <br>
                <input type="submit" value="Go" id="sumbit" href="#">
            </form>
        </div>
    </div>
</body>
</html></code>```

Title: Break <option> items in loop

Body:
I am trying to loop 100 values from an API into a dropdown list. When the function runs the page loads all 100 values but inserts them into the list on 1 line, rather than on 100 separate lines. I have tried adding a break tag to the loop but that didn't work.
How do you separate each item onto its own line?

// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
    // var xhr = new XMLHttpRequest();
    // xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
    // xhr.onreadystatechange = function() {
    //      if (xhr.readyState == 4 && xhr.status == 200) {
    //          var items = JSON.parse(xhr.responseText);
                var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
                var output = '<select>'
                for (var i in items) {
                    output += '<option>' + items[i].address + '</option>
'
                }
                output += '</select>'
                document.getElementById("replaceOption").innerHTML = output
    //      }
    // }
    // xhr.send();
};

<!DOCTYPE html>

    <title></title>

            <form>
                <select>
                    <option id="addressList" value="select station" selected="selected">Select Station..</option>
                    <option id="replaceOption">0</option>
                </select>

                <input type="submit" value="Go" id="sumbit" href="#">
            </form>

Body:
Append your options to the select element it's self. The reason why it's all on one line is because you're adding the new options inside an existing option rather than appending them after the existing option.

// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
    var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
    for (var i in items) {
        document.getElementById("mySelect").innerHTML += '<option>' + items[i].address + '</option>';
    }
};

<!DOCTYPE html>
<html>
<head>
    <script src="stations.js"></script>
    <title></title>
</head>
<body onload="addressList()">
    <div>
        <div id="addressDropdown">
            <form>
                <select id="mySelect">
                    <option id="addressList" value="select station" selected="selected">Select Station..</option>
                    <option id="replaceOption">0</option>
                </select>
                <br>
                <input type="submit" value="Go" id="sumbit" href="#">
            </form>
        </div>
    </div>
</body>
</html>


问:
Xamarin Can not compile using Android version 7
I Can not compile using Android version 7.
I want to get a plan for Android 7 in the 2015 Visual Studio.
I have installed sdk completely, installed Java Development Kit 1.8.0.92
But none of the above versions of Android 6 will be displayed for selection

Please give me a solution in this regard, thanks all

答:
The solution is on upgrading xamarin android
With the update, all versions of the api were finally made available
Thanks to the advice of all loved ones


问:
How To Write Series Of Number In Excel
I want to write numbers in excel starting from 000001 till 999999

I have done like this =TEXT(A2,"000001") but i am not been able to generate series even though not able to separate this in different attributes

Further I want to distribute each number in each different cell for example like this

```<code>A           B         C        D         E         F       G

000001      0         0        0         0         0       1

000002      0         0        0         0         0       2

till

999999      9          9       9         9          9       9
</code>```

答:
(Write this formula in Column A and extend it down to row 999999)

generating the series:

=RIGHT(10^6, 6-LEN(ROW(A1)))&ROW(A1)

Write this formula in Column B and extend it to Column G, then
  extend the range of B1:G1 to B999999:G999999

Distributing digits

=MID($A1,COLUMN(A1),1)

Title: How To Write Series Of Number In Excel

Body:
I want to write numbers in excel starting from 000001 till 999999

I have done like this =TEXT(A2,"000001") but i am not been able to generate series even though not able to separate this in different attributes

Further I want to distribute each number in each different cell for example like this

A           B         C        D         E         F       G

000001      0         0        0         0         0       1

000002      0         0        0         0         0       2

till

999999      9          9       9         9          9       9


问:
Strange behavior with Observable results in Angular/Typescript
I have the following problem. Imagine a single Angular 2 service:

```<code>validate() {
        return this.http.get('api/validate', data); }
</code>```

When I am trying to consume the above API, everything is Okay with that:

```<code>this.ValidationService.validate().subscribe(result => {
            console.log('data returned from api', result);
        });
</code>```

and the result is an object:

```<code>{status: "success", data: {…}}
</code>```

However, what will drive me crazy is when I am trying:

```<code>this.ValidationService.validate().subscribe(result => {
                console.log('data returned from api', result.data);
            });
</code>```

Typescript complains there is no data property and there is a compilation error!! At the same time from the following I am getting true...

```<code>this.ValidationService.validate().subscribe(result => {
            console.log('data returned from api', result.hasOwnProperty('data'));
        });
</code>```

I also tried result['data']. It did not work as well. Any idea about what may happen?

答:
Try adding an any type for the result like below:

```<code>this.ValidationService.validate().subscribe((result:any) => {
</code>```

You may want to add proper typings for your responses as well, this will make your code more readable and maintainable

Body:
I have the following problem. Imagine a single Angular 2 service:

validate() {
        return this.http.get('api/validate', data); }

When I am trying to consume the above API, everything is Okay with that:

this.ValidationService.validate().subscribe(result => {
            console.log('data returned from api', result);
        });

and the result is an object:

{status: "success", data: {…}}

However, what will drive me crazy is when I am trying:

this.ValidationService.validate().subscribe(result => {
                console.log('data returned from api', result.data);
            });

Typescript complains there is no data property and there is a compilation error!! At the same time from the following I am getting true...

this.ValidationService.validate().subscribe(result => {
            console.log('data returned from api', result.hasOwnProperty('data'));
        });

I also tried result['data']. It did not work as well. Any idea about what may happen?

Body:
Try adding an any type for the result like below:

this.ValidationService.validate().subscribe((result:any) => {

You may want to add proper typings for your responses as well, this will make your code more readable and maintainable


问:
Combine toHaveBeenCalledTimes with toBeGreaterThan
Is there a way in jasmine where I can combine toHaveBeenCalledTimes with toBeGreaterThan?

I want to know whether the spy object has called a particular method at least 2 times.

spy Object

```<code>spyOn(component.videos, 'update').and.callThrough();
</code>```

I know we can verify it for exact number of times, but in my case update method can be called any number of times. I want to check if it has been called at least twice

something like below expect statement

```<code>expect(component.videos.update).toHaveBeenCalledTimes(2).toBeGreaterThan(2);
</code>```

I know it is a wrong syntax, but is there anything similar to that?

答:
They are different assertions that aren't supposed to be chained.

It likely should be:

```<code>expect(component.videos.update.calls.count()).not.toBeLessThan(2);
</code>```

Body:
Is there a way in jasmine where I can combine toHaveBeenCalledTimes with toBeGreaterThan?

I want to know whether the spy object has called a particular method at least 2 times.

spy Object

spyOn(component.videos, 'update').and.callThrough();

I know we can verify it for exact number of times, but in my case update method can be called any number of times. I want to check if it has been called at least twice

something like below expect statement

expect(component.videos.update).toHaveBeenCalledTimes(2).toBeGreaterThan(2);

I know it is a wrong syntax, but is there anything similar to that?

Body:
They are different assertions that aren't supposed to be chained.

It likely should be:

expect(component.videos.update.calls.count()).not.toBeLessThan(2);


问:
Turning a hard error on incorrect template instantiation in SFINAE context into a soft error
Let's say we're given a template instantiation Container (think Container being an std::vector) and a non-template type T, and we need to check if we can call push_back on an object of type Container<T>. Here's the code that uses the detector idiom:

#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <type_traits>
#include <boost/iterator.hpp>
#include <boost/range.hpp>

template<typename, typename>
struct replace
{
    using type = struct Error;
};

template<template<typename...> class Container, typename U, typename T>
struct replace<Container, T>
{
    using type = Container<T>;
};

template<typename Container, typename T>
using replace_t = typename replace<Container, T>::type;

template<typename Placeholder, template<typename...> class Op, typename... Args>
struct isDetected : std::false_type {};

template<template<typename...> class Op, typename... Args>
struct isDetected<std::void_t<Op<Args...>>, Op, Args...> : std::true_type {};

template<typename Container, typename T>
using pushBackDetector = decltype(std::declval<Container&>().push_back(std::declval<T>()));

template<typename Container, typename T>
bool canPushBack()
{
    return isDetected<void, pushBackDetector, Container, T> {};
}

int main()
{
    std::cout << canPushBack<replace_t<std::vector<int>, double>, double>() << std::endl;
    std::cout << canPushBack<replace_t<std::set<int>, double>, double>() << std::endl;
    std::cout << canPushBack<replace_t<boost::iterator_range<std::string::iterator>, std::string::iterator>, double>() << std::endl;

    //std::cout << canPushBack<replace_t<boost::iterator_range<std::string::iterator>, int>, double>() << std::endl;
}
```

<p>A live example is available at Wandbox.</p>

<p>Indeed, it correctly deduces that we can call <code>push_back</code> on <code>std::vector<double></code>, but we can't do that on <code>std::set<double></code> or on <code>boost::iterator_range<std::string::iterator></code>.</p>

<p>Now let's check if we can call <code>push_back</code> on <code>boost::iterator_range<int></code> and uncomment the last line! And now the code explodes so beautifully that I won't give the full error message here (better to do that on the live example linked above), but the gist of it is the compiler trying to instantiate <code>boost::iterator_range<int></code> and turning the failure to instantiate some base type of that one into a hard error:</p>

```/opt/wandbox/boost-1.65.1/clang-5.0.0/include/boost/iterator/iterator_categories.hpp:119:60: error: no type named 'iterator_category' in 'std::__1::iterator_traits<int>'
        typename boost::detail::iterator_traits<Iterator>::iterator_category
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~
/opt/wandbox/boost-1.65.1/clang-5.0.0/include/boost/range/iterator_range_core.hpp:156:32: note: in instantiation of template class 'boost::iterators::iterator_traversal<int>' requested here
        BOOST_DEDUCED_TYPENAME iterator_traversal<IteratorT>::type
                               ^
/opt/wandbox/boost-1.65.1/clang-5.0.0/include/boost/range/iterator_range_core.hpp:436:67: note: in instantiation of template class 'boost::iterator_range_detail::pure_iterator_traversal<int>' requested here
                    BOOST_DEDUCED_TYPENAME iterator_range_detail::pure_iterator_traversal<IteratorT>::type
                                                                  ^
prog.cc:31:61: note: in instantiation of template class 'boost::iterator_range<int>' requested here
using pushBackDetector = decltype(std::declval<Container&>().push_back(std::declval<T>()));
                                                            ^
prog.cc:28:31: note: in instantiation of template type alias 'pushBackDetector' requested here
struct isDetected<std::void_t<Op<Args...>>, Op, Args...> : std::true_type {};
                              ^
prog.cc:36:12: note: during template argument deduction for class template partial specialization 'isDetected<std::void_t<Op<Args...> >, Op, Args...>' [with Op = pushBackDetector, Args = <boost::iterator_range<int>, double>]
    return isDetected<void, pushBackDetector, Container, T> {};
           ^
```

On one hand, this makes perfect sense — indeed, int is not an iterator. On the other hand, it's very desirable to catch this incorrect instantiation and just return false from canPushBack() in this case. So, this is the question: is it possible to turn this hard error into a soft error and handle it gracefully?

答:
No, you cannot take a template that doesn't support SFINAE-detection and make it SFINAE-friendly without manual work specific to the type in question, and sometimes that isn't enough.

The best you can do is write a manual trait that does it for you, and an alias that SFINAE checks if it can be applied, and only returns a type if it can be.

What more, it isn't possible to detect if something is an iterator.  There are no standard-mandated SFINAE-friendly "is X an iterator" tests.  As a general rule, all iterators must support std::iterator_traits<T>, but there are zero requirements that non-iterators must generate a SFINAE friendly result when you pass them to std::iterator_traits, and in my experience passing void* to std::iterator_traits generates a non-SFINAE friendly result.

You could try to hack one -- detect the various things that an iterator must do (be dereferenceable, incrementable, equally compariable), but even there a type may not have SFINAE-friendly errors when you try it.  For example, take non-equally compariable type and put it in a std::vector, and attempting to do == can fail to compile with a hard error (at least the last time I checked).

A simple case is:

```<code>template<class T>
struct problem {
  static_assert(!std::is_same<T,int>{}, "oh oh");
};
</code>```

passing int to problem cannot be SFINAE detected as being a problem.  If you instantiate problem<int>, you get a hard error.

Body:
Let's say we're given a template instantiation Container (think Container being an std::vector) and a non-template type T, and we need to check if we can call push_back on an object of type Container<T>. Here's the code that uses the detector idiom:

#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <type_traits>
#include <boost/iterator.hpp>
#include <boost/range.hpp>

template<typename, typename>
struct replace
{
    using type = struct Error;
};

template<template<typename...> class Container, typename U, typename T>
struct replace<Container, T>
{
    using type = Container<T>;
};

template<typename Container, typename T>
using replace_t = typename replace<Container, T>::type;

template<typename Placeholder, template<typename...> class Op, typename... Args>
struct isDetected : std::false_type {};

template<template<typename...> class Op, typename... Args>
struct isDetected<std::void_t<Op<Args...>>, Op, Args...> : std::true_type {};

template<typename Container, typename T>
using pushBackDetector = decltype(std::declval<Container&>().push_back(std::declval<T>()));

template<typename Container, typename T>
bool canPushBack()
{
    return isDetected<void, pushBackDetector, Container, T> {};
}

int main()
{
    std::cout << canPushBack<replace_t<std::vector<int>, double>, double>() << std::endl;
    std::cout << canPushBack<replace_t<std::set<int>, double>, double>() << std::endl;
    std::cout << canPushBack<replace_t<boost::iterator_range<std::string::iterator>, std::string::iterator>, double>() << std::endl;

    //std::cout << canPushBack<replace_t<boost::iterator_range<std::string::iterator>, int>, double>() << std::endl;
}

A live example is available at Wandbox.

Indeed, it correctly deduces that we can call push_back on std::vector<double>, but we can't do that on std::set<double> or on boost::iterator_range<std::string::iterator>.

Now let's check if we can call push_back on boost::iterator_range<int> and uncomment the last line! And now the code explodes so beautifully that I won't give the full error message here (better to do that on the live example linked above), but the gist of it is the compiler trying to instantiate boost::iterator_range<int> and turning the failure to instantiate some base type of that one into a hard error:

/opt/wandbox/boost-1.65.1/clang-5.0.0/include/boost/iterator/iterator_categories.hpp:119:60: error: no type named 'iterator_category' in 'std::__1::iterator_traits<int>'
        typename boost::detail::iterator_traits<Iterator>::iterator_category
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~
/opt/wandbox/boost-1.65.1/clang-5.0.0/include/boost/range/iterator_range_core.hpp:156:32: note: in instantiation of template class 'boost::iterators::iterator_traversal<int>' requested here
        BOOST_DEDUCED_TYPENAME iterator_traversal<IteratorT>::type
                               ^
/opt/wandbox/boost-1.65.1/clang-5.0.0/include/boost/range/iterator_range_core.hpp:436:67: note: in instantiation of template class 'boost::iterator_range_detail::pure_iterator_traversal<int>' requested here
                    BOOST_DEDUCED_TYPENAME iterator_range_detail::pure_iterator_traversal<IteratorT>::type
                                                                  ^
prog.cc:31:61: note: in instantiation of template class 'boost::iterator_range<int>' requested here
using pushBackDetector = decltype(std::declval<Container&>().push_back(std::declval<T>()));
                                                            ^
prog.cc:28:31: note: in instantiation of template type alias 'pushBackDetector' requested here
struct isDetected<std::void_t<Op<Args...>>, Op, Args...> : std::true_type {};
                              ^
prog.cc:36:12: note: during template argument deduction for class template partial specialization 'isDetected<std::void_t<Op<Args...> >, Op, Args...>' [with Op = pushBackDetector, Args = <boost::iterator_range<int>, double>]
    return isDetected<void, pushBackDetector, Container, T> {};
           ^

On one hand, this makes perfect sense — indeed, int is not an iterator. On the other hand, it's very desirable to catch this incorrect instantiation and just return false from canPushBack() in this case. So, this is the question: is it possible to turn this hard error into a soft error and handle it gracefully?

Body:
No, you cannot take a template that doesn't support SFINAE-detection and make it SFINAE-friendly without manual work specific to the type in question, and sometimes that isn't enough.

The best you can do is write a manual trait that does it for you, and an alias that SFINAE checks if it can be applied, and only returns a type if it can be.

What more, it isn't possible to detect if something is an iterator.  There are no standard-mandated SFINAE-friendly "is X an iterator" tests.  As a general rule, all iterators must support std::iterator_traits<T>, but there are zero requirements that non-iterators must generate a SFINAE friendly result when you pass them to std::iterator_traits, and in my experience passing void* to std::iterator_traits generates a non-SFINAE friendly result.

You could try to hack one -- detect the various things that an iterator must do (be dereferenceable, incrementable, equally compariable), but even there a type may not have SFINAE-friendly errors when you try it.  For example, take non-equally compariable type and put it in a std::vector, and attempting to do == can fail to compile with a hard error (at least the last time I checked).

A simple case is:

template<class T>
struct problem {
  static_assert(!std::is_same<T,int>{}, "oh oh");
};

passing int to problem cannot be SFINAE detected as being a problem.  If you instantiate problem<int>, you get a hard error.


问:
How do I set the version information for an existing .exe, .dll?
As part of our build process I need to set the version information for all of our compiled binaries. Some of the binaries already have version information (added at compile time) and some do not.

I want to be able to apply the following information:

Company Name

Copyright Notice

Product Name

Product Description

File Version

Product Version

All of these attributes are specified by the build script and must be applied after compilation. These are standard binaries (not assemblies) compiled with C++ Builder 2007.

How can I do this?

答:
verpatch is good, but doesn't handle unicode characters...

try ResourceLib

OwnerDisplayName: Carl

LastEditorDisplayName: Robert Gamble


问:
Adding extra content to Class Based View and filtering it
I've built a for-loop in my HTML template and its nearly working. The issue I'm having is its listing Matches that are apart of a different tour.

I think the way to fix this is adding a filter to the view that basically says "only pull in the matches to do with this tour" which is what I've tried to do below in the Match.objects.filter() but it isnt working and I'm not sure why.

```<code>class CricketCalendar(generic.ListView):
    template_name="monthly_view/cricket-monthly-view.html"
    context_object_name='cricket_monthly_view'
    queryset = CricketMonthlyView.objects.all()

    def get_context_data(self, **kwargs):
        context = super(CricketCalendar, self).get_context_data(**kwargs)
        context['Tour'] = Tour.objects.all()
        context['Match'] = Match.objects.filter(tour=self.request.Tour)
        return context
</code>```

I have also tried the following and neither worked:

```<code>self.kwargs['pk']
self.kwargs['Tour']
</code>```

Edit, forgot to add the following:

Monthly View models.py:

```<code>class CricketMonthlyView(models.Model):
    tour = models.ForeignKey('cricket.Tour', on_delete=models.CASCADE,
related_name='tour_name')
    match_id = models.ForeignKey('cricket.Match', on_delete=models.CASCADE)
</code>```

and the URLs.py:

```<code>url(r'^monthly-view/$', monthly_view.CricketCalendar.as_view(), name='cricket-monthly'),
</code>```

Cricket models.py:

```<code>class Tour(models.Model):
    name = models.CharField(max_length=200)
    tier_level = models.ForeignKey('sports.Tier')
    country = CountryField()
class Match(models.Model):
    tour = models.ForeignKey('Tour', on_delete=models.CASCADE)
</code>```

And the HTML Template:

```<code>{% for match_info in cricket_monthly_view %}
 {% for tour in Tour %}
<ul>
  <li>{{tour.name}}</li>
</ul>
{% for match in Match %}
  <ul>
    <li>{{match.home_team}}</li>
    <li>{{match.away_team}}</li>
  </ul>
{% endfor %}
{% endfor %}
</code>```

{% endfor %}

答:
This is a great place for adding a break-point. You pretty much want to know the fields on your context, and on self. Add import pdb; pdb.set_trace() in get_context_data, and you'll be able to see the fields on your objects. Use dir(obj) and obj.keys() in order to see all the fields on something.

Alternatively, if you have access to the tour object in your context variable, in your template you can get its matching Matches with tour.match_set.all

Also, be careful about naming the context variable Tour with a capital T, because that's the name of your model.

Body:
I've built a for-loop in my HTML template and its nearly working. The issue I'm having is its listing Matches that are apart of a different tour.

I think the way to fix this is adding a filter to the view that basically says "only pull in the matches to do with this tour" which is what I've tried to do below in the Match.objects.filter() but it isnt working and I'm not sure why.

class CricketCalendar(generic.ListView):
    template_name="monthly_view/cricket-monthly-view.html"
    context_object_name='cricket_monthly_view'
    queryset = CricketMonthlyView.objects.all()

    def get_context_data(self, **kwargs):
        context = super(CricketCalendar, self).get_context_data(**kwargs)
        context['Tour'] = Tour.objects.all()
        context['Match'] = Match.objects.filter(tour=self.request.Tour)
        return context

I have also tried the following and neither worked:

self.kwargs['pk']
self.kwargs['Tour']

Edit, forgot to add the following:

Monthly View models.py:

class CricketMonthlyView(models.Model):
    tour = models.ForeignKey('cricket.Tour', on_delete=models.CASCADE,
related_name='tour_name')
    match_id = models.ForeignKey('cricket.Match', on_delete=models.CASCADE)

and the URLs.py:

url(r'^monthly-view/$', monthly_view.CricketCalendar.as_view(), name='cricket-monthly'),

Cricket models.py:

class Tour(models.Model):
    name = models.CharField(max_length=200)
    tier_level = models.ForeignKey('sports.Tier')
    country = CountryField()
class Match(models.Model):
    tour = models.ForeignKey('Tour', on_delete=models.CASCADE)

And the HTML Template:

{% for match_info in cricket_monthly_view %}
 {% for tour in Tour %}

{{tour.name}}

{% for match in Match %}

{{match.home_team}}

{{match.away_team}}

{% endfor %}
{% endfor %}

{% endfor %}


问:
Splayed table upsert leading to error: `cast
I built a data loader prototype that saves CSV into splayed tables. The workflow is as follows:

Create schema the first time e.g. volatilitysurface table:

```<code>volatilitysurface::([date:`datetime$(); ccypair:`symbol$()] atm_convention:`symbol$(); premium_included:`boolean$(); smile_type:`symbol$(); vs_type:`symbol$(); delta_ratio:`float$(); delta_setting:`float$(); wing_extrapolation:`float$(); spread_type:`symbol$());
</code>```

For every file in the rawdata folder import it:

```<code>myfiles:@[system;"dir /b /o:gn ",string `$getenv[`KDBRAWDATA],"*.volatilitysurface.csv 2> nul";()];
if[myfiles~();.lg.o[`load;"no volatilitysurface files found!"];:0N];
.lg.o[`load;"loading data files ..."];
/ load each file
{
  mypath:"" sv (string `$getenv[`KDBRAWDATA];x);
  .lg.o[`load;"loading file name '",mypath,"' ..."];
  myfile:hsym`$mypath;
  tmp1:select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from ("ZSSSSSFFFS";enlist ",")0:myfile;
  `volatilitysurface upsert tmp1;
} @/: myfiles;
delete tmp1 from `.;
.Q.gc[];
.lg.o[`done;"loading volatilitysurface data done"];

.lg.o[`save;"saving volatilitysurface schema to ",string afolder];
volatilitysurface::0!volatilitysurface;
.Q.dpft[afolder;`;`ccypair;`volatilitysurface];
.lg.o[`cleanup;"removing volatilitysurface from memory"];
delete volatilitysurface from `.;
.Q.gc[];
.lg.o[`done;"saving volatilitysurface schema done"];
</code>```

This works perfectly. I use .Q.gc[]; frequently to avoid hitting the wsfull. When new CSV files are available I open the existing schema, upsert into it and save it again effectively overwriting the existing HDB file system.

Open schema:

```<code>.lg.o[`open;"tables already exists, opening the schema ..."];
@[system;"l ",(string afolder) _ 0;{.lg.e[`open;"failed to load hdb directory: ", x]; 'x}];
/ Re-create table index
volatilitysurface::`date`ccypair xkey select from volatilitysurface;
</code>```

Re-run step #2 to append new CSV files into the existing volatilitysurfacetable, it upserts the first CSV perfectly but the second CSV fails with:

```<code>error: `cast
</code>```

I debug to the point of the error and to double-check I see that the metadata of tmp1 and volatilitysurface are perfectly the same. Any ideas why this is happening? I get the same issue with any other table. I have tried cleaning the keys from the table after every upsert but doesn't help i.e.

```<code>volatilitysurface::0!volatilitysurface;
volatilitysurface::`date`ccypair xkey volatilitysurface;
</code>```

And the metadata comparison at the point of the cast error:

```<code>meta tmp1
c                 | t f a
------------------| -----
date              | z
ccypair           | s
atm_convention    | s
premium_included  | b
smile_type        | s
vs_type           | s
delta_ratio       | f
delta_setting     | f
wing_extrapolation| f
spread_type       | s

meta volatilitysurface
c                 | t f a
------------------| -----
date              | z
ccypair           | s   p
atm_convention    | s
premium_included  | b
smile_type        | s
vs_type           | s
delta_ratio       | f
delta_setting     | f
wing_extrapolation| f
spread_type       | s
</code>```

UPDATE Using the input of the answer below I tried using Torq's .loader.loadallfiles function like this (it doesn't fail but nothing happens either, the table is not created in memory and the data is not written to the database):

```<code>.loader.loadallfiles[`headers`types`separator`tablename`dbdir`dataprocessfunc!(`x`ccypair`atm_convention`premium_included`smile_type`vs_type`delta_ratio`delta_setting`wing_extrapolation`spread_type;"ZSSSSSFFFS";enlist ",";`volatilitysurface;`:hdb; {[p;t] select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from t}); `:rawdata]
</code>```

UDPATE2 This is the output I get from TorQ:

```<code>2017.11.20D08:46:12.550618000|wsp18497wn|dataloader|dataloader1|INF|dataloader|**** LOADING :rawdata/20171102_113420.disccurve.csv ****
2017.11.20D08:46:12.550618000|wsp18497wn|dataloader|dataloader1|INF|dataloader|reading in data chunk
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|Read 10000 rows
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|processing data
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|Enumerating
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 4525 rows to :hdb/2017.09.12/volatilitysurface/
2017.11.20D08:46:12.581819000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 4744 rows to :hdb/2017.09.13/volatilitysurface/
2017.11.20D08:46:12.659823000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 731 rows to :hdb/2017.09.14/volatilitysurface/
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|init|retrieving sort settings from :C:/Dev/torq//config/sort.csv
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sort|sorting the volatilitysurface table
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sorttab|No sort parameters have been specified for : volatilitysurface. Using default parameters
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sortfunction|sorting :hdb/2017.09.05/volatilitysurface/ by these columns : sym, time
2017.11.20D08:46:12.753428000|wsp18497wn|dataloader|dataloader1|ERR|sortfunction|failed to sort :hdb/2017.09.05/volatilitysurface/ by these columns : sym, time.  The error was: hdb/2017.09.
</code>```

I get the following error sorttab|No sort parameters have been specified for : volatilitysurface. Using default parameters where is this sorttab documented? does it use the table PK by default?

UPDATE3 Ok fixed UPDATE2 out by providing a non-default sort.csv under my config folder:

```<code>tabname,att,column,sort
default,p,sym,1
default,,time,1
volatilitysurface,,date,1
volatilitysurface,,ccypair,1
</code>```

But now I see that if I call the function multiple times on the same files, it simply appends duplicated data instead of upserting it.

UPDATE4 Still not there yet ... assuming I can check to make sure that no duplicate file is used. When I load and then start the database I get some structure back that ressembles some sort of dictionary and not a table.

```<code>2017.10.31| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.01| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.02| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.03| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
sym       | `AUDNOK`AUDCNH`AUDJPY`AUDHKD`AUDCHF`AUDSGD`AUDCAD`AUDDKK`CADSGD`C..
</code>```

Note that date is actually datetime Z and not just date. My full and latest version of the function invocation is:

```<code>target:hsym `$("" sv ("./";getenv[`KDBHDB];"/volatilitysurface"));
rawdatadir:hsym `$getenv[`KDBRAWDATA];
.loader.loadallfiles[`headers`types`separator`tablename`dbdir`partitioncol`dataprocessfunc!(`x`ccypair`atm_convention`premium_included`smile_type`vs_type`delta_ratio`delta_setting`wing_extrapolation`spread_type;"ZSSSSSFFFS";enlist ",";`volatilitysurface;target;`date;{[p;t] select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from t}); rawdatadir];
</code>```

答:
I'm going to add a second answer here to try and tackle the question about using TorQ's data loader.

I'd like to clarify what output you are getting after running this function? There should be some logging messages output, can you post these? For example when I run the function:

```<code>jmcmurray@homer ~/deploy/TorQ (master) $ q torq.q -procname loader -proctype loader -debug
<torq startup messages removed>
q).loader.loadallfiles[`headers`types`separator`tablename`dbdir`partitioncol`dataprocessfunc!(c;"TSSFJFFJJBS";enlist",";`quotes;`:testdb;`date;{[p;t] select date:.z.d,time:TIME,sym:INSTRUMENT,BID,ASK from t});`:csvtest]
2017.11.17D15:03:20.312336000|homer.aquaq.co.uk|loader|loader|INF|dataloader|**** LOADING :csvtest/tradesandquotes20140421.csv ****
2017.11.17D15:03:20.319110000|homer.aquaq.co.uk|loader|loader|INF|dataloader|reading in data chunk
2017.11.17D15:03:20.339414000|homer.aquaq.co.uk|loader|loader|INF|dataloader|Read 11000 rows
2017.11.17D15:03:20.339463000|homer.aquaq.co.uk|loader|loader|INF|dataloader|processing data
2017.11.17D15:03:20.339519000|homer.aquaq.co.uk|loader|loader|INF|dataloader|Enumerating
2017.11.17D15:03:20.340061000|homer.aquaq.co.uk|loader|loader|INF|dataloader|writing 11000 rows to :testdb/2017.11.17/quotes/
2017.11.17D15:03:20.341669000|homer.aquaq.co.uk|loader|loader|INF|dataloader|**** LOADING :csvtest/tradesandquotes20140422.csv ****
2017.11.17D15:03:20.349606000|homer.aquaq.co.uk|loader|loader|INF|dataloader|reading in data chunk
2017.11.17D15:03:20.370793000|homer.aquaq.co.uk|loader|loader|INF|dataloader|Read 11000 rows
2017.11.17D15:03:20.370858000|homer.aquaq.co.uk|loader|loader|INF|dataloader|processing data
2017.11.17D15:03:20.370911000|homer.aquaq.co.uk|loader|loader|INF|dataloader|Enumerating
2017.11.17D15:03:20.371441000|homer.aquaq.co.uk|loader|loader|INF|dataloader|writing 11000 rows to :testdb/2017.11.17/quotes/
2017.11.17D15:03:20.460118000|homer.aquaq.co.uk|loader|loader|INF|init|retrieving sort settings from :/home/jmcmurray/deploy/TorQ/config/sort.csv
2017.11.17D15:03:20.466690000|homer.aquaq.co.uk|loader|loader|INF|sort|sorting the quotes table
2017.11.17D15:03:20.466763000|homer.aquaq.co.uk|loader|loader|INF|sorttab|No sort parameters have been specified for : quotes. Using default parameters
2017.11.17D15:03:20.466820000|homer.aquaq.co.uk|loader|loader|INF|sortfunction|sorting :testdb/2017.11.17/quotes/ by these columns : sym, time
2017.11.17D15:03:20.527216000|homer.aquaq.co.uk|loader|loader|INF|applyattr|applying p attr to the sym column in :testdb/2017.11.17/quotes/
2017.11.17D15:03:20.535095000|homer.aquaq.co.uk|loader|loader|INF|sort|finished sorting the quotes table
</code>```

After all this, I can run \l testdb and there is a table called "quotes" containing my loaded data

If you can post logging messages like these, it could be helpful to see what's going on.

UPDATE

"But now I see that if I call the function multiple times on the same files, it simply appends duplicated data instead of upserting it."

If I'm understanding the problem correctly, it sounds like you likely shouldn't call the function multiple times on the same files. Another process within TorQ could be useful here, the "file alerter". This process will monitor a directory for new & updated files, and can call a function on any that appear (so you can have it call the loader function with every new file automatically). It has a number of options such as moving files after processing (so you can "archive" loaded CSVs)

Note that the file alerter requires that a function take exactly two parameters - the directory & the file name. This effectively means you will need a "wrapper" function around the loader function, which takes a dictionary & a directory. I don't think TorQ includes a function similar to .loader.loadallfiles for a single file, so it might be necessary to copy the target file to a temporary directory, run loadallfiles on that directory and then delete the file from there before loading the next.

Body:
I built a data loader prototype that saves CSV into splayed tables. The workflow is as follows:

Create schema the first time e.g. volatilitysurface table:

volatilitysurface::([date:`datetime$(); ccypair:`symbol$()] atm_convention:`symbol$(); premium_included:`boolean$(); smile_type:`symbol$(); vs_type:`symbol$(); delta_ratio:`float$(); delta_setting:`float$(); wing_extrapolation:`float$(); spread_type:`symbol$());

For every file in the rawdata folder import it:

myfiles:@[system;"dir /b /o:gn ",string `$getenv[`KDBRAWDATA],"*.volatilitysurface.csv 2> nul";()];
if[myfiles~();.lg.o[`load;"no volatilitysurface files found!"];:0N];
.lg.o[`load;"loading data files ..."];
/ load each file
{
  mypath:"" sv (string `$getenv[`KDBRAWDATA];x);
  .lg.o[`load;"loading file name '",mypath,"' ..."];
  myfile:hsym`$mypath;
  tmp1:select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from ("ZSSSSSFFFS";enlist ",")0:myfile;
  `volatilitysurface upsert tmp1;
} @/: myfiles;
delete tmp1 from `.;
.Q.gc[];
.lg.o[`done;"loading volatilitysurface data done"];

.lg.o[`save;"saving volatilitysurface schema to ",string afolder];
volatilitysurface::0!volatilitysurface;
.Q.dpft[afolder;`;`ccypair;`volatilitysurface];
.lg.o[`cleanup;"removing volatilitysurface from memory"];
delete volatilitysurface from `.;
.Q.gc[];
.lg.o[`done;"saving volatilitysurface schema done"];

This works perfectly. I use .Q.gc[]; frequently to avoid hitting the wsfull. When new CSV files are available I open the existing schema, upsert into it and save it again effectively overwriting the existing HDB file system.

Open schema:

.lg.o[`open;"tables already exists, opening the schema ..."];
@[system;"l ",(string afolder) _ 0;{.lg.e[`open;"failed to load hdb directory: ", x]; 'x}];
/ Re-create table index
volatilitysurface::`date`ccypair xkey select from volatilitysurface;

Re-run step #2 to append new CSV files into the existing volatilitysurfacetable, it upserts the first CSV perfectly but the second CSV fails with:

error: `cast

I debug to the point of the error and to double-check I see that the metadata of tmp1 and volatilitysurface are perfectly the same. Any ideas why this is happening? I get the same issue with any other table. I have tried cleaning the keys from the table after every upsert but doesn't help i.e.

volatilitysurface::0!volatilitysurface;
volatilitysurface::`date`ccypair xkey volatilitysurface;

And the metadata comparison at the point of the cast error:

meta tmp1
c                 | t f a
------------------| -----
date              | z
ccypair           | s
atm_convention    | s
premium_included  | b
smile_type        | s
vs_type           | s
delta_ratio       | f
delta_setting     | f
wing_extrapolation| f
spread_type       | s

meta volatilitysurface
c                 | t f a
------------------| -----
date              | z
ccypair           | s   p
atm_convention    | s
premium_included  | b
smile_type        | s
vs_type           | s
delta_ratio       | f
delta_setting     | f
wing_extrapolation| f
spread_type       | s

UPDATE Using the input of the answer below I tried using Torq's .loader.loadallfiles function like this (it doesn't fail but nothing happens either, the table is not created in memory and the data is not written to the database):

.loader.loadallfiles[`headers`types`separator`tablename`dbdir`dataprocessfunc!(`x`ccypair`atm_convention`premium_included`smile_type`vs_type`delta_ratio`delta_setting`wing_extrapolation`spread_type;"ZSSSSSFFFS";enlist ",";`volatilitysurface;`:hdb; {[p;t] select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from t}); `:rawdata]

UDPATE2 This is the output I get from TorQ:

2017.11.20D08:46:12.550618000|wsp18497wn|dataloader|dataloader1|INF|dataloader|**** LOADING :rawdata/20171102_113420.disccurve.csv ****
2017.11.20D08:46:12.550618000|wsp18497wn|dataloader|dataloader1|INF|dataloader|reading in data chunk
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|Read 10000 rows
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|processing data
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|Enumerating
2017.11.20D08:46:12.566218000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 4525 rows to :hdb/2017.09.12/volatilitysurface/
2017.11.20D08:46:12.581819000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 4744 rows to :hdb/2017.09.13/volatilitysurface/
2017.11.20D08:46:12.659823000|wsp18497wn|dataloader|dataloader1|INF|dataloader|writing 731 rows to :hdb/2017.09.14/volatilitysurface/
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|init|retrieving sort settings from :C:/Dev/torq//config/sort.csv
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sort|sorting the volatilitysurface table
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sorttab|No sort parameters have been specified for : volatilitysurface. Using default parameters
2017.11.20D08:46:12.737827000|wsp18497wn|dataloader|dataloader1|INF|sortfunction|sorting :hdb/2017.09.05/volatilitysurface/ by these columns : sym, time
2017.11.20D08:46:12.753428000|wsp18497wn|dataloader|dataloader1|ERR|sortfunction|failed to sort :hdb/2017.09.05/volatilitysurface/ by these columns : sym, time.  The error was: hdb/2017.09.

I get the following error sorttab|No sort parameters have been specified for : volatilitysurface. Using default parameters where is this sorttab documented? does it use the table PK by default?

UPDATE3 Ok fixed UPDATE2 out by providing a non-default sort.csv under my config folder:

tabname,att,column,sort
default,p,sym,1
default,,time,1
volatilitysurface,,date,1
volatilitysurface,,ccypair,1

But now I see that if I call the function multiple times on the same files, it simply appends duplicated data instead of upserting it.

UPDATE4 Still not there yet ... assuming I can check to make sure that no duplicate file is used. When I load and then start the database I get some structure back that ressembles some sort of dictionary and not a table.

2017.10.31| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.01| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.02| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
2017.11.03| (,`volatilitysurface)!,+`date`ccypair`atm_convention`premium_incl..
sym       | `AUDNOK`AUDCNH`AUDJPY`AUDHKD`AUDCHF`AUDSGD`AUDCAD`AUDDKK`CADSGD`C..

Note that date is actually datetime Z and not just date. My full and latest version of the function invocation is:

target:hsym `$("" sv ("./";getenv[`KDBHDB];"/volatilitysurface"));
rawdatadir:hsym `$getenv[`KDBRAWDATA];
.loader.loadallfiles[`headers`types`separator`tablename`dbdir`partitioncol`dataprocessfunc!(`x`ccypair`atm_convention`premium_included`smile_type`vs_type`delta_ratio`delta_setting`wing_extrapolation`spread_type;"ZSSSSSFFFS";enlist ",";`volatilitysurface;target;`date;{[p;t] select date,ccypair,atm_convention,premium_included,smile_type,vs_type,delta_ratio,delta_setting,wing_extrapolation,spread_type from update date:x, premium_included:?[premium_included = `$"true";1b;0b] from t}); rawdatadir];

Body:
I'm going to add a second answer here to try and tackle the question about using TorQ's data loader.

I'd like to clarify what output you are getting after running this function? There should be some logging messages output, can you post these? For example when I run the function:

jmcmurray@homer ~/deploy/TorQ (master) $ q torq.q -procname loader -proctype loader -debug
<torq startup messages removed>
q).loader.loadallfiles[`headers`types`separator`tablename`dbdir`partitioncol`dataprocessfunc!(c;"TSSFJFFJJBS";enlist",";`quotes;`:testdb;`date;{[p;t] select date:.z.d,time:TIME,sym:INSTRUMENT,BID,ASK from t});`:csvtest]
2017.11.17D15:03:20.312336000|homer.aquaq.co.uk|loader|loader|INF|dataloader|**** LOADING :csvtest/tradesandquotes20140421.csv ****
2017.11.17D15:03:20.319110000|homer.aquaq.co.uk|loader|loader|INF|dataloader|reading in data chunk
2017.11.17D15:03:20.339414000|homer.aquaq.co.uk|loader|loader|INF|dataloader|Read 11000 rows
2017.11.17D15:03:20.339463000|homer.aquaq.co.uk|loader|loader|INF|dataloader|processing data
2017.11.17D15:03:20.339519000|homer.aquaq.co.uk|loader|loader|INF|dataloader|Enumerating
2017.11.17D15:03:20.340061000|homer.aquaq.co.uk|loader|loader|INF|dataloader|writing 11000 rows to :testdb/2017.11.17/quotes/
2017.11.17D15:03:20.341669000|homer.aquaq.co.uk|loader|loader|INF|dataloader|**** LOADING :csvtest/tradesandquotes20140422.csv ****
2017.11.17D15:03:20.349606000|homer.aquaq.co.uk|loader|loader|INF|dataloader|reading in data chunk
2017.11.17D15:03:20.370793000|homer.aquaq.co.uk|loader|loader|INF|dataloader|Read 11000 rows
2017.11.17D15:03:20.370858000|homer.aquaq.co.uk|loader|loader|INF|dataloader|processing data
2017.11.17D15:03:20.370911000|homer.aquaq.co.uk|loader|loader|INF|dataloader|Enumerating
2017.11.17D15:03:20.371441000|homer.aquaq.co.uk|loader|loader|INF|dataloader|writing 11000 rows to :testdb/2017.11.17/quotes/
2017.11.17D15:03:20.460118000|homer.aquaq.co.uk|loader|loader|INF|init|retrieving sort settings from :/home/jmcmurray/deploy/TorQ/config/sort.csv
2017.11.17D15:03:20.466690000|homer.aquaq.co.uk|loader|loader|INF|sort|sorting the quotes table
2017.11.17D15:03:20.466763000|homer.aquaq.co.uk|loader|loader|INF|sorttab|No sort parameters have been specified for : quotes. Using default parameters
2017.11.17D15:03:20.466820000|homer.aquaq.co.uk|loader|loader|INF|sortfunction|sorting :testdb/2017.11.17/quotes/ by these columns : sym, time
2017.11.17D15:03:20.527216000|homer.aquaq.co.uk|loader|loader|INF|applyattr|applying p attr to the sym column in :testdb/2017.11.17/quotes/
2017.11.17D15:03:20.535095000|homer.aquaq.co.uk|loader|loader|INF|sort|finished sorting the quotes table

After all this, I can run \l testdb and there is a table called "quotes" containing my loaded data

If you can post logging messages like these, it could be helpful to see what's going on.

UPDATE

"But now I see that if I call the function multiple times on the same files, it simply appends duplicated data instead of upserting it."

If I'm understanding the problem correctly, it sounds like you likely shouldn't call the function multiple times on the same files. Another process within TorQ could be useful here, the "file alerter". This process will monitor a directory for new & updated files, and can call a function on any that appear (so you can have it call the loader function with every new file automatically). It has a number of options such as moving files after processing (so you can "archive" loaded CSVs)

Note that the file alerter requires that a function take exactly two parameters - the directory & the file name. This effectively means you will need a "wrapper" function around the loader function, which takes a dictionary & a directory. I don't think TorQ includes a function similar to .loader.loadallfiles for a single file, so it might be necessary to copy the target file to a temporary directory, run loadallfiles on that directory and then delete the file from there before loading the next.


问:
How to get random value of attribute of Enum on each iteration?
I have created such Enum object:

```<code>class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    RANDOM = random.choice([FEMALE, MALE])
</code>```

and i want to get really random value each time, but it does not work:

```<code>>>> class Gender(Enum):
...    MALE = 'male'
...    FEMALE = 'female'
...    RANDOM = choice([MALE, FEMALE])
...
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
</code>```

I have also tried use lambda, but it's looks not so good, although it works:

```<code>Gender.RANDOM()
</code>```

Are there other way to get random values each time, without using lambda expressions?

We use this enum object as default value of the argument of the some method that's why it should be an attribute, not a function, because when we use Gender.FEMALE it is not a function, it's an attribute and Gender.RANDOM should be an attribute too:

```<code>def full_name(gender=Gender.FEMALE):
    ...

def full_name(gender=Gender.RANDOM):
    ...
</code>```

答:
I think you want a method random, instead to save the value directly in the variable, because if you do that, the value will never change:

If you DON'T WANT A FUNCTION

import random
import enum

```<code>class Gender(enum.Enum):

  MALE = 'male'
  FEMALE = 'female'
  RANDOM = random.choice([MALE, FEMALE])

  def __getattribute__(self,item):
    if item == "RANDOM":
      Gender.RANDOM = random.choice([self.MALE, self.FEMALE])
      return Gender.RANDOM
    else:
      return object.__getattribute__(self, item)

gender = Gender()
</code>```

look:

```<code>   gender.RANDOM
=> 'female'
   gender.RANDOM
=> 'male'
   gender.RANDOM
=> 'male'
   gender.RANDOM
=> 'male'
   gender.RANDOM
=> 'female'
   gender.RANDOM
=> 'male'
   gender.RANDOM
=> 'male'
   gender.RANDOM
=> 'female'
</code>```

Body:
I have created such Enum object:

class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    RANDOM = random.choice([FEMALE, MALE])

and i want to get really random value each time, but it does not work:

>>> class Gender(Enum):
...    MALE = 'male'
...    FEMALE = 'female'
...    RANDOM = choice([MALE, FEMALE])
...
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>

I have also tried use lambda, but it's looks not so good, although it works:

Gender.RANDOM()

Are there other way to get random values each time, without using lambda expressions?

We use this enum object as default value of the argument of the some method that's why it should be an attribute, not a function, because when we use Gender.FEMALE it is not a function, it's an attribute and Gender.RANDOM should be an attribute too:

def full_name(gender=Gender.FEMALE):
    ...

def full_name(gender=Gender.RANDOM):
    ...

Body:
I think you want a method random, instead to save the value directly in the variable, because if you do that, the value will never change:

If you DON'T WANT A FUNCTION

import random
import enum

class Gender(enum.Enum):

  MALE = 'male'
  FEMALE = 'female'
  RANDOM = random.choice([MALE, FEMALE])

  def __getattribute__(self,item):
    if item == "RANDOM":
      Gender.RANDOM = random.choice([self.MALE, self.FEMALE])
      return Gender.RANDOM
    else:
      return object.__getattribute__(self, item)

gender = Gender()

look:

   gender.RANDOM
=> 'female'
   gender.RANDOM
=> 'male'
   gender.RANDOM
=> 'male'
   gender.RANDOM
=> 'male'
   gender.RANDOM
=> 'female'
   gender.RANDOM
=> 'male'
   gender.RANDOM
=> 'male'
   gender.RANDOM
=> 'female'


问:
Rails: Hide "Edit" and "Destroy" unless logged in as Admin
I'm brand new to rails, and am creating a simple glossary app using Rails 5 with gems Devise and Pundit. I generated an Admin model with Devise; that's the only role that needs to be logged in. I installed Pundit to create policies that would allow me to hide the "Edit," "Destroy," and "New" buttons unless logged in as admin.
Glossary App Index

After adding the below policy code to my index.html.erb file to hide the 'Edit' and 'Destroy' buttons, I'm getting an "Undefined method 'current_user'" error.

```<code><tbody>
      <% @terms.each do |term| %>
        <tr>
          <td><%= term.name %></td>
          <td><%= term.category %></td>
          <td><%= term.definition %></td>
          <td><%= link_to 'Show', term, class: 'btn btn-mini' %></td>
          <td>
            <% if policy(@term).edit? %>
              <%= link_to 'Edit', edit_term_path(term), class: 'btn btn-mini' %>
            <% end %>
          </td>
          <td>
            <% if policy(@term).destroy? %>
              <%= link_to 'Destroy', term, method: :delete, class: 'btn btn-mini', data: { confirm: 'Are you sure?' } %>
            <% end %>
          </td>
        </tr>
      <% end %>
    </tbody>
</code>```

Since I didn't generate a "User" model with Devise, but generated an "Admin" model instead, it seemed logical that the error was referring to the word "user" in my new policies. So I replaced "user" with "admin" in my application_policy.rb and terms_policy.rb. Clearly I don't understand what "user" means in this error, as I'm still getting it.

I don't know what exactly you need to see, so here are my models, controllers, and policies:

application_record.rb

```<code>class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end
</code>```

admin.rb

```<code>class Admin < ApplicationRecord
  has_many :terms
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :trackable, :timeoutable, :lockable
end
</code>```

term.rb

```<code>class Term < ApplicationRecord
  belongs_to :admin

  def self.search(search)
    if search
      where(["name LIKE ?","%#{search}%"])
    else
      all
    end
  end

end
</code>```

application_controller.rb

```<code>class ApplicationController < ActionController::Base
  include Pundit
  protect_from_forgery with: :exception
  before_action :set_current_user

  def set_current_user
    Term.current_user = current_user
  end
end
</code>```

terms_controller.rb

```<code>class TermsController < ApplicationController
  before_action :set_term, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_admin!, :only => [:new, :edit, :create, :destroy]

  # GET /terms
  # GET /terms.json
  def index
    @terms = Term.search(params[:search])
  end

  # GET /terms/1
  # GET /terms/1.json
  def show
  end

  # GET /terms/new
  def new
    @term = Term.new
  end

  # GET /terms/1/edit
  def edit
    @hide_edit_button = true
  end

  # POST /terms
  # POST /terms.json
  def create
    @term = Term.new(term_params)

    respond_to do |format|
      if @term.save
        format.html { redirect_to @term, notice: 'Term was successfully created.' }
        format.json { render :show, status: :created, location: @term }
      else
        format.html { render :new }
        format.json { render json: @term.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /terms/1
  # PATCH/PUT /terms/1.json
  def update
    respond_to do |format|
      if @term.update(term_params)
        format.html { redirect_to @term, notice: 'Term was successfully updated.' }
        format.json { render :show, status: :ok, location: @term }
      else
        format.html { render :edit }
        format.json { render json: @term.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /terms/1
  # DELETE /terms/1.json
  def destroy
    @term.destroy
    respond_to do |format|
      format.html { redirect_to terms_url, notice: 'Term was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_term
      @term = Term.find(params[:id])
    end

# Never trust parameters from the scary internet, only allow the white list through.
def term_params
  params.require(:term).permit(:name, :category, :definition)
end

def verify_is_admin
      (current_admin.nil?) ? redirect_to(root_path) :
(redirect_to(root_path) unless current_admin.admin?)
    end
end
</code>```

application_policy.rb

```<code>class ApplicationPolicy
  attr_reader :admin, :record

  def initialize(admin, record)
    @admin = admin
    @record = record
  end

  def index?
    false
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  def scope
    Pundit.policy_scope!(admin, record.class)
  end

  class Scope
    attr_reader :admin, :scope

    def initialize(admin, scope)
      @admin = admin
      @scope = scope
    end

    def resolve
      scope
    end
  end
end
</code>```

terms_policy.rb

```<code>class TermPolicy < ApplicationPolicy
  def index?
    true
  end

  def create?
    user.present?
  end

  def update?
    return true if user.present?
  end

  def edit?
    user.admin?
  end

  def destroy?
    user.admin?
  end
end
</code>```

I've tried implementing suggestions from Access to current_user from within a model in Ruby on Rails, undefined local variable or method `current_user' using devise & rails 3.2, https://code.tutsplus.com/tutorials/authorization-with-pundit--cms-28202, and a smattering of other sources. I'm sure these are all great resources, but at this stage I need something a little more targeted to my project and level of familiarity with Rails.

Let me know what else I can provide. Thanks for your help!

答:
Hi you can try to add some

```<code>  before_action :ensure_admin, except: [:show, :edit, :update]
  before_action :ensure_admin_or_user, only: [:edit, :update, :account]
</code>```

in your controller

with method =>

```<code>  def ensure_admin
    if current_user.nil? || current_user.is_at_least?(:manager) == false
      flash[:notice] = I18n.t('must_be_admin')
      redirect_to root_path
      return true
    end
    false
  end
</code>```

Hopes its helps you !

Body:
I'm brand new to rails, and am creating a simple glossary app using Rails 5 with gems Devise and Pundit. I generated an Admin model with Devise; that's the only role that needs to be logged in. I installed Pundit to create policies that would allow me to hide the "Edit," "Destroy," and "New" buttons unless logged in as admin.
Glossary App Index

After adding the below policy code to my index.html.erb file to hide the 'Edit' and 'Destroy' buttons, I'm getting an "Undefined method 'current_user'" error.

      <% @terms.each do |term| %>

          <%= term.name %>
          <%= term.category %>
          <%= term.definition %>
          <%= link_to 'Show', term, class: 'btn btn-mini' %>

            <% if policy(@term).edit? %>
              <%= link_to 'Edit', edit_term_path(term), class: 'btn btn-mini' %>
            <% end %>

            <% if policy(@term).destroy? %>
              <%= link_to 'Destroy', term, method: :delete, class: 'btn btn-mini', data: { confirm: 'Are you sure?' } %>
            <% end %>

      <% end %>

Since I didn't generate a "User" model with Devise, but generated an "Admin" model instead, it seemed logical that the error was referring to the word "user" in my new policies. So I replaced "user" with "admin" in my application_policy.rb and terms_policy.rb. Clearly I don't understand what "user" means in this error, as I'm still getting it.

I don't know what exactly you need to see, so here are my models, controllers, and policies:

application_record.rb

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

admin.rb

class Admin < ApplicationRecord
  has_many :terms
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :trackable, :timeoutable, :lockable
end

term.rb

class Term < ApplicationRecord
  belongs_to :admin

  def self.search(search)
    if search
      where(["name LIKE ?","%#{search}%"])
    else
      all
    end
  end

end

application_controller.rb

class ApplicationController < ActionController::Base
  include Pundit
  protect_from_forgery with: :exception
  before_action :set_current_user

  def set_current_user
    Term.current_user = current_user
  end
end

terms_controller.rb

class TermsController < ApplicationController
  before_action :set_term, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_admin!, :only => [:new, :edit, :create, :destroy]

  # GET /terms
  # GET /terms.json
  def index
    @terms = Term.search(params[:search])
  end

  # GET /terms/1
  # GET /terms/1.json
  def show
  end

  # GET /terms/new
  def new
    @term = Term.new
  end

  # GET /terms/1/edit
  def edit
    @hide_edit_button = true
  end

  # POST /terms
  # POST /terms.json
  def create
    @term = Term.new(term_params)

    respond_to do |format|
      if @term.save
        format.html { redirect_to @term, notice: 'Term was successfully created.' }
        format.json { render :show, status: :created, location: @term }
      else
        format.html { render :new }
        format.json { render json: @term.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /terms/1
  # PATCH/PUT /terms/1.json
  def update
    respond_to do |format|
      if @term.update(term_params)
        format.html { redirect_to @term, notice: 'Term was successfully updated.' }
        format.json { render :show, status: :ok, location: @term }
      else
        format.html { render :edit }
        format.json { render json: @term.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /terms/1
  # DELETE /terms/1.json
  def destroy
    @term.destroy
    respond_to do |format|
      format.html { redirect_to terms_url, notice: 'Term was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_term
      @term = Term.find(params[:id])
    end

# Never trust parameters from the scary internet, only allow the white list through.
def term_params
  params.require(:term).permit(:name, :category, :definition)
end

def verify_is_admin
      (current_admin.nil?) ? redirect_to(root_path) :
(redirect_to(root_path) unless current_admin.admin?)
    end
end

application_policy.rb

class ApplicationPolicy
  attr_reader :admin, :record

  def initialize(admin, record)
    @admin = admin
    @record = record
  end

  def index?
    false
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  def scope
    Pundit.policy_scope!(admin, record.class)
  end

  class Scope
    attr_reader :admin, :scope

    def initialize(admin, scope)
      @admin = admin
      @scope = scope
    end

    def resolve
      scope
    end
  end
end

terms_policy.rb

class TermPolicy < ApplicationPolicy
  def index?
    true
  end

  def create?
    user.present?
  end

  def update?
    return true if user.present?
  end

  def edit?
    user.admin?
  end

  def destroy?
    user.admin?
  end
end

I've tried implementing suggestions from Access to current_user from within a model in Ruby on Rails, undefined local variable or method `current_user' using devise & rails 3.2, https://code.tutsplus.com/tutorials/authorization-with-pundit--cms-28202, and a smattering of other sources. I'm sure these are all great resources, but at this stage I need something a little more targeted to my project and level of familiarity with Rails.

Let me know what else I can provide. Thanks for your help!

Body:
Hi you can try to add some

  before_action :ensure_admin, except: [:show, :edit, :update]
  before_action :ensure_admin_or_user, only: [:edit, :update, :account]

in your controller

with method =>

  def ensure_admin
    if current_user.nil? || current_user.is_at_least?(:manager) == false
      flash[:notice] = I18n.t('must_be_admin')
      redirect_to root_path
      return true
    end
    false
  end

Hopes its helps you !