问:
Clustering markers from geojson using google maps
I created html page using Google Maps Javascript API. This map displays markers from geojson file. Everything works well. I want to add clustering of markers. But for some reason this does not work. I'm not very good with Javascript. Tell me please how to change my code.

var map;
function initMap() {

  var styleArray = [
    {
      featureType: 'all',
      stylers: [
        { saturation: -80 }
      ]
    },{
      featureType: 'road.arterial',
      elementType: 'geometry',
      stylers: [
        { hue: '#00ffee' },
        { saturation: 50 }
      ]
    },{
      featureType: 'poi.business',
      elementType: 'labels',
      stylers: [
        { visibility: 'off' }
      ]
    }
  ];

  var mapOptions = {
    zoom: 14,
    center: new google.maps.LatLng(42.34, -71.05),
    styles: styleArray
  };

  var map = new google.maps.Map(document.getElementById('map'),
    mapOptions);

  // Load GeoJSON.
  map.data.loadGeoJson('/map.geojson');

  map.data.setStyle(function(feature) {
    return {icon:feature.getProperty('icon')};
  });

  var infoWindow = new google.maps.InfoWindow({
        content: "",
        pixelOffset: new google.maps.Size(0, -40),
        maxWidth: 250
  });

  map.data.addListener('mouseover', function(event) {
    var desc = event.feature.getProperty("description");
    var titl = event.feature.getProperty("address");
    var myadd = event.feature.getProperty("status");
    var myimage = event.feature.getProperty("image");
    var myland = event.feature.getProperty("land");
    var mysize = event.feature.getProperty("size");
    var myunits = event.feature.getProperty("units");
    var myphaze = event.feature.getProperty("permit");
    var contentString = '
' + titl + '

Address: ' + myadd + '
Land Sq. Feet: ' + myland + '
Building Size: ' + mysize + '
Residential Units: ' + myunits + '
Project Phase: ' + myphaze + '

Project Description: ' + desc + '

';
    infoWindow.setContent(contentString);

    var anchor = new google.maps.MVCObject();
    anchor.setValues({ //position of the point
            position: event.latLng,
            anchorPoint: new google.maps.Point(0, -10)
    });

    infoWindow.open(map, anchor);

  });

  var markerCluster = new MarkerClusterer(map, markers);

}```

答:
The answer of @Vadim is good, but it took me a while to find out how to use custom marker icon instead of the default red ones as

```<code>map.data.setStyle(function(feature) {
    return {icon:feature.getProperty('icon')};
});
</code>```

does not work
This works:

```<code>    var markers = features.map(function (feature) {
        var g = feature.getGeometry();
        var iconurl = feature.getProperty('icon');
        var marker = new google.maps.Marker({
          'position': g.get(0) ,
          'icon': iconurl
        });
        return marker;
    });
</code>```

Body:
The answer of @Vadim is good, but it took me a while to find out how to use custom marker icon instead of the default red ones as

map.data.setStyle(function(feature) {
    return {icon:feature.getProperty('icon')};
});

does not work
This works:

    var markers = features.map(function (feature) {
        var g = feature.getGeometry();
        var iconurl = feature.getProperty('icon');
        var marker = new google.maps.Marker({
          'position': g.get(0) ,
          'icon': iconurl
        });
        return marker;
    });


来源: stackexchange

问:
Invalid Trigger Exception
I am a newcomer in ORACLE SQL, I am trying to create a trigger to generate auto_incement serial number as a primary key in my table but no idea what mistake I am making, due to which I am getting :

error while performing partial saving of event: error code=4098 ST=
  java.sql.BatchUpdateException: ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n, caused by : \"ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n\"

My SQL Statement is :

```<code>create global temporary table STAGING_ERROR_REASON (   STAGING_REASON_ID number(4) constraint STAGING_REASON_ID not null   ,REASON nvarchar2(1024) not null   ,constraint PK_STAGING_REASON_ID PRIMARY KEY(STAGING_REASON_ID) );

create sequence STAGING_SEQ_ERROR_REASON start with 1 increment by 1 minvalue 1 maxvalue 10000;

CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
   BEFORE INSERT ON STAGING_ERROR_REASON
   REFERENCING NEW AS NEW
   FOR EACH ROW
BEGIN
   if(:NEW.STAGING_REASON_ID is null) then
      SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL
          INTO :NEW.STAGING_REASON_ID
   END;

ALTER TRIGGER "STAGING_TRIGGER_ERROR_REASON" ENABLE;
</code>```

答:
In Oracle every SELECT statement should have a FROM clause. You should use at least</p>

```<code>SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL INTO :NEW.STAGING_REASON_ID FROM DUAL;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Invalid Trigger Exception

Body:
I am a newcomer in ORACLE SQL, I am trying to create a trigger to generate auto_incement serial number as a primary key in my table but no idea what mistake I am making, due to which I am getting :

error while performing partial saving of event: error code=4098 ST=
  java.sql.BatchUpdateException: ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n, caused by : \"ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n\"

My SQL Statement is :

create global temporary table STAGING_ERROR_REASON (   STAGING_REASON_ID number(4) constraint STAGING_REASON_ID not null   ,REASON nvarchar2(1024) not null   ,constraint PK_STAGING_REASON_ID PRIMARY KEY(STAGING_REASON_ID) );

create sequence STAGING_SEQ_ERROR_REASON start with 1 increment by 1 minvalue 1 maxvalue 10000;

CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
   BEFORE INSERT ON STAGING_ERROR_REASON
   REFERENCING NEW AS NEW
   FOR EACH ROW
BEGIN
   if(:NEW.STAGING_REASON_ID is null) then
      SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL
          INTO :NEW.STAGING_REASON_ID
   END;

ALTER TRIGGER "STAGING_TRIGGER_ERROR_REASON" ENABLE;

Body:
In Oracle every SELECT statement should have a FROM clause. You should use at least

SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL INTO :NEW.STAGING_REASON_ID FROM DUAL;


问:
How to align the input fields?

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

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

      <input class="form-control" id="ex1" placeholder="Last name" type="text">

```

The two input fields do not align in the same line when i take the label off the second field how can this be corrected ?

答:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

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

    <link rel="stylesheet" type="text/css" href="mystyle.css">

    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

    <form>

            Name
            <input class="form-control" id="ex1" placeholder="First name" type="text">

            <input class="form-control" id="ex1" placeholder="Last name" type="text">

    </form>

```

Title: How to align the input fields?

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

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

      <input class="form-control" id="ex1" placeholder="Last name" type="text">

The two input fields do not align in the same line when i take the label off the second field how can this be corrected ?

Body:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <!-- website templates CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <!-- custom  CSS -->
    <link rel="stylesheet" type="text/css" href="mystyle.css">
    <!-- website templates  fonts -->
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

</head>
<body>
<div class="container">
    <form>
     <div class="form-group row">
          <div class="col-xs-6 form-field">
            <label for="ex1" style="margin-bottom:0">Name</label>
            <input class="form-control" id="ex1" placeholder="First name" type="text">
          </div>
          <div class="col-xs-6 form-field">
          <label></label>
            <input class="form-control" id="ex1" placeholder="Last name" type="text">
          </div>
        </div>
    </form>
</div>

</body>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--  website template JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- custom date picker  JavaScript -->
<script src="/js/myScript1.js"></script>
</html>


问:
No such module 'FBAudienceNetwork' in XCode 9 Swift 4
I installed the FBAudienceNetwork (version 4.26.0) with CocoaPods (version 1.3.1). I followed the official manual as published at https://developers.facebook.com/docs/audience-network/ios, but the Xcode still not recognized the framework.

Just to be clear - I opened the project from xcworkspace file.

I tried the following steps with no success:

Install the framework manually, adding the ~/Documents/FacebookSDK path to Framework Search Path

Make sure that the pods project compiled using Swift 4

Added also FBSDKCoreKit (with Bolts) and FBSDKShareKit (both frameworks imported successfully)

Clean the project, delete DerivedData and also clean the pods cache and reinstalling the pods

Nothing worked so far. Anyone faced the same issue and know the reason?

答:
From the audience network installation guide

Good luck


问:
.net 4 Architecture: MVC, WCF Data Services, Repository Pattern, Entity Framework come together?
I have the luxury of starting from scratch with all the latest a greatest .net 4 bits & bobs. My app must support different clients including an MVC Website, iphone App, andriod App & other websites

My application processes quite a bit of spatial data and will need to rely on caching because it exposes geo RSS feeds to allow areas to be rendered as polygons on Bing Maps Ajax 7.

I know I want to use all the above technologies, BUT I'm not yet 100% sure how they all come together.

Sadly E.F. 4 doesn't support spatial data types OR SqlDependecy cache invalidation. SO for some of my data access I've decided to fall back on ADO .net 2 SqlCommands / Stored Procedures (I also think it's going to be worthwhile having SQL Spatial functions pre-compiled and occurring inside of SQL Server).

Hence from my current understanding, here is what I'm thinking:

1) I'll have an .edmx which does Data Access for types with no spatial properties. I will then have Repositories for those types which talk the the .edmx and return POCO objects (using the EF4 Poco Templates).

2) I'll have repositories with hand written ADO .net 2 code for the types with spatial bits.

3) I'll have Service Layer classes (hand written) that encapsulate the repositories (not know how they're implemented or what they are talking to). Here I'll implement security and business logic.

4) I'll have a WCF Data Service (.net 4) deployed in a separate application that exposes the Service layer as OData for the different clients to consume.

5) My MVC as will talk to my WCF Data Service layer from controller code.

6) Other clients will talk to the WCF Data Service layer and deal with the OData they way they wish.

Does that make sense? Using OData for invoking business operations instead of just CRUD? Are there major road blocks and challengers with security and identity over Odata?

Also is it going to be too onerous and should I be looking for some type of hybrid for better performance & less code, like talking directly with (3) from my web app and breaking the layer cake?

答:
Agree with below that sounds like a fair amount of unknowns in the architecting of your system -keep it simple as much as possible - having 2 separate DALs (ODATA and your custom one) is a recipe for code maintainability hell. -you may want to skip the odata part.

your Parts 2&3, 6 seems a bit iffy if your clients need access to the spatial data types concurrently with the ODATA service  REST data. not sure how you can solve that

I will say that ODATA can be accessed by .NET client apps very easily, and there is support for client access via Javascript, Java (see RESTLET) -its great from my limited experience with it for .NET service and .NET clients -haven't used it yet on non .NET clients

Good Luck.. I'd like to know how this all turns out.

ContentLicense: CC BY-SA 2.5


问:
Jmeter Pre-request Script to set value of HTTP Headers
I am trying to execute a pre-request script in Jmeter (similar to what you can do in postman) in order to set Header values at the beginning of every request.
How I can do it?

I am trying to set some Header values in my HTTP Header Manager when the request is made with the pre-request script script below. The values for these headers should be set by this script.

This is the script that I use in postman:

```<code>var client = "SHA256 Credential=" + environment["id"];
var timestamp = Math.floor(Date.now() / 1000);

postman.setEnvironmentVariable('client', client);
postman.setEnvironmentVariable('timestamp', timestamp);
</code>```

(environment["id"] being a preset header).

答:
Assuming that you have id set as a User Defined Variable you can add a HTTP Header Manager as a child of your request and configure it to add the following headers:

Name: client, Value: SHA256 Credential=${id}

Name: timestamp, Value: ${__groovy(Math.round(System.currentTimeMillis()/1000),)}

Where:

${id} is a reference to the id JMeter Variable (you need to set it somehow)

__groovy() is a JMeter Function allowing execution of arbitrary Groovy code

Body:
I am trying to execute a pre-request script in Jmeter (similar to what you can do in postman) in order to set Header values at the beginning of every request.
How I can do it?

I am trying to set some Header values in my HTTP Header Manager when the request is made with the pre-request script script below. The values for these headers should be set by this script.

This is the script that I use in postman:

var client = "SHA256 Credential=" + environment["id"];
var timestamp = Math.floor(Date.now() / 1000);

postman.setEnvironmentVariable('client', client);
postman.setEnvironmentVariable('timestamp', timestamp);

(environment["id"] being a preset header).


问:
SSRS: Repeat Down Total from Matrix in all rows
Need some help in SSRS,

New to this so apologies ahead if not entirely up to scratch with answers.

I am trying to get the Total of a column and repeat the value of that total (Total Checks - see image) across all the rows.

Below is image:

I have tried multiple different ways, each time with failure.

Any help would be much appreciated.

Thanks,

答:
Depending on where you are getting your data from, you have different options.  For example, within SQL you could use windowed functions:

```<code>select Date
      ,Checker
      ,sum(Checker) over () as TotalChecks
      ,sum(Checker) over (partition by Date) as TotalChecksByDate
from table
</code>```

or within SSRS expressions by explicitly stating your scope, either for the dataset as a whole:

```<code>=sum(Fields!Checker.Value, "YourDataset")
</code>```

or just for the grouping within your table:

```<code>=sum(Fields!Checker.Value, "YourTableGroupName")
</code>```

Body:
Depending on where you are getting your data from, you have different options.  For example, within SQL you could use windowed functions:

select Date
      ,Checker
      ,sum(Checker) over () as TotalChecks
      ,sum(Checker) over (partition by Date) as TotalChecksByDate
from table

or within SSRS expressions by explicitly stating your scope, either for the dataset as a whole:

=sum(Fields!Checker.Value, "YourDataset")

or just for the grouping within your table:

=sum(Fields!Checker.Value, "YourTableGroupName")


问:
Is Oracle alter table drop constraint drop index syntactically valid?
I have Oracle 11.2.0.2.0 and a table with unique constraint created by following script:

```<code>    create table foo (id varchar(26) not null, name varchar(50) not null);
    alter table foo add constraint pk_foo primary key (id);
    /**/
    alter table foo add constraint un_foo unique (name);
</code>```

I need to drop the unique constraint, which is easy:

```<code>    alter table foo drop constraint un_foo;
</code>```

The trouble is: when the database is backuped in SQL Developer and then restored, then the un_foo unique index is created by explicit command placed at /**/ line:

```<code>    CREATE UNIQUE INDEX un_foo ON foo (name);
</code>```

Such an explicitly-created index is not deleted by the alter command above. I realized following command works:

```<code>    alter table foo drop constraint un_foo drop index;
</code>```

For primary key, similar command alter table foo drop primary key drop index is in documentation or in Oracle Developer Community discussion. Also, this answer at AskTom uses this syntax too (for keep index). However I don't see any reasoning for such syntax in railroad diagram of alter table command.

Question: is the syntax alter table foo drop constraint un_foo drop index legal? If so, based on what documentation or flow in railroad diagram? If not, why the command doesn't fail?

Thanks!

答:
According to @Chris Saxon's answer to my equivalent question posted to AskTom, the syntax is confirmed as working but not present in documentation.
The decision whether it is doc bug or unintended side effect is still unresolved.

I personally decided to rely on the syntax since, among other things, it is advised also in My Oracle Support.

If absolute safety (read: conforming to the documentation) is required, the only possibility is to use statement alter table foo drop unique (name) drop index;.

I summarized (not so substantial) circumstances around this issue in blogpost (in Czech).

Body:
I have Oracle 11.2.0.2.0 and a table with unique constraint created by following script:

    create table foo (id varchar(26) not null, name varchar(50) not null);
    alter table foo add constraint pk_foo primary key (id);
    /**/
    alter table foo add constraint un_foo unique (name);

I need to drop the unique constraint, which is easy:

    alter table foo drop constraint un_foo;

The trouble is: when the database is backuped in SQL Developer and then restored, then the un_foo unique index is created by explicit command placed at /**/ line:

    CREATE UNIQUE INDEX un_foo ON foo (name);

Such an explicitly-created index is not deleted by the alter command above. I realized following command works:

    alter table foo drop constraint un_foo drop index;

For primary key, similar command alter table foo drop primary key drop index is in documentation or in Oracle Developer Community discussion. Also, this answer at AskTom uses this syntax too (for keep index). However I don't see any reasoning for such syntax in railroad diagram of alter table command.

Question: is the syntax alter table foo drop constraint un_foo drop index legal? If so, based on what documentation or flow in railroad diagram? If not, why the command doesn't fail?

Thanks!


问:
What is the difference between an expression and a statement in Python?
In Python, what is the difference between expressions and statements?</p>

答:
An expression is something that can be reduced to a value, for example "1+3" is an expression, but "foo = 1+3" is not.

It's easy to check:

```<code>print(foo = 1+3)
</code>```

If it doesn't work, it's a statement, if it does, it's an expression.

Another statement could be:

```<code>class Foo(Bar): pass
</code>```

as it cannot be reduced to a value.

Body:
An expression is something that can be reduced to a value, for example "1+3" is an expression, but "foo = 1+3" is not.

It's easy to check:

print(foo = 1+3)

If it doesn't work, it's a statement, if it does, it's an expression.

Another statement could be:

class Foo(Bar): pass

as it cannot be reduced to a value.

ContentLicense: CC BY-SA 4.0


问:
How to fix if one press one operator and then another operator in Calculator?
I'm building a calculator for FreeCodeCamp challenge. My code is almost done except for several problems. One of the problems is the repeating operators. For example, if someone press "5+" then changed his mind, pressing the "-" instead, the result should be "5-" instead.

Here is my original code from my Codepen:

$(document).ready(function() {

  var mainMath = "0";
  var subMath = "0";
  var finalset = "";
  var subMatharray = [];
  var equaltrue = false;
  update();

  $("button").click(function(){
    calculate($(this).attr("value"));
  });

  function calculate(keyitem) {
    console.log("buttonpress: " + keyitem);
    switch(keyitem) {
      case "clear":
        clearScreen();
        break;
      case "%":
        percentageScreen();
        break;
      case "/":
      case "*":
      case "+":
      case "-":
        addOperator(keyitem);
        break;
      case "plusminus":
        plusminusScreen();
        break;
      case "0":
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
        addNumber(keyitem);
        break;
      case ".":
        addDecimal(keyitem);
        break;
      case "=":
        solveEqual(keyitem);
        break;
    }
    update();
    };

  function clearScreen() {
     mainMath = "0";
     subMath = "0";
     subMatharray = [];
    if(mainMath.length > 0){
      $(".entry").css("font-size", "4em");
    }
    console.log("clearMain: " + mainMath);
    console.log("clearSub: " + subMath);
  };

  function plusminusScreen() {
     mainMath = -1 * mainMath;
    finalset = mainMath;
    console.log("plusminusMain: " + mainMath);
    console.log("plusminusFinal: " + finalset);
  };

  function addNumber(keyitem) {
    if (mainMath == "0"){
      mainMath = keyitem/*mainMath.replace("0", keyitem);*/
      finalset = mainMath;
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }
    if (equaltrue == true){
      mainMath = keyitem;
      subMath = "0";
      subMatharray = [];
      console.log("addNumberEqualmain: " + mainMath);
    }
    mainMath+=keyitem;
    finalset = mainMath;

    console.log("addedMain: " + mainMath);
    console.log("addedFinalset: " + finalset);
    console.log("addedarray: " + subMatharray);

    if(mainMath.length > 8){
      $(".entry").css("font-size", "1.5em");
    }

  };

  function addOperator(keyitem){
    if (equaltrue == true){
      subMatharray = [];
      console.log("addOpEqualarray: " + subMatharray);
    }
    subMatharray.push(mainMath,keyitem);
    subMath = subMatharray.join("");
    mainMath = "0";
    console.log("addOpSub: " + subMath);
    console.log("addOpMain: " + mainMath);
    console.log("addOpMainarray: " + subMatharray);
    console.log("equaltrueTest: " + equaltrue);
  };

  function addDecimal(keyitem){
    if (mainMath.indexOf(keyitem) === -1){
      if(mainMath == "0") {
        mainMath = "0" + keyitem;
        return;
      }
    } else {
        return;
      }
    addNumber(keyitem);
  };

  function solveEqual(keyitem) {
    mainMath = eval(subMath+mainMath);
    console.log("solveEqualresult: " + mainMath);
    subMatharray.push(finalset);
    subMath = subMatharray.join("");
    console.log("solveEqualhistory: " + subMath);
    console.log("solveEqualarray: " + subMatharray);
    var finalresult = mainMath.toString();
    if(finalresult.length > 8){
      $(".entry").css("font-size", "1.5em");
    }
    equaltrue = true;
  };

  function update(){
  $("#answer").html(mainMath);
  $("#history").html(subMath);
};

});

/*Problems
2. I need to work on percentage button soon...
3. fix the problem if someone click an operator more than one.
*/```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Roboto:300,400');
h1, h2, h3, p {
  font-family: 'Roboto', sans-serif;
}
html, body{
  height:100%;
  margin: 0;
  background-color: #ffffff;
}
.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  display:flex;
  flex-direction:column;
  justify-content:center;
  align-items:center;
  background-repeat: no-repeat;
    background-size: cover;
  background-position: center center;
  padding: 160px 0;
}
.calculatorbox {
  width: 300px;
  margin: 0 auto;
  border: 1px solid #000000;
}
.calheader {
  text-align: center;
}
.calwindow {
  background: #000000;
  position: relative;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
   -webkit-flex-direction: column; /* Safari */
  flex-direction:         column;
  -webkit-justify-content: flex-end;
  justify-content: flex-end;
  -webkit-align-items: flex-end;
  align-items: flex-end;
  padding: 10px 0;
  box-sizing: border-box;
}
.entry {
  font-size: 4em;
  display: block;
  line-height: 1em;
}
.entryhistory {
  font-size: 1em;
  letter-spacing: 2px;
  padding-right: 5px;
}
.entry p, .entryhistory p {
  margin: 0;
  color: #ffffff;
}
sup {
  top: -0.5em;
}

sub {
  bottom: -0em;
}
.row {
  clear: both;
  width: 100%;
  display: flex;
}
button {
  display: inline-block;
  border: none;
  padding: 0;
  outline: none;
  cursor: pointer;
}
.key {
  width: 75px;
  height: 70px;
  font-size: 22px;
  border-top: 1px solid rgba(0, 0, 0, 0.3);
  border-right: 1px solid rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
}
.key.btnspan {
  width: 150px;
}
.key.topcolor {
  background: #d9d9d9;
}
.key.orange {
  background: #ff8c00;
  color: #ffffff;
}</code>```

Simple Calculator

0

        <button class="key topcolor" value="clear">C</button>
        <button class="key topcolor" value="plusminus">+/−</button>
        <button class="key topcolor" value="%">%</button>
        <button class="key orange" value="/">÷</button>

        <button class="key" value="7">7</button>
        <button class="key" value="8">8</button>
        <button class="key" value="9">9</button>
        <button class="key orange" value="*">×</button>

        <button class="key" value="4">4</button>
        <button class="key" value="5">5</button>
        <button class="key" value="6">6</button>
        <button class="key orange" value="-">−</button>

        <button class="key" value="1">1</button>
        <button class="key" value="2">2</button>
        <button class="key" value="3">3</button>
        <button class="key orange" value="+">+</button>

        <button class="key btnspan" value="0">0</button>
        <button class="key" value=".">.</button>
        <button class="key orange" value="=">=</button>

```
</div>
</div>
</p>

<p>I have tried to attempt to edit the code but it's not working very well. Here is my attempt at this area in <code>function addOperator()</code>.</p>

```function addOperator(keyitem){
    var opkeyitem = "";
    oppArray.push(keyitem);
    console.log("addoppArray: " + oppArray);
    if (oppArray.length > 1){
            oppArray.shift();
      opkeyitem = oppArray.toString();
      subMatharray[1] = opkeyitem;
      subMath = subMatharray.join("");
      oppArray = [];
      console.log("addoppArrayShift: " + oppArray);
      console.log("addoppSubShift: " + subMatharray);
     } else if(oppArray.length == 1) {
      opkeyitem = oppArray.toString();
       if (equaltrue == true){
      subMatharray = [];
      console.log("addOpEqualarray: " + subMatharray);
    }
    subMatharray.push(mainMath,opkeyitem);
    subMath = subMatharray.join("");
    mainMath = "0";
    oppArray = [];
    }
  };
```

My idea was to store the operators pressed in an array. If it's more than one operator, then the array should knock off the first element and use the last element and add/replace it to the history area.

How do you suggest I go about solving this problem?

答:
You need to remember what was the last pressed button and change the logic of addOperator function accordingly. If the last pressed button was operator and someone pressed operator again, it should first pop the original one out of the array, where you are saving pressed buttons and then push the new one into it.

A simple boolean variable lastPressedIsOperator could do all the job or create a more general lastPressedType string variable and change it to 'operator'/'number'/etc. accordingly to last pressed button. Then in addOperator first check what is in that variable and act accordingly as I described above.

Body:
I'm building a calculator for FreeCodeCamp challenge. My code is almost done except for several problems. One of the problems is the repeating operators. For example, if someone press "5+" then changed his mind, pressing the "-" instead, the result should be "5-" instead.

Here is my original code from my Codepen:

$(document).ready(function() {

  var mainMath = "0";
  var subMath = "0";
  var finalset = "";
  var subMatharray = [];
  var equaltrue = false;
  update();

  $("button").click(function(){
    calculate($(this).attr("value"));
  });

  function calculate(keyitem) {
    console.log("buttonpress: " + keyitem);
    switch(keyitem) {
      case "clear":
        clearScreen();
        break;
      case "%":
        percentageScreen();
        break;
      case "/":
      case "*":
      case "+":
      case "-":
        addOperator(keyitem);
        break;
      case "plusminus":
        plusminusScreen();
        break;
      case "0":
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
        addNumber(keyitem);
        break;
      case ".":
        addDecimal(keyitem);
        break;
      case "=":
        solveEqual(keyitem);
        break;
    }
    update();
    };

  function clearScreen() {
     mainMath = "0";
     subMath = "0";
     subMatharray = [];
    if(mainMath.length > 0){
      $(".entry").css("font-size", "4em");
    }
    console.log("clearMain: " + mainMath);
    console.log("clearSub: " + subMath);
  };

  function plusminusScreen() {
     mainMath = -1 * mainMath;
    finalset = mainMath;
    console.log("plusminusMain: " + mainMath);
    console.log("plusminusFinal: " + finalset);
  };

  function addNumber(keyitem) {
    if (mainMath == "0"){
      mainMath = keyitem/*mainMath.replace("0", keyitem);*/
      finalset = mainMath;
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }
    if (equaltrue == true){
      mainMath = keyitem;
      subMath = "0";
      subMatharray = [];
      console.log("addNumberEqualmain: " + mainMath);
    }
    mainMath+=keyitem;
    finalset = mainMath;

    console.log("addedMain: " + mainMath);
    console.log("addedFinalset: " + finalset);
    console.log("addedarray: " + subMatharray);

    if(mainMath.length > 8){
      $(".entry").css("font-size", "1.5em");
    }

  };

  function addOperator(keyitem){
    if (equaltrue == true){
      subMatharray = [];
      console.log("addOpEqualarray: " + subMatharray);
    }
    subMatharray.push(mainMath,keyitem);
    subMath = subMatharray.join("");
    mainMath = "0";
    console.log("addOpSub: " + subMath);
    console.log("addOpMain: " + mainMath);
    console.log("addOpMainarray: " + subMatharray);
    console.log("equaltrueTest: " + equaltrue);
  };

  function addDecimal(keyitem){
    if (mainMath.indexOf(keyitem) === -1){
      if(mainMath == "0") {
        mainMath = "0" + keyitem;
        return;
      }
    } else {
        return;
      }
    addNumber(keyitem);
  };

  function solveEqual(keyitem) {
    mainMath = eval(subMath+mainMath);
    console.log("solveEqualresult: " + mainMath);
    subMatharray.push(finalset);
    subMath = subMatharray.join("");
    console.log("solveEqualhistory: " + subMath);
    console.log("solveEqualarray: " + subMatharray);
    var finalresult = mainMath.toString();
    if(finalresult.length > 8){
      $(".entry").css("font-size", "1.5em");
    }
    equaltrue = true;
  };

  function update(){
  $("#answer").html(mainMath);
  $("#history").html(subMath);
};

});

/*Problems
2. I need to work on percentage button soon...
3. fix the problem if someone click an operator more than one.
*/

@import url('https://fonts.googleapis.com/css?family=Roboto:300,400');
h1, h2, h3, p {
  font-family: 'Roboto', sans-serif;
}
html, body{
  height:100%;
  margin: 0;
  background-color: #ffffff;
}
.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  display:flex;
  flex-direction:column;
  justify-content:center;
  align-items:center;
  background-repeat: no-repeat;
    background-size: cover;
  background-position: center center;
  padding: 160px 0;
}
.calculatorbox {
  width: 300px;
  margin: 0 auto;
  border: 1px solid #000000;
}
.calheader {
  text-align: center;
}
.calwindow {
  background: #000000;
  position: relative;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
   -webkit-flex-direction: column; /* Safari */
  flex-direction:         column;
  -webkit-justify-content: flex-end;
  justify-content: flex-end;
  -webkit-align-items: flex-end;
  align-items: flex-end;
  padding: 10px 0;
  box-sizing: border-box;
}
.entry {
  font-size: 4em;
  display: block;
  line-height: 1em;
}
.entryhistory {
  font-size: 1em;
  letter-spacing: 2px;
  padding-right: 5px;
}
.entry p, .entryhistory p {
  margin: 0;
  color: #ffffff;
}
sup {
  top: -0.5em;
}

sub {
  bottom: -0em;
}
.row {
  clear: both;
  width: 100%;
  display: flex;
}
button {
  display: inline-block;
  border: none;
  padding: 0;
  outline: none;
  cursor: pointer;
}
.key {
  width: 75px;
  height: 70px;
  font-size: 22px;
  border-top: 1px solid rgba(0, 0, 0, 0.3);
  border-right: 1px solid rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
}
.key.btnspan {
  width: 150px;
}
.key.topcolor {
  background: #d9d9d9;
}
.key.orange {
  background: #ff8c00;
  color: #ffffff;
}

Simple Calculator

0

        <button class="key topcolor" value="clear">C</button>
        <button class="key topcolor" value="plusminus">+/−</button>
        <button class="key topcolor" value="%">%</button>
        <button class="key orange" value="/">÷</button>

        <button class="key" value="7">7</button>
        <button class="key" value="8">8</button>
        <button class="key" value="9">9</button>
        <button class="key orange" value="*">×</button>

        <button class="key" value="4">4</button>
        <button class="key" value="5">5</button>
        <button class="key" value="6">6</button>
        <button class="key orange" value="-">−</button>

        <button class="key" value="1">1</button>
        <button class="key" value="2">2</button>
        <button class="key" value="3">3</button>
        <button class="key orange" value="+">+</button>

        <button class="key btnspan" value="0">0</button>
        <button class="key" value=".">.</button>
        <button class="key orange" value="=">=</button>

I have tried to attempt to edit the code but it's not working very well. Here is my attempt at this area in function addOperator().

function addOperator(keyitem){
    var opkeyitem = "";
    oppArray.push(keyitem);
    console.log("addoppArray: " + oppArray);
    if (oppArray.length > 1){
            oppArray.shift();
      opkeyitem = oppArray.toString();
      subMatharray[1] = opkeyitem;
      subMath = subMatharray.join("");
      oppArray = [];
      console.log("addoppArrayShift: " + oppArray);
      console.log("addoppSubShift: " + subMatharray);
     } else if(oppArray.length == 1) {
      opkeyitem = oppArray.toString();
       if (equaltrue == true){
      subMatharray = [];
      console.log("addOpEqualarray: " + subMatharray);
    }
    subMatharray.push(mainMath,opkeyitem);
    subMath = subMatharray.join("");
    mainMath = "0";
    oppArray = [];
    }
  };

My idea was to store the operators pressed in an array. If it's more than one operator, then the array should knock off the first element and use the last element and add/replace it to the history area.

How do you suggest I go about solving this problem?


问:
How to clear the cache of an asp.net application from another asp.net application on the same server?
Got a bit of an odd problem. Here goes:

I have two ASP.NET applications: A web app and a web service app.

Information arriving via the webservice effects data in the database used by the web app.

One particular bit of data controls items in a drop down menu - when the data is altered in the app it can call:

```<code>HttpContext.Current.Cache.Remove
</code>```

but I now need to clear the cache in the web service as i can recieve messages which update that information.

Can anyone recommend a way of doing this?

答:
You can try SQL Dependency. It will trigger an event when the table you have subscribed has any changes.

https://www.codeproject.com/Articles/12335/Using-SqlDependency-for-data-change-events

Body:
Got a bit of an odd problem. Here goes:

I have two ASP.NET applications: A web app and a web service app.

Information arriving via the webservice effects data in the database used by the web app.

One particular bit of data controls items in a drop down menu - when the data is altered in the app it can call:

HttpContext.Current.Cache.Remove

but I now need to clear the cache in the web service as i can recieve messages which update that information.

Can anyone recommend a way of doing this?


问:
Jquery multiple div slide toggle inside ul li
I have multiple divs inside ul li

```<code><div>
  <ul>
    <li>
      <div id="flip" class="manage-image-container">
        <a href="#">
          <img src="/files/images/icns/settings-1.svg" alt="">
        </a>
        <h4>TEST</h4>
      </div>
    </li>
    <li>
      <div id="flip" class="manage-image-container">
        <a href="#">
          <img src="/files/images/icns/settings-1.svg" alt="">
        </a>
        <h4>TEST</h4>
      </div>
    </li>
    <li>
      <div id="flip" class="manage-image-container">
        <a href="#">
          <img src="/files/images/icns/settings-1.svg" alt="">
        </a>
        <h4>TEST</h4>
      </div>
    </li>
  </ul>
</div>
</code>```

Im using this for the script for the slide toggle

```<code>$('#panel').hide();
$("#flip").click(function () {
    $(this).next("#panel").slideToggle("slow");
});
</code>```

it only toggles on the first
 but not on the rest of the
. Dont know what i'm doing wrong. The  $(this).next("#panel").slideToggle("slow"); doesn't seem to be working.

i have added the jsfiddle link

答:
dont use same ID for more than 1 divs. that violates w3c standard

use class for your jquery selector for the click()

i dont see id="panel" in your html. use class instead

$('.panel').hide();
$(".flip").click(function() {
    $(this).next(".panel").slideToggle("slow");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.manage-account-master {
    width: 100%;
    height: 100%;
    margin: 0 auto;
}

.manage-account-master-top {
    width: 100%;
    height: 50%;
}

.manage-account-master-bottom {
    width: 100%;
    height: 50%;
}

.manage-account-1 {
    width: 50%;
    float: left;
    height: 100%;
    position: relative;
}

.manage-account-2 {
    width: 50%;
    float: right;
    height: 100%;
    position: relative;
}

.manage-account-3 {
    width: 50%;
    float: left;
    height: 100%;
    position: relative;
}

.manage-account-4 {
    width: 50%;
    float: right;
    height: 100%;
    position: relative;
}

.manage-account-inner {
    display: table;
    position: absolute;
    height: 100%;
    width: 100%;
}

.manage-account-inner-1 {
    display: table-cell;
    vertical-align: middle;
}

.manage-account-inner-2 {
    margin-left: auto;
    margin-right: auto;
    max-width: 600px;
    text-align: center;
    h4 {
        font-size: 1.2rem;
    }
    ul {
        display: block;
    }
}

.rig {
    max-width: 100%;
    margin: 0 auto;
    padding: 0;
    list-style: none;
    max-height: 100%;
}

.rig li {
    display: inline-block;
    width: 50%;
    vertical-align: middle;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    float: left;
}

.manage-image-container {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: block;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    -ms-flex-pack: center;
    justify-content: center;
    height: 100%;
    width: 100%;
}

.manage-image-container img {
    width: 80px !important;
    margin: auto;
    position: relative;
    height: auto;
    z-index: 40;
    padding-top: 25px;
}

#panel,
#flip {
    padding: 5px;
    text-align: center;
}

#panel {
    background: aliceblue;
    display: none;
}</code>```

Cats

                            Menus

Dogs

                            Menus

Horses

                            Menus

Settings

                            Menus

```

Also on JSFiddle.

Body:
I have multiple divs inside ul li

TEST

TEST

TEST

Im using this for the script for the slide toggle

$('#panel').hide();
$("#flip").click(function () {
    $(this).next("#panel").slideToggle("slow");
});

it only toggles on the first
 but not on the rest of the
. Dont know what i'm doing wrong. The  $(this).next("#panel").slideToggle("slow"); doesn't seem to be working.

i have added the jsfiddle link

Body:
dont use same ID for more than 1 divs. that violates w3c standard

use class for your jquery selector for the click()

i dont see id="panel" in your html. use class instead

$('.panel').hide();
$(".flip").click(function() {
    $(this).next(".panel").slideToggle("slow");
});

.manage-account-master {
    width: 100%;
    height: 100%;
    margin: 0 auto;
}

.manage-account-master-top {
    width: 100%;
    height: 50%;
}

.manage-account-master-bottom {
    width: 100%;
    height: 50%;
}

.manage-account-1 {
    width: 50%;
    float: left;
    height: 100%;
    position: relative;
}

.manage-account-2 {
    width: 50%;
    float: right;
    height: 100%;
    position: relative;
}

.manage-account-3 {
    width: 50%;
    float: left;
    height: 100%;
    position: relative;
}

.manage-account-4 {
    width: 50%;
    float: right;
    height: 100%;
    position: relative;
}

.manage-account-inner {
    display: table;
    position: absolute;
    height: 100%;
    width: 100%;
}

.manage-account-inner-1 {
    display: table-cell;
    vertical-align: middle;
}

.manage-account-inner-2 {
    margin-left: auto;
    margin-right: auto;
    max-width: 600px;
    text-align: center;
    h4 {
        font-size: 1.2rem;
    }
    ul {
        display: block;
    }
}

.rig {
    max-width: 100%;
    margin: 0 auto;
    padding: 0;
    list-style: none;
    max-height: 100%;
}

.rig li {
    display: inline-block;
    width: 50%;
    vertical-align: middle;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    float: left;
}

.manage-image-container {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: block;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    -ms-flex-pack: center;
    justify-content: center;
    height: 100%;
    width: 100%;
}

.manage-image-container img {
    width: 80px !important;
    margin: auto;
    position: relative;
    height: auto;
    z-index: 40;
    padding-top: 25px;
}

#panel,
#flip {
    padding: 5px;
    text-align: center;
}

#panel {
    background: aliceblue;
    display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="manage-account-master">
    <div class="manage-account-inner">
        <div class="manage-account-inner-1">
            <div class="manage-account-inner-2">
                <ul class="rig">
                    <li>
                        <div class="flip manage-image-container">
                            <a href="#">
                                <img src="https://creativecommons.org/wp-content/uploads/2016/06/search.png" alt="">
                            </a>
                            <h4>Cats</h4>
                        </div>
                        <div class="panel">
                            Menus
                        </div>
                    </li>
                    <li>
                        <div class="flip manage-image-container">
                            <a href="#">
                                <img src="https://maxcdn.icons8.com/Share/icon/Very_Basic//upload_21600.png" alt="">
                            </a>
                            <h4>Dogs</h4>
                        </div>
                        <div class="panel">
                            Menus
                        </div>
                    </li>
                    <li>
                        <div class="flip manage-image-container">
                            <a href="#">
                                <img src="http://freedesignfile.com/upload/2017/09/house-icon-vector.jpg" alt="">
                            </a>
                            <h4>Horses</h4>
                        </div>
                        <div class="panel">
                            Menus
                        </div>
                    </li>
                    <li>
                        <div class="flip manage-image-container">
                            <a href="#">
                                <img src="https://lh3.googleusercontent.com/ez8pDFoxU2ZqDmyfeIjIba6dWisd8MY_6choHhZNpO0WwLhICu0v0s5eV2WHOhuhKw=w170" alt="">
                            </a>
                            <h4>Settings</h4>
                        </div>
                        <div class="panel">
                            Menus
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>

Also on JSFiddle.


问:
Can I pass the output from Date.toString() to the Date constructor?
I have the output from Date.toString() and need to convert it back to a Date:

```<code>var dateString = new Date().toString();
// in Chrome: "Tue Nov 14 2017 09:06:46 GMT+0100 (Mitteleuropäische Zeit)"
// in IE11:   "Tue Nov 14 2017 09:07:38 GMT+0100 (Mitteleuropäische Zeit)"
// in FF:     "Tue Nov 14 2017 09:08:15 GMT+0100"
</code>```

Can I do this?

```<code>var date = new Date(dateString);
</code>```

I need to support IE11, Chrome and FF. I have tried it in these browsers and it works (on my machine).

However I'm not sure if this is safe because several sources say that you should not parse Date strings (e.g. MDN). Is this valid for for the output of Date.toString() too?

Should I use moment.js?

Unfortunately I'm not in control of the code which generates the date string.

答:
Give a try and you'll have your answer.</p>

```<code>console.log(new Date(new Date().toString())); // 2017-11-14T08:38:09.000Z
</code>```

Body:
I have the output from Date.toString() and need to convert it back to a Date:

var dateString = new Date().toString();
// in Chrome: "Tue Nov 14 2017 09:06:46 GMT+0100 (Mitteleuropäische Zeit)"
// in IE11:   "Tue Nov 14 2017 09:07:38 GMT+0100 (Mitteleuropäische Zeit)"
// in FF:     "Tue Nov 14 2017 09:08:15 GMT+0100"

Can I do this?

var date = new Date(dateString);

I need to support IE11, Chrome and FF. I have tried it in these browsers and it works (on my machine).

However I'm not sure if this is safe because several sources say that you should not parse Date strings (e.g. MDN). Is this valid for for the output of Date.toString() too?

Should I use moment.js?

Unfortunately I'm not in control of the code which generates the date string.

Body:
Give a try and you'll have your answer.

console.log(new Date(new Date().toString())); // 2017-11-14T08:38:09.000Z


问:
Products are not showed under catalog page
My problem is when I add a product from catalog-product and associate it with a specific category. This product is not displayed on the category page.

For example: if I add a product and associate it with furniture section. When I click furniture page, there is no any product displayed on the furniture page.

I can't find a bug log online. But it is working on my localhost. Just no works for my live site.

Does anyone find the same problem before? And how can I fix it?

I turn on the debug mode and got this error:

```<code>[PrestaShopDatabaseException]
Access denied for user 'XXXXXX'@'%' to database 'XXXX'

CREATE TEMPORARY TABLE ps_cat_restriction ENGINE=MEMORY SELECT DISTINCT cp.id_product, p.id_manufacturer, product_shop.condition, p.weight FROM ps_category c STRAIGHT_JOIN ps_category_product cp ON (c.id_category = cp.id_category AND c.nleft >= 35 AND c.nright <= 52 AND c.active = 1) STRAIGHT_JOIN ps_product_shop product_shop ON (product_shop.id_product = cp.id_product AND product_shop.id_shop = 1) STRAIGHT_JOIN ps_product p ON (p.id_product=cp.id_product) WHERE product_shop.`active` = 1 AND product_shop.`visibility` IN ("both", "catalog")
</code>```

答: You need to grant 'create temporary tables' privileges to your MySQL user.</p>

Body:
My problem is when I add a product from catalog-product and associate it with a specific category. This product is not displayed on the category page.

For example: if I add a product and associate it with furniture section. When I click furniture page, there is no any product displayed on the furniture page.

I can't find a bug log online. But it is working on my localhost. Just no works for my live site.

Does anyone find the same problem before? And how can I fix it?

I turn on the debug mode and got this error:

[PrestaShopDatabaseException]
Access denied for user 'XXXXXX'@'%' to database 'XXXX'

CREATE TEMPORARY TABLE ps_cat_restriction ENGINE=MEMORY SELECT DISTINCT cp.id_product, p.id_manufacturer, product_shop.condition, p.weight FROM ps_category c STRAIGHT_JOIN ps_category_product cp ON (c.id_category = cp.id_category AND c.nleft >= 35 AND c.nright <= 52 AND c.active = 1) STRAIGHT_JOIN ps_product_shop product_shop ON (product_shop.id_product = cp.id_product AND product_shop.id_shop = 1) STRAIGHT_JOIN ps_product p ON (p.id_product=cp.id_product) WHERE product_shop.`active` = 1 AND product_shop.`visibility` IN ("both", "catalog")


问:
Loading feature module from another Angular4 project
This is regarding Angular4 project setup.

Is it possible to load the feature module from another Angular4 project?

The approach I am trying was to keep the project repositories separate and load feature modules conditionally into the main project. So that the development will be isolated and independent.
Any insights into this or is there any other better approach?

答:
In my opinion you should pull it out and create separate library then include (i don't now how yet) it in both project, for example like Angular Material 2.

I think when you create separate project with only this feature module and then export it in app module you can then install it with npm and import in many projects.


问:
How to get event target/this without putting the event listener in the HTML tag?
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use

$(document).ready(function(){})

I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?

//$(document).ready(function() {
  window.onload = startup;
  function startup() {
    $("img").hide();
    //$("button").click(showImage(this));
  }
  function showImage(e) {
    var chosen = e.value;
    $('#' + chosen).fadeIn(500);
    $('img:not(#' + chosen + ')').hide();
  }
//});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}</code>```

<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>```

Thanks in advance!

PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.

PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D

PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)

答:
Firstly you need to define function() in a click function so it should look like this:

```<code>    $("button").click(function() {
        //code to execute here
    });
</code>```

Instead of this:

```<code>    $("button").click(//code to execute here);
</code>```

When calling this in a button it will refer to the button and if I understand your code right, the image is hidden therefore if that is the button then you can't click a hidden image, if you're using a separate button to hide the image then in the click function you need to have e stated as the image element.

To use this you also need to call it as $(this) not just this.

Body:
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use

$(document).ready(function(){})

I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?

//$(document).ready(function() {
  window.onload = startup;
  function startup() {
    $("img").hide();
    //$("button").click(showImage(this));
  }
  function showImage(e) {
    var chosen = e.value;
    $('#' + chosen).fadeIn(500);
    $('img:not(#' + chosen + ')').hide();
  }
//});

body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}

<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>

Thanks in advance!

PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.

PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D

PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)

Body:
Firstly you need to define function() in a click function so it should look like this:

    $("button").click(function() {
        //code to execute here
    });

Instead of this:

    $("button").click(//code to execute here);

When calling this in a button it will refer to the button and if I understand your code right, the image is hidden therefore if that is the button then you can't click a hidden image, if you're using a separate button to hide the image then in the click function you need to have e stated as the image element.

To use this you also need to call it as $(this) not just this.


问:
Freely convert between List<T> and IEnumerable<T>
How can I convert a List<MyObject> to an IEnumerable<MyObject> and then back again?

I want to do this in order to run a series of LINQ statements on the List, e. g. Sort()

答:
Aside: Note that the standard LINQ operators (as per the earlier example) don't change the existing list - list.OrderBy(...).ToList() will create a new list based on the re-ordered sequence. It is pretty easy, however, to create an extension method that allows you to use lambdas with List<T>.Sort:

```<code>static void Sort<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
}

static void SortDescending<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(y), selector(x)));
}
</code>```

Then you can use:

```<code>list.Sort(x=>x.SomeProp); // etc
</code>```

This updates the existing list in the same way that List<T>.Sort usually does.

OwnerDisplayName: TK

Body:
Aside: Note that the standard LINQ operators (as per the earlier example) don't change the existing list - list.OrderBy(...).ToList() will create a new list based on the re-ordered sequence. It is pretty easy, however, to create an extension method that allows you to use lambdas with List<T>.Sort:

static void Sort<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
}

static void SortDescending<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(y), selector(x)));
}

Then you can use:

list.Sort(x=>x.SomeProp); // etc

This updates the existing list in the same way that List<T>.Sort usually does.

OwnerDisplayName: Marc Gravell

LastEditorDisplayName: Marc Gravell


问:
jpa mysql table does not exists autoGenerate doesn't work
i am trying to insert a Employee entity into the database. I am using JPA and the database is mysql. When I try to insert the entity, it gives me tables must be created I assume that I dont have to create the table. Entity will automatically create the table with the annotated name. Please find the exception and code below.

```<code>    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'gsq.articles' doesn't exist
Error Code: 1146
Call: CREATE TABLE articles (id INTEGER AUTO_INCREMENT NOT NULL, libelle VARCHAR(255), ENTREPRISE_id INTEGER, PRIMARY KEY (id))
Query: DataModifyQuery(sql="CREATE TABLE articles (id INTEGER AUTO_INCREMENT NOT NULL, libelle VARCHAR(255), ENTREPRISE_id INTEGER, PRIMARY KEY (id))")
[EL Fine]: 2017-11-12 20:57:29.914--ServerSession(162116790)--Connection(578752466)--CREATE TABLE entreprise (id INTEGER AUTO_INCREMENT NOT NULL, libelle VARCHAR(255) UNIQUE, PRIMARY KEY (id))
[EL Fine]: 2017-11-12 20:57:29.919--ServerSession(162116790)--SELECT 1
[EL Warning]: 2017-11-12 20:57:29.921--ServerSession(162116790)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'gsq.entreprise' doesn't exist
Error Code: 1146
Call: CREATE TABLE entreprise (id INTEGER AUTO_INCREMENT NOT NULL, libelle VARCHAR(255) UNIQUE, PRIMARY KEY (id))
Query: DataModifyQuery(sql="CREATE TABLE entreprise (id INTEGER AUTO_INCREMENT NOT NULL, libelle VARCHAR(255) UNIQUE, PRIMARY KEY (id))")
[EL Fine]: 2017-11-12 20:57:29.922--ServerSession(162116790)--Connection(578752466)--CREATE TABLE users (ID BIGINT AUTO_INCREMENT NOT NULL, password VARCHAR(255), type VARCHAR(255), username VARCHAR(255) UNIQUE, PRIMARY KEY (ID))
[EL Fine]: 2017-11-12 20:57:29.927--ServerSession(162116790)--SELECT 1
[EL Warning]: 2017-11-12 20:57:29.929--ServerSession(162116790)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'gsq.users' doesn't exist
Error Code: 1146
Call: CREATE TABLE users (ID BIGINT AUTO_INCREMENT NOT NULL, password VARCHAR(255), type VARCHAR(255), username VARCHAR(255) UNIQUE, PRIMARY KEY (ID))
Query: DataModifyQuery(sql="CREATE TABLE users (ID BIGINT AUTO_INCREMENT NOT NULL, password VARCHAR(255), type VARCHAR(255), username VARCHAR(255) UNIQUE, PRIMARY KEY (ID))")
[EL Fine]: 2017-11-12 20:57:29.93--ServerSession(162116790)--Connection(578752466)--ALTER TABLE articles ADD CONSTRAINT FK_articles_ENTREPRISE_id FOREIGN KEY (ENTREPRISE_id) REFERENCES entreprise (id)
[EL Fine]: 2017-11-12 20:57:29.935--ServerSession(162116790)--SELECT 1
[EL Warning]: 2017-11-12 20:57:29.936--ServerSession(162116790)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'gsq.articles' doesn't exist
Error Code: 1146
Call: ALTER TABLE articles ADD CONSTRAINT FK_articles_ENTREPRISE_id FOREIGN KEY (ENTREPRISE_id) REFERENCES entreprise (id)
Query: DataModifyQuery(sql="ALTER TABLE articles ADD CONSTRAINT FK_articles_ENTREPRISE_id FOREIGN KEY (ENTREPRISE_id) REFERENCES entreprise (id)")
[EL Fine]: 2017-11-12 20:57:30.035--ServerSession(162116790)--Connection(578752466)--SELECT id, libelle FROM entreprise
[EL Fine]: 2017-11-12 20:57:30.035--ServerSession(162116790)--SELECT 1
[EL Warning]: 2017-11-12 20:57:30.035--UnitOfWork(1734860123)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'gsq.entreprise' doesn't exist
Error Code: 1146
Call: SELECT id, libelle FROM entreprise
Query: ReadAllQuery(referenceClass=Entreprise sql="SELECT id, libelle FROM entreprise")
Exception in thread "AWT-EventQueue-0" javax.persistence.RollbackException: Transaction rolled back because transaction was set to RollbackOnly.
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:92)
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
    at controlleur.Executerequest.closeEntityManager(Executerequest.java:73)
    at frame.ArticlesFram.MajComBox(ArticlesFram.java:385)
    at frame.ArticlesFram.<init>(ArticlesFram.java:53)
    at frame.ArticlesFram$13.run(ArticlesFram.java:501)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="GSQPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>entities.Articles</class>
    <class>entities.Entreprise</class>
    <class>entities.Users</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/gsq"/>
      <property name="javax.persistence.jdbc.password" value=""/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="eclipselink.logging.level.sql" value="FINE"/>
      <property name="eclipselink.logging.parameters" value="true"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
</persistence>
</code>```

Artcile entity

```<code>@Entity
@Table(name = "articles")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Articles.findAll", query = "SELECT a FROM Articles a"),
    @NamedQuery(name = "Articles.findById", query = "SELECT a FROM Articles a WHERE a.id = :id"),
     @NamedQuery(name = "Articles.findByLibelle", query = "SELECT a FROM Articles a WHERE a.libelle = :libelle")})
public class Articles implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;

    @Column(name = "libelle")
    private String libelle;
    @ManyToOne
    private Entreprise entreprise;

    public Articles() {
    }

    public Articles(Integer id) {
        this.id = id;
    }

}
</code>```

答: the problem was at the database level and not with jpa I solved it by connecting to another database thx </p>

Body:
i am trying to insert a Employee entity into the database. I am using JPA and the database is mysql. When I try to insert the entity, it gives me tables must be created I assume that I dont have to create the table. Entity will automatically create the table with the annotated name. Please find the exception and code below.

    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'gsq.articles' doesn't exist
Error Code: 1146
Call: CREATE TABLE articles (id INTEGER AUTO_INCREMENT NOT NULL, libelle VARCHAR(255), ENTREPRISE_id INTEGER, PRIMARY KEY (id))
Query: DataModifyQuery(sql="CREATE TABLE articles (id INTEGER AUTO_INCREMENT NOT NULL, libelle VARCHAR(255), ENTREPRISE_id INTEGER, PRIMARY KEY (id))")
[EL Fine]: 2017-11-12 20:57:29.914--ServerSession(162116790)--Connection(578752466)--CREATE TABLE entreprise (id INTEGER AUTO_INCREMENT NOT NULL, libelle VARCHAR(255) UNIQUE, PRIMARY KEY (id))
[EL Fine]: 2017-11-12 20:57:29.919--ServerSession(162116790)--SELECT 1
[EL Warning]: 2017-11-12 20:57:29.921--ServerSession(162116790)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'gsq.entreprise' doesn't exist
Error Code: 1146
Call: CREATE TABLE entreprise (id INTEGER AUTO_INCREMENT NOT NULL, libelle VARCHAR(255) UNIQUE, PRIMARY KEY (id))
Query: DataModifyQuery(sql="CREATE TABLE entreprise (id INTEGER AUTO_INCREMENT NOT NULL, libelle VARCHAR(255) UNIQUE, PRIMARY KEY (id))")
[EL Fine]: 2017-11-12 20:57:29.922--ServerSession(162116790)--Connection(578752466)--CREATE TABLE users (ID BIGINT AUTO_INCREMENT NOT NULL, password VARCHAR(255), type VARCHAR(255), username VARCHAR(255) UNIQUE, PRIMARY KEY (ID))
[EL Fine]: 2017-11-12 20:57:29.927--ServerSession(162116790)--SELECT 1
[EL Warning]: 2017-11-12 20:57:29.929--ServerSession(162116790)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'gsq.users' doesn't exist
Error Code: 1146
Call: CREATE TABLE users (ID BIGINT AUTO_INCREMENT NOT NULL, password VARCHAR(255), type VARCHAR(255), username VARCHAR(255) UNIQUE, PRIMARY KEY (ID))
Query: DataModifyQuery(sql="CREATE TABLE users (ID BIGINT AUTO_INCREMENT NOT NULL, password VARCHAR(255), type VARCHAR(255), username VARCHAR(255) UNIQUE, PRIMARY KEY (ID))")
[EL Fine]: 2017-11-12 20:57:29.93--ServerSession(162116790)--Connection(578752466)--ALTER TABLE articles ADD CONSTRAINT FK_articles_ENTREPRISE_id FOREIGN KEY (ENTREPRISE_id) REFERENCES entreprise (id)
[EL Fine]: 2017-11-12 20:57:29.935--ServerSession(162116790)--SELECT 1
[EL Warning]: 2017-11-12 20:57:29.936--ServerSession(162116790)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'gsq.articles' doesn't exist
Error Code: 1146
Call: ALTER TABLE articles ADD CONSTRAINT FK_articles_ENTREPRISE_id FOREIGN KEY (ENTREPRISE_id) REFERENCES entreprise (id)
Query: DataModifyQuery(sql="ALTER TABLE articles ADD CONSTRAINT FK_articles_ENTREPRISE_id FOREIGN KEY (ENTREPRISE_id) REFERENCES entreprise (id)")
[EL Fine]: 2017-11-12 20:57:30.035--ServerSession(162116790)--Connection(578752466)--SELECT id, libelle FROM entreprise
[EL Fine]: 2017-11-12 20:57:30.035--ServerSession(162116790)--SELECT 1
[EL Warning]: 2017-11-12 20:57:30.035--UnitOfWork(1734860123)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'gsq.entreprise' doesn't exist
Error Code: 1146
Call: SELECT id, libelle FROM entreprise
Query: ReadAllQuery(referenceClass=Entreprise sql="SELECT id, libelle FROM entreprise")
Exception in thread "AWT-EventQueue-0" javax.persistence.RollbackException: Transaction rolled back because transaction was set to RollbackOnly.
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:92)
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
    at controlleur.Executerequest.closeEntityManager(Executerequest.java:73)
    at frame.ArticlesFram.MajComBox(ArticlesFram.java:385)
    at frame.ArticlesFram.<init>(ArticlesFram.java:53)
    at frame.ArticlesFram$13.run(ArticlesFram.java:501)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="GSQPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>entities.Articles</class>
    <class>entities.Entreprise</class>
    <class>entities.Users</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/gsq"/>
      <property name="javax.persistence.jdbc.password" value=""/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="eclipselink.logging.level.sql" value="FINE"/>
      <property name="eclipselink.logging.parameters" value="true"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
</persistence>

Artcile entity

@Entity
@Table(name = "articles")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Articles.findAll", query = "SELECT a FROM Articles a"),
    @NamedQuery(name = "Articles.findById", query = "SELECT a FROM Articles a WHERE a.id = :id"),
     @NamedQuery(name = "Articles.findByLibelle", query = "SELECT a FROM Articles a WHERE a.libelle = :libelle")})
public class Articles implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;

    @Column(name = "libelle")
    private String libelle;
    @ManyToOne
    private Entreprise entreprise;

    public Articles() {
    }

    public Articles(Integer id) {
        this.id = id;
    }

}


问:
.Net core 2.0 Not showing even after trying multiple recommended fixes
My visual studio 2017 is not detecting .Net core 2.0 no matter what I do. I am running visual studio 15.4.3 and installed .Net core multiple times with reboots. (no effect)

I tried multiple things like editing the .csproj file and the global.json if it was there (no effect). If I check dotnet --version in my user folder I get "1.0.0-preview2-003121" while if I try it in the "C:\Program Files\dotnet" folder I get "2.0.2"

Even my Environment-variables are not showing any weird path directions to older .Net versions.

Does anyone know a fix  which has not been named in these topics?

ASP.NET Core 2 template missing in VS 2017

.NET Core 2.0 missing from my Visual Studio

https://developercommunity.visualstudio.com/content/problem/61785/net-framework-47-not-listed-as-a-target-framework.html

Every tip is appreciated.

答:
Ok after writing the question I realized what the answer was.
As dumb as it sounds I only installed the x64 version and not the x86 so it was never displayed in my SDK folder. </p>

<p>Hopefully this helps another person with the same brain-malfunction =) </p>

Body:
Ok after writing the question I realized what the answer was.
As dumb as it sounds I only installed the x64 version and not the x86 so it was never displayed in my SDK folder.

Hopefully this helps another person with the same brain-malfunction =)


问:
Vue equivalent of setTimeout?
I'm making a shopping cart system with Laravel and Vue. When I add an item to the basket, I display a confirmation message by toggling a Vue variable being watched by a v-if:

```<code><div class="alert alert-success" v-if="basketAddSuccess" transition="expand">Added to the basket</div>
</code>```

And the JS:

```<code>addToBasket: function(){
                item = this.product;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
            }
</code>```

(And yes, I will be adding this in a then-catch shortly).

This works fine and the message appears. However, I'd like the message to disappear again after a certain time, say a few seconds. How can I do this with Vue? I've tried setTimeOut but Vue doesn't seem to like it, saying it's undefined.

EDIT: I was misspelling setTimeout like an idiot. However, it still doesn't work:

My function is now:

```<code>addToBasket: function(){
                item = this.photo;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
                setTimeout(function(){
                    this.basketAddSuccess = false;
                }, 2000);
            }
</code>```

答:
vuejs 2

first add this to methods

```<code>methods:{
    sayHi: function () {
      var v = this;
      setTimeout(function () {
        v.message = "Hi Vue!";
    }, 3000);
   }
</code>```

after that call this method on mounted

```<code>mounted () {
  this.sayHi()
}
</code>```

Title: Vue equivalent of setTimeout?

Body:
I'm making a shopping cart system with Laravel and Vue. When I add an item to the basket, I display a confirmation message by toggling a Vue variable being watched by a v-if:

Added to the basket

And the JS:

addToBasket: function(){
                item = this.product;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
            }

(And yes, I will be adding this in a then-catch shortly).

This works fine and the message appears. However, I'd like the message to disappear again after a certain time, say a few seconds. How can I do this with Vue? I've tried setTimeOut but Vue doesn't seem to like it, saying it's undefined.

EDIT: I was misspelling setTimeout like an idiot. However, it still doesn't work:

My function is now:

addToBasket: function(){
                item = this.photo;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
                setTimeout(function(){
                    this.basketAddSuccess = false;
                }, 2000);
            }

Body:
vuejs 2

first add this to methods

methods:{
    sayHi: function () {
      var v = this;
      setTimeout(function () {
        v.message = "Hi Vue!";
    }, 3000);
   }

after that call this method on mounted

mounted () {
  this.sayHi()
}


问:
Reading Javascript FormData value in Asp.net Web api Httpresponsemessage
I have a Web api which is decorated with [HttpPost] which is used to upload all information passed in parameter but getting this error

Error

Controller

```<code>  [HttpPost]
   public HttpResponseMessage questionnairesubmit(HttpRequestMessage form)
    {

     //want to get json of "questionlist" which is send from javascript like
      var QuestionnaireList = JsonConvert.DeserializeObject<List<outRightLogos.Areas.client.WebApiModel.AttributeValueTB>>(form["questionlist"]);

    }
</code>```

Here is javascript sending Json model with name questionlist this I want to fetch in controller.I read FormData() from Here

Javascript

```<code>var data = new FormData();
var QuestionnaireList = [];
 QuestionnaireList.push({

            FieldID: $(this).attr("data-fieldid"),
            attributeID: $(this).attr("data-attributeid"),
            attributeValue: $(this).val(),
            websitesID: 2,
            OrderID: $('#orderid').val(),
            orderbitID: $('#orderbidid').val(),
            serviceId: $(this).attr("data-serviceid"),
            subServiceId: $(this).attr("data-subserviceid"),
            IsSubmit: IsSubmit,
        });

data.append("questionlist", JSON.stringify(QuestionnaireList));
$.ajax({
                    type: "POST",
                    url: path,
                    contentType: 'application/json',//"application/json; charset=utf-8",
                    processData: false,
                    dataType: "json",
                    data: data,

                    success: function (result) {

                        if (result.sucess == "save") {
                            alert('Your form has been saved.');

                        }
                        else if (result.sucess == "Submit") {
                            alert('Your form has been submitted.');
                            window.location.href = result.Url;
                        }
                    },
                    error: function (result) {
                        alert('Oh no ');
                    }

                });
</code>```

Here is a model class AttributeValueTB

Class

```<code> public class AttributeValueTB
{
    public long attributeValueID { get; set; }

    [Required]
    [StringLength(200)]
    public string attributeValueCode { get; set; }

    public int FieldID { get; set; }

    public int attributeID { get; set; }

    public string attributeValue { get; set; }

    public int websitesID { get; set; }

    public long OrderID { get; set; }
    public long orderbitID { get; set; }
    public long serviceId { get; set; }
    public long subServiceId { get; set; }
    public string extra1 { get; set; }
    public string extra2 { get; set; }
    [StringLength(200)]
    public string attributeCode { get; set; }
    public bool isActive { get; set; }

    public bool isShow { get; set; }
    public bool IsSubmit { get; set; }

    [Column(TypeName = "date")]
    public DateTime? createDate { get; set; }

    [Column(TypeName = "date")]
    public DateTime? modifiedDate { get; set; }

    public int? createBy { get; set; }

    public int? modifiedBy { get; set; }

    [Column(TypeName = "timestamp")]
    [MaxLength(8)]
    [Timestamp]
    public byte[] Timestamp { get; set; }
}
</code>```

答:
You don't need to serialize anything manually, as long as you've provided a model class in C#.

Json.NET is quite smart and serializes your parameters automagically.

```<code>[HttpPost]
public HttpResponseMessage QuestionnaireSubmit(AttributeValueTB form)
{
   // Form is serialized and can be used here

}
</code>```

If you'd like to read the cookies too, you could use Request.Cookies in this method.

Body:
I have a Web api which is decorated with [HttpPost] which is used to upload all information passed in parameter but getting this error

Error

Controller

  [HttpPost]
   public HttpResponseMessage questionnairesubmit(HttpRequestMessage form)
    {

     //want to get json of "questionlist" which is send from javascript like
      var QuestionnaireList = JsonConvert.DeserializeObject<List<outRightLogos.Areas.client.WebApiModel.AttributeValueTB>>(form["questionlist"]);

    }

Here is javascript sending Json model with name questionlist this I want to fetch in controller.I read FormData() from Here

Javascript

var data = new FormData();
var QuestionnaireList = [];
 QuestionnaireList.push({

            FieldID: $(this).attr("data-fieldid"),
            attributeID: $(this).attr("data-attributeid"),
            attributeValue: $(this).val(),
            websitesID: 2,
            OrderID: $('#orderid').val(),
            orderbitID: $('#orderbidid').val(),
            serviceId: $(this).attr("data-serviceid"),
            subServiceId: $(this).attr("data-subserviceid"),
            IsSubmit: IsSubmit,
        });

data.append("questionlist", JSON.stringify(QuestionnaireList));
$.ajax({
                    type: "POST",
                    url: path,
                    contentType: 'application/json',//"application/json; charset=utf-8",
                    processData: false,
                    dataType: "json",
                    data: data,

                    success: function (result) {

                        if (result.sucess == "save") {
                            alert('Your form has been saved.');

                        }
                        else if (result.sucess == "Submit") {
                            alert('Your form has been submitted.');
                            window.location.href = result.Url;
                        }
                    },
                    error: function (result) {
                        alert('Oh no ');
                    }

                });

Here is a model class AttributeValueTB

Class

 public class AttributeValueTB
{
    public long attributeValueID { get; set; }

    [Required]
    [StringLength(200)]
    public string attributeValueCode { get; set; }

    public int FieldID { get; set; }

    public int attributeID { get; set; }

    public string attributeValue { get; set; }

    public int websitesID { get; set; }

    public long OrderID { get; set; }
    public long orderbitID { get; set; }
    public long serviceId { get; set; }
    public long subServiceId { get; set; }
    public string extra1 { get; set; }
    public string extra2 { get; set; }
    [StringLength(200)]
    public string attributeCode { get; set; }
    public bool isActive { get; set; }

    public bool isShow { get; set; }
    public bool IsSubmit { get; set; }

    [Column(TypeName = "date")]
    public DateTime? createDate { get; set; }

    [Column(TypeName = "date")]
    public DateTime? modifiedDate { get; set; }

    public int? createBy { get; set; }

    public int? modifiedBy { get; set; }

    [Column(TypeName = "timestamp")]
    [MaxLength(8)]
    [Timestamp]
    public byte[] Timestamp { get; set; }
}

Body:
You don't need to serialize anything manually, as long as you've provided a model class in C#.

Json.NET is quite smart and serializes your parameters automagically.

[HttpPost]
public HttpResponseMessage QuestionnaireSubmit(AttributeValueTB form)
{
   // Form is serialized and can be used here

}

If you'd like to read the cookies too, you could use Request.Cookies in this method.


问:
Invalid Trigger Exception
I am a newcomer in ORACLE SQL, I am trying to create a trigger to generate auto_incement serial number as a primary key in my table but no idea what mistake I am making, due to which I am getting :

error while performing partial saving of event: error code=4098 ST=
  java.sql.BatchUpdateException: ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n, caused by : \"ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n\"

My SQL Statement is :

```<code>create global temporary table STAGING_ERROR_REASON (   STAGING_REASON_ID number(4) constraint STAGING_REASON_ID not null   ,REASON nvarchar2(1024) not null   ,constraint PK_STAGING_REASON_ID PRIMARY KEY(STAGING_REASON_ID) );

create sequence STAGING_SEQ_ERROR_REASON start with 1 increment by 1 minvalue 1 maxvalue 10000;

CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
   BEFORE INSERT ON STAGING_ERROR_REASON
   REFERENCING NEW AS NEW
   FOR EACH ROW
BEGIN
   if(:NEW.STAGING_REASON_ID is null) then
      SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL
          INTO :NEW.STAGING_REASON_ID
   END;

ALTER TRIGGER "STAGING_TRIGGER_ERROR_REASON" ENABLE;
</code>```

答:
You could use:</p>

```<code>CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
BEFORE INSERT ON STAGING_ERROR_REASON REFERENCING NEW
AS NEW FOR EACH ROW
BEGIN
 if(:NEW.STAGING_REASON_ID is null) then
 :NEW.STAGING_REASON_ID := (SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL FROM dual);
 end if;
END;
</code>```

Title: Invalid Trigger Exception

Body:
I am a newcomer in ORACLE SQL, I am trying to create a trigger to generate auto_incement serial number as a primary key in my table but no idea what mistake I am making, due to which I am getting :

error while performing partial saving of event: error code=4098 ST=
  java.sql.BatchUpdateException: ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n, caused by : \"ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n\"

My SQL Statement is :

create global temporary table STAGING_ERROR_REASON (   STAGING_REASON_ID number(4) constraint STAGING_REASON_ID not null   ,REASON nvarchar2(1024) not null   ,constraint PK_STAGING_REASON_ID PRIMARY KEY(STAGING_REASON_ID) );

create sequence STAGING_SEQ_ERROR_REASON start with 1 increment by 1 minvalue 1 maxvalue 10000;

CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
   BEFORE INSERT ON STAGING_ERROR_REASON
   REFERENCING NEW AS NEW
   FOR EACH ROW
BEGIN
   if(:NEW.STAGING_REASON_ID is null) then
      SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL
          INTO :NEW.STAGING_REASON_ID
   END;

ALTER TRIGGER "STAGING_TRIGGER_ERROR_REASON" ENABLE;

Body:
You could use:

CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
BEFORE INSERT ON STAGING_ERROR_REASON REFERENCING NEW
AS NEW FOR EACH ROW
BEGIN
 if(:NEW.STAGING_REASON_ID is null) then
 :NEW.STAGING_REASON_ID := (SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL FROM dual);
 end if;
END;


问:
Add a user to group docker and such a user can access unauthorized directories in container by mounting directories via -v
In my centos system, I add a user to group docker, and I found such a user can access any folder by attach folder to container via docker run -it -v path-to-directory:directory-in-container. For example, I have a folder with mode 700 which can only access by root, but if someone who doesn't have permission to access this folder run a container and mount this folder to container, he can access this folder in container.How can I prevent such a user to attach unauthorized directories to docker container? My docker version is 17.03.0-ce, system os centOS 7.0. Thanks!

答:
You should refer and follow the container principles for security or external volume permission setting up. But you want to test simply for container features.
You can set up the path-to-directory access mode 777, yes it's world-readable-writable access mode. It's no additional owner-group setting and access mode setting for any container volume mapping.

```<code>chmod 777 /path/to/directory
</code>```

Body:
You should refer and follow the container principles for security or external volume permission setting up. But you want to test simply for container features.
You can set up the path-to-directory access mode 777, yes it's world-readable-writable access mode. It's no additional owner-group setting and access mode setting for any container volume mapping.

chmod 777 /path/to/directory


问:
How to align the input fields?

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

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

      <input class="form-control" id="ex1" placeholder="Last name" type="text">

```

The two input fields do not align in the same line when i take the label off the second field how can this be corrected ?

答:
Make the label as siblings of the form-group instead if you are planning to use only one label, and you can instead use  or any other element, because semantically speaking,  is not for this kind of naming, much like using
 in Contact Person instead of a  with style

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

Contact Person

  Name

      <input class="form-control" id="ex1" placeholder="First name" type="text">

      <input class="form-control" id="ex1" placeholder="Last name" type="text">

```

Title: How to align the input fields?

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

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

      <input class="form-control" id="ex1" placeholder="Last name" type="text">

The two input fields do not align in the same line when i take the label off the second field how can this be corrected ?

Body:
Make the label as siblings of the form-group instead if you are planning to use only one label, and you can instead use <span> or any other element, because semantically speaking, <label> is not for this kind of naming, much like using <h1> in Contact Person instead of a <label> with style

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

<section class="section-component">
  <h1>Contact Person</h1>
  <label for="ex1">Name</label>
  <div class="form-group row">
    <div class="col-xs-6 form-field">
      <input class="form-control" id="ex1" placeholder="First name" type="text">
    </div>
    <div class="col-xs-6 form-field">
      <input class="form-control" id="ex1" placeholder="Last name" type="text">
    </div>
  </div>
</section>


问:
Anchor links not working in IE or Firefox
I'm building a site in Chrome and just discovered none of my anchor links work in IE or Firefox.

I'm coding it in Wordpress like:

Menu link:

```<code>http://dev.legendpower.com/contact/#Offices
</code>```

Anchor:

```<code><a name="offices" class="anchor"><h3 style="text-align: center;"><span
style="color: #000000;">Legend offices.</span></h3></a>
</code>```

Strangely, there is one page on the whole site where the anchor link is working, and I can't for the life of me figure out what if anything there is different on that page. The coding there goes like...

Menu Link:

```<code>http://dev.legendpower.com/markets/#Casestudies
</code>```

Anchor:

```<code><a name="casestudies" class="anchor"><h3 style="text-align: center;"><span
style="color: #000000;">Case studies.</span></h3></a><p></p><p>The case
studies below are just a subset of our customer-base. We’ve installed over
200 Harmonizers in almost every type of building. Click on an image to
access the case study.</p>
</code>```

Does anyone know the solution to this?

答:
hope you doing well...

Please use this snippet

```<code>    <a href="http://dev.legendpower.com/contact/#Offices" name="casestudies"
    class="anchor">The case studies below are just a subset of our customer-
    base. We’ve installed over 200 Harmonizers in almost every type of
    building. Click on an image to access the case study.</a>
</code>```

Body:
I'm building a site in Chrome and just discovered none of my anchor links work in IE or Firefox.

I'm coding it in Wordpress like:

Menu link:

http://dev.legendpower.com/contact/#Offices

Anchor:

Legend offices.

Strangely, there is one page on the whole site where the anchor link is working, and I can't for the life of me figure out what if anything there is different on that page. The coding there goes like...

Menu Link:

http://dev.legendpower.com/markets/#Casestudies

Anchor:

Case studies.

The case
studies below are just a subset of our customer-base. We’ve installed over
200 Harmonizers in almost every type of building. Click on an image to
access the case study.

Does anyone know the solution to this?

Body:
hope you doing well...

Please use this snippet

    <a href="http://dev.legendpower.com/contact/#Offices" name="casestudies"
    class="anchor">The case studies below are just a subset of our customer-
    base. We’ve installed over 200 Harmonizers in almost every type of
    building. Click on an image to access the case study.</a>


问:
how to upgrade dotnetcore from version 1.0.4 to version 2.0.2 on centos?
how to upgrade .net-core from version 1.0.4 to version 2.0.2 on centos?
I have some asp.net core applications run on centos version 7.4.1708, now the version of dotnet is 1.0.4, so how to upgrade it to version 2.0.2? Thanks a lot!

Sorry, I got it, somehow  the Microsoft Product feed had been removed for mistake,  that's it.

Some pits or tips: generally, .net-core 1.0 will be installed at /opt/dotnet
and .net-core 2.0.0 will be installed at /usr/share/dotnet, so when you finish
upgrade , you might wander why the result of command "dotnet --version" still is 1.0.4, you need unlink /usr/local/bin/dotnet and ln -s usr/share/dotnet/dotnet since /usr/local/bin is prior to /usr/bin by default.

If your applications were developed under .net-core 1.0, they don't work under
.net-core 2.0.0, the error will be
"It was not possible to find any compatible framework version
The specified framework 'Microsoft.NETCore.App', version '1.1.2' was not found.
  - Check application dependencies and target a framework version installed at:      /
  - Alternatively, install the framework version '1.1.2'"

Under .net-core version 2.0.2 circumstance, no aforementioned troublesome issue.

csproj file:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="1.1.2" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql.Design" Version="1.1.2" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
  </ItemGroup>
</Project>
```

答:
You have more than one SDK on your centOS.
If you try

```<code>/usr/bin/dotnet --version
</code>```

command you will see the version is 2.0.2

you can solve the problem like this:

```<code>rm -f /usr/local/bin/dotnet
ln -s /usr/share/dotnet/dotnet /usr/local/bin/dotnet
</code>```

Body:
You have more than one SDK on your centOS.
If you try

/usr/bin/dotnet --version

command you will see the version is 2.0.2

you can solve the problem like this:

rm -f /usr/local/bin/dotnet
ln -s /usr/share/dotnet/dotnet /usr/local/bin/dotnet


问:
One page wordpress template with subscription option
I'm new to wordpress. I have to create a one page template for my site and show a subscribe textbox on it with my own custom style. Later, I will use it to send monthly newsletters. What can be the simplest way to do that? I saw into some plugins like newsletter, subscribe2, but they are complicated and I don't know how to integrate them with my text box. They just provide some sort of widget to show on sidebar. Any tutorial or simple plugin? Please help!</p>

答:
Subscribe2 complicated?

You can do auto-download/install from the administration area, you literally only have to config a few options.

http://codex.wordpress.org/Managing_Plugins#Installing_Plugins

Maybe it's just me, but the screenshots certainly make the plugin appear to be very straight-forward.
http://wordpress.org/extend/plugins/subscribe2/screenshots/