问:
Connection with API while using node.js failed
I'm a beginner and I tried to connect to an api while using node.js.
So I tried to get the information of an simple api.

It is just a try. If anyone could help me, or has a better solution for another api, where I need an api-key it would be a pleasure for me.

```<code>var http = require('http');

var options = {
     host: 'api-sandbox.oanda.com',
     port: 80,
     path: '/v1/prices?instruments=EUR_USD%2CUSD_JPY',
    method: 'GET',
};

 http.request(options, function (res) {
     var body = '';

     res.on('data', function (chunk) {
         body += chunk;
     });

     res.on('end', function () {
         var price = JSON.parse(body);
        console.log(price);
     })
}).end();
</code>```

答:
Here is the result I've received using your details:

```<code>HTTP/1.1 401 UNAUTHORIZED
Server: openresty/1.9.15.1
Date: Tue, 05 Dec 2017 20:19:19 GMT
Content-Type: application/json
Content-Length: 140
Connection: keep-alive
Access-Control-Allow-Origin: *

{
    "code" : 3,
    "message" : "This request requires authorization",
    "moreInfo" : "http:\/\/developer.oanda.com\/docs\/v1\/auth\/#overview"
}
</code>```

First of all, I'd like to recommend you using HTTPS protocol. Also, according to their documentation Authentication is required there. Please check the notes:

"Our documentation uses the fxTrade URL for all examples. To use the
  practice trading environment simply replace the base of the url with
  the appropriate one listed above and follow any necessary
  authentication."

Here is the link:
http://developer.oanda.com/rest-live/authentication/

You'll see that they have HTTPS based requests with Authentication. Means you need to provide with Authorization headers like this:

Authorization: Bearer 12345678900987654321-abc34135acde13f13530"

Refer to the link to see how to send HTTPS requests with options in NodeJS:

https://nodejs.org/api/https.html#https_https_request_options_callback

In the end, you will have something like that:

```<code>const https = require('https');

const options = {
  hostname: 'api-fxtrade.oanda.com',
  port: 443,
  path: '/v1/prices?instruments=EUR_USD',
  method: 'GET',
  headers: {
    Authorization: 'Bearer 12345678900987654321-abc34135acde13f13530'
  }
};

const req = https.request(options, (res) => {

  res.on('data', (data) => {
    process.stdout.write(data);
  });
});

req.on('error', (err) => {
  console.error(err);
});
req.end();
</code>```

Don't forget to use your won Auth Token provided by oanda.

Body:
I'm a beginner and I tried to connect to an api while using node.js.
So I tried to get the information of an simple api.

It is just a try. If anyone could help me, or has a better solution for another api, where I need an api-key it would be a pleasure for me.

var http = require('http');

var options = {
     host: 'api-sandbox.oanda.com',
     port: 80,
     path: '/v1/prices?instruments=EUR_USD%2CUSD_JPY',
    method: 'GET',
};

 http.request(options, function (res) {
     var body = '';

     res.on('data', function (chunk) {
         body += chunk;
     });

     res.on('end', function () {
         var price = JSON.parse(body);
        console.log(price);
     })
}).end();

Body:
Here is the result I've received using your details:

HTTP/1.1 401 UNAUTHORIZED
Server: openresty/1.9.15.1
Date: Tue, 05 Dec 2017 20:19:19 GMT
Content-Type: application/json
Content-Length: 140
Connection: keep-alive
Access-Control-Allow-Origin: *

{
    "code" : 3,
    "message" : "This request requires authorization",
    "moreInfo" : "http:\/\/developer.oanda.com\/docs\/v1\/auth\/#overview"
}

First of all, I'd like to recommend you using HTTPS protocol. Also, according to their documentation Authentication is required there. Please check the notes:

"Our documentation uses the fxTrade URL for all examples. To use the
  practice trading environment simply replace the base of the url with
  the appropriate one listed above and follow any necessary
  authentication."

Here is the link:
http://developer.oanda.com/rest-live/authentication/

You'll see that they have HTTPS based requests with Authentication. Means you need to provide with Authorization headers like this:

Authorization: Bearer 12345678900987654321-abc34135acde13f13530"

Refer to the link to see how to send HTTPS requests with options in NodeJS:

https://nodejs.org/api/https.html#https_https_request_options_callback

In the end, you will have something like that:

const https = require('https');

const options = {
  hostname: 'api-fxtrade.oanda.com',
  port: 443,
  path: '/v1/prices?instruments=EUR_USD',
  method: 'GET',
  headers: {
    Authorization: 'Bearer 12345678900987654321-abc34135acde13f13530'
  }
};

const req = https.request(options, (res) => {

  res.on('data', (data) => {
    process.stdout.write(data);
  });
});

req.on('error', (err) => {
  console.error(err);
});
req.end();

Don't forget to use your won Auth Token provided by oanda.


来源: stackexchange

问:
Hibernate - Log4j - Trace ERROR
After J. Roberson kindly asked me to create a new answer because my code changed but didnt got fixed. First code and problem, I checked all answers at Thread, but they didnt helped me, I stil get an error and cant use

SessionFactory factory = new Configuration();

Problem :

```<code>    0 [main] DEBUG org.jboss.logging  - Logging Provider: org.jboss.logging.Log4jLoggerProvider
16 [main] DEBUG org.hibernate.integrator.internal.IntegratorServiceImpl  - Adding Integrator [org.hibernate.cfg.beanvalidation.BeanValidationIntegrator].
21 [main] DEBUG org.hibernate.integrator.internal.IntegratorServiceImpl  - Adding Integrator [org.hibernate.secure.spi.JaccIntegrator].
40 [main] DEBUG org.hibernate.integrator.internal.IntegratorServiceImpl  - Adding Integrator [org.hibernate.cache.internal.CollectionCacheInvalidator].
Exception in thread "main" java.lang.NoSuchFieldError: TRACE
    at org.jboss.logging.Log4jLogger.translate(Log4jLogger.java:60)
    at org.jboss.logging.Log4jLogger.doLog(Log4jLogger.java:40)
    at org.jboss.logging.Logger.trace(Logger.java:107)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.registerStrategyImplementor(StrategySelectorImpl.java:66)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorBuilder.addDialect(StrategySelectorBuilder.java:237)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorBuilder.addDialects(StrategySelectorBuilder.java:188)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorBuilder.buildSelector(StrategySelectorBuilder.java:154)
    at org.hibernate.boot.registry.BootstrapServiceRegistryBuilder.build(BootstrapServiceRegistryBuilder.java:222)
    at org.hibernate.cfg.Configuration.<init>(Configuration.java:118)
    at main.java.Main.main(Main.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code>```

答: You can use log4j.1.2.12 or a higher version to fix this issue. log4j 1.2.17 can be downloaded from here.</p>

ContentLicense: CC BY-SA 3.0

Title: Hibernate - Log4j - Trace ERROR

Body:
After J. Roberson kindly asked me to create a new answer because my code changed but didnt got fixed. First code and problem, I checked all answers at Thread, but they didnt helped me, I stil get an error and cant use

SessionFactory factory = new Configuration();

Problem :

    0 [main] DEBUG org.jboss.logging  - Logging Provider: org.jboss.logging.Log4jLoggerProvider
16 [main] DEBUG org.hibernate.integrator.internal.IntegratorServiceImpl  - Adding Integrator [org.hibernate.cfg.beanvalidation.BeanValidationIntegrator].
21 [main] DEBUG org.hibernate.integrator.internal.IntegratorServiceImpl  - Adding Integrator [org.hibernate.secure.spi.JaccIntegrator].
40 [main] DEBUG org.hibernate.integrator.internal.IntegratorServiceImpl  - Adding Integrator [org.hibernate.cache.internal.CollectionCacheInvalidator].
Exception in thread "main" java.lang.NoSuchFieldError: TRACE
    at org.jboss.logging.Log4jLogger.translate(Log4jLogger.java:60)
    at org.jboss.logging.Log4jLogger.doLog(Log4jLogger.java:40)
    at org.jboss.logging.Logger.trace(Logger.java:107)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.registerStrategyImplementor(StrategySelectorImpl.java:66)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorBuilder.addDialect(StrategySelectorBuilder.java:237)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorBuilder.addDialects(StrategySelectorBuilder.java:188)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorBuilder.buildSelector(StrategySelectorBuilder.java:154)
    at org.hibernate.boot.registry.BootstrapServiceRegistryBuilder.build(BootstrapServiceRegistryBuilder.java:222)
    at org.hibernate.cfg.Configuration.<init>(Configuration.java:118)
    at main.java.Main.main(Main.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)


问:
how to check result of doctrine statement
I use this code to remove data from database using doctrine

```<code>$user = $em->getReference('model\User', $id);
$em->remove($user);
$em->flush();
</code>```

how I can check if the $user is deleted or not?

what is the returned data from $em->flush();?

答:
i have used try and catch() blocks to solve this issue
when try excute correctly i have return true and in catch i return False

Body:
I use this code to remove data from database using doctrine

$user = $em->getReference('model\User', $id);
$em->remove($user);
$em->flush();

how I can check if the $user is deleted or not?

what is the returned data from $em->flush();?


问:
Is it possible to convert a connection object to an array in PHP
I'm wondering if it's possible to convert a database connection object to an array in PHP? I've been researching, it seems you can cast an object as an array, but it doesn't seem to work for a connection object. Here's my script:

```<code><?php

$dbHost="host";
$dbUser="user";
$dbPass="";
$dbName="root";

$dbConn = mysqli_connect($dbHost,$dbUser,$dbPass,$dbName);

$dbParts = (array) $dbConn;

for ($i=0;$i <=3; $i++){

echo $dbParts[$i];

}
?>
</code>```

Any help would be greatly appreciated!

**[EDIT]**Why I need to access the db connection as an array is because I need to be able to call certain urls in a script, based on what database I'm connected to, as each environment has a different database.

答:
Well after a little digging I found this ( Tested ).
It relies on you having access to $dbConn.

You can get the database name being used, using something like...

```<code>$result=mysqli_query($dbConn,'SELECT DATABASE() as dbName');
$rows = mysqli_fetch_assoc($result);
var_dump($rows);
</code>```

which you'd probably turn into a function to make it useful along the lines of...

```<code>function getDatabaseName($databaseConnection){
    $result=mysqli_query($databaseConnection,'SELECT DATABASE() as dbName');
    $row = mysqli_fetch_assoc($result);
    return $row['dbName'];
//    var_dump($rows);
}

$currentDatabase = getDatabaseName($dbConn);
echo $currentDatabase;
</code>```

You'll have to play with this to suit...

Body:
I'm wondering if it's possible to convert a database connection object to an array in PHP? I've been researching, it seems you can cast an object as an array, but it doesn't seem to work for a connection object. Here's my script:

<?php

$dbHost="host";
$dbUser="user";
$dbPass="";
$dbName="root";

$dbConn = mysqli_connect($dbHost,$dbUser,$dbPass,$dbName);

$dbParts = (array) $dbConn;

for ($i=0;$i <=3; $i++){

echo $dbParts[$i];

}
?>

Any help would be greatly appreciated!

**[EDIT]**Why I need to access the db connection as an array is because I need to be able to call certain urls in a script, based on what database I'm connected to, as each environment has a different database.

Body:
Well after a little digging I found this ( Tested ).
It relies on you having access to $dbConn.

You can get the database name being used, using something like...

$result=mysqli_query($dbConn,'SELECT DATABASE() as dbName');
$rows = mysqli_fetch_assoc($result);
var_dump($rows);

which you'd probably turn into a function to make it useful along the lines of...

function getDatabaseName($databaseConnection){
    $result=mysqli_query($databaseConnection,'SELECT DATABASE() as dbName');
    $row = mysqli_fetch_assoc($result);
    return $row['dbName'];
//    var_dump($rows);
}

$currentDatabase = getDatabaseName($dbConn);
echo $currentDatabase;

You'll have to play with this to suit...


问:
Edit file using chef
I know there are a lot of answers plus solved ones too but nothing seems to work for me, What I'm trying to do is I want to add few lines of code after tomcat is completed with it's installation in /var/lib/tomcat8/conf/catalina.properties file.

here is what i have tried so far the simple ruby way and with chef utils too.

```<code>File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
  f << "\n"
  f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
end

ruby_block "insert_line" do
  block do
    file = Chef::Util::FileEdit.new("/var/lib/tomcat8/conf/catalina.properties")
    file.insert_line_if_no_match("/javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl/", "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl")
    file.write_file
  end
end

file '/var/lib/tomcat8/conf/catalina.properties' do
   action :create
   owner 'root'
   group 'root'
   content File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
      f << "\n"
      f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
    end
end

file '/var/lib/tomcat8/conf/catalina.properties' do
   action :create
   owner 'root'
   group 'root'
   content File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
      f << "\n"
      f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
    end
end
</code>```

I tried putting puts "testing" and it seems that chef isn't even getting into code.

答:
Check out the poise-file and line cookbooks for examples of how to do this more safely.

We overall do not recommend this approach as it creates very brittle code that is often non-convergent (as you noticed). The better method is to use a template resource to control the entire file in a convergent manner.

Title: Edit file using chef

Body:
I know there are a lot of answers plus solved ones too but nothing seems to work for me, What I'm trying to do is I want to add few lines of code after tomcat is completed with it's installation in /var/lib/tomcat8/conf/catalina.properties file.

here is what i have tried so far the simple ruby way and with chef utils too.

File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
  f << "\n"
  f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
end

ruby_block "insert_line" do
  block do
    file = Chef::Util::FileEdit.new("/var/lib/tomcat8/conf/catalina.properties")
    file.insert_line_if_no_match("/javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl/", "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl")
    file.write_file
  end
end

file '/var/lib/tomcat8/conf/catalina.properties' do
   action :create
   owner 'root'
   group 'root'
   content File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
      f << "\n"
      f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
    end
end

file '/var/lib/tomcat8/conf/catalina.properties' do
   action :create
   owner 'root'
   group 'root'
   content File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
      f << "\n"
      f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
    end
end

I tried putting puts "testing" and it seems that chef isn't even getting into code.


问:
Referencing an Array outside its range
this program creates an image with 100 boxes, after the box is created, it's 4 coordinates are stored in the index of the class array Tile so I can refernce each tile later in my code. This works fine, excpect that I can not reference the Tile array in my main function, only in the Draw() function where it is created. Any solutions would be appreciated.

EDIT: Making Tiles* Tile[100] global does not seem to solve the issue.

Simplified Code:

```<code>#include <iostream>
class Tiles {
public:
    Tiles() : mA (1){}
    double mA;
};

void Function1() {
    Tiles Tile[5];
    Tile[1].mA = 10;
}

int main(int iArgc, char** cppArgv) {
    Function1();
    Tile[1].mA = 2;  // ERROR "Tile" is unidentified.
    return 0;
}
</code>```

Full Code:

```<code>#include <iostream>
#include <glut.h>
class Tiles {
public:
 Tiles() : mA () , mB() , mC() , mD() , mCP(){}
 double mA[2] , mB[2] , mC[2] , mD[2]  , mCP[2];
};

void Draw() {
 glClear(GL_COLOR_BUFFER_BIT);
 glColor3f(1.0, 1.0, 1.0);
 double dX1 = 0.0, dY1 = 0.0, dMidX = 0.0, dMidY = 0.0, dXC = 0.0, dYC = 0.0;
 int sq = 0, row = 1, CoordMap = 0;
 Tiles Tile[100];
   //Tiles* Tile = new Tiles[100]; doesnt seem to be any different..
     for (int i=0; i < 10;i++ ) { // ROWS
     for (int i2=0; i2 < 10; i2++) { // BOXES
      glBegin(GL_LINE_STRIP);
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mA[1] = dX1;
      Tile[sq].mA[2] = dY1;// Bottom Left
      dX1 = dX1 + .1;
      dXC = dX1;
      dYC = dY1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mB[1] = dX1;
      Tile[sq].mB[2] = dY1;// Bottom Right
      dY1 = dY1 + .1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mC[1] = dX1;
      Tile[sq].mC[2] = dY1;// Top Left
      dX1 = dX1 - .1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mD[1] = dX1;
      Tile[sq].mD[2] = dY1;// Top Right
      glEnd();
      glBegin(GL_POINTS);
      glVertex3f((dX1 + .05) , (dY1 - .05), 0.0);
      glEnd();
      ++sq;
      dX1 = dXC;
      dY1 = dYC;
        }
      row++;
      dX1 = 0.0;
      dY1 = ((row * .1) - .1);
        }
     glFlush();
    }

void Initialize() {
 glClearColor(0.0, 0.0, 0.0, 0.0);
 glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}

int main(int iArgc, char** cppArgv) {
 glutInit(&iArgc, cppArgv);
 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
 glutInitWindowSize(250, 250);
 glutInitWindowPosition(200, 200);
 glutCreateWindow("XoaX.net");
 Initialize();
 glutDisplayFunc(Draw);
 glutMainLoop();
 //Tile[2].mA[1] = 2; //
 return 0;
}
</code>```

This code is modified from it's orginal version written by XoaX - Michael Hall.

Thank you

答: To make your Tiles array accesible from main() you must declare Tiles within the main() scope. For example, move your declaration Tiles Tile[100]; to global scope, i.e. just before void Draw() { line.

ContentLicense: CC BY-SA 2.5

Title: Referencing an Array outside its range

Body:
this program creates an image with 100 boxes, after the box is created, it's 4 coordinates are stored in the index of the class array Tile so I can refernce each tile later in my code. This works fine, excpect that I can not reference the Tile array in my main function, only in the Draw() function where it is created. Any solutions would be appreciated.

EDIT: Making Tiles* Tile[100] global does not seem to solve the issue.

Simplified Code:

#include <iostream>
class Tiles {
public:
    Tiles() : mA (1){}
    double mA;
};

void Function1() {
    Tiles Tile[5];
    Tile[1].mA = 10;
}

int main(int iArgc, char** cppArgv) {
    Function1();
    Tile[1].mA = 2;  // ERROR "Tile" is unidentified.
    return 0;
}

Full Code:

#include <iostream>
#include <glut.h>
class Tiles {
public:
 Tiles() : mA () , mB() , mC() , mD() , mCP(){}
 double mA[2] , mB[2] , mC[2] , mD[2]  , mCP[2];
};

void Draw() {
 glClear(GL_COLOR_BUFFER_BIT);
 glColor3f(1.0, 1.0, 1.0);
 double dX1 = 0.0, dY1 = 0.0, dMidX = 0.0, dMidY = 0.0, dXC = 0.0, dYC = 0.0;
 int sq = 0, row = 1, CoordMap = 0;
 Tiles Tile[100];
   //Tiles* Tile = new Tiles[100]; doesnt seem to be any different..
     for (int i=0; i < 10;i++ ) { // ROWS
     for (int i2=0; i2 < 10; i2++) { // BOXES
      glBegin(GL_LINE_STRIP);
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mA[1] = dX1;
      Tile[sq].mA[2] = dY1;// Bottom Left
      dX1 = dX1 + .1;
      dXC = dX1;
      dYC = dY1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mB[1] = dX1;
      Tile[sq].mB[2] = dY1;// Bottom Right
      dY1 = dY1 + .1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mC[1] = dX1;
      Tile[sq].mC[2] = dY1;// Top Left
      dX1 = dX1 - .1;
      glVertex3f(dX1, dY1, 0.0);
      Tile[sq].mD[1] = dX1;
      Tile[sq].mD[2] = dY1;// Top Right
      glEnd();
      glBegin(GL_POINTS);
      glVertex3f((dX1 + .05) , (dY1 - .05), 0.0);
      glEnd();
      ++sq;
      dX1 = dXC;
      dY1 = dYC;
        }
      row++;
      dX1 = 0.0;
      dY1 = ((row * .1) - .1);
        }
     glFlush();
    }

void Initialize() {
 glClearColor(0.0, 0.0, 0.0, 0.0);
 glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}

int main(int iArgc, char** cppArgv) {
 glutInit(&iArgc, cppArgv);
 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
 glutInitWindowSize(250, 250);
 glutInitWindowPosition(200, 200);
 glutCreateWindow("XoaX.net");
 Initialize();
 glutDisplayFunc(Draw);
 glutMainLoop();
 //Tile[2].mA[1] = 2; //
 return 0;
}

This code is modified from it's orginal version written by XoaX - Michael Hall.

Thank you


问:
How to position image to be directly vertically centered between two elements
I am trying to get the Texas icon directly centered between the span and h1 element.

Here is the Screen Capture

I tried googling but I think I might be phrasing what I need poorly. Is it that I have to adjust the padding and margin in css? I just want to move the icon down the y-axis.

Thank you

```<code> <header id="top" class="main-header">
      <span class="title">Keep it Weird in</span>
   <div>
    <img class="texas-icon" src="https://image.ibb.co/cGRVFG/texasicon_1.png" alt="texasicon_1" border="0"></a>
      </div>
      <h1>Austin</h1>

    .main-header {
  padding-top: 170px;
  height: 850px;
  background: linear-gradient(lightblue, transparent 90%),
              linear-gradient(0deg, #fff, transparent),
              #ffa949 url('https://media.giphy.com/media/3ohs7I9ho0H4dfeP7y/giphy.gif') no-repeat center;

  background-size: cover;

}

.title {
  color: white;
  font-size: 1.625rem; /* 26px/16px */
  letter-spacing: .065em;
  font-weight: 200px;
  padding-bottom: 10px;
}
h1 {
  font-size: 12.5rem; /* 90px/16px  */
  color: rgba(255, 255, 255, 1);
  text-transform: capitalize;
  font-weight: normal;
  text-align: center;
  line-height: 1.3;
  margin: 12px 0px 0px;
     }
</code>```

答:
Thank you for the support. Unfortunately, none of the solutions worked but I decided just to change the line height of the h1 element and was able to get the result I wanted. I learned so many new things from the responses to my question. Again, thank you.
Updated Screen Capture</p>

Body:
I am trying to get the Texas icon directly centered between the span and h1 element.

Here is the Screen Capture

I tried googling but I think I might be phrasing what I need poorly. Is it that I have to adjust the padding and margin in css? I just want to move the icon down the y-axis.

Thank you

      Keep it Weird in

Austin

    .main-header {
  padding-top: 170px;
  height: 850px;
  background: linear-gradient(lightblue, transparent 90%),
              linear-gradient(0deg, #fff, transparent),
              #ffa949 url('https://media.giphy.com/media/3ohs7I9ho0H4dfeP7y/giphy.gif') no-repeat center;

  background-size: cover;

}

.title {
  color: white;
  font-size: 1.625rem; /* 26px/16px */
  letter-spacing: .065em;
  font-weight: 200px;
  padding-bottom: 10px;
}
h1 {
  font-size: 12.5rem; /* 90px/16px  */
  color: rgba(255, 255, 255, 1);
  text-transform: capitalize;
  font-weight: normal;
  text-align: center;
  line-height: 1.3;
  margin: 12px 0px 0px;
     }


问:
Need a string with a $ in powershell inside ' '
I am trying to write a PS script to find a share named C$$ but PS is interpreting the $ sign and I want to pass it into the filter.
Normally \ stops this but after googling I cant get a working solution.

```<code>$string = "Name='C\$\$'"
Write-Host $string
get-wmiobject -Class Win32_share -filter $string
</code>```

The write host returns Name='C\$\$'
I need it to return C$$

答:
There's several ways to do this.  Note in the first one that you only need to escape the first $.

```<code>$string = "Name='C`$$'"
$string = "Name='C$$'"
$string = 'Name=''C$$'''
$string = "Name='C{0}'" -f '$$'
$string = @'
Name='C$$'
'@
$string = @"
Name='C`$$'
"@
</code>```

Body:
I am trying to write a PS script to find a share named C$$ but PS is interpreting the $ sign and I want to pass it into the filter.
Normally \ stops this but after googling I cant get a working solution.

$string = "Name='C\$\$'"
Write-Host $string
get-wmiobject -Class Win32_share -filter $string

The write host returns Name='C\$\$'
I need it to return C$$

Body:
There's several ways to do this.  Note in the first one that you only need to escape the first $.

$string = "Name='C`$$'"
$string = "Name='C$$'"
$string = 'Name=''C$$'''
$string = "Name='C{0}'" -f '$$'
$string = @'
Name='C$$'
'@
$string = @"
Name='C`$$'
"@


问:
ESLINT errors ( Error '$' is not defined)
I have Brackets installed, and i getting ESLINT error, as far as i know i dont have ESLINT installed

That is the first time i get this error, my question is, how do i install ESLINT and configure it that i don't receive the errors. ( The JavaScript code is copied from CODEPEN so it should be ok)

The main problem is ESLINt, i tried with other JS plugins and get the same error, as i said its the first time im getting this error.

答:
You need to add the '$' to the globals object inside your .eslintrc file.

Like so:

```<code>"eslintConfig": {
    "globals": {
        "$": true
    }
}
</code>```

Body:
You need to add the '$' to the globals object inside your .eslintrc file.

Like so:

"eslintConfig": {
    "globals": {
        "$": true
    }
}


问:
Set ggplot title to reflect dplyr grouping
I've got a grouped dataframe generated in dplyr where each group reflects a unique combination of factor variable levels. I'd like to plot the different groups using code similar to this post. However, I can't figure out how to include two (or more) variables in the title of my plots, which is a hassle since I've got a bunch of different combinations.

Fake data and plotting code:

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

spiris<-iris
spiris$site<-as.factor(rep(c("A","B","C")))
spiris$year<-as.factor(rep(2012:2016))
spiris$treatment<-as.factor(rep(1:2))

g<-spiris %>%
  group_by(site, Species) %>%
  do(plots=ggplot(data=.) +
       aes(x=Petal.Width)+geom_histogram()+
       facet_grid(treatment~year))
       ##Need code for title here
g[[3]] ##view plots
</code>```

I need the title of each plot to reflect both "site" and "Species".  Any ideas?

答:
You just need to set the title with ggtitle():

```<code>g <- spiris %>% group_by(site, Species) %>% do(plots = ggplot(data = .) +
    aes(x = Petal.Width) + geom_histogram() + facet_grid(treatment ~
    year) + ggtitle(paste(.$Species,.$site,sep=" - ")))
</code>```

Body:
I've got a grouped dataframe generated in dplyr where each group reflects a unique combination of factor variable levels. I'd like to plot the different groups using code similar to this post. However, I can't figure out how to include two (or more) variables in the title of my plots, which is a hassle since I've got a bunch of different combinations.

Fake data and plotting code:

library(dplyr)
library(ggplot2)

spiris<-iris
spiris$site<-as.factor(rep(c("A","B","C")))
spiris$year<-as.factor(rep(2012:2016))
spiris$treatment<-as.factor(rep(1:2))

g<-spiris %>%
  group_by(site, Species) %>%
  do(plots=ggplot(data=.) +
       aes(x=Petal.Width)+geom_histogram()+
       facet_grid(treatment~year))
       ##Need code for title here
g[[3]] ##view plots

I need the title of each plot to reflect both "site" and "Species".  Any ideas?

Body:
You just need to set the title with ggtitle():

g <- spiris %>% group_by(site, Species) %>% do(plots = ggplot(data = .) +
    aes(x = Petal.Width) + geom_histogram() + facet_grid(treatment ~
    year) + ggtitle(paste(.$Species,.$site,sep=" - ")))


问:
Php to replace @username with link to twitter account
I assume this is some to do with regex, but it's an art all it's own - and I need some help.

When we display a story, we store all the text in a varilable - let's say $story.

What i'd like is to do a str_replace (I think that's what I need) that says something like this "If the text contains @something then turn it into a link like @something- but only do this if there's nothing before the @ symbol" (to exclude email addresses)

Also, we'd need to stop the 'something' if there's a space or punctuation after it. so that @something. doesn't turn into @something.

Any suggestions on how to make this work?

答:
```<code>$input = preg_replace('/(^|\s)@([a-z0-9_]+)/i',
                      '$1<a href="http://www.twitter.com/$2">@$2</a>',
                       $input);
</code>```

See it

It matches a @ which is preceded by whitespace or nothing ( when it is at the beginning).

It can also be shorted using positive lookbehind as:

```<code>$input = preg_replace('/(?<=^|\s)@([a-z0-9_]+)/i',
                      '<a href="http://www.twitter.com/$1">@$1</a>',
                      $input);
</code>```

Which matches only the twitter name but only if there is space or nothing before that.

Body:
$input = preg_replace('/(^|\s)@([a-z0-9_]+)/i',
                      '$1<a href="http://www.twitter.com/$2">@$2</a>',
                       $input);

See it

It matches a @ which is preceded by whitespace or nothing ( when it is at the beginning).

It can also be shorted using positive lookbehind as:

$input = preg_replace('/(?<=^|\s)@([a-z0-9_]+)/i',
                      '<a href="http://www.twitter.com/$1">@$1</a>',
                      $input);

Which matches only the twitter name but only if there is space or nothing before that.


问:
Maven scope provided and transitive dependencies
I have a dependency with one of the jar and i have marked it as provided in pom xml. It seems only some of the transitive dependency jar are marked as provided and not packaged with the war but others are still scope as compile and  packaged with war libs.Do i need to explicitly mark the scope as provided for all the transitive dependencies.

Dependency in pom xml:

```<code><dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <scope>provided</scope>
</dependency>
</code>```

Dependency tree:

```<code>[INFO] +- org.apache.camel:camel-ftp:jar:2.17.0.redhat-630262:provided
[INFO] |  +- com.jcraft:jsch:jar:0.1.54:provided
[INFO] |  +- commons-net:commons-net:jar:3.3.0.redhat-3:provided
[INFO] |  +- com.sun.xml.bind:jaxb-core:jar:2.2.11:compile
[INFO] |  \- com.sun.xml.bind:jaxb-impl:jar:2.2.11.redhat-2:compile
[INFO] +- org.apache.camel:camel-csv:jar:2.17.0.redhat-630262:provided
</code>```

plugin version Details:

```<code><maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <cdi.api.version>1.2.0.redhat-2</cdi.api.version>
        <javax.inject.version>1.0.0.redhat-6</javax.inject.version>
        <sonar.host.url>http://vfrde2srta0401.agcs.biz:9000</sonar.host.url>
        <xerces.version>2.11.0-22</xerces.version>
        <xmlunit.version>1.6</xmlunit.version>
        <maven.compilerplugin.version>3.7.0</maven.compilerplugin.version>
        <maven.releaseplugin.version>2.5.3</maven.releaseplugin.version>
        <maven.warplugin.version>3.2.0</maven.warplugin.version>
        <maven.jarplugin.version>3.0.2</maven.jarplugin.version>
        <maven.surefireplugin.version>2.20.1</maven.surefireplugin.version>
        <maven.coberturaplugin.version>2.7</maven.coberturaplugin.version>
</code>```

答:
As a few people noted already, transitive dependencies of your provided scoped dependencies should get scope provided in your project. However, the scope can be changed to compile if you have other dependencies in scope compile that have the same transitive dependencies. In your case, these two:

```<code>[INFO] |  +- com.sun.xml.bind:jaxb-core:jar:2.2.11:compile
[INFO] |  \- com.sun.xml.bind:jaxb-impl:jar:2.2.11.redhat-2:compile
</code>```

are probably pulled in transitively by another dependency in your pom than camel-ftp. You need to run mvn dependency:tree -Dverbose to get a hint of why these two got their scope updated to compile.

Body:
I have a dependency with one of the jar and i have marked it as provided in pom xml. It seems only some of the transitive dependency jar are marked as provided and not packaged with the war but others are still scope as compile and  packaged with war libs.Do i need to explicitly mark the scope as provided for all the transitive dependencies.

Dependency in pom xml:

<dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-ftp</artifactId>
            <scope>provided</scope>
</dependency>

Dependency tree:

[INFO] +- org.apache.camel:camel-ftp:jar:2.17.0.redhat-630262:provided
[INFO] |  +- com.jcraft:jsch:jar:0.1.54:provided
[INFO] |  +- commons-net:commons-net:jar:3.3.0.redhat-3:provided
[INFO] |  +- com.sun.xml.bind:jaxb-core:jar:2.2.11:compile
[INFO] |  \- com.sun.xml.bind:jaxb-impl:jar:2.2.11.redhat-2:compile
[INFO] +- org.apache.camel:camel-csv:jar:2.17.0.redhat-630262:provided

plugin version Details:

<maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <cdi.api.version>1.2.0.redhat-2</cdi.api.version>
        <javax.inject.version>1.0.0.redhat-6</javax.inject.version>
        <sonar.host.url>http://vfrde2srta0401.agcs.biz:9000</sonar.host.url>
        <xerces.version>2.11.0-22</xerces.version>
        <xmlunit.version>1.6</xmlunit.version>
        <maven.compilerplugin.version>3.7.0</maven.compilerplugin.version>
        <maven.releaseplugin.version>2.5.3</maven.releaseplugin.version>
        <maven.warplugin.version>3.2.0</maven.warplugin.version>
        <maven.jarplugin.version>3.0.2</maven.jarplugin.version>
        <maven.surefireplugin.version>2.20.1</maven.surefireplugin.version>
        <maven.coberturaplugin.version>2.7</maven.coberturaplugin.version>

Body:
As a few people noted already, transitive dependencies of your provided scoped dependencies should get scope provided in your project. However, the scope can be changed to compile if you have other dependencies in scope compile that have the same transitive dependencies. In your case, these two:

[INFO] |  +- com.sun.xml.bind:jaxb-core:jar:2.2.11:compile
[INFO] |  \- com.sun.xml.bind:jaxb-impl:jar:2.2.11.redhat-2:compile

are probably pulled in transitively by another dependency in your pom than camel-ftp. You need to run mvn dependency:tree -Dverbose to get a hint of why these two got their scope updated to compile.


问:
Multiple functions across columns of a dataframe in Python
How can i apply functions in the one line of code as below. I want to calculate mean,STD etc etc for the data set of which link has been shared below. In the given example i have already calculated "mean" and now i want to add some code and find other functions like STD etc.

```<code>df1 = df.loc[(df.time>=171) & (df.time<=174)[['S08','S09','S41']].mean(axis=1)
</code>```

click here for the dataset (CSV file) i am referring to the column names

In the image above i need the mean and STD (blue) but in different Dataframe not same.

Body:
How can i apply functions in the one line of code as below. I want to calculate mean,STD etc etc for the data set of which link has been shared below. In the given example i have already calculated "mean" and now i want to add some code and find other functions like STD etc.

df1 = df.loc[(df.time>=171) & (df.time<=174)[['S08','S09','S41']].mean(axis=1)

click here for the dataset (CSV file) i am referring to the column names

In the image above i need the mean and STD (blue) but in different Dataframe not same.

Body:
Try this:

In [24]: df.loc[(df.time>=171) & (df.time<=174),['S08','S09','S41']].T.agg(['mean','std']).T
Out[24]:
           mean       std
17131  1.014278  0.007357
17132  1.010441  0.005698
17133  1.008947  0.006189
17134  1.006198  0.008981
17135  1.003360  0.012050
17136  1.002270  0.012952
17137  1.000827  0.014543
17138  0.999155  0.010764
17139  0.998330  0.010462
17140  0.996994  0.009813
...         ...       ...
17421  1.005489  0.068211
17422  1.054022  0.126477
17423  1.109993  0.174473
17424  1.143518  0.192038
17425  1.143594  0.168867
17426  1.126942  0.117057
17427  1.088270  0.080759
17428  1.046547  0.053798
17429  1.005698  0.025103
17430  0.981894  0.027097

[300 rows x 2 columns]


问:
How to cut the output of my python program?
Hello I am a python beginner and I am actually writing  a programm which calculates the area of an circle by asking the user for an radius.
My Problem: The ouput is like this '47529.15525615998'
So my question is how to shorten the output so that it would be for example '47529.155'?

Here is my code:

import math

def compute_area(r):

area=(r*r)*math.pi

print(float(area),("Centimeter"))

r=(float(input("Radius: ")))

compute_area(r)

答:
use the following format to truncate float ("%.Nf") N=number of points after .

print("%.3f" %float(area),("Centimeter"))


问:
powershell from chef resource powershell_script
I am trying to use one var declared outside chef resource  powershell_script.
    cn_name = powershell.exe  hostname
    puts cn_name ## will print like WIN-I5NP98N6JUE.cpteam.local
Now , i am trying to get the thumbprint of the root CA cert installed in this host.

```<code>powershell_script 'import CA_cert' do
    code <<-EOH
    $Thumbprint = (Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object {$_.Subject -match "CN="#{cn_name}""}).Thumbprint;
    EOH
end
This is printing like : + ... ct -match "CN="WIN-I5NP98N6JUEcpteam.local""}).Thumbprint;
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token 'WIN-I5NP98N6JUEcpteam.local""' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken
</code>```

Kindly help me here how to escape those quotes./ before quotes doesnt work.
Thanks!

答: That should be {$_.Subject -match "CN=#{cn_name}"}), you don't need the extra quotes at all.

Body:
I am trying to use one var declared outside chef resource  powershell_script.
    cn_name = powershell.exe  hostname
    puts cn_name ## will print like WIN-I5NP98N6JUE.cpteam.local
Now , i am trying to get the thumbprint of the root CA cert installed in this host.

powershell_script 'import CA_cert' do
    code <<-EOH
    $Thumbprint = (Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object {$_.Subject -match "CN="#{cn_name}""}).Thumbprint;
    EOH
end
This is printing like : + ... ct -match "CN="WIN-I5NP98N6JUEcpteam.local""}).Thumbprint;
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token 'WIN-I5NP98N6JUEcpteam.local""' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken

Kindly help me here how to escape those quotes./ before quotes doesnt work.
Thanks!


问:
How to force tomcat to reload recently compiled class/war files
We have a set of running servlets on a tomcat engine. When we compile a java file and build the war, tomcat takes an indeterminate amount of time to reload it. Sometimes 3 seconds, sometimes 30, etc. Current workaround is to stop tomcat and restart it using a shell script. We set up the autodeploy and reloadable flag to true but it is not working reliably. Any idea how to make this happen? Pointers appreciated, too. This is about tomcat v6.0.20 on ubuntu.

Here is an extract of our conf/server.xml file:

```<code><Engine name="Catalina" defaultHost="localhost">

  <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
         resourceName="UserDatabase"/>

  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true"
        xmlValidation="false" xmlNamespaceAware="false">

    <DefaultContext reloadable="true">
    </DefaultContext>

    <!-- SingleSignOn valve, share authentication between web applications
         Documentation at: /docs/config/valve.html -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
    -->

  </Host>
</Engine>
</code>```

答:
If you are having this problem for development, I highly recommend jetty.  It is embeddable in your code so you can run a class in your code and start up a server for your webapp!

You can debug application in Eclipse if you use that as your build environment (I remember debugging Tomcat applications in Eclipse, but I've forgotten how), make an ant build target to run jetty (i.e. ant jetty), or use maven to start your jetty server using the jetty plugin (mvn jetty:run).

With jetty, you can also host a server similar to Tomcat, where you copy new wars and they take affect immediately.

We use Tomcat for our server applications because support is familiar with it, but I find jetty essential for development.

Body:
We have a set of running servlets on a tomcat engine. When we compile a java file and build the war, tomcat takes an indeterminate amount of time to reload it. Sometimes 3 seconds, sometimes 30, etc. Current workaround is to stop tomcat and restart it using a shell script. We set up the autodeploy and reloadable flag to true but it is not working reliably. Any idea how to make this happen? Pointers appreciated, too. This is about tomcat v6.0.20 on ubuntu.

Here is an extract of our conf/server.xml file:

<Engine name="Catalina" defaultHost="localhost">

  <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
         resourceName="UserDatabase"/>

  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true"
        xmlValidation="false" xmlNamespaceAware="false">

    <DefaultContext reloadable="true">
    </DefaultContext>

  </Host>
</Engine>


问:
LAST_DDL_TIME Not Changing after create or replace package body again
On Nov 24 th, we created the package body. Again today we created (create or replace) the same package body object, but last DDL date has not changed. Is there any reason for this ?

Below is the query I'm using

```<code>SELECT object_name, object_type, created, last_ddl_time, status FROM ALL_OBJECTS WHERE OBJECT_NAME = 'xxxxxxxxx';
</code>```

答:
Your query could be wrong.

You need to add this to your WHERE clause:
 AND OBJECT_TYPE = 'PACKAGE BODY'

Your query would bring back the SPEC as well as the BODY and only the BODY was updated...theoretically since you're not saying exactly HOW you updated your package.

Body:
On Nov 24 th, we created the package body. Again today we created (create or replace) the same package body object, but last DDL date has not changed. Is there any reason for this ?

Below is the query I'm using

SELECT object_name, object_type, created, last_ddl_time, status FROM ALL_OBJECTS WHERE OBJECT_NAME = 'xxxxxxxxx';


问:
Dynamic/scrollable container size in Cytoscape (+ cy.fit() issues)
So I've been giving Cytoscape a try recently. My project's goal is basically a collaborative graph that people will be able to add/remove nodes to/from, making it grow in the process. The graph will include many compound nodes.

Most of the examples I've seen use container div that takes 100% of the screen space. This is fine for "controlled" graphs but won't work in my case because its size is intended to be dynamic.

Here's a JSFiddle using the circle layout within a fixed 3000px/3000px container:
https://jsfiddle.net/Jeto143/zj8ed82a/5/

Is there any way to have the container size be dynamic as opposed to stating it explicitly? Or do I have to compute the new optimal container size each time somehow, and then call cy.resize()?
edit: actually, using 100%/100% into cy.fit() might just work no matter how large the network is gonna be, so please ignore this question is this is the case.

Is there a recommended layout for displaying large/unknown amounts of data in a non-hierarchical way that would "smartly" place nodes (including compound ones) in the most efficient way possible, all the while avoiding any overlap? (I guess that's a lot to ask...)

Why doesn't cy.fit() seem to be working in my example? I'm using it both at graph initialization and when CTRL+clicking nodes (to show closed neighborhood), but it doesn't seem to like the 3000x3000px container (seems better with 100%x100%).
edit: also ignore this question if you ignored 1., as again it seems fine with 100%/100%.

Any help/suggestions would be greatly appreciated.

Thank you very much in advance.

答:
TLDR: It's (1).

Cytoscape has a pannable viewport, like a map.  You can define the dimensions of the viewport (div) in CSS.  What's displayed in the viewport is a function of the positions of the nodes, the zoom level, and the pan level -- just like what is visible in a map's viewport is a function of zoom, pan, and positions of points of interest.

So either you have to

(a) rethink your UI in terms of zoom and pan and use those in-built facilities in Cytoscape, or

(b) disable zoom and pan in Cytoscape (probably stay at (0, 0) at zoom 1) and let the user scroll the page as you add content to the graph and resize its container div to accommodate the new content.


问:
React giving me 403 forbidden error when making an API call
I am using react to switch images using the Snoowrap Reddit api wrapper. When I use this function just using Node.js and the app module it works normally:

```<code>reddit.getSubreddit('pics').getRandomSubmission().then(function(post){
       return(post.url.toString());
     });
</code>```

This is what the function looks like with my normal NodeJS app this code here works 100% fine

```<code>app.get('/getimage', function(req, res){
  r.getSubreddit(subreddit).getRandomSubmission().then(function(post){
    if(post.url.includes(".jpg") || post.url.includes(".png")){
      res.send(post.url);
      res.end();
    }
    else{
      res.send("No picture extension as .jpg .png")
      console.log("No .jpg Extension");
    }
});
  console.log("Pressed!");
});
</code>```

This code here gives me an unhandled 403 rejection Error I downloaded the chrome browser CORS header extension and it fixed theAccess-Control-Allow-Origin error but now its giving me a 403 error

```<code>getPic: function() {
     reddit.getSubreddit('pics').getRandomSubmission().then(function(post){
       return(post.url.toString());
     });

   },
</code>```

答:
A common request that may result in a 403 Forbidden response is a HTTP GET request for a web page performed by a web browser to retrieve the page for display to a user in a browser window.

This maybe caused for the CORS extension, if I was you I would try to configure my server as a CORS server instead of using a chrome extension.
You can use this npm

```<code>npm install cors --save
</code>```

Before your app.get(...) write a const cors = require('cors') and app.use(cors())

I maybe wrong, but give it a try!

Body:
I am using react to switch images using the Snoowrap Reddit api wrapper. When I use this function just using Node.js and the app module it works normally:

reddit.getSubreddit('pics').getRandomSubmission().then(function(post){
       return(post.url.toString());
     });

This is what the function looks like with my normal NodeJS app this code here works 100% fine

app.get('/getimage', function(req, res){
  r.getSubreddit(subreddit).getRandomSubmission().then(function(post){
    if(post.url.includes(".jpg") || post.url.includes(".png")){
      res.send(post.url);
      res.end();
    }
    else{
      res.send("No picture extension as .jpg .png")
      console.log("No .jpg Extension");
    }
});
  console.log("Pressed!");
});

This code here gives me an unhandled 403 rejection Error I downloaded the chrome browser CORS header extension and it fixed theAccess-Control-Allow-Origin error but now its giving me a 403 error

getPic: function() {
     reddit.getSubreddit('pics').getRandomSubmission().then(function(post){
       return(post.url.toString());
     });

   },

Body:
A common request that may result in a 403 Forbidden response is a HTTP GET request for a web page performed by a web browser to retrieve the page for display to a user in a browser window.

This maybe caused for the CORS extension, if I was you I would try to configure my server as a CORS server instead of using a chrome extension.
You can use this npm

npm install cors --save

Before your app.get(...) write a const cors = require('cors') and app.use(cors())

I maybe wrong, but give it a try!


问:
load json data in vue
I am trying to load my data/data.json file to my component so that I can display the data when a particular part is clicked.

Snippet of my data

```<code>"colors": [
      {"id": 1, "type": "direct", "primary": "red", "hex": [1, 4]},
      {"id": 2, "type": "direct", "primary": "yellow", "hex": [2, 5]},
      {"id": 3, "type": "direct", "primary": "blue", "hex": [3, 6]},
      {"id": 4, "type": "split", "primary": "red", "hex": [1, 7, 8]},
      {"id": 5, "type": "split", "primary": "yellow", "hex": [2, 9, 10]},
      {"id": 6, "type": "split", "primary": "blue", "hex": [3, 11, 12]},
      {"id": 7, "type": "analogous", "primary": "red", "hex": [1, 13, 14]},
      {"id": 8, "type": "analogous", "primary": "yellow", "hex": [2, 15, 16]},
      {"id": 9, "type": "analogous", "primary": "blue", "hex": [3, 17, 18]}
    ]
</code>```

I have a another data set that is connected to the hex data that's why they are just numbered

For the loading in the data, I have it as follows:

```<code>var app = new Vue({
el:"#app",
data:function() {
    return{
        json: null
    }
},
methods: {

}
});

$.getJSON('data/data.json', function (json) {
    app.json = json;
});
</code>```

What is a good way to add it to my components so that I can properly display what data I am wanting to show?

答:
You could load it within the component itself once it's mounted, using the mounted hook:

```<code>// ...
data () {
  return { json: null }
},
mounted () {
  $.getJSON('data/data.json', json => {
    this.json = json
  })
}
</code>```

Title: load json data in vue

Body:
I am trying to load my data/data.json file to my component so that I can display the data when a particular part is clicked.

Snippet of my data

"colors": [
      {"id": 1, "type": "direct", "primary": "red", "hex": [1, 4]},
      {"id": 2, "type": "direct", "primary": "yellow", "hex": [2, 5]},
      {"id": 3, "type": "direct", "primary": "blue", "hex": [3, 6]},
      {"id": 4, "type": "split", "primary": "red", "hex": [1, 7, 8]},
      {"id": 5, "type": "split", "primary": "yellow", "hex": [2, 9, 10]},
      {"id": 6, "type": "split", "primary": "blue", "hex": [3, 11, 12]},
      {"id": 7, "type": "analogous", "primary": "red", "hex": [1, 13, 14]},
      {"id": 8, "type": "analogous", "primary": "yellow", "hex": [2, 15, 16]},
      {"id": 9, "type": "analogous", "primary": "blue", "hex": [3, 17, 18]}
    ]

I have a another data set that is connected to the hex data that's why they are just numbered

For the loading in the data, I have it as follows:

var app = new Vue({
el:"#app",
data:function() {
    return{
        json: null
    }
},
methods: {

}
});

$.getJSON('data/data.json', function (json) {
    app.json = json;
});

What is a good way to add it to my components so that I can properly display what data I am wanting to show?

Body:
You could load it within the component itself once it's mounted, using the mounted hook:

// ...
data () {
  return { json: null }
},
mounted () {
  $.getJSON('data/data.json', json => {
    this.json = json
  })
}


问:
CSS - selectors accessibility
All,

I cannot for the life of me figure out what is wrong with this simple code. Its fairly basic CSS but the browser (FF) totally ignores the last CSS selection code.

Here is the html:

```<code><div id="cat_box01">
    <a href="#"><img src="i/cat/cat_img01.jpg" /></a>
    <class="sizes_txt">Sizes:</class>
</div>
</code>```

And here is the CSS:

```<code>#cat_box01 {
    background: rgba(255,43,43,1); /* colouring the background as a test */
    height: 250px;
    width: 500px;
    padding: 10px;
    border: 0;
    margin: 0px;
    position: absolute;
    top: 98px;
    left: 16px;
    z-index: 1;
}

#cat_box01 a img {
    height: 200px;
    width: auto;
    position: relative;
    left: 5px;
    padding: 5px;
    border: 0;
    margin: 0;
    opacity: 0.9;
}

#cat_box01 .sizes_txt {
    position: relative;
    left: 300px;
    padding: 0;
    border: 0;
    margin: 0;
    font-family: Helvetica, Georgia, Arial, sans-serif;
    font-size: 10px;
}
</code>```

Its the #cat_box01 .sizes_txt syntax that is not run. What is it that I am doing wrong here? Cheers for helping a newbie :)

答:
<class> is not a valid dom element

use   instead

Title: CSS - selectors accessibility

Body:
All,

I cannot for the life of me figure out what is wrong with this simple code. Its fairly basic CSS but the browser (FF) totally ignores the last CSS selection code.

Here is the html:

    <class="sizes_txt">Sizes:</class>

And here is the CSS:

#cat_box01 {
    background: rgba(255,43,43,1); /* colouring the background as a test */
    height: 250px;
    width: 500px;
    padding: 10px;
    border: 0;
    margin: 0px;
    position: absolute;
    top: 98px;
    left: 16px;
    z-index: 1;
}

#cat_box01 a img {
    height: 200px;
    width: auto;
    position: relative;
    left: 5px;
    padding: 5px;
    border: 0;
    margin: 0;
    opacity: 0.9;
}

#cat_box01 .sizes_txt {
    position: relative;
    left: 300px;
    padding: 0;
    border: 0;
    margin: 0;
    font-family: Helvetica, Georgia, Arial, sans-serif;
    font-size: 10px;
}

Its the #cat_box01 .sizes_txt syntax that is not run. What is it that I am doing wrong here? Cheers for helping a newbie :)

Body:
<class> is not a valid dom element

use <span class="sizes_txt"> </span> instead


问:
JHipster new User Registration -> MailConnectException
I am getting to know JHipster and Spring better and better but I have an issue with registrating a new User. When I try to register a new User I receive the below error message. According to this Stackoverflow issue Email service in Jhipster I have to fill in the properties in application-dev.yml or application-prod.yml.

The web-app should be used from different persons, who should be able to register themselves. I don't think that this is the correct way to go? Am I missing something here? Do I need a SMTP Server for this to work?

```<code>2017-12-05 09:19:58.006  WARN 31208 --- [irpd-Executor-2] irpd.service.MailService                 : Email could not be sent to user 'test.test@gmail.com'

org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection refused: connect. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection refused: connect
</code>```

I have the following entry in my application-dev.yaml:

```<code> mail:
        host: localhost
        port: 25
        username:
        password:
    messages:
        cache-seconds: 1
    thymeleaf:
        cache: false
    http:
        multipart:
            max-file-size: 5MB
            max-request-size: 20MB
</code>```

答: Yes you need an SMTP server. Check our tips section on www.jhipster.tech, you'll find how to configure email and how to use MailDev with Docker </p>

Body:
I am getting to know JHipster and Spring better and better but I have an issue with registrating a new User. When I try to register a new User I receive the below error message. According to this Stackoverflow issue Email service in Jhipster I have to fill in the properties in application-dev.yml or application-prod.yml.

The web-app should be used from different persons, who should be able to register themselves. I don't think that this is the correct way to go? Am I missing something here? Do I need a SMTP Server for this to work?

2017-12-05 09:19:58.006  WARN 31208 --- [irpd-Executor-2] irpd.service.MailService                 : Email could not be sent to user 'test.test@gmail.com'

org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection refused: connect. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection refused: connect

I have the following entry in my application-dev.yaml:

 mail:
        host: localhost
        port: 25
        username:
        password:
    messages:
        cache-seconds: 1
    thymeleaf:
        cache: false
    http:
        multipart:
            max-file-size: 5MB
            max-request-size: 20MB


问:
LinkedList Queue to List of Integers Method C#
I have two classes that represent a linked list implementation of a queue. Ultimately, I want to be able to bind an object of the queue to a list (to be able to bind it to a gird view).

However, trying to use foreach in methods will not work as 'Queue does not have a public definition for GetEnumerator'.

I need a method in the base class (queue) that will return all the node's data items in their order in the form of an array/list.

Any help would be much appreciated.

```<code>public class Queue
{
    private Node Head;
    private Node Tail;
    private int Count = 0;
    public Queue() { }
    public void Enqueue(int OrderID)
    {
        Node newNode = new Node(OrderID);
        if (Head == null)
        {
            Head = newNode;
            Tail = Head;
        }
        else
        {
            Tail.Next = newNode;
            Tail = Tail.Next;
        }
        Count++;
    }
    public int Dequeue()
    {
        if (Head == null)
        {
            throw new Exception("Nothing in queue.");
        }
        int Result = Head.OrderID;
        Head = Head.Next;
        return Result;
    }

    public int getCount()
    {
        return Count;
    }

}

public class Node
{
    public int OrderID { get; set; }
    public Node Next { get; set; }
    public Node(int ID)
    {
        this.OrderID = ID;
    }
}
</code>```

答:
You can create recursive method to perform it.

```<code>    public List<Node> GetAllNodes()
    {
        var allNodes = new List<Node>();
        GetAllNodesRecursive(allNodes, Head);
        return allNodes;
    }

    private void GetAllNodesRecursive(List<Node> allNodes, Node node)
    {
        if (node == null)
        {
            return;
        }
        allNodes.Add(node);
        GetAllNodesRecursive(allNodes, node.Next);
    }
</code>```

Usage

```<code>        var queue = new Queue();
        queue.Enqueue(1);
        queue.Enqueue(2);
        queue.Enqueue(4);
        var nodeList = queue.GetAllNodes();
</code>```

To retrieve list of OrderId integers;

```<code>var orderIDList = queue.GetAllNodes().Select(x => x.OrderId).ToList();
</code>```

Body:
I have two classes that represent a linked list implementation of a queue. Ultimately, I want to be able to bind an object of the queue to a list (to be able to bind it to a gird view).

However, trying to use foreach in methods will not work as 'Queue does not have a public definition for GetEnumerator'.

I need a method in the base class (queue) that will return all the node's data items in their order in the form of an array/list.

Any help would be much appreciated.

public class Queue
{
    private Node Head;
    private Node Tail;
    private int Count = 0;
    public Queue() { }
    public void Enqueue(int OrderID)
    {
        Node newNode = new Node(OrderID);
        if (Head == null)
        {
            Head = newNode;
            Tail = Head;
        }
        else
        {
            Tail.Next = newNode;
            Tail = Tail.Next;
        }
        Count++;
    }
    public int Dequeue()
    {
        if (Head == null)
        {
            throw new Exception("Nothing in queue.");
        }
        int Result = Head.OrderID;
        Head = Head.Next;
        return Result;
    }

    public int getCount()
    {
        return Count;
    }

}

public class Node
{
    public int OrderID { get; set; }
    public Node Next { get; set; }
    public Node(int ID)
    {
        this.OrderID = ID;
    }
}

Body:
You can create recursive method to perform it.

    public List<Node> GetAllNodes()
    {
        var allNodes = new List<Node>();
        GetAllNodesRecursive(allNodes, Head);
        return allNodes;
    }

    private void GetAllNodesRecursive(List<Node> allNodes, Node node)
    {
        if (node == null)
        {
            return;
        }
        allNodes.Add(node);
        GetAllNodesRecursive(allNodes, node.Next);
    }

Usage

        var queue = new Queue();
        queue.Enqueue(1);
        queue.Enqueue(2);
        queue.Enqueue(4);
        var nodeList = queue.GetAllNodes();

To retrieve list of OrderId integers;

var orderIDList = queue.GetAllNodes().Select(x => x.OrderId).ToList();


问:
Java 9 + Maven: What happens if two dependencies export the same module?
I'm getting a java.lang.NoSuchMethodError trying to invoke a Java method. As far as I can tell, the classpath is identical at compile-time and runtime-time so this error should not be occurring.

Repro steps:

Create 4 Maven projects:

MyLibrary

ExtensionPresent

ExtensionMissing

UserCode

Modules ExtensionPresent and ExtensionMissing export the same module name.

ExtensionMissing exports:

```<code>package dummy;

public class Extension {}
</code>```

ExtensionPresent exports:

```<code>package dummy;

public class Extension {

    public static void present() {
        System.out.println("Extension present!");
    }
}
</code>```

MyLibrary declares ExtensionMissing as a dependency.

UserCode declares MyLibrary as a dependency.

UserCode.main() invokes Extension.present(). This triggers a compile-time error because ExtensionMissing does not contain this method.

Now for the interesting part... In the UserCode project, add ExtensionPresent as a dependency after MyLibrary.

I no longer get a compiler error (the method is now present at compile-time).

When I try invoking UserCode.main() I get:

```<code>--- exec-maven-plugin:1.6.0:exec (default-cli) @ mavenproject3 ---
Exception in thread "main" java.lang.NoSuchMethodError: dummy.Extension.present()V
</code>```

Is this a bug in my project configuration, Maven's implementation, or the JDK tools?

(On a side-note, I am doing this in an attempt to solve: Implementing a (compile-time) plugin architecture without split packages)

UPDATE: Here is an executable testcase: https://github.com/cowwoc/exec-maven-plugin-class-shadowing

答:
When I enable debug logging, I see the plugins firing the following commands:

compiler-maven-plugin is invoking: javac -d ~/UserCode/target/classes -classpath ~/UserCode/target/classes: --module-path ~/.m2/repository/ExtensionPresent/1.0-SNAPSHOT/ExtensionPresent-1.0-SNAPSHOT.jar:~/.m2/repository/MyLibrary/1.0-SNAPSHOT/MyLibrary-1.0-SNAPSHOT.jar:~/.m2/repository/ExtensionMissing/1.0-SNAPSHOT/ExtensionMissing-1.0-SNAPSHOT.jar: -sourcepath ~/UserCode/src/main/java:~/UserCode/target/generated-sources/annotations: -s ~/UserCode/target/generated-sources/annotations -g -nowarn -target 9 -source 9 -encoding UTF-8

maven-exec-plugin is invoking java, --module-path, ~/UserCode/target/classes:~/.m2/repository/MyLibrary/1.0-SNAPSHOT/MyLibrary-1.0-SNAPSHOT.jar:~/.m2/repository/ExtensionMissing/1.0-SNAPSHOT/ExtensionMissing-1.0-SNAPSHOT.jar:~/.m2/repository/ExtensionPresent/1.0-SNAPSHOT/ExtensionPresent-1.0-SNAPSHOT.jar, -m, UserCode/com.usercode.Main]

This led me to believe that maven-exec-plugin is listing the dependencies in the wrong order. I tried invoking the application manually, swapping the order of dependencies, and sure enough the program runs.

I filed a bug report against maven-exec-plugin.

I filed a second bug report against maven-compiler-plugin because it seems that it also passes the wrong order to javac depending on the name of the project directory (odd but true).

Body:
I'm getting a java.lang.NoSuchMethodError trying to invoke a Java method. As far as I can tell, the classpath is identical at compile-time and runtime-time so this error should not be occurring.

Repro steps:

Create 4 Maven projects:

MyLibrary

ExtensionPresent

ExtensionMissing

UserCode

Modules ExtensionPresent and ExtensionMissing export the same module name.

ExtensionMissing exports:

package dummy;

public class Extension {}

ExtensionPresent exports:

package dummy;

public class Extension {

    public static void present() {
        System.out.println("Extension present!");
    }
}

MyLibrary declares ExtensionMissing as a dependency.

UserCode declares MyLibrary as a dependency.

UserCode.main() invokes Extension.present(). This triggers a compile-time error because ExtensionMissing does not contain this method.

Now for the interesting part... In the UserCode project, add ExtensionPresent as a dependency after MyLibrary.

I no longer get a compiler error (the method is now present at compile-time).

When I try invoking UserCode.main() I get:

--- exec-maven-plugin:1.6.0:exec (default-cli) @ mavenproject3 ---
Exception in thread "main" java.lang.NoSuchMethodError: dummy.Extension.present()V

Is this a bug in my project configuration, Maven's implementation, or the JDK tools?

(On a side-note, I am doing this in an attempt to solve: Implementing a (compile-time) plugin architecture without split packages)

UPDATE: Here is an executable testcase: https://github.com/cowwoc/exec-maven-plugin-class-shadowing


问:
how to sorting according to the value of a field? mongo
I have a set of data. When I select the filter conditions, I want to query all the data and put the values that conform to the screening conditions to display in front of the query results.

for example

```<code>[
    {color: 'blue', name: 'four'},
    {color: 'green', name: 'five'},
    {color: 'red', name: 'one'},
    {color: 'red', name: 'two'},
    {color: 'red', name: 'three'}
]
</code>```

when i choose color:red, and limit 4, I want to get the data

```<code>[
    {color: 'red', name: 'one'},
    {color: 'red', name: 'two'},
    {color: 'red', name: 'three'},
    {color .........}// the fourth of data are not concerned for now
]
</code>```

and when i choose color:blue, and limit 4, I want to get the data

```<code>[
    {color: 'blue', name: 'four'},
    {color  ........},
    {color  ........},
    {color .........}// now just care the first data
]
</code>```

Have some function to achieve this？

My english is so poor, I hope the meaning is clear.

anyway, thanks!

答:
In your specific example you can write this:

```<code>db.color.aggregate([{
    $addFields : {
        "rank" : { // add a field called rank to all our documents
            $cond: {
                if: { $eq: [ "$color", "blue" ] }, // if the color value matches "blue"
                then: 0, // then we want items to be on the top
                else: 1 // else we want them to be in the second part
            }
        }
    }
}, {
    $sort : {"rank" : 1} // sort ascending by our newly created "rank" field
}])
</code>```

If you are using an older version of MongoDB (<3.4) that does not support $addFields yet you can instead resort to using $project instead like so:

```<code>db.color.aggregate([{
    $project : {
        "color": 1, // we want to retain the value of the color field
        "name": 1, // the same goes for the name field
        "rank" : { // add a field called rank to all our documents
            $cond: {
                if: { $eq: [ "$color", "blue" ] }, // if the color value matches "blue"
                then: 0, // then we want items to be on the top
                else: 1 // else we want them to be in the second part
            }
        }
    }
}, {
    $sort : {"rank" : 1} // sort ascending by our newly created "rank" field
}])
</code>```

Body:
I have a set of data. When I select the filter conditions, I want to query all the data and put the values that conform to the screening conditions to display in front of the query results.

for example

[
    {color: 'blue', name: 'four'},
    {color: 'green', name: 'five'},
    {color: 'red', name: 'one'},
    {color: 'red', name: 'two'},
    {color: 'red', name: 'three'}
]

when i choose color:red, and limit 4, I want to get the data

[
    {color: 'red', name: 'one'},
    {color: 'red', name: 'two'},
    {color: 'red', name: 'three'},
    {color .........}// the fourth of data are not concerned for now
]

and when i choose color:blue, and limit 4, I want to get the data

[
    {color: 'blue', name: 'four'},
    {color  ........},
    {color  ........},
    {color .........}// now just care the first data
]

Have some function to achieve this？

My english is so poor, I hope the meaning is clear.

anyway, thanks!

Body:
In your specific example you can write this:

db.color.aggregate([{
    $addFields : {
        "rank" : { // add a field called rank to all our documents
            $cond: {
                if: { $eq: [ "$color", "blue" ] }, // if the color value matches "blue"
                then: 0, // then we want items to be on the top
                else: 1 // else we want them to be in the second part
            }
        }
    }
}, {
    $sort : {"rank" : 1} // sort ascending by our newly created "rank" field
}])

If you are using an older version of MongoDB (<3.4) that does not support $addFields yet you can instead resort to using $project instead like so:

db.color.aggregate([{
    $project : {
        "color": 1, // we want to retain the value of the color field
        "name": 1, // the same goes for the name field
        "rank" : { // add a field called rank to all our documents
            $cond: {
                if: { $eq: [ "$color", "blue" ] }, // if the color value matches "blue"
                then: 0, // then we want items to be on the top
                else: 1 // else we want them to be in the second part
            }
        }
    }
}, {
    $sort : {"rank" : 1} // sort ascending by our newly created "rank" field
}])


问:
How can I change all forms properties in C# Windows Application
Example:

1- List all forms (opened and closed Forms) in the C# windows forms project

2 - Set properties like at:

```<code>* Size
* StartPosition
*ShowInTaskbar
</code>```

3- Call this before the application start.

With this I want to set properties only once in the beginning for all forms and have the same standard. Thank you.

答:
You could do this during run-time with an extension method.

```<code>public static class FormExtensions
{
    public static Form SetFormProperties(this Form form)
    {
        form.Height = 100;
        form.Width = 100;
        form.StartPosition = FormStartPosition.WindowsDefaultLocation;
        form.ShowInTaskbar = true;
        return form;
    }
}
</code>```

And then call it when you create an instance of a form.

```<code>var newForm = new SomeForm().SetFormProperties();
</code>```

Body:
Example:

1- List all forms (opened and closed Forms) in the C# windows forms project

2 - Set properties like at:

* Size
* StartPosition
*ShowInTaskbar

3- Call this before the application start.

With this I want to set properties only once in the beginning for all forms and have the same standard. Thank you.

Body:
You could do this during run-time with an extension method.

public static class FormExtensions
{
    public static Form SetFormProperties(this Form form)
    {
        form.Height = 100;
        form.Width = 100;
        form.StartPosition = FormStartPosition.WindowsDefaultLocation;
        form.ShowInTaskbar = true;
        return form;
    }
}

And then call it when you create an instance of a form.

var newForm = new SomeForm().SetFormProperties();


问:
How to only pass non-empty variables as function parameters?
I have a function that will always receive 3 arguments; at least one arg will have a value, but one or more may not. After working with the arguments in this function, I need to send only the arguments with values to another function. Furthermore, the second function needs at least 2 args, so I only want to execute it if at least 2 of my args have a value. What is the best way to accomplish this?

Here is an example of my code structure:

```<code>function doSomething(arg1, arg2, arg3) {
    // Do something with args

    // Only want to send args with values to this function (min 2 args)
    return doSomethingElse(arg1, arg2, arg3);

}
</code>```

Edit: The second function, doSomethingElse(), can receive any number of args with a minimum of 2.

答:
You first filter the arguments object to ensure that there are no undefined values. From there you can pass the arguments object (via spread) into the next function if there are two or more.

function doSomething(arg1, arg2, arg3) {
  const totalArgs = [...arguments].filter(arg => arg !== undefined);

  if (totalArgs.length >= 2) {
    return doSomethingElse(...totalArgs);
  } else {
    console.log('Not enough arguments supplied');
  }
}

function doSomethingElse() {
  Array.from(arguments).forEach(arg => console.log(arg));
}

// doSomethingElse() fires
doSomething(1,2);
// doSomethingElse() doesn't fire. Not enough arguments.
doSomething(1);```

Body:
I have a function that will always receive 3 arguments; at least one arg will have a value, but one or more may not. After working with the arguments in this function, I need to send only the arguments with values to another function. Furthermore, the second function needs at least 2 args, so I only want to execute it if at least 2 of my args have a value. What is the best way to accomplish this?

Here is an example of my code structure:

function doSomething(arg1, arg2, arg3) {
    // Do something with args

    // Only want to send args with values to this function (min 2 args)
    return doSomethingElse(arg1, arg2, arg3);

}

Edit: The second function, doSomethingElse(), can receive any number of args with a minimum of 2.


问:
how to combine two different record sets In SSIS
Have two table

Table Model

```<code>Id      int Unchecked
MakeId  int Unchecked
Name    nvarchar(255)
</code>```

Table Feature

```<code> FId    int Checked
</code>```

Both table have no relation . Want a record set having both table column.

Table Destination

```<code>Id      int Unchecked
MakeId  int Unchecked
Name    nvarchar(255)
FId int Checked
</code>```

can not use bellow sql because i have two datasouce,one for Model and another one for Feature(this one select just top 1 record)

```<code>select Id,MakeId,Name,(select top 1 Fid from Feature) as Fid from Model
</code>```

答: What I'd do, since you only want a single TOP 1 result from Feature, is save that value to a variable in the Control Flow with an Execute SQL task. Then in the Data Flow, configure your source data connection, and run that to a Derived Column task. Then define a new column that uses the Feature variable you created. Then you can run the output of the Derived Column to your destination (or other task, etc).</p>

Body:
Have two table

Table Model

Id      int Unchecked
MakeId  int Unchecked
Name    nvarchar(255)

Table Feature

 FId    int Checked

Both table have no relation . Want a record set having both table column.

Table Destination

Id      int Unchecked
MakeId  int Unchecked
Name    nvarchar(255)
FId int Checked

can not use bellow sql because i have two datasouce,one for Model and another one for Feature(this one select just top 1 record)

select Id,MakeId,Name,(select top 1 Fid from Feature) as Fid from Model


答:
You can use the rest operator:

function one(...args) {
  console.log(args.length);
  two(...args);
}

function two(...args) {
  console.log(args.length);
}

one(1, 2, 3, 4);```

Title: How to only pass non-empty variables as function parameters?


答:
What about this?</p>

```<code>function doSomething(arg1, arg2, arg3) {
    // Do something with args

    // Only want to send args with values to this function (min 2 args)
    if ([arg1, arg2, arg3].filter(arg => null != arg).length >= 2) {
        return doSomethingElse(arg1, arg2, arg3);
    }
}
</code>```

Body:
What about this?

function doSomething(arg1, arg2, arg3) {
    // Do something with args

    // Only want to send args with values to this function (min 2 args)
    if ([arg1, arg2, arg3].filter(arg => null != arg).length >= 2) {
        return doSomethingElse(arg1, arg2, arg3);
    }
}


问:
What's the easiest way to create an Excel table with C#?
I have some tabular data that I'd like to turn into an Excel table.

Software available:

.NET 4 (C#)

Excel 2010 (using the Excel API is OK)

I prefer not to use any 3rd party libraries

Information about the data:

A couple million rows

5 columns, all strings (very simple and regular table structure)

In my script I'm currently using a nested List data structure but I can change that

Performance of the script is not critical

Searching online gives many results, and I'm confused whether I should use OleDb, ADO RecordSets, or something else. Some of these technologies seem like overkill for my scenario, and some seem like they might be obsolete.

What is the very simplest way to do this?

Edit: this is a one-time script I intend to run from my attended desktop.

答:
Avoid using COM interop at all costs. Use a third-party API. Really. In fact, if you're doing this server-side, you virtually have to. There are plenty of free options. I highly recommend using EPPlus, but there are also enterprise-level solutions available. I've used EPPlus a fair amount, and it works great. Unlike interop, it allows you to generate Excel files without requiring Excel to be installed on the machine, which means you also don't have to worry about COM objects sticking around as background processes. Even with proper object disposal, the Excel processes don't always end.

http://epplus.codeplex.com/releases/view/42439

I know you said you want to avoid third-party libraries, but they really are the way to go. Microsoft does not recommend automating Office. It's really not meant to be automated anyway.

http://support.microsoft.com/kb/257757

However, you may want to reconsider inserting "a couple million rows" into a single spreadsheet.


问:
How do I make an animation grow and then stay that size?
I can't seem to make an animation grow then stay that size for another animation.  I have tried android:fillEnabled="true" & android:fillAfter="true" but they don't seem to work.

答:
I will take a guess that you are using xml animations, which are acting on drawables.
The second animation is going to use the same drawable values available to the first animation (these values don't actually change, which is why the second animation doesn't work as expected), the best way I would go about this is to dynamically make each animation in code, there by having reference to all values / attributes changed in each animation

https://developer.android.com/guide/topics/graphics/prop-animation.html

should give a good over view of how to do this dynamically


问:
Plotnine bar plot order by variable
I have a question on ordering bar plots. For example:

http://pythonplot.com/#bar-counts

```<code>(ggplot(mpg) +
aes(x='manufacturer') +
geom_bar(size=20) +
coord_flip() +
ggtitle('Number of Cars by Make')
)
</code>```

how to order by "mpg" ?

答:
Thanks to has2k1: https://github.com/has2k1/plotnine/issues/94

If the x mapping is an ordered categorical, it is respected.

```<code>from plydata import *
from plotnine import *
from plotnine.data import mpg

# count the manufacturer and sort by the count (see, plydata documentation
# or find out how to do the same thing using raw pandas)
m_categories = (
    mpg
    >> count('manufacturer', sort=True)
    >> pull('manufacturer')
)

df = mpg.copy()
df['manufacturer'] = pd.Categorical(df['manufacturer'],     categories=m_categories, ordered=True)

(ggplot(df) +
   aes(x='manufacturer') +
geom_bar(size=20) +
coord_flip() +
ggtitle('Number of Cars by Make')
)
</code>```

Title: Plotnine bar plot order by variable

Body:
I have a question on ordering bar plots. For example:

http://pythonplot.com/#bar-counts

(ggplot(mpg) +
aes(x='manufacturer') +
geom_bar(size=20) +
coord_flip() +
ggtitle('Number of Cars by Make')
)

how to order by "mpg" ?

Body:
Thanks to has2k1: https://github.com/has2k1/plotnine/issues/94

If the x mapping is an ordered categorical, it is respected.

from plydata import *
from plotnine import *
from plotnine.data import mpg

# count the manufacturer and sort by the count (see, plydata documentation
# or find out how to do the same thing using raw pandas)
m_categories = (
    mpg
    >> count('manufacturer', sort=True)
    >> pull('manufacturer')
)

df = mpg.copy()
df['manufacturer'] = pd.Categorical(df['manufacturer'],     categories=m_categories, ordered=True)

(ggplot(df) +
   aes(x='manufacturer') +
geom_bar(size=20) +
coord_flip() +
ggtitle('Number of Cars by Make')
)


问:
Webpack.mix, vue.js - compilation parameters
I have a webpack.mix.js file (laravel mix) that I use for compiling javascript and scss. It works well, but I need a dynamic parameter. Right now I have:

```<code>//let result = 'https://www.web1.com/';
let result = 'https://stage.web1.com/';

    output: {
        publicPath: result,
        chunkFilename: 'js/[name].js'
    },
</code>```

This works fine, but I have to change the parameter manually when I switch between the localhost/stage/live version.

What I would like to do is to run:

```<code>npm run local
npm run stage
npm run live
</code>```

and the path parameter would be inserted automatically.

Right now, the npm run prod executes this:

```<code>cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
</code>```

How can I insert a parameter into this last line?

答:
To expand on @Ohgodwhy's comment:</p>

```<code>let result = process.env.NODE_ENV == "production" ?
  'https://www.web1.com/' :
  'https://stage.web1.com/'
</code>```

Body:
I have a webpack.mix.js file (laravel mix) that I use for compiling javascript and scss. It works well, but I need a dynamic parameter. Right now I have:

//let result = 'https://www.web1.com/';
let result = 'https://stage.web1.com/';

    output: {
        publicPath: result,
        chunkFilename: 'js/[name].js'
    },

This works fine, but I have to change the parameter manually when I switch between the localhost/stage/live version.

What I would like to do is to run:

npm run local
npm run stage
npm run live

and the path parameter would be inserted automatically.

Right now, the npm run prod executes this:

cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

How can I insert a parameter into this last line?

Body:
To expand on @Ohgodwhy's comment:

let result = process.env.NODE_ENV == "production" ?
  'https://www.web1.com/' :
  'https://stage.web1.com/'


问:
.map() is not a function Error on Mapping Dynamically created Object
I am trying to map a dynamically created Object to an Array like this

```<code>          params.junctionBarriers = dojo.toJson(junctionBarriers);
          // printing the object in the console (Please look at attached image)
          console.log(params.junctionBarriers);

          var value = [];
          var data = params.junctionBarriers.map(function (s) {
             value.push(webMercatorUtils.xyToLngLat(s.x, s.y, true));
              return s;
          })
</code>```

but I am getting this error

params.junctionBarriers.map is not a function

As you can see from the image the params.junctionBarriers is dynamically loaded but the .map() is not valid. Why is this, and how I can fix it?

答:
Look at the documentation for dojo.toJson

That method converts an object to a string in JSON format.

A String does not have the method map.

So why don't you simply do junctionBarriers.map? given you already have the array of objects in that variable (which is NOT params.junctionBarriers)

ContentLicense: CC BY-SA 4.0

Body:
I am trying to map a dynamically created Object to an Array like this

          params.junctionBarriers = dojo.toJson(junctionBarriers);
          // printing the object in the console (Please look at attached image)
          console.log(params.junctionBarriers);

          var value = [];
          var data = params.junctionBarriers.map(function (s) {
             value.push(webMercatorUtils.xyToLngLat(s.x, s.y, true));
              return s;
          })

but I am getting this error

params.junctionBarriers.map is not a function

As you can see from the image the params.junctionBarriers is dynamically loaded but the .map() is not valid. Why is this, and how I can fix it?


问:
Cannot assign property of struct returned from method
I got the following error which I translated from German:

error BC30068: The Expression is a value and cannot be target of an assignment.

I am trying to do the following:

```<code>sheet.Cells(row, col).Value = newVal ' this is VB
</code>```

Where I have declared Cells as:

```<code>public Cell Cells(int x, int y) // this is C#
{
    return new Cell(this, x, y);
}

public struct Cell
{
    Worksheet ws;
    int x;
    int y;

    public Cell(Worksheet ws, int x, int y)
    {
        this.ws = ws;
        this.x = x;
        this.y = y;
    }

    public object Value
    {
        get { return ws.GetCellValue(x, y); }
        set { ws.SetCellValue(x, y, value); }
    }
}
</code>```

How can I solve this problem? I do not want Cell to be a Class but instead to be a struct, because otherwise any access would create a new object on the heap. Sure I could cache all created Cell Objects but this could introduce bugs and wastes lots of memory and a new layer of indirection.

Is there a better way to do it?

答:
The behavior you are seeing is a consequence of the fact that .net makes no distinction between struct properties and methods which mutate the fields struct itself and those which do not.  Ideally, .net languages would forbid the use of any mutating methods and properties on read-only structs, while permitting non-mutating ones.  Unfortunately, since .net provides no indication of whether a struct method or property will mutate the underlying struct, today's C# and vb.net simply assume that property setters will affect the underlying struct, and other methods will not.  Older C# compilers allow the invocation of all struct member code, including property getters, often with undesired results.

It's too bad that Microsoft decided that structs should be mutated using property setters, rather than specifying that structs which were going to be mutable should either expose fields directly or else be modified using static methods.  Had they adopted such an approach on things like Point, the complaints which caused mutable structs to be branded as "evil" would have been averted, and code such as yours would have worked just fine.  Oh well, so much for the wonders of useless "encapsulation".

Body:
I got the following error which I translated from German:

error BC30068: The Expression is a value and cannot be target of an assignment.

I am trying to do the following:

sheet.Cells(row, col).Value = newVal ' this is VB

Where I have declared Cells as:

public Cell Cells(int x, int y) // this is C#
{
    return new Cell(this, x, y);
}

public struct Cell
{
    Worksheet ws;
    int x;
    int y;

    public Cell(Worksheet ws, int x, int y)
    {
        this.ws = ws;
        this.x = x;
        this.y = y;
    }

    public object Value
    {
        get { return ws.GetCellValue(x, y); }
        set { ws.SetCellValue(x, y, value); }
    }
}

How can I solve this problem? I do not want Cell to be a Class but instead to be a struct, because otherwise any access would create a new object on the heap. Sure I could cache all created Cell Objects but this could introduce bugs and wastes lots of memory and a new layer of indirection.

Is there a better way to do it?


问:
How to hook up NSWindowDelegate in macOS game template
This is a "how-to" for related question:
cocoa windowDidEnterFullScreen not being called

Using the Xcode (9.1) macOS "game" template -

I would like to create a simple NSWindowDelegate using the AppDelegate class. However I can't seem to connect the given NSWindow outlet to anything.

```<code>// AppDelegate.h
#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>

@property (assign) IBOutlet NSWindow *window; // won't connect

@end
</code>```

I assume I'm supposed to connect to a "Window" within the storyboard. This is what happens when I try to connect - the inspector does not show up.

What am I missing here?

Note: I'm just playing around so I don't care if AppDelegate is the right place or not, I just want something to work.

EDIT 1

Using suggestion from answer, I've tried connecting the 'TestFullscreen' window to the AppDelegate object, but it still won't connect, either from the AppDelegate inspector or the property declaration in the code.

答:
You should have a Delegate object and that is what should hook up to your window.

It looks like you are currently attempting to connect the window to itself. Also it doesn't appear you have a view for the window either, so you'll need to add that for the window content.

Body:
This is a "how-to" for related question:
cocoa windowDidEnterFullScreen not being called

Using the Xcode (9.1) macOS "game" template -

I would like to create a simple NSWindowDelegate using the AppDelegate class. However I can't seem to connect the given NSWindow outlet to anything.

// AppDelegate.h
#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>

@property (assign) IBOutlet NSWindow *window; // won't connect

@end

I assume I'm supposed to connect to a "Window" within the storyboard. This is what happens when I try to connect - the inspector does not show up.

What am I missing here?

Note: I'm just playing around so I don't care if AppDelegate is the right place or not, I just want something to work.

EDIT 1

Using suggestion from answer, I've tried connecting the 'TestFullscreen' window to the AppDelegate object, but it still won't connect, either from the AppDelegate inspector or the property declaration in the code.


问:
Java Futures & Fast Dot Product
I'm trying to implement a dot product that leverages concurrency to run faster. I'm going for a divide and conquer approach where I split the vector into smaller and smaller bits then finally sum all the components together. But, instead of returning the values right away, I return Futures that will eventually contain the results.

Here's my attempt so far:

```<code>Future<Double> dotProduct(double[] x, double[] d, int start, int end) {
    if ((end-start) == 1) {
      return executor.submit(() -> {
        return x[start] * d[start];
      });
    } else if ((end-start) == 0) {
      return executor.submit(() -> {
        return 0.0;
      });
    }

    int middle = (start+end)/2;
    Future<Double> leftDotProduct = dotProduct(x, d, start, middle);
    Future<Double> rightDotProduct = dotProduct(x, d, middle, end);

    return executor.submit(() -> {
      double l = leftDotProduct.get();
      double r = rightDotProduct.get();
      return l + r;
    });
  }

  // Usage:
  Future<Double> v = dotProduct(x, d, 0, x.length);
  v.get()
</code>```

It produces correct results but it still runs slower than the equivalent sequential implementation. I've tested on small (4 entries) and large (20,000) entries.

I was thinking the slow down might be due to the recursive calls and setting up new stacks. But I'm not even sure how to redesign the algo if that was the case.

Any thoughts on what could be causing the delay and how to improve it would be really appreciated!

Edit:

For more context, I want to return futures because ultimately I aim to use this method to multiply a matrix by a vector:

```<code>  double[] parMult(double[] x) {
    if (this.getWidth() != x.length)
      throw new ArithmeticException("The matrix and vector are of incompatible sizes");

    // Create an array of futures that will store all the results from dot poduct
    Future<Double>[] f = new Future[this.getHeight()];
    for (int i=0; i<this.getHeight(); i++) {
      f[i] = dotProduct(x, this.data[i]);
    }

    // Get the values of all futures
    double[] b = new double[this.getHeight()];
    try {
      for (int i = 0; i < this.getHeight(); i++) {
        b[i] = f[i].get();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return b;
  }
</code>```

答:
When you call Future.get() you wait for the future to complete. So, what just happened is you introduced all the overhead of an executor with numerous tasks to dispatch and you forced your code to run almost serially because you block.

What you are looking for instead is Fork+Join. The cumulative sum of products is a classic example of the fork+join pattern.

Title: Java Futures & Fast Dot Product

Body:
I'm trying to implement a dot product that leverages concurrency to run faster. I'm going for a divide and conquer approach where I split the vector into smaller and smaller bits then finally sum all the components together. But, instead of returning the values right away, I return Futures that will eventually contain the results.

Here's my attempt so far:

Future<Double> dotProduct(double[] x, double[] d, int start, int end) {
    if ((end-start) == 1) {
      return executor.submit(() -> {
        return x[start] * d[start];
      });
    } else if ((end-start) == 0) {
      return executor.submit(() -> {
        return 0.0;
      });
    }

    int middle = (start+end)/2;
    Future<Double> leftDotProduct = dotProduct(x, d, start, middle);
    Future<Double> rightDotProduct = dotProduct(x, d, middle, end);

    return executor.submit(() -> {
      double l = leftDotProduct.get();
      double r = rightDotProduct.get();
      return l + r;
    });
  }

  // Usage:
  Future<Double> v = dotProduct(x, d, 0, x.length);
  v.get()

It produces correct results but it still runs slower than the equivalent sequential implementation. I've tested on small (4 entries) and large (20,000) entries.

I was thinking the slow down might be due to the recursive calls and setting up new stacks. But I'm not even sure how to redesign the algo if that was the case.

Any thoughts on what could be causing the delay and how to improve it would be really appreciated!

Edit:

For more context, I want to return futures because ultimately I aim to use this method to multiply a matrix by a vector:

  double[] parMult(double[] x) {
    if (this.getWidth() != x.length)
      throw new ArithmeticException("The matrix and vector are of incompatible sizes");

    // Create an array of futures that will store all the results from dot poduct
    Future<Double>[] f = new Future[this.getHeight()];
    for (int i=0; i<this.getHeight(); i++) {
      f[i] = dotProduct(x, this.data[i]);
    }

    // Get the values of all futures
    double[] b = new double[this.getHeight()];
    try {
      for (int i = 0; i < this.getHeight(); i++) {
        b[i] = f[i].get();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return b;
  }