问:
Error with web.config and CDATA
I am getting the following error when I run my code:

System.Configuration.ConfigurationErrorsException: 'The configuration section cannot contain a CDATA or text element'

The application builds just fine but when I select the link to go to the view "about" in the application it throws the error above.

This is the line that it highlights in the code:

```<code>string conn = ConfigurationManager.ConnectionStrings["CountryConnectionString"].ConnectionString;
</code>```

and this is the connection string in the web.config file:

```<code> <add name="CountryConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=TestData" providerName="System.Data.SqlClient"  />
</code>```

If more is needed let me know and I can post whatever you need

Here is the entire web config file

```<code><?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application,   please     visit
  https://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <httpModules>
          <add name="ApplicationInsightsWebTracking"       type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral"     publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
</assemblyBinding>
  </runtime>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking"   type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
  </system.webServer>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
  </system.codedom>
  <connectionStrings>
<add name="CountryConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=TestData" providerName="System.Data.SqlClient"  />
  </connectionStrings>
</configuration>
</code>```

答:
Short solution: remove al whitespace between tags.

If I copy your config contains a character that renders as whitespace but actually isn't. To the config parser anything other than spaces and tabs, is text. Text is not allowed in config files.

```<code>// the spacing character
Encoding.UTF8.GetBytes(new[] { ' ' })[0] // yields 194
Encoding.UTF8.GetBytes(new[] { ' ' })[1] // yields 160

// the actual space
Encoding.UTF8.GetBytes(new[] { ' ' })[0] // yields 32
</code>```

Try to change the config to:

```<code> <connectionStrings><add name="CountryConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=TestData" providerName="System.Data.SqlClient"  /></connectionStrings>
</code>```

Before re-adding spaces and enters

```<code><connectionStrings>
    <add name="CountryConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=TestData" providerName="System.Data.SqlClient"  />
</connectionStrings>
</code>```

Title: Error with web.config and CDATA

Body:
I am getting the following error when I run my code:

System.Configuration.ConfigurationErrorsException: 'The configuration section cannot contain a CDATA or text element'

The application builds just fine but when I select the link to go to the view "about" in the application it throws the error above.

This is the line that it highlights in the code:

string conn = ConfigurationManager.ConnectionStrings["CountryConnectionString"].ConnectionString;

and this is the connection string in the web.config file:

 <add name="CountryConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=TestData" providerName="System.Data.SqlClient"  />

If more is needed let me know and I can post whatever you need

Here is the entire web config file

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

<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <httpModules>
          <add name="ApplicationInsightsWebTracking"       type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral"     publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
</assemblyBinding>
  </runtime>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking"   type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
  </system.webServer>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
  </system.codedom>
  <connectionStrings>
<add name="CountryConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=TestData" providerName="System.Data.SqlClient"  />
  </connectionStrings>
</configuration>

Body:
Short solution: remove al whitespace between tags.

If I copy your config contains a character that renders as whitespace but actually isn't. To the config parser anything other than spaces and tabs, is text. Text is not allowed in config files.

// the spacing character
Encoding.UTF8.GetBytes(new[] { ' ' })[0] // yields 194
Encoding.UTF8.GetBytes(new[] { ' ' })[1] // yields 160

// the actual space
Encoding.UTF8.GetBytes(new[] { ' ' })[0] // yields 32

Try to change the config to:

 <connectionStrings><add name="CountryConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=TestData" providerName="System.Data.SqlClient"  /></connectionStrings>

Before re-adding spaces and enters

<connectionStrings>
    <add name="CountryConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=TestData" providerName="System.Data.SqlClient"  />
</connectionStrings>


来源: stackexchange

问:
Graphene Django "Must provide query string"
I have setup a Graphene server using Django. When I run my queries through GraphiQL (the web client), everything works fine. However, when I run from anywhere else, I get the error: "Must provide query string."

I did some troubleshooting. GraphiQL sends POST data to the GraphQL server with Content-Type: application/json. Here is the body of the request that I copied from Chrome network tab for GraphiQL:

```<code>{"query":"query PartnersQuery {\n  partners{\n    name\n    url\n    logo\n  }\n}","variables":"null","operationName":"PartnersQuery"}
</code>```

When I copy it to Postman with Content-Type: application/json, I get the following response:

```<code>{
  "errors": [
    {
      "message": "Must provide query string."
    }
  ]
}
</code>```

What can be the cause of this problem? I have not done anything crazy with the schema. Just followed the tutorials from graphene's docs. What else can cause an issue like this?

答:
This error is raised when parse_body is unable to parse the incoming data.  I'd start there by looking at the data passed into this method and ensuring it's of the correct type.

For example, the multipart/form-data section naively returns request.POST, which may need to be overwritten to handle, for example, the request that apollo-upload-client sends for file upload handling.
In our case we created a view to both require a login and to support the apollo-upload-client use case and it works fine.

ContentLicense: CC BY-SA 3.0

Body:
I have setup a Graphene server using Django. When I run my queries through GraphiQL (the web client), everything works fine. However, when I run from anywhere else, I get the error: "Must provide query string."

I did some troubleshooting. GraphiQL sends POST data to the GraphQL server with Content-Type: application/json. Here is the body of the request that I copied from Chrome network tab for GraphiQL:

{"query":"query PartnersQuery {\n  partners{\n    name\n    url\n    logo\n  }\n}","variables":"null","operationName":"PartnersQuery"}

When I copy it to Postman with Content-Type: application/json, I get the following response:

{
  "errors": [
    {
      "message": "Must provide query string."
    }
  ]
}

What can be the cause of this problem? I have not done anything crazy with the schema. Just followed the tutorials from graphene's docs. What else can cause an issue like this?


问:
Logging from Docker
I have a rails app running through docker. I bring up the app with docker-compose (config below). The whole app covers a mysql, redis, rails (including sidekiq workers), nginx (with react frontend) and a rsyslog server, which forwards all logs to Loggly

My problem is realated to the logging part. Logs from all services basically gets forwarded, except from my logs from sidekiq.
When I start sidekiq with bundler exec sidekiq the logs are output to the console (stdout), but I dont see them when I tail /var/log/messages on the rsyslog server.

I followed this tutorial when setting up the logging on docker:

https://medium.com/@yoanis_gil/logging-with-docker-part-1-b23ef1443aac

My thinking is that everything that goes to stdout in a docker container should be logged to the docker log mechanism - and with my setup that means it should go to the syslog server...

The docker-compose file:

```<code>version: '3'

services:
  nginx:
    image: nginx
    depends_on:
      - api
      - syslog
    ports:
      - "80:8080"

    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "nginx"
        syslog-address: "tcp://localhost:5514"
    networks:
      - phototankswarm
    env_file: .env.dev
    volumes:
      - ./frontend/nginx/conf.d:/etc/nginx/conf.d
      - ./frontend/public:/www

  db:
    image: mysql
    env_file: .env.dev
    depends_on:
      - syslog
    networks:
      - phototankswarm
    ports:
      - "3306:3306"
    volumes:
      - ./backend/sql/data:/var/lib/mysql
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "mysql"
        syslog-address: "tcp://localhost:5514"

  redis:
    image: redis
    depends_on:
      - syslog
    networks:
      - phototankswarm
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "redis"
        syslog-address: "tcp://localhost:5514"

  api:
    image: pt-rails
    env_file: .env.dev
    networks:
      - phototankswarm
    command: >
      sh -c '
      rails s -p 3000 -b 0.0.0.0;
      '
    volumes:
      - /Users/martinhinge/Pictures/docker/phototank:/media/phototank
      - ./backend:/usr/src/app
    ports:
      - "3000:3000"
    depends_on:
      - db
      - redis
      - syslog
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "rails"
        syslog-address: "tcp://localhost:5514"

  syslog:
    image: syslog
    ports:
      - "localhost:5514:514"
    networks:
      - phototankswarm
    volumes:
      - /tmp:/var/log/syslog

networks:
  phototankswarm:
</code>```

答:
As suggested by @Robert in the comments the solution is to run bundle commands as part of the CMD in the docker-compose file:

The api service in my compose file thus becomes:

```<code>api:
    image: pt-rails
    env_file: .env.dev
    networks:
      - phototankswarm
    command: >
      sh -c '
      bundle exec sidekiq -d -L /dev/stdout && bundle exec rails s -p 3000 -b 0.0.0.0
      '
    volumes:
      - /Users/martinhinge/Pictures/docker/phototank:/media/phototank
      - ./backend:/usr/src/app
    ports:
      - "3000:3000"
    depends_on:
      - db
      - redis
      - syslog
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "rails"
        syslog-address: "tcp://localhost:5514"
</code>```

Title: Logging from Docker

Body:
I have a rails app running through docker. I bring up the app with docker-compose (config below). The whole app covers a mysql, redis, rails (including sidekiq workers), nginx (with react frontend) and a rsyslog server, which forwards all logs to Loggly

My problem is realated to the logging part. Logs from all services basically gets forwarded, except from my logs from sidekiq.
When I start sidekiq with bundler exec sidekiq the logs are output to the console (stdout), but I dont see them when I tail /var/log/messages on the rsyslog server.

I followed this tutorial when setting up the logging on docker:

https://medium.com/@yoanis_gil/logging-with-docker-part-1-b23ef1443aac

My thinking is that everything that goes to stdout in a docker container should be logged to the docker log mechanism - and with my setup that means it should go to the syslog server...

The docker-compose file:

version: '3'

services:
  nginx:
    image: nginx
    depends_on:
      - api
      - syslog
    ports:
      - "80:8080"

    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "nginx"
        syslog-address: "tcp://localhost:5514"
    networks:
      - phototankswarm
    env_file: .env.dev
    volumes:
      - ./frontend/nginx/conf.d:/etc/nginx/conf.d
      - ./frontend/public:/www

  db:
    image: mysql
    env_file: .env.dev
    depends_on:
      - syslog
    networks:
      - phototankswarm
    ports:
      - "3306:3306"
    volumes:
      - ./backend/sql/data:/var/lib/mysql
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "mysql"
        syslog-address: "tcp://localhost:5514"

  redis:
    image: redis
    depends_on:
      - syslog
    networks:
      - phototankswarm
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "redis"
        syslog-address: "tcp://localhost:5514"

  api:
    image: pt-rails
    env_file: .env.dev
    networks:
      - phototankswarm
    command: >
      sh -c '
      rails s -p 3000 -b 0.0.0.0;
      '
    volumes:
      - /Users/martinhinge/Pictures/docker/phototank:/media/phototank
      - ./backend:/usr/src/app
    ports:
      - "3000:3000"
    depends_on:
      - db
      - redis
      - syslog
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "rails"
        syslog-address: "tcp://localhost:5514"

  syslog:
    image: syslog
    ports:
      - "localhost:5514:514"
    networks:
      - phototankswarm
    volumes:
      - /tmp:/var/log/syslog

networks:
  phototankswarm:

Body:
As suggested by @Robert in the comments the solution is to run bundle commands as part of the CMD in the docker-compose file:

The api service in my compose file thus becomes:

api:
    image: pt-rails
    env_file: .env.dev
    networks:
      - phototankswarm
    command: >
      sh -c '
      bundle exec sidekiq -d -L /dev/stdout && bundle exec rails s -p 3000 -b 0.0.0.0
      '
    volumes:
      - /Users/martinhinge/Pictures/docker/phototank:/media/phototank
      - ./backend:/usr/src/app
    ports:
      - "3000:3000"
    depends_on:
      - db
      - redis
      - syslog
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "rails"
        syslog-address: "tcp://localhost:5514"


问:
d3 Exit / Update function in animation
I am trying to do an animation that shows data from ten different points. The graphic is coded so that the sensors (displayed through circles) change their color and size depending on the overall data obtained over one hour (total number of entries and average of speed).

Through this entry (Transition not working d3) and the code from this simulation of Gapminder (https://bost.ocks.org/mike/nations/), I have been able to animate the chart. However, because of the structure of the code, the exit and update function do not work. The first entry in the data at Hour 1 only has one object and therefore only one circle is drawn. This circle gets updated through time, but the other sensors are not drawn (and therefore not updated).

I am considering recreating a first empty object for each sensor to draw them at the beginning of the animation. However, I would like to avoid that.

The code is this:

```<code>//FUNCTION TO GET THE DATA BY HOUR
function getDataByHour (hour) {
    var allBridges = new Array();
    var found;
    for (b = 0; b < boatsByHour.length; b++){
        bridges.forEach(function(br,i){
            if (boatsByHour[b].sensorID== br.id){
                xy = projection([br.longitude, br.latitude])}
        });
        if (boatsByHour[b].hour == hour){
            found = true;
            bridgeNumber = boatsByHour[b].sensorID;
            allBridges.push({
                "numberBoats": (boatsByHour[b].numberBoats),
                "speed": (boatsByHour[b].speedAvg),
                "bridge": boatsByHour[b].sensorID,
                "longitude": xy[0],
                "latitude": xy[1],
                "hour": boatsByHour[b].hour
            })
        }
    }
    return allBridges;
}

//SENSORS
var sensor = plot.append("g")
    .attr("class","bridges")
    .selectAll(".sensors")
    .data(getDataByHour(timeRange[0]))
    .call(animateSensors)
    .enter()
    .append("circle")
    .attr("class","sensors")
    .attr("cx", function(d,i){return d.longitude})
    .attr("cy", function(d,i){return d.latitude})
    .on("mouseover",function(d){console.log(d)});

sensor.exit().remove();

plot
    .transition()
    .duration(300000)
    .ease(d3.easeLinear)
    .tween("hour", tweenHour)

//FUNCTION THAT UPDATES THE ANIMATION
function animateSensors (sensor){
    sensor
        .attr("r",function(d){return radiusScale(d.numberBoats)})
        .style("fill",function(d){return colorScale(d.speed)});
}

function tweenHour(){
    var hour = d3.interpolateNumber (timeRange[0],timeRange[1]);

    return function(h){
        displayHour(hour(h))}
}

function displayHour(hour) {
    sensor.data(getDataByHour(Math.floor(hour))).call(animateSensors);
}
</code>```

I have tried different ways of including the enter() and exit (). If I add the enter() and append the circles inside the 'animateSensors' function, all the circles (sensors) are drawn. However they are not being updated, so at the end, I get thousands of circles drawn in the SVG even if the exit().remove() update is in it.

Thanks

答:
Ok, now it works. Instead of calling the first part of the data (where there is only 1 circle is drawn instead of the total 10), I had to call data that had data for all the circles (like the last point):

```<code>var sensor = plot.append("g")
        .attr("class","bridges")
        .selectAll(".bridge")
        .data(getDataByHour(timeRange[1])) // instead of getDataByHour(timeRange[0])
        .enter()
        .append("circle")
        .attr("class",function(d){return "bridge " + d.bridge})
        .attr("cx", function(d,i){return d.longitude})
        .attr("cy", function(d,i){return d.latitude})
        .on("mouseover",function(d){console.log(d)});
</code>```

The animation starts correctly thanks to the function tweenHour

```<code>function tweenHour(){
        var hour = d3.interpolateNumber (timeRange[0],timeRange[1]);

        return function(h){
            displayHour(hour(h))}
    }
</code>```

Title: d3 Exit / Update function in animation

Body:
I am trying to do an animation that shows data from ten different points. The graphic is coded so that the sensors (displayed through circles) change their color and size depending on the overall data obtained over one hour (total number of entries and average of speed).

Through this entry (Transition not working d3) and the code from this simulation of Gapminder (https://bost.ocks.org/mike/nations/), I have been able to animate the chart. However, because of the structure of the code, the exit and update function do not work. The first entry in the data at Hour 1 only has one object and therefore only one circle is drawn. This circle gets updated through time, but the other sensors are not drawn (and therefore not updated).

I am considering recreating a first empty object for each sensor to draw them at the beginning of the animation. However, I would like to avoid that.

The code is this:

//FUNCTION TO GET THE DATA BY HOUR
function getDataByHour (hour) {
    var allBridges = new Array();
    var found;
    for (b = 0; b < boatsByHour.length; b++){
        bridges.forEach(function(br,i){
            if (boatsByHour[b].sensorID== br.id){
                xy = projection([br.longitude, br.latitude])}
        });
        if (boatsByHour[b].hour == hour){
            found = true;
            bridgeNumber = boatsByHour[b].sensorID;
            allBridges.push({
                "numberBoats": (boatsByHour[b].numberBoats),
                "speed": (boatsByHour[b].speedAvg),
                "bridge": boatsByHour[b].sensorID,
                "longitude": xy[0],
                "latitude": xy[1],
                "hour": boatsByHour[b].hour
            })
        }
    }
    return allBridges;
}

//SENSORS
var sensor = plot.append("g")
    .attr("class","bridges")
    .selectAll(".sensors")
    .data(getDataByHour(timeRange[0]))
    .call(animateSensors)
    .enter()
    .append("circle")
    .attr("class","sensors")
    .attr("cx", function(d,i){return d.longitude})
    .attr("cy", function(d,i){return d.latitude})
    .on("mouseover",function(d){console.log(d)});

sensor.exit().remove();

plot
    .transition()
    .duration(300000)
    .ease(d3.easeLinear)
    .tween("hour", tweenHour)

//FUNCTION THAT UPDATES THE ANIMATION
function animateSensors (sensor){
    sensor
        .attr("r",function(d){return radiusScale(d.numberBoats)})
        .style("fill",function(d){return colorScale(d.speed)});
}

function tweenHour(){
    var hour = d3.interpolateNumber (timeRange[0],timeRange[1]);

    return function(h){
        displayHour(hour(h))}
}

function displayHour(hour) {
    sensor.data(getDataByHour(Math.floor(hour))).call(animateSensors);
}

I have tried different ways of including the enter() and exit (). If I add the enter() and append the circles inside the 'animateSensors' function, all the circles (sensors) are drawn. However they are not being updated, so at the end, I get thousands of circles drawn in the SVG even if the exit().remove() update is in it.

Thanks

Body:
Ok, now it works. Instead of calling the first part of the data (where there is only 1 circle is drawn instead of the total 10), I had to call data that had data for all the circles (like the last point):

var sensor = plot.append("g")
        .attr("class","bridges")
        .selectAll(".bridge")
        .data(getDataByHour(timeRange[1])) // instead of getDataByHour(timeRange[0])
        .enter()
        .append("circle")
        .attr("class",function(d){return "bridge " + d.bridge})
        .attr("cx", function(d,i){return d.longitude})
        .attr("cy", function(d,i){return d.latitude})
        .on("mouseover",function(d){console.log(d)});

The animation starts correctly thanks to the function tweenHour

function tweenHour(){
        var hour = d3.interpolateNumber (timeRange[0],timeRange[1]);

        return function(h){
            displayHour(hour(h))}
    }


问:
How to center absolutely positioned children of a flex container in Safari?
I have a container that contains both an image, and some text. I want the text to be vertically and horizontally centered in the middle of the image.

It seems that the easiest, forward-thinking method is to use Flexbox and absolute positioning of the text:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.text {
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <div class='text'>
    This should be centered
  </div>
  <img src="https://placehold.it/250x250" />
</div></code>```

The text is centered in both axes. This seems to work in all modern browsers..... except Safari.

Safari appear to not center the text at all. It's just sitting at the top/left of the container like a normal absolutely positioned element would be in a non-flexbox layout.

Safari (wrong):

All other browsers (correct):

I thought Flexbox was really ready for primetime, but this seems like a deal-breaker considering how many people using Safari on iOS. Centering content horizontally and vertically is something Flexbox should be great at.

My only real alternative here is to not use Flexbox and then use:

```<code>.text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}
</code>```

But I would much rather be using Flexbox for progressive reasons.

Is there anything I'm missing here? As much as I hate to ask for it, is there some of Safari-only work-around here? Is there any solution to this besides just "not using flexbox" because if that is the answer in mid-2017 that is going to be disappointing.

JSFiddle for reference: https://jsfiddle.net/z7kh5Laz/4/

答:
Respectfully, there are a few wrong assumptions in your question:

"Safari (wrong): [image]" - Safari is not necessarily wrong.

"All other browsers (correct): [image]" - The other browsers are not necessarily correct.

"I thought Flexbox was really ready for primetime.." - It is. 98% of browsers support flexbox.

"Centering content horizontally and vertically is something Flexbox should be great at." - It is.

Is there anything I'm missing here?

Yes, the part in the spec where it says that absolutely-positioned flex items ignore flex properties.

4.1. Absolutely-Positioned Flex
  Children

An absolutely-positioned child of a flex
  container does not participate in flex layout.

If some browsers choose to apply flex properties to absolutely-positioned flex items, that's their choice. But if a browser ignores flex properties on such elements, that doesn't necessarily mean they are in violation of the spec.

In reading the entire section in the spec, there doesn't appear to be a clear right or wrong.

For a more stable and reliable solution, don't use flex properties to position out-of-flow elements. Use CSS positioning properties instead:

Center text over an image in flexbox

Body:
I have a container that contains both an image, and some text. I want the text to be vertically and horizontally centered in the middle of the image.

It seems that the easiest, forward-thinking method is to use Flexbox and absolute positioning of the text:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.text {
  position: absolute;
}

    This should be centered

The text is centered in both axes. This seems to work in all modern browsers..... except Safari.

Safari appear to not center the text at all. It's just sitting at the top/left of the container like a normal absolutely positioned element would be in a non-flexbox layout.

Safari (wrong):

All other browsers (correct):

I thought Flexbox was really ready for primetime, but this seems like a deal-breaker considering how many people using Safari on iOS. Centering content horizontally and vertically is something Flexbox should be great at.

My only real alternative here is to not use Flexbox and then use:

.text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}

But I would much rather be using Flexbox for progressive reasons.

Is there anything I'm missing here? As much as I hate to ask for it, is there some of Safari-only work-around here? Is there any solution to this besides just "not using flexbox" because if that is the answer in mid-2017 that is going to be disappointing.

JSFiddle for reference: https://jsfiddle.net/z7kh5Laz/4/


问:
xcodebuild archive path of newly created archive
When I archive from the command line using xcodebuild archive, how can I get the path to the newly created archive?  I'd like to follow on with an -exportArchive command to create an adhoc distribution.

I know that I can define an -archivePath, however if I do that then Organizer doesnt know where about this archive, so that's no good.

Thoughts?

答:
you can simply create a variable holding the path of the archive you want to generate. Then use the same path when you want to export

$ARCHIVE_PATH="<path_of_your_archive>" # can be something like "build/app_name.xcarchive"

# ARCHIVING

xcodebuild archive \
    -workspace "${APP_NAME}.xcworkspace" \
    -configuration $CONFIGUATION \
    -scheme $SCHEME \
    -archivePath $ARCHIVE_PATH

# EXPORTING

xcodebuild -exportArchive \
     -archivePath $ARCHIVE_PATH \
     -exportPath $OUTPUT_DIRECTORY \
     -exportOptionsPlist exportPlist.plist
```

Hope this helps you in any way!

Body:
you can simply create a variable holding the path of the archive you want to generate. Then use the same path when you want to export

$ARCHIVE_PATH="<path_of_your_archive>" # can be something like "build/app_name.xcarchive"

# ARCHIVING

xcodebuild archive \
    -workspace "${APP_NAME}.xcworkspace" \
    -configuration $CONFIGUATION \
    -scheme $SCHEME \
    -archivePath $ARCHIVE_PATH

# EXPORTING

xcodebuild -exportArchive \
     -archivePath $ARCHIVE_PATH \
     -exportPath $OUTPUT_DIRECTORY \
     -exportOptionsPlist exportPlist.plist

Hope this helps you in any way!

ContentLicense: CC BY-SA 4.0


问:
Common.Logging.NLog not available for net core?
I'm currently using Common.Logging version 3.4.0-beta2 and NLog 5.0.0-beta07 on netcoreapp1.1. (its and ASP Net Core mvc project)
I cannot find Common.Logging.NLog specific version for that case.

In case it is not yet available, which log file option do I have as adapter for net core?

答:
There isn't a package for NLog 5 and Common logging currently.

Alternatives are:

liblog:

just copy the file liblog.cs, see website

Manually rename the namespace YourRootNamespace to your project's root namespace.

Enable LIBLOG_PORTABLE compiler directive.

Or use Microsoft's logging abstraction. See docs how to log
and install NLog.Web.AspNetCore, and check install instructions


问:
Angular fails to assign http returned result to the variable
I am trying to make an app using ionic2 + angular2, I have a trouble of getting account verification result (0:failed 1:success) from server api.

Here is the ResultCode class

```<code>export class ResultCode{
  result: number;
}
</code>```

And here is the service code

```<code>@Injectable()
export class LoginService{
  private headers = new Headers({'Content-Type': 'application/json'});
  constructor(private http:Http){ }

  authenticate(url:string,email:string, password:string): Promise<ResultCode>{
    return this.http
      .get(url)
      .toPromise()
      .then(res => res.json() as ResultCode)
      .catch(this.handleError);
  }
  private extractData(res: Response) {
    let body = res.json();
    return body.result || { };
  }
  private handleError (error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
</code>```

Here is the LoginPage code

```<code>export class LoginPage {
  resultCode:ResultCode;

  private loginForm : FormGroup;
  constructor(
   public navCtrl: NavController,
   private loginService:LoginService,
   private formBuilder: FormBuilder) {
    this.loginForm = this.formBuilder.group({
     email: ['',[Validators.required,Validators.email]],
     password: ['',[Validators.required,Validators.minLength(6)]]
    });

  }
  login(){
   let email = this.loginForm.get('email').value;
   let password = this.loginForm.get('password').value;
   let url = `https://www.xxxx.com/api.pl?fn=login&email=${email}&password=${password}`;
   this.authenticate(url,email,password);
   console.log("result == " + this.resultCode.result);

  }
  authenticate(url,email,password){
    this.loginService.authenticate(url,email,password)
    .then(result=> this.resultCode = result);
  }

}
</code>```

And I get result == undefined from console.

I can get the result

result == 0
  from console, if i print it inside the .then()

```<code>  authenticate(url,email,password){
    this.loginService.authenticate(url,email,password)
    .then(result=> console.log("result == " + result.result));
  }
</code>```

I am wondering if the console.log is executed before authenticate() function is done?  Thank you for your help.

答:
Let's have a closer look at our code here:

login() {
   //...
   this.authenticate(url,email,password);
   console.log("result == " + this.resultCode.result);
   //...
}
```

<p>The reason the console prints <code>result == undefined</code> is because inside login() you are making an asynchronous call with <code>authenticate()</code>. <em>While</em> this is running, the execution of the rest of the program continues down to <code>console.log()</code>. Because console.log() executes much faster than making a network request with authenticate(), it prints undefined, although later the value inside <code>this.resultCode</code> is actually 0.</p>

<p>In order to handle the response later in your program you have to wait until it arrives. So anything you want to do <em>after</em> the network request has completed needs to be coded inside the <code>.then()</code> part of your <code>authenticate()</code> function like this:</p>

<pre class="lang-js prettyprint-override"><code>authenticate (url,email,password){
    this.loginService.authenticate(url,email,password)
        .then((result) => {
           // NOW WE ARE ALWAYS SURE THE RESPONSE HAS ARRIVED
           this.resultCode = result
        });
}
</code>```

Now, since you have the synchronous function login() calling the asynchronous authenticate(), you may want to do some things but only after login() and whatever it calls has completed.

The best way to do this is by using Promises. This is how I would change your code to support that:

login(){
   let email = this.loginForm.get('email').value;
   let password = this.loginForm.get('password').value;
   let url = `https://www.xxxx.com/api.pl?fn=login&email=${email}&password=${password}`;

   return new Promise((resolve, reject) => { // notice we now return a Promise here too
       this.authenticate(url,email,password)
           .then(result){
                this.resultCode = result;
                resolve (result);
           }
    };
}

authenticate(url,email,password){
    return new Promise((resolve, reject) => { // notice we now return a Promise
        this.loginService.authenticate(url,email,password)
            .then((result) => { resolve(result)); } // notice the change here, resolving the value outwards to the caller
    };
}
```

<p>Now in anywhere else in your LoginPage code where you want to run code that you are sure is executed after login has taken place completely you can just do:</p>

<pre class="lang-js prettyprint-override"><code>login().then(){
    // NOW WE ARE SURE LOGIN HAS COMPLETED
}
</code>```

Body:
I am trying to make an app using ionic2 + angular2, I have a trouble of getting account verification result (0:failed 1:success) from server api.

Here is the ResultCode class

export class ResultCode{
  result: number;
}

And here is the service code

@Injectable()
export class LoginService{
  private headers = new Headers({'Content-Type': 'application/json'});
  constructor(private http:Http){ }

  authenticate(url:string,email:string, password:string): Promise<ResultCode>{
    return this.http
      .get(url)
      .toPromise()
      .then(res => res.json() as ResultCode)
      .catch(this.handleError);
  }
  private extractData(res: Response) {
    let body = res.json();
    return body.result || { };
  }
  private handleError (error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

Here is the LoginPage code

export class LoginPage {
  resultCode:ResultCode;

  private loginForm : FormGroup;
  constructor(
   public navCtrl: NavController,
   private loginService:LoginService,
   private formBuilder: FormBuilder) {
    this.loginForm = this.formBuilder.group({
     email: ['',[Validators.required,Validators.email]],
     password: ['',[Validators.required,Validators.minLength(6)]]
    });

  }
  login(){
   let email = this.loginForm.get('email').value;
   let password = this.loginForm.get('password').value;
   let url = `https://www.xxxx.com/api.pl?fn=login&email=${email}&password=${password}`;
   this.authenticate(url,email,password);
   console.log("result == " + this.resultCode.result);

  }
  authenticate(url,email,password){
    this.loginService.authenticate(url,email,password)
    .then(result=> this.resultCode = result);
  }

}

And I get result == undefined from console.

I can get the result

result == 0
  from console, if i print it inside the .then()

  authenticate(url,email,password){
    this.loginService.authenticate(url,email,password)
    .then(result=> console.log("result == " + result.result));
  }

I am wondering if the console.log is executed before authenticate() function is done?  Thank you for your help.

Body:
Let's have a closer look at our code here:

login() {
   //...
   this.authenticate(url,email,password);
   console.log("result == " + this.resultCode.result);
   //...
}

The reason the console prints result == undefined is because inside login() you are making an asynchronous call with authenticate(). While this is running, the execution of the rest of the program continues down to console.log(). Because console.log() executes much faster than making a network request with authenticate(), it prints undefined, although later the value inside this.resultCode is actually 0.

In order to handle the response later in your program you have to wait until it arrives. So anything you want to do after the network request has completed needs to be coded inside the .then() part of your authenticate() function like this:

authenticate (url,email,password){
    this.loginService.authenticate(url,email,password)
        .then((result) => {
           // NOW WE ARE ALWAYS SURE THE RESPONSE HAS ARRIVED
           this.resultCode = result
        });
}

Now, since you have the synchronous function login() calling the asynchronous authenticate(), you may want to do some things but only after login() and whatever it calls has completed.

The best way to do this is by using Promises. This is how I would change your code to support that:

login(){
   let email = this.loginForm.get('email').value;
   let password = this.loginForm.get('password').value;
   let url = `https://www.xxxx.com/api.pl?fn=login&email=${email}&password=${password}`;

   return new Promise((resolve, reject) => { // notice we now return a Promise here too
       this.authenticate(url,email,password)
           .then(result){
                this.resultCode = result;
                resolve (result);
           }
    };
}

authenticate(url,email,password){
    return new Promise((resolve, reject) => { // notice we now return a Promise
        this.loginService.authenticate(url,email,password)
            .then((result) => { resolve(result)); } // notice the change here, resolving the value outwards to the caller
    };
}

Now in anywhere else in your LoginPage code where you want to run code that you are sure is executed after login has taken place completely you can just do:

login().then(){
    // NOW WE ARE SURE LOGIN HAS COMPLETED
}


问:
Show input in Symbolic form without computation in Maxima
In Maxima when I enter for example:

I can see my input in a "readable" way, in order to verify everything I have typed in is interpreted the way I want. I want to be able to at first see my input in symbolic form and after that the result of my computation. For example when I define x as 5 I want the same result as above and after that the simplified form.

Is that possible? I use wxmaxima.

Another simple example for illustration: When I enter 5*5 I want an output saying 5 5 and then a second output with 25.

答:
Maybe you can get the effect you want by disabling simplification.

```<code>(%i1) simp:false;
(%o1)                                false
(%i2) x:5;
(%o2)                                  5
(%i3) 34*sqrt(x+ 7)/(7*x^2);
                                34 sqrt(5 + 7)
(%o3)                           --------------
                                        2
                                     7 5
(%i4) %, simp;
                                  68 sqrt(3)
(%o4)                             ----------
                                     175
</code>```

Simplification, in Maxima, means applying arithmetic and algebraic identities. Many important operations such as adding and multiplying numbers are carried out by simplification in Maxima, so if you disable simplification, you will get results that are pretty different from what you would get with simplification enabled. But you can get the usual result by simplifying it, as in %i3 above.

Body:
Maybe you can get the effect you want by disabling simplification.

(%i1) simp:false;
(%o1)                                false
(%i2) x:5;
(%o2)                                  5
(%i3) 34*sqrt(x+ 7)/(7*x^2);
                                34 sqrt(5 + 7)
(%o3)                           --------------
                                        2
                                     7 5
(%i4) %, simp;
                                  68 sqrt(3)
(%o4)                             ----------
                                     175

Simplification, in Maxima, means applying arithmetic and algebraic identities. Many important operations such as adding and multiplying numbers are carried out by simplification in Maxima, so if you disable simplification, you will get results that are pretty different from what you would get with simplification enabled. But you can get the usual result by simplifying it, as in %i3 above.


问:
How can I implement JQuery promise and .map()?
I have an array. Usually the array has around 5 objects. And I hope the system will loop the array, each object in the array will generate a window(I use kendo window). And users will do some manipulations in the prompted window, after the ajax send the value and successfully returned the value. The window will be closed, and then prompt up the next window based on the object in the array. So how can I make .each() wait until the window closed then open another window?

I know JQuery promise, and .map(), but I don't know how to implement it?

答:
Have a look at below code snippet. I have simulated async behavior(window sequences) with setTimeout. Creating kendoUI window code goes where I have used setTimeout

No jQuery promise is being used. All are plain javascript.

var array = [3, 6, 2, 5, 10],
    iTaskCounter = -1;

function doSomething(item, fnNextJob) {
  // Showing dialog and doing something
  // Now mocked with setTimeout
  console.log("Task: ", item);
  setTimeout(function() {
    console.log("Calling next task");
    fnNextJob();
  }, item * 1000);
}

function executeTask() {
    iTaskCounter++;
    if(iTaskCounter < array.length) {
      doSomething(array[iTaskCounter], executeTask);
    } else {
      console.log("Task completed");
    }
}
console.log("Start task");
executeTask();```


问:
Using Ajax in django template to update an element
So I have a button that is suppose to "Add" an "Item" to a list and update the list on the same page without refreshing it.

Adding the Item without redirecting worked. but the element is not refreshed properly

Here is my script:

```<code><div id="list">
    {% for item in items %}
        {{ item.name }}
    {% endfor %}
</div>

<button id="add" type="submit">+</button>

<script>
    $('#add').click(function () {
        $.get('/url/page/', function (data) {
            $('#list').html(data);
        });
    });
</script>
</code>```

views.py

```<code>def add_to_list(request, item_id, list_id):
      item, created = List.objects.get_or_create(list_id=list_id,
      item_id=item_id)
     return HttpResponse(request)
</code>```

I feel like I have to add something in the views? and maybe use json code?

答:
You should append the result of your request to the div element. Try this:

```<code> $('#add').click(function () {
    $.get('/url/page/', function (data) {
        $('#list').append(data);
    });
});
</code>```

Assuming that data that you receive from GET request is not an object but just a string. If it is an object add data.name:

```<code>$('#list').append(data.name)
</code>```

Hope it helps.

Body:
So I have a button that is suppose to "Add" an "Item" to a list and update the list on the same page without refreshing it.

Adding the Item without redirecting worked. but the element is not refreshed properly

Here is my script:

    {% for item in items %}
        {{ item.name }}
    {% endfor %}

<button id="add" type="submit">+</button>

views.py

def add_to_list(request, item_id, list_id):
      item, created = List.objects.get_or_create(list_id=list_id,
      item_id=item_id)
     return HttpResponse(request)

I feel like I have to add something in the views? and maybe use json code?

Body:
You should append the result of your request to the div element. Try this:

 $('#add').click(function () {
    $.get('/url/page/', function (data) {
        $('#list').append(data);
    });
});

Assuming that data that you receive from GET request is not an object but just a string. If it is an object add data.name:

$('#list').append(data.name)

Hope it helps.


问:
JQuery and set data more permanently
Hi

I used jquery in my application and I have a problem but I think it is necessarly to look at this code :

```<code>        $("#btnAddToBasket").click(function () {
            var id = $("#ProductIDAtBasket").text();
            var count = $("#BasketAddedValueText").val();
            //ajax request
            $.ajax({ type: "Post",
                url: "Services/NewE_ShopServices.asmx" + "/" + "GetPrice",
                data: "{" + "count" + ":" + count + ", goodcode : " + id + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: AjaxSucceeded,
                async: true,
                cache: false,
                error: AjaxFailed
            });
        });

        function AjaxSucceeded(result) {
            var res = result.d;
            res = res.split(';');
            $("#spanFinalPrice").text(res[2]);
            $("#spanAbsolutePrice").text(res[3]);
            $("#spanDiscount").text(res[4]);
            $("#spanCount").text(res[1]);
            $("#AddBasketDiv").hide("slow");
        }

        function AjaxFailed(result) {
            alert(result.responseText);
        }
</code>```

As you can see at the following there is ajax send method to web service I get the values and put results using ajaxsucceeded method into the page it works fine and suitable but my problem is that it is basket viewer and I want to be more permanent for example in this page when you go to other page and back to it the contains will be omitted I can use session and cookies in the webservice class but how I can read from jQuery code? what is solution is there any other solution ?

答:
If I am understanding it correctly, you are adding things to a basket, but they are not persisting on other pages? I.E, you add a product to your basket, and then move to another page and the item is not in the basket?

If so you need to check a couple of things:

How are you storing the basket on the server side. Do you put the items in Session?

Are you reading from that basket to pre-populate the basket in a state before you add items in?

ContentLicense: CC BY-SA 2.5

Title: JQuery and set data more permanently

Body:
Hi

I used jquery in my application and I have a problem but I think it is necessarly to look at this code :

        $("#btnAddToBasket").click(function () {
            var id = $("#ProductIDAtBasket").text();
            var count = $("#BasketAddedValueText").val();
            //ajax request
            $.ajax({ type: "Post",
                url: "Services/NewE_ShopServices.asmx" + "/" + "GetPrice",
                data: "{" + "count" + ":" + count + ", goodcode : " + id + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: AjaxSucceeded,
                async: true,
                cache: false,
                error: AjaxFailed
            });
        });

        function AjaxSucceeded(result) {
            var res = result.d;
            res = res.split(';');
            $("#spanFinalPrice").text(res[2]);
            $("#spanAbsolutePrice").text(res[3]);
            $("#spanDiscount").text(res[4]);
            $("#spanCount").text(res[1]);
            $("#AddBasketDiv").hide("slow");
        }

        function AjaxFailed(result) {
            alert(result.responseText);
        }

As you can see at the following there is ajax send method to web service I get the values and put results using ajaxsucceeded method into the page it works fine and suitable but my problem is that it is basket viewer and I want to be more permanent for example in this page when you go to other page and back to it the contains will be omitted I can use session and cookies in the webservice class but how I can read from jQuery code? what is solution is there any other solution ?


问:
Synchronizing a Block of Code - Exercise 13-2
In this exercise, we will attempt to synchronize a block of code. Within that block of code, we will get the lock on an object so that other threads cannot modify it while the block of code is executing. We will be creating three threads that will all attempt to manipulate the same object. Each thread will output a single letter 100 times and then increment that letter by one. The object we will be using is StringBuffer. We could synchronize on a String object, but strings cannot be modified once they are created, so we would not be able to increment the letter without generating a new String object. The final output should have 100 A’s, 100 B’s, and 100 C’s, all in unbroken lines.

Create a class and extend the Thread class.

Override the run() method of Thread. This is where the synchronized block of code will go.

For our three thread objects to share the same object, we will need to create a constructor that accepts a StringBuffer object in the argument.

The synchronized block of code will obtain a lock on the StringBuffer object from step 3.

Within the block, output the StringBuffer 100 times and then increment the letter in the StringBuffer. You can check Chapter 5 for StringBuffer (StringBuilder) methods that will help with this.

Finally, in the main() method, create a single StringBuffer object using the letter A, then create three instances of our class and start all three of them.

Solution:

public class OCJPThread extends Thread{

```<code>StringBuffer sb;
public OCJPThread(StringBuffer sb) {
    this.sb =sb;
}

public void run(){
    synchronized (sb) {
        System.out.println(Thread.currentThread().getName());
        for(int i=1;i<=100;i++)
            System.out.print(sb);

        System.out.println();
        sb.setCharAt(0, (char)(sb.charAt(0)+1));

    }
}

public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("A");
    OCJPThread t1 =new OCJPThread(sb);
    OCJPThread t2 =new OCJPThread(sb);
    OCJPThread t3 =new OCJPThread(sb);

    t1.start();
    t2.start();
    t3.start();
}
</code>```

}
output
Thread-0
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Thread-2
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
Thread-1
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

Question : If I am using Stringbuilder or StringBuffer, it doesn't matter as I am using syncronized block.

But if I use synchronized(this) instead of stringbuffer object. Output is unpredicatable. As string buffer is already syncronized, why do we need to do it ourselves?

答: You're passing the same reference to all three threads. If they synchronize on this, then they can all write to the StringBuffer at the same time. If they synchronize on the common StringBuffer, then only one thread can access it at a time.

Body:
In this exercise, we will attempt to synchronize a block of code. Within that block of code, we will get the lock on an object so that other threads cannot modify it while the block of code is executing. We will be creating three threads that will all attempt to manipulate the same object. Each thread will output a single letter 100 times and then increment that letter by one. The object we will be using is StringBuffer. We could synchronize on a String object, but strings cannot be modified once they are created, so we would not be able to increment the letter without generating a new String object. The final output should have 100 A’s, 100 B’s, and 100 C’s, all in unbroken lines.

Create a class and extend the Thread class.

Override the run() method of Thread. This is where the synchronized block of code will go.

For our three thread objects to share the same object, we will need to create a constructor that accepts a StringBuffer object in the argument.

The synchronized block of code will obtain a lock on the StringBuffer object from step 3.

Within the block, output the StringBuffer 100 times and then increment the letter in the StringBuffer. You can check Chapter 5 for StringBuffer (StringBuilder) methods that will help with this.

Finally, in the main() method, create a single StringBuffer object using the letter A, then create three instances of our class and start all three of them.

Solution:

public class OCJPThread extends Thread{

StringBuffer sb;
public OCJPThread(StringBuffer sb) {
    this.sb =sb;
}

public void run(){
    synchronized (sb) {
        System.out.println(Thread.currentThread().getName());
        for(int i=1;i<=100;i++)
            System.out.print(sb);

        System.out.println();
        sb.setCharAt(0, (char)(sb.charAt(0)+1));

    }
}

public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("A");
    OCJPThread t1 =new OCJPThread(sb);
    OCJPThread t2 =new OCJPThread(sb);
    OCJPThread t3 =new OCJPThread(sb);

    t1.start();
    t2.start();
    t3.start();
}

}
output
Thread-0
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Thread-2
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
Thread-1
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

Question : If I am using Stringbuilder or StringBuffer, it doesn't matter as I am using syncronized block.

But if I use synchronized(this) instead of stringbuffer object. Output is unpredicatable. As string buffer is already syncronized, why do we need to do it ourselves?


问:
Provide an image for WhatsApp link sharing
How can we include an image in our website to display in WhatsApp when we share a link like this?

答: Had same issue, added og:image and it didn't work while the url end with slash sign (/). After removing the slash from the URL - the image get loaded.. Interesting bug...</p>


问:
Bootstrap datepicker disabling past dates without current date
I wanted to disable all past date before current date, not with current date. I am trying by bootstrap datepicker library "bootstrap-datepicker" and using following code:

```<code>$('#date').datepicker({
    startDate: new Date()
});
</code>```

It works fine. But it is disabling date till today.

As example if today is 04-20-2013 and i disable past dates by setting startDate: new Date(). but I am able to select date from 04-21-2013.

UPDATED: i can solve it as following for UTC zone:

```<code>var d = new Date();
options["startDate"] = new Date(d.setDate(d.getDate() - 1));
</code>```

or startDate: "+0d"

But these methods don't work when UTC is a day ahead. For my client in California that means at 5:00 pm my client can no longer select his local current date as a valid date. In order to fix this I am temporarily using startDate: "-1d", but of course before 5 that means yesterday is visible.

Has anyone come up with a better method for now as I do not want to tell users to put in a UTC date?

答:
The following worked for me</p>

```<code>$('.input-group.date').datepicker({
     format: 'dd/mm/yyyy',
     startDate: new Date()
});
</code>```

Body:
I wanted to disable all past date before current date, not with current date. I am trying by bootstrap datepicker library "bootstrap-datepicker" and using following code:

$('#date').datepicker({
    startDate: new Date()
});

It works fine. But it is disabling date till today.

As example if today is 04-20-2013 and i disable past dates by setting startDate: new Date(). but I am able to select date from 04-21-2013.

UPDATED: i can solve it as following for UTC zone:

var d = new Date();
options["startDate"] = new Date(d.setDate(d.getDate() - 1));

or startDate: "+0d"

But these methods don't work when UTC is a day ahead. For my client in California that means at 5:00 pm my client can no longer select his local current date as a valid date. In order to fix this I am temporarily using startDate: "-1d", but of course before 5 that means yesterday is visible.

Has anyone come up with a better method for now as I do not want to tell users to put in a UTC date?

Body:
The following worked for me

$('.input-group.date').datepicker({
     format: 'dd/mm/yyyy',
     startDate: new Date()
});


问:
I want to use WebSockets to send and receive data in REACT NATIVE
I want to send and receive data using facebook's suggestion
https://facebook.github.io/react-native/docs/network.html#websocket
but when I run the code it fails to import the "WebSocket" and app
crashes.
The code in the render method works just fine, but I do not want to
render a view again and again just to send data.
I want the code in componentWillMount function to run to send and
receive data. Please help me. I will be thankful to you. </p>

```<code>import React, { Component } from 'react';
import WS from 'react-native-websocket';
import { View } from 'react-native';

export default class Example extends Component {

  componentWillMount() {

const ws = new WebSocket('ws://host.com/path');

ws.onopen = () => {
  // connection opened

  ws.send('something'); // send a message
};

ws.onmessage = (e) => {
  // a message was received
  console.log(e.data);
};

ws.onerror = (e) => {
  // an error occurred
  console.log(e.message);
};

ws.onclose = (e) => {
  // connection closed
  console.log(e.code, e.reason);
};

  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <WS
          ref={ref => { this.ws = ref }}
          url="http://34.206.187.250:1880/ws/praduman"
          onOpen={() => {
            console.log('Open!')
            this.ws.send('Hello')
          }}
          onMessage={console.log}
          onError={console.log}
          onClose={console.log}
          reconnect
        />
      </View>
    )
  }
}
</code>```

答:
Try this:</p>

```<code>import React, { Component } from 'react'
import { AppRegistry, View } from 'react-native'
import WS from 'react-native-websocket'

export default class Example extends Component {
  _onOpen() {
      console.log('Open!')
      this.ws.send('Hello')
   }
  _onMessage(event) {
      console.log('Data',event)
   }
   _onError(error) {
      console.log('Error',error)
   }
   _onClose() {
      console.log('Close!')
   }

  render () {
    return (
      <View style={{flex: 1}}>
        <WS
          ref={ref => {this.ws = ref}}
          url="wss://echo.websocket.org/"
          onOpen={() => this._onOpen.bind(this)}
          onMessage={(event) => this._onMessage.bind(this)}
          onError={(error) => this._onError.bind(this)}
          onClose={() => this._onClose.bind(this)}
        />
      </View>
    )
  }
}
</code>```

Body:
I want to send and receive data using facebook's suggestion
https://facebook.github.io/react-native/docs/network.html#websocket
but when I run the code it fails to import the "WebSocket" and app
crashes.
The code in the render method works just fine, but I do not want to
render a view again and again just to send data.
I want the code in componentWillMount function to run to send and
receive data. Please help me. I will be thankful to you.

import React, { Component } from 'react';
import WS from 'react-native-websocket';
import { View } from 'react-native';

export default class Example extends Component {

  componentWillMount() {

const ws = new WebSocket('ws://host.com/path');

ws.onopen = () => {
  // connection opened

  ws.send('something'); // send a message
};

ws.onmessage = (e) => {
  // a message was received
  console.log(e.data);
};

ws.onerror = (e) => {
  // an error occurred
  console.log(e.message);
};

ws.onclose = (e) => {
  // connection closed
  console.log(e.code, e.reason);
};

  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <WS
          ref={ref => { this.ws = ref }}
          url="http://34.206.187.250:1880/ws/praduman"
          onOpen={() => {
            console.log('Open!')
            this.ws.send('Hello')
          }}
          onMessage={console.log}
          onError={console.log}
          onClose={console.log}
          reconnect
        />
      </View>
    )
  }
}

Body:
Try this:

import React, { Component } from 'react'
import { AppRegistry, View } from 'react-native'
import WS from 'react-native-websocket'

export default class Example extends Component {
  _onOpen() {
      console.log('Open!')
      this.ws.send('Hello')
   }
  _onMessage(event) {
      console.log('Data',event)
   }
   _onError(error) {
      console.log('Error',error)
   }
   _onClose() {
      console.log('Close!')
   }

  render () {
    return (
      <View style={{flex: 1}}>
        <WS
          ref={ref => {this.ws = ref}}
          url="wss://echo.websocket.org/"
          onOpen={() => this._onOpen.bind(this)}
          onMessage={(event) => this._onMessage.bind(this)}
          onError={(error) => this._onError.bind(this)}
          onClose={() => this._onClose.bind(this)}
        />
      </View>
    )
  }
}


问:
Correct way of using async each method to avoid reference errors
I am making a series of database calls, and want to return something once they have all executed.

I am using the async module to help with this and applying a function to each element in an array.

```<code>    async.each(items, sqlCall(),
    function(err) {
        if( err ) {
          // All processing will now stop.
          console.log('A call failed');
        } else {
            console.log("finished async operations");
        }
    });
</code>```

I define sqlCall as follows

```<code>sqlCall = function(item , callback){
        console.log("arr is " + JSON.stringify(item));
        lampInfo = item[0];
        userRoom = item[1];
        sql = item[2];
        console.log('sql is ' + sql);
        connection.query(sql, function(error, results, fields) {
            if (error){
                console.log("why error");
                callback(error);
            }
            else {
                console.log("successful call");
                lampSavingsStatement[savingsCalc(lampInfo, results[0], energyPrice)] = userRoom;
                callback();
            }
        });
    }
</code>```

lampSavingsStatement is a global dictionary and savingsCalc is another method

I keep getting a reference error, where arr is undefined, and am not sure what the problem is.

For an example of what items is

```<code>[ [ { lampName: '2ft T5 14W', number: '12', hours: '3' },
    'room2',
    'SELECT * FROM `lightstoled` WHERE `techid` = \'2ft T5 14W\'' ] ]
</code>```

答:
You are passing to async.each the result of sqlCall(), not the function.

Try this instead:

```<code>async.each(items, sqlCall, function (err) { ... });
</code>```

Body:
I am making a series of database calls, and want to return something once they have all executed.

I am using the async module to help with this and applying a function to each element in an array.

    async.each(items, sqlCall(),
    function(err) {
        if( err ) {
          // All processing will now stop.
          console.log('A call failed');
        } else {
            console.log("finished async operations");
        }
    });

I define sqlCall as follows

sqlCall = function(item , callback){
        console.log("arr is " + JSON.stringify(item));
        lampInfo = item[0];
        userRoom = item[1];
        sql = item[2];
        console.log('sql is ' + sql);
        connection.query(sql, function(error, results, fields) {
            if (error){
                console.log("why error");
                callback(error);
            }
            else {
                console.log("successful call");
                lampSavingsStatement[savingsCalc(lampInfo, results[0], energyPrice)] = userRoom;
                callback();
            }
        });
    }

lampSavingsStatement is a global dictionary and savingsCalc is another method

I keep getting a reference error, where arr is undefined, and am not sure what the problem is.

For an example of what items is

[ [ { lampName: '2ft T5 14W', number: '12', hours: '3' },
    'room2',
    'SELECT * FROM `lightstoled` WHERE `techid` = \'2ft T5 14W\'' ] ]

Body:
You are passing to async.each the result of sqlCall(), not the function.

Try this instead:

async.each(items, sqlCall, function (err) { ... });


问:
Work with many-to many relationships C#
Good evening!
I use Asp.net MVC with EF.
I have 2 models

```<code> public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Category> categories { get; set; }
    }

    public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Product> products { get; set; }
    }
</code>```

many-to many add normaly work, if I add new product, but if i try update product entity,new relationship doesnt add.
I add new products like this

```<code>Product product= new Product{...};
product.categories.Add(db.Categories.First())//example
</code>```

How I can add/delete relationships in product entity update?

答:
First, your ICollection<T> should be a virtual property:

```<code>public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}

public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}
</code>```

Next, create an association table between the two:

```<code>public class ProductCategory
{
    public virtual Product Product { get; set; }
    public virtual Category Category { get; set; }
}
</code>```

Then in your dbContext, add the relationships:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<ProductCategory>()
       .HasKey(c => new { c.CategoryId, c.ProductId });

   modelBuilder.Entity<Product>()
       .HasMany(c => c.ProductCategories)
       .WithRequired()
       .HasForeignKey(c => c.ProductId);

   modelBuilder.Entity<Category>()
       .HasMany(c => c.ProductCategories)
       .WithRequired()
       .HasForeignKey(c => c.CategoryId);
}
</code>```

Title: Work with many-to many relationships C#

Body:
Good evening!
I use Asp.net MVC with EF.
I have 2 models

 public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Category> categories { get; set; }
    }

    public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Product> products { get; set; }
    }

many-to many add normaly work, if I add new product, but if i try update product entity,new relationship doesnt add.
I add new products like this

Product product= new Product{...};
product.categories.Add(db.Categories.First())//example

How I can add/delete relationships in product entity update?

Body:
First, your ICollection<T> should be a virtual property:

public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}

public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}

Next, create an association table between the two:

public class ProductCategory
{
    public virtual Product Product { get; set; }
    public virtual Category Category { get; set; }
}

Then in your dbContext, add the relationships:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<ProductCategory>()
       .HasKey(c => new { c.CategoryId, c.ProductId });

   modelBuilder.Entity<Product>()
       .HasMany(c => c.ProductCategories)
       .WithRequired()
       .HasForeignKey(c => c.ProductId);

   modelBuilder.Entity<Category>()
       .HasMany(c => c.ProductCategories)
       .WithRequired()
       .HasForeignKey(c => c.CategoryId);
}


问:
How can I set up different build configurations for ASP.Net web site projects?
According to an earlier question about Visual Studio configurations, there's no way to use Visual Studio's configuration manager to create different configurations for an ASP.net web site project.

For normal projects, we have #if directives that switch certain server or database variables depending on whether we're debugging or in production.  This doesn't work for web sites.

For example, in a class (in App_Code) that defines a web site's back-end server connection, there might be a chunk of code like this which overrides production values in the web.config if you want to run a debug server on your local machine:

```<code>#if DEBUGLOCAL
           ServerProperties.ServerIP = "localhost";
           ServerProperties.DataContextIP = "localhost";
#endif
</code>```

This doesn't work, since there's no "Debug Local" configuration for the website, thus no DEBUGLOCAL defined.

Have you found a good way to work around problems like this?  Besides (I hope) refactoring everything so all those references live in a class library project?

ETA: Can web deployment projects help here?

答: Perhaps a Web Deployment project that does some swapping in the web.config may be of some help?  Another thought would be to have a connection string in the web.config that pulls various values from a pre-specified database that can exist in each environment to allow for easy changes to the settings without needing to touch any files.</p>

OwnerDisplayName: Darcy Casselman

Body:
According to an earlier question about Visual Studio configurations, there's no way to use Visual Studio's configuration manager to create different configurations for an ASP.net web site project.

For normal projects, we have #if directives that switch certain server or database variables depending on whether we're debugging or in production.  This doesn't work for web sites.

For example, in a class (in App_Code) that defines a web site's back-end server connection, there might be a chunk of code like this which overrides production values in the web.config if you want to run a debug server on your local machine:

#if DEBUGLOCAL
           ServerProperties.ServerIP = "localhost";
           ServerProperties.DataContextIP = "localhost";
#endif

This doesn't work, since there's no "Debug Local" configuration for the website, thus no DEBUGLOCAL defined.

Have you found a good way to work around problems like this?  Besides (I hope) refactoring everything so all those references live in a class library project?

ETA: Can web deployment projects help here?

LastEditorDisplayName: Darcy Casselman

OwnerDisplayName: JB King


问:
Html2Canvas Rotated td is showing only first 3 letters
I tried using htmltocanvas to make png of selected html in my web page, though its giving perfect output but i am facing few issues which are as follows:

Rotated td's in which text is coming through knockout is showing only first 3 letters in the converted image via html2canvas.

dotted borders are coming as solid borders.

答:
In my case, I needed dashed borders.
Solved by drawing the borders myself, over the canvas returned by html2canvas.

Here are the steps:

Collect all border data in the HTML;

Remove the borders from the HTML, so the html2canvas wont draw them;

Call the html2canvas;

In the onrendered callback, draw the borders and restore the borders in the HTML.

Here is a fiddle. The tocanvas function has the same signature of html2canvas.

Result


问:
Set a typeface of a MenuItem
I have subMenus:

```<code>@Override
    public boolean onCreateOptionsMenu(Menu menu) {

        SubMenu subMenuFile = menu.addSubMenu("Font type");

        SubMenu subMenuEdit = menu.addSubMenu("Font size");
        subMenuEdit.add(Menu.NONE, IDM_FONT_SIZE, Menu.NONE, "Change size of font");

        return super.onCreateOptionsMenu(menu);
    }
</code>```

I want to set their typeface. Can I do it? Menu.XML file doesn't support the attribute android:typeface="serif". The compiler says: "Error: String types not allowed (at 'typeface' with value 'Arial')"
Then I have done this:

```<code>@Override
    public boolean onCreateOptionsMenu(Menu menu) {

        SubMenu subMenuFile = menu.addSubMenu("Font type");

        for(int i = 0; i < fontFaces.length; ++i) {
         subMenuFile.add(Menu.NONE, IDM_FONT_TYPE, Menu.NONE, Html.fromHtml("<b>html</b>"));
        }

        SubMenu subMenuEdit = menu.addSubMenu("Font size");
        subMenuEdit.add(Menu.NONE, IDM_FONT_SIZE, Menu.NONE, "Change size of font");

        return super.onCreateOptionsMenu(menu);
    }
</code>```

I have seen, that the submenu supports different styles, but the application finishes with an error. Here is the log:

```<code>01-12 10:04:18.103: ERROR/AndroidRuntime(1078): FATAL EXCEPTION: main
01-12 10:04:18.103: ERROR/AndroidRuntime(1078): java.lang.IllegalArgumentException: Invalid payload item type
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.util.EventLog.writeEvent(Native Method)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.app.Activity.onMenuItemSelected(Activity.java:2204)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:748)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:137)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:873)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.widget.AdapterView.performItemClick(AdapterView.java:284)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.widget.ListView.performItemClick(ListView.java:3513)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:1800)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.os.Handler.handleCallback(Handler.java:587)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.os.Looper.loop(Looper.java:123)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.app.ActivityThread.main(ActivityThread.java:3647)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at java.lang.reflect.Method.invokeNative(Native Method)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at java.lang.reflect.Method.invoke(Method.java:507)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at dalvik.system.NativeStart.main(Native Method)
01-12 10:04:22.393: ERROR/InputDispatcher(67): channel '406c4fb8 android.htmleditor/android.htmleditor.MainActivity (server)' ~ Consumer closed input channel or an error occurred.  events=0x8
01-12 10:04:22.393: ERROR/InputDispatcher(67): channel '406c4fb8 android.htmleditor/android.htmleditor.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-12 10:04:23.263: ERROR/InputDispatcher(67): Received spurious receive callback for unknown input channel.  fd=175, events=0x8
</code>```

How can I set a typeface of a MenuItem?

答:
You can provide custom layout for your item and use typeface that you need through xml.

See the answer here: https://stackoverflow.com/a/24807645/4958167

And here is an article how to create typefaced text view.

Title: Set a typeface of a MenuItem

Body:
I have subMenus:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {

        SubMenu subMenuFile = menu.addSubMenu("Font type");

        SubMenu subMenuEdit = menu.addSubMenu("Font size");
        subMenuEdit.add(Menu.NONE, IDM_FONT_SIZE, Menu.NONE, "Change size of font");

        return super.onCreateOptionsMenu(menu);
    }

I want to set their typeface. Can I do it? Menu.XML file doesn't support the attribute android:typeface="serif". The compiler says: "Error: String types not allowed (at 'typeface' with value 'Arial')"
Then I have done this:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {

        SubMenu subMenuFile = menu.addSubMenu("Font type");

        for(int i = 0; i < fontFaces.length; ++i) {
         subMenuFile.add(Menu.NONE, IDM_FONT_TYPE, Menu.NONE, Html.fromHtml("html"));
        }

        SubMenu subMenuEdit = menu.addSubMenu("Font size");
        subMenuEdit.add(Menu.NONE, IDM_FONT_SIZE, Menu.NONE, "Change size of font");

        return super.onCreateOptionsMenu(menu);
    }

I have seen, that the submenu supports different styles, but the application finishes with an error. Here is the log:

01-12 10:04:18.103: ERROR/AndroidRuntime(1078): FATAL EXCEPTION: main
01-12 10:04:18.103: ERROR/AndroidRuntime(1078): java.lang.IllegalArgumentException: Invalid payload item type
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.util.EventLog.writeEvent(Native Method)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.app.Activity.onMenuItemSelected(Activity.java:2204)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:748)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:143)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:137)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:873)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.widget.AdapterView.performItemClick(AdapterView.java:284)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.widget.ListView.performItemClick(ListView.java:3513)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:1800)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.os.Handler.handleCallback(Handler.java:587)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.os.Looper.loop(Looper.java:123)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at android.app.ActivityThread.main(ActivityThread.java:3647)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at java.lang.reflect.Method.invokeNative(Native Method)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at java.lang.reflect.Method.invoke(Method.java:507)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-12 10:04:18.103: ERROR/AndroidRuntime(1078):     at dalvik.system.NativeStart.main(Native Method)
01-12 10:04:22.393: ERROR/InputDispatcher(67): channel '406c4fb8 android.htmleditor/android.htmleditor.MainActivity (server)' ~ Consumer closed input channel or an error occurred.  events=0x8
01-12 10:04:22.393: ERROR/InputDispatcher(67): channel '406c4fb8 android.htmleditor/android.htmleditor.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-12 10:04:23.263: ERROR/InputDispatcher(67): Received spurious receive callback for unknown input channel.  fd=175, events=0x8

How can I set a typeface of a MenuItem?


问:
makefile execute after modify the input or only not executed input
I need to do a makefile for run some programs. Every time I run that script all the file are processed also if the file are not changed. I'm sure there is a problem on my code but I don't understand where I made the mistakes.

```<code>RDIR=RAW
OUTDIR=Fusion_res/kallisto
RFILES:=$(wildcard $(RDIR)/*_R1_001.fastq.gz)
DATABASE=/home/sbsuser/databases/Kallsto_hg38_87
OUTFILE=$(patsubst %_R1_001.fastq.gz,%_R2_001.fastq.gz,$(RFILES))
OUTKAL=$(patsubst $(RDIR)/%_R1_001.fastq.gz,$(OUTDIR)/%,$(RFILES))
.PHONY: clean all

all: $(OUTFILE) $(RFILES) $(OUTDIR) $(OUTKAL)

#$(OUTKAL) $(OUTFILE): $(RDIR)/%._R1_001.fastq.gz
#   echo "kallisto  quant -i" $(DATABASE)/transcripts.idx -b 100 -o $@ --fusion $< $(OUTFILE)

$(OUTDIR)/%: $(RDIR)/%_R1_001.fastq.gz $(OUTFILE)
      kallisto  quant -i $(DATABASE)/transcripts.idx -b 100  --fusion --rf-stranded -o $@ $(RDIR)/$*_R1_00
1.fastq.gz   $(RDIR)/$*_R2_001.fastq.gz

$(OUTDIR):
    mkdir -p $(OUTDIR)

clean::
    $(RM) -rf $(OUTDIR)
</code>```

I suppose if the found some change on the input file and on the output execute the command. I don't know why every time force re-run. In some case Is that I want but I wan to also if there is some new input execute only that.
Thanks so much

答:
A couple of things:

1)  $(OUTDIR)/% is dependent on $(OUTFILE) (which is a list of all outfiles).  Therefore if you change any one of the OUTFILEs, you make everything in $(OUTDIR)/% obsolete.   I believe what you want is this:

```<code>$(OUTDIR)/%_R1_001.fastq.gz: $(RDIR)/%_R2_001.fastq.gz
    .... (rules to make out/R1 from raw/R2

$(RDIR)/%_R2_001.fastq.gz: $(RDIR)/%_R1_001.fastq.gz
    .... (rules to make R2 from R1
</code>```

This makes each file dependent only on the files that effect it.

2) you have the target all dependent on $(OUTDIR) which is a directory.  If you use parallel make, it may generate the $(OUTDIR) after it generates the other dependencies of all: (some of which would depend on $(OUTDIR) being created).     What you want there is to remove all's dependency on $(OUTDIR), and add the line:

```<code>$(OUTFILE) : | $(OUTDIR)
</code>```

Notice the |, which means order only (don't consider $(OUTFILE) out of date if $(OUTDIR) is newer.   This is important, as a directory's timestamp is updated each time a file in the directory is changed, and so it tends to be newer than its contents.

Body:
I need to do a makefile for run some programs. Every time I run that script all the file are processed also if the file are not changed. I'm sure there is a problem on my code but I don't understand where I made the mistakes.

RDIR=RAW
OUTDIR=Fusion_res/kallisto
RFILES:=$(wildcard $(RDIR)/*_R1_001.fastq.gz)
DATABASE=/home/sbsuser/databases/Kallsto_hg38_87
OUTFILE=$(patsubst %_R1_001.fastq.gz,%_R2_001.fastq.gz,$(RFILES))
OUTKAL=$(patsubst $(RDIR)/%_R1_001.fastq.gz,$(OUTDIR)/%,$(RFILES))
.PHONY: clean all

all: $(OUTFILE) $(RFILES) $(OUTDIR) $(OUTKAL)

#$(OUTKAL) $(OUTFILE): $(RDIR)/%._R1_001.fastq.gz
#   echo "kallisto  quant -i" $(DATABASE)/transcripts.idx -b 100 -o $@ --fusion $< $(OUTFILE)

$(OUTDIR)/%: $(RDIR)/%_R1_001.fastq.gz $(OUTFILE)
      kallisto  quant -i $(DATABASE)/transcripts.idx -b 100  --fusion --rf-stranded -o $@ $(RDIR)/$*_R1_00
1.fastq.gz   $(RDIR)/$*_R2_001.fastq.gz

$(OUTDIR):
    mkdir -p $(OUTDIR)

clean::
    $(RM) -rf $(OUTDIR)

I suppose if the found some change on the input file and on the output execute the command. I don't know why every time force re-run. In some case Is that I want but I wan to also if there is some new input execute only that.
Thanks so much

Body:
A couple of things:

1)  $(OUTDIR)/% is dependent on $(OUTFILE) (which is a list of all outfiles).  Therefore if you change any one of the OUTFILEs, you make everything in $(OUTDIR)/% obsolete.   I believe what you want is this:

$(OUTDIR)/%_R1_001.fastq.gz: $(RDIR)/%_R2_001.fastq.gz
    .... (rules to make out/R1 from raw/R2

$(RDIR)/%_R2_001.fastq.gz: $(RDIR)/%_R1_001.fastq.gz
    .... (rules to make R2 from R1

This makes each file dependent only on the files that effect it.

2) you have the target all dependent on $(OUTDIR) which is a directory.  If you use parallel make, it may generate the $(OUTDIR) after it generates the other dependencies of all: (some of which would depend on $(OUTDIR) being created).     What you want there is to remove all's dependency on $(OUTDIR), and add the line:

$(OUTFILE) : | $(OUTDIR)

Notice the |, which means order only (don't consider $(OUTFILE) out of date if $(OUTDIR) is newer.   This is important, as a directory's timestamp is updated each time a file in the directory is changed, and so it tends to be newer than its contents.


问:
AWS SSH: Permission denied (publickey)
I'm trying to connect to AWS instance. I know that I definitely have the keypair downloaded on my desktop, but for some reason it doesn't recognize it? I've changed the permissions by using chmod 400 but the following still happens:

martycep:~ martincepeda1$ ssh -v -i “privatekey.pem” ec2-user@ec2-xx-xx-xx-xx.us-east-2.compute.amazonaws.com
Warning: Identity file privatekey.pem not accessible: No such file or directory.
OpenSSH_6.9p1, LibreSSL 2.1.8
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 21: Applying options for *
debug1: Connecting to ec2-xx-xx-xxx-xx.us-east-2.compute.amazonaws.com [xx.xx.xxx.xx] port 22.
debug1: Connection established.
debug1: identity file /Users/martincepeda1/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.9
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1
debug1: match: OpenSSH_6.6.1 pat OpenSSH_6.6.1* compat 0x04000000
debug1: Authenticating to ec2-xx-xx-xxx-xx.us-east-2.compute.amazonaws.com:22 as 'ec2-user'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client chacha20-poly1305@openssh.com <implicit> none
debug1: kex: client->server chacha20-poly1305@openssh.com <implicit> none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key:xxxxxxxxxxxxxx
debug1: Host 'ec2-xx-xx-xxx-xx.us-east-2.compute.amazonaws.com' is known and matches the ECDSA host key.
debug1: Found key in /Users/martincepeda1/.ssh/known_hosts:6
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/martincepeda1/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: /Users/martincepeda1/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: /Users/martincepeda1/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Trying private key: /Users/martincepeda1/.ssh/id_dsa
debug1: Trying private key: /Users/martincepeda1/.ssh/id_ecdsa
debug1: Trying private key: /Users/martincepeda1/.ssh/id_ed25519
debug1: No more authentication methods to try.
Permission denied (publickey).
martycep:~ martincepeda1$

Any suggestions/ideas would be appreciated. Thanks.

答:
Can you check this:

You are using the correct key location.

The Key has correct permissions.

Are you using the correct Key?

Title: AWS SSH: Permission denied (publickey)


问:
Why am I getting "Commit failed with error: pathspec ... did not match any file(s)"?
I am having some issues with Git.

I have a repository where I can commit any file to without problem. However, there is a single file 'Funder.php' which, when I try committing, tells me there is an error  as:

```<code>Commit failed with error:
pathspec 'application/libraries/Funder.php' did not match any file(s) known to git.
</code>```

I am quite new to this, so was wondering if anybody could please help?

答:
if working from terminal ensure that you have a message flag in your command.

git commit "Your Commit Message" //Throws an error: pathspec '3.

git commit -m "Your Commit Message" //No error thrown

Body:
I am having some issues with Git.

I have a repository where I can commit any file to without problem. However, there is a single file 'Funder.php' which, when I try committing, tells me there is an error  as:

Commit failed with error:
pathspec 'application/libraries/Funder.php' did not match any file(s) known to git.

I am quite new to this, so was wondering if anybody could please help?


问:
Spring JDBCTemplate vs Plain JDBC for inserting large numbers of records
We have to insert 2 millions of records across multiple tables and right now we are writing into a CSV file and using db2 import to load into database.

We wanted to change this logic to some kind of JDBC. While looking into multiple options, I am confused with Spring JDBC template and plain JDBC.

Let us say I wanted to insert 1 million records into 10 tables, each of which will have 100 thousand, and all these are simple JDBC statements (not prepared statements because I don't know which table I am dealing with at runtime).

Whatever system we choose will need to handle inserting up to 15 million records for a peak request.

Which framework will be better?

答:
If you want to move a lot of data, then using JDBC (or any library building on top of JDBC) may be a bad choice, compared to using bulk copy tools (like db2import). JDBC is going to be orders of magnitude slower, because

JDBC is a very chatty protocol, and

usually bulk copy tools relax constraints during the copy process.

The difference in time can be extreme: what takes the bulk copy tool 10 minutes can take hours using JDBC. You'll want to create a prototype and do some timings and be certain about what kind of performance you'll get before you commit to something like this.