问:
Ionic 3 - App shows blank screen after build with --prod
It only happens with --prod and on the phone (Android). A weird thing is that if I touch anywhere (even if it's all white) the event that's supposed to be fired at that specific location is fired and suddenly the content is shown.

I read something about the TypeScript version having conflict with @ionic/app-scripts and how I needed to downgrade to TypeScript 2.0.x, but if I do that I get an error on the build that shouts:

Cannot read property 'Private' of undefined: tsickle.js:118:40

I guess that has something to do with all the other versions of my dependencies conflicting with that version of TS.

Here's my package.json:

```<code> {
  "name": "green-dragon",
  "version": "0.0.1",
  "author": "Test",
  "homepage": "http://www.huskysoftware.com.ar/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.4.3",
    "@angular/compiler": "4.4.3",
    "@angular/compiler-cli": "4.4.3",
    "@angular/core": "4.4.3",
    "@angular/forms": "4.4.3",
    "@angular/http": "4.4.3",
    "@angular/platform-browser": "4.4.3",
    "@angular/platform-browser-dynamic": "4.4.3",
    "@ionic-native/core": "4.3.0",
    "@ionic-native/geolocation": "^4.4.2",
    "@ionic-native/network": "^4.3.1",
    "@ionic-native/splash-screen": "4.3.0",
    "@ionic-native/status-bar": "4.3.0",
    "cordova-android": "6.3.0",
    "cordova-ios": "^4.5.1",
    "cordova-plugin-compat": "^1.2.0",
    "cordova-plugin-device": "^1.1.4",
    "cordova-plugin-geolocation": "^3.0.0",
    "cordova-plugin-ionic-webview": "^1.1.15",
    "cordova-plugin-network-information": "^1.3.3",
    "cordova-plugin-splashscreen": "^4.0.3",
    "cordova-plugin-statusbar": "git+https://github.com/apache/cordova-plugin-statusbar.git",
    "cordova-plugin-whitelist": "^1.3.1",
    "ionic-angular": "3.7.1",
    "ionic-native": "^2.9.0",
    "ionic-plugin-keyboard": "^2.2.1",
    "ionicons": "3.0.0",
    "lodash": "^4.17.4",
    "moment": "^2.19.1",
    "rxjs": "5.4.3",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@ionic/app-scripts": "3.1.4",
    "typescript": "2.0.9"
  },
  "description": "A beer map app",
  "cordova": {
    "plugins": {
      "cordova-plugin-device": {},
      "cordova-plugin-ionic-webview": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-statusbar": {},
      "ionic-plugin-keyboard": {},
      "cordova-plugin-network-information": {},
      "cordova-plugin-whitelist": {},
      "cordova-plugin-geolocation": {
        "GEOLOCATION_USAGE_DESCRIPTION": "Encontrar bares cercanos"
      }
    },
    "platforms": [
      "ios",
      "android"
    ]
  }
}
</code>```

Apparently, the --minifyjs flag is the one breaking here. But still dont know why

答:
I would like to give 2 clues here.

--prod uses AOT. So you cannot use private properties on your *.html file. So you need to find out where you have used it. Hope this error helps you to find out it. Cannot read property 'Private' of undefined: tsickle.js:118:40

I highly suggest you upgrade your app to latest Ionic 3.9.2

Body:
It only happens with --prod and on the phone (Android). A weird thing is that if I touch anywhere (even if it's all white) the event that's supposed to be fired at that specific location is fired and suddenly the content is shown.

I read something about the TypeScript version having conflict with @ionic/app-scripts and how I needed to downgrade to TypeScript 2.0.x, but if I do that I get an error on the build that shouts:

Cannot read property 'Private' of undefined: tsickle.js:118:40

I guess that has something to do with all the other versions of my dependencies conflicting with that version of TS.

Here's my package.json:

 {
  "name": "green-dragon",
  "version": "0.0.1",
  "author": "Test",
  "homepage": "http://www.huskysoftware.com.ar/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.4.3",
    "@angular/compiler": "4.4.3",
    "@angular/compiler-cli": "4.4.3",
    "@angular/core": "4.4.3",
    "@angular/forms": "4.4.3",
    "@angular/http": "4.4.3",
    "@angular/platform-browser": "4.4.3",
    "@angular/platform-browser-dynamic": "4.4.3",
    "@ionic-native/core": "4.3.0",
    "@ionic-native/geolocation": "^4.4.2",
    "@ionic-native/network": "^4.3.1",
    "@ionic-native/splash-screen": "4.3.0",
    "@ionic-native/status-bar": "4.3.0",
    "cordova-android": "6.3.0",
    "cordova-ios": "^4.5.1",
    "cordova-plugin-compat": "^1.2.0",
    "cordova-plugin-device": "^1.1.4",
    "cordova-plugin-geolocation": "^3.0.0",
    "cordova-plugin-ionic-webview": "^1.1.15",
    "cordova-plugin-network-information": "^1.3.3",
    "cordova-plugin-splashscreen": "^4.0.3",
    "cordova-plugin-statusbar": "git+https://github.com/apache/cordova-plugin-statusbar.git",
    "cordova-plugin-whitelist": "^1.3.1",
    "ionic-angular": "3.7.1",
    "ionic-native": "^2.9.0",
    "ionic-plugin-keyboard": "^2.2.1",
    "ionicons": "3.0.0",
    "lodash": "^4.17.4",
    "moment": "^2.19.1",
    "rxjs": "5.4.3",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@ionic/app-scripts": "3.1.4",
    "typescript": "2.0.9"
  },
  "description": "A beer map app",
  "cordova": {
    "plugins": {
      "cordova-plugin-device": {},
      "cordova-plugin-ionic-webview": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-statusbar": {},
      "ionic-plugin-keyboard": {},
      "cordova-plugin-network-information": {},
      "cordova-plugin-whitelist": {},
      "cordova-plugin-geolocation": {
        "GEOLOCATION_USAGE_DESCRIPTION": "Encontrar bares cercanos"
      }
    },
    "platforms": [
      "ios",
      "android"
    ]
  }
}

Apparently, the --minifyjs flag is the one breaking here. But still dont know why


来源: stackexchange

问:
How do I get placeholder text in firefox and other browsers that don't support the html5 tag option?
This works in Chrome and any other browser that supports placeholder text in HTML5

```<code><input id="name" name="name"  type="text" placeholder="Please enter your name..." required /> <br />
</code>```

But, it doesn't work in 3.5 and earlier of Firefox, and obviously IE8, and possibly other browsers.

How do I achieve the same thing (preferably in HTML/CSS - if not I am open to suggestions), to support all the older browsers? If not every single browser, at least Firefox and IE.

Safari and Chrome already support it (or the latest versions anyway).

Thanks.

答:
Here is the simplest solution that I found working everywhere:

```<code><input id="search"
   name="search"
   onblur="if (this.value == '') {this.value = 'PLACEHOLDER';}"
   onfocus="if (this.value == 'PLACEHOLDER') {this.value = '';}"
/>
</code>```

Replace PLACEHOLDER with your own.

At the moment, FF3 does not yet support the "placeholder" attribute of the "input" element. FF4, Opera11 and Chrome8 support it partially, i.e. they render the placeholder text in the field, but do not delete it when the user focuses in the field, which is worse that not supporting it at all.

ContentLicense: CC BY-SA 2.5

Body:
This works in Chrome and any other browser that supports placeholder text in HTML5

<input id="name" name="name"  type="text" placeholder="Please enter your name..." required />

But, it doesn't work in 3.5 and earlier of Firefox, and obviously IE8, and possibly other browsers.

How do I achieve the same thing (preferably in HTML/CSS - if not I am open to suggestions), to support all the older browsers? If not every single browser, at least Firefox and IE.

Safari and Chrome already support it (or the latest versions anyway).

Thanks.

Body:
Here is the simplest solution that I found working everywhere:

<input id="search"
   name="search"
   onblur="if (this.value == '') {this.value = 'PLACEHOLDER';}"
   onfocus="if (this.value == 'PLACEHOLDER') {this.value = '';}"
/>

Replace PLACEHOLDER with your own.

At the moment, FF3 does not yet support the "placeholder" attribute of the "input" element. FF4, Opera11 and Chrome8 support it partially, i.e. they render the placeholder text in the field, but do not delete it when the user focuses in the field, which is worse that not supporting it at all.


问:
After upgrade from Clarion 9 to Clarion 10 an error acquiring
After upgrade app from  Clarion 9.1 to Clarion 10 and after first build an error acquiring.

Error: Unresolved External SHGetFolderPathA in EFOCUS.obj. I include efocus.clw in solution. Efocus.clw and efocus.inc are in C10 folder.

Help me please

答:
I dont use the enhanced focus feature, but a couple of things might help:

SHGetFolderPathA is deprecated but should still be around since its in Shell32.dll. Its possible SV eliminated it from their lib in lieu of the replacement call (see https://msdn.microsoft.com/en-us/library/windows/desktop/bb762181(v=vs.85).aspx ), but I doubt it. Even so, you could make your own lib using the DLL and Libmaker.exe (which is shipped in \c10\bin).

It may be simpler than this. Delete the clw and obj from your app folder (or sub-folder where the .RED directs them) and recompile.

ContentLicense: CC BY-SA 3.0


问:
Correct format for input data on CloudML
I'm trying to send a job up to my object detection model on CloudML to get predictions. I'm following the guide at https://cloud.google.com/ml-engine/docs/online-predict but I'm getting an error when submitting the request:

RuntimeError: Prediction failed: Error processing input: Expected uint8, got '\xf6>\x00\x01\x04\xa4d\x94...(more bytes)...\x00\x10\x10\x10\x04\x80\xd9' of type 'str' instead.

This is my code:

```<code>img = base64.b64encode(open("file.jpg", "rb").read()).decode('utf-8')
json = {"b64": img}
result = predict_json(project, model, json, "v1")
</code>```

答: My fault, I forgot to add --input_type encoded_image_string_tensor when I exported the graph.

Body:
I'm trying to send a job up to my object detection model on CloudML to get predictions. I'm following the guide at https://cloud.google.com/ml-engine/docs/online-predict but I'm getting an error when submitting the request:

RuntimeError: Prediction failed: Error processing input: Expected uint8, got '\xf6>\x00\x01\x04\xa4d\x94...(more bytes)...\x00\x10\x10\x10\x04\x80\xd9' of type 'str' instead.

This is my code:

img = base64.b64encode(open("file.jpg", "rb").read()).decode('utf-8')
json = {"b64": img}
result = predict_json(project, model, json, "v1")


问:
How to find the sum of the minor diagonal in a matrix (JAVA)
I am trying to find the sum of the minor diagonal in a matrix, but my code only shows the first number in the matrix. Is there any way to fix it?</p>

```<code>//sum of minor diagonal in matrix
public static int minorDiagonal(int[][] array){
    int k = 0, j = 0;
    int sumMinD = 0;
     k = array.length - 1;
    for ( j = 0, k = 0; j <= array.length && k >= 0; j++, k--) {
            sumMinD += array[j][k];

    }
return sumMinD;
}
</code>```

答:
Consider you had following matrix:

1 2 5

4 1 3

0 9 4

Minor diagonal consists of 0 + 1 + 5 = 6

The elements of minor diagonal are at positions: [2][0], [1][1] and [0][2]

Your code is:

```<code>for ( j = 0, k = 0; j <= array.length && k >= 0; j++, k--) {
        sumMinD += array[j][k];
}
</code>```

Your k is initialized to zero and you keep decreasing it, you will get ArrayIndexOutOfBounds exception, change your j to yourMatrix.length-1 make j decrease on every iteration j-- and k increase k++, and you should have it fixed.

Your final working loop would be:

```<code>for ( j = array.length-1, k = 0; j >= 0; j--, k++) {
        sumMinD += array[j][k];
}
</code>```

Body:
I am trying to find the sum of the minor diagonal in a matrix, but my code only shows the first number in the matrix. Is there any way to fix it?

//sum of minor diagonal in matrix
public static int minorDiagonal(int[][] array){
    int k = 0, j = 0;
    int sumMinD = 0;
     k = array.length - 1;
    for ( j = 0, k = 0; j <= array.length && k >= 0; j++, k--) {
            sumMinD += array[j][k];

    }
return sumMinD;
}

Body:
Consider you had following matrix:

1 2 5

4 1 3

0 9 4

Minor diagonal consists of 0 + 1 + 5 = 6

The elements of minor diagonal are at positions: [2][0], [1][1] and [0][2]

Your code is:

for ( j = 0, k = 0; j <= array.length && k >= 0; j++, k--) {
        sumMinD += array[j][k];
}

Your k is initialized to zero and you keep decreasing it, you will get ArrayIndexOutOfBounds exception, change your j to yourMatrix.length-1 make j decrease on every iteration j-- and k increase k++, and you should have it fixed.

Your final working loop would be:

for ( j = array.length-1, k = 0; j >= 0; j--, k++) {
        sumMinD += array[j][k];
}


问:
Taking care of daylight saving time when converting timezone
I have a Redshift data table where all time values are stored in CST and I convert the time values to the respective timezone based on the zip code (location).

While I do that, I understand that all time values are in Standard time and hence my function usage is

```<code>CASE WHEN **** convert_timezone('CST', 'EST', time_column)
     WHEN **** convert_timezone('CST', 'MST', time_column)
....
END
</code>```

This may not be applicable once we enter into Daylight Savings time. How can I take care of this such that I do not modify the SQL query again in 2018 March and in future?

答:
Don't use time zone abbreviations.  The are somewhat ambiguous, and can only refer to one aspect of the time zone. Instead, use a full IANA time zone identifier, such as America/Chicago for US Central time.

This is explained well in the Redshift docs:

Using a Time Zone Name

If you specify a time zone using a time zone name, CONVERT_TIMEZONE automatically adjusts for Daylight Saving Time (DST), or any other local seasonal protocol, such as Summer Time, Standard Time, or Winter Time, that is in force for that time zone during the date and time specified by 'timestamp'. For example, 'Europe/London' represents UTC in the winter and UTC+1 in the summer.

As far as the "...based on the zip code" part of your question, understand that not every ZIP code is locality-based.  There are also technical assignments, overseas APO/FPO addresses, US territories, and other edge cases.  Additionally, some zip codes may straddle more than one time zone.

A better approach, when possible, is to:

Get an approximation of latitude/longitude coordinates - using a variety of techniques depending on your source data. For example, geocoding APIs can take a street address and give a lat/lon.

Then determine the time zone identifier for that location, using one of the techniques listed here.

Body:
I have a Redshift data table where all time values are stored in CST and I convert the time values to the respective timezone based on the zip code (location).

While I do that, I understand that all time values are in Standard time and hence my function usage is

CASE WHEN **** convert_timezone('CST', 'EST', time_column)
     WHEN **** convert_timezone('CST', 'MST', time_column)
....
END

This may not be applicable once we enter into Daylight Savings time. How can I take care of this such that I do not modify the SQL query again in 2018 March and in future?


答:
The minor diagonal of a matrix, like the major diagonal, runs across the center diagonal.  But the minor diagonal runs from the upper right to the lower left.  Assuming you had a 4x4 matrix, you want to sum the following four points:

```<code>(0, 3)
(1, 2)
(2, 1)
(3, 0)
</code>```

Translating this into a loop gives us the following:

```<code>int sumMinD = 0;
int k = Math.min(array.length, array[0].length);
for (int i=0; i < k; ++i) {
    sumMinD += array[i][k - 1 - i];
}
</code>```

I use Math.min to find the smaller of the row or column length when figuring out how long the minor diagonal is.  This covers the edge case of a rectangular matrix where the height and width may not be equal.

Demo

Title: How to find the sum of the minor diagonal in a matrix (JAVA)

Body:
The minor diagonal of a matrix, like the major diagonal, runs across the center diagonal.  But the minor diagonal runs from the upper right to the lower left.  Assuming you had a 4x4 matrix, you want to sum the following four points:

(0, 3)
(1, 2)
(2, 1)
(3, 0)

Translating this into a loop gives us the following:

int sumMinD = 0;
int k = Math.min(array.length, array[0].length);
for (int i=0; i < k; ++i) {
    sumMinD += array[i][k - 1 - i];
}

I use Math.min to find the smaller of the row or column length when figuring out how long the minor diagonal is.  This covers the edge case of a rectangular matrix where the height and width may not be equal.

Demo


问:
How to get historical weather data (Temperature) on hourly basis for Chicago, IL
I need the historical weather data (Temperature) on hourly basis for Chicago, IL (Zip code 60603)

Basically i need it for the month of June and July 2017 either hourly or in 15 mins interval.

I have searched on NOAA, Weather underground etc. But haven't found anything relevant to my use case. Tried my hands on scraping using R and Python, but no luck.

Here is a snippet for the same

R :

```<code>library(httr)
library(XML)
url <- "http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php"
response <- GET(url,query=list(zipCodeList="10001",
                           product="time-series",
                           begin=format(Sys.Date(),"%Y-%m-%d"),
                           Unit="e",
                           temp="temp",rh="rh",wspd="wspd"))
doc   <- content(response,type="text/xml", encoding = "UTF-8")   # XML document with the data
# extract the date-times
dates <- doc["//time-layout/start-valid-time"]
dates <- as.POSIXct(xmlSApply(dates,xmlValue),format="%Y-%m-%dT%H:%M:%S")
# extract the actual data
data   <- doc["//parameters/*"]
data   <- sapply(data,function(d)removeChildren(d,kids=list("name")))
result <- do.call(data.frame,lapply(data,function(d)xmlSApply(d,xmlValue)))
colnames(result) <- sapply(data,xmlName)
# combine into a data frame
result <- data.frame(dates,result)
head(result)
</code>```

Error :

```<code>Error in UseMethod("xmlSApply") :
no applicable method for 'xmlSApply' applied to an object of class "list"
</code>```

Python :

```<code>from pydap.client import open_url

# setup the connection
url = 'http://nomads.ncdc.noaa.gov/dods/NCEP_NARR_DAILY/197901/197901/narr-
a_221_197901dd_hh00_000'
modelconn = open_url(url)
tmp2m = modelconn['tmp2m']

# grab the data
lat_index = 200    # you could tie this to tmp2m.lat[:]
lon_index = 200    # you could tie this to tmp2m.lon[:]
print(tmp2m.array[:,lat_index,lon_index] )
</code>```

Error :

```<code> HTTPError: 503 Service Temporarily Unavailable
</code>```

Any other solution is appreciated either in R or Python or any related online dataset link

答:
Just to provide a python solution for whoever comes by this question looking for one. This will (per the post) go through each day in June and July 2017 getting all observations for a given location. This does not restrict to 15 minute or hourly but does provide all data observed on the day. Additional parsing of observation time per observation is necessary but this is a start.

WunderWeather

pip install WunderWeather
pip install arrow

```<code>import arrow # learn more: https://python.org/pypi/arrow
from WunderWeather import weather # learn more: https://python.org/pypi/WunderWeather

api_key = ''
extractor = weather.Extract(api_key)
zip = '02481'

begin_date = arrow.get("201706","YYYYMM")
end_date = arrow.get("201708","YYYYMM").shift(days=-1)
for date in arrow.Arrow.range('day',begin_date,end_date):
  # get date object for feature
  # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.weather.Extract.date
  date_weather = extractor.date(zip,date.format('YYYYMMDD'))

  # use shortcut to get observations and data
  # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.date.Observation
  for observation in date_weather.observations:
    print("Date:",observation.date_pretty)
    print("Temp:",observation.temp_f)
</code>```

Body:
I need the historical weather data (Temperature) on hourly basis for Chicago, IL (Zip code 60603)

Basically i need it for the month of June and July 2017 either hourly or in 15 mins interval.

I have searched on NOAA, Weather underground etc. But haven't found anything relevant to my use case. Tried my hands on scraping using R and Python, but no luck.

Here is a snippet for the same

R :

library(httr)
library(XML)
url <- "http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php"
response <- GET(url,query=list(zipCodeList="10001",
                           product="time-series",
                           begin=format(Sys.Date(),"%Y-%m-%d"),
                           Unit="e",
                           temp="temp",rh="rh",wspd="wspd"))
doc   <- content(response,type="text/xml", encoding = "UTF-8")   # XML document with the data
# extract the date-times
dates <- doc["//time-layout/start-valid-time"]
dates <- as.POSIXct(xmlSApply(dates,xmlValue),format="%Y-%m-%dT%H:%M:%S")
# extract the actual data
data   <- doc["//parameters/*"]
data   <- sapply(data,function(d)removeChildren(d,kids=list("name")))
result <- do.call(data.frame,lapply(data,function(d)xmlSApply(d,xmlValue)))
colnames(result) <- sapply(data,xmlName)
# combine into a data frame
result <- data.frame(dates,result)
head(result)

Error :

Error in UseMethod("xmlSApply") :
no applicable method for 'xmlSApply' applied to an object of class "list"

Python :

from pydap.client import open_url

# setup the connection
url = 'http://nomads.ncdc.noaa.gov/dods/NCEP_NARR_DAILY/197901/197901/narr-
a_221_197901dd_hh00_000'
modelconn = open_url(url)
tmp2m = modelconn['tmp2m']

# grab the data
lat_index = 200    # you could tie this to tmp2m.lat[:]
lon_index = 200    # you could tie this to tmp2m.lon[:]
print(tmp2m.array[:,lat_index,lon_index] )

Error :

 HTTPError: 503 Service Temporarily Unavailable

Any other solution is appreciated either in R or Python or any related online dataset link

Body:
Just to provide a python solution for whoever comes by this question looking for one. This will (per the post) go through each day in June and July 2017 getting all observations for a given location. This does not restrict to 15 minute or hourly but does provide all data observed on the day. Additional parsing of observation time per observation is necessary but this is a start.

WunderWeather

pip install WunderWeather
pip install arrow

import arrow # learn more: https://python.org/pypi/arrow
from WunderWeather import weather # learn more: https://python.org/pypi/WunderWeather

api_key = ''
extractor = weather.Extract(api_key)
zip = '02481'

begin_date = arrow.get("201706","YYYYMM")
end_date = arrow.get("201708","YYYYMM").shift(days=-1)
for date in arrow.Arrow.range('day',begin_date,end_date):
  # get date object for feature
  # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.weather.Extract.date
  date_weather = extractor.date(zip,date.format('YYYYMMDD'))

  # use shortcut to get observations and data
  # http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.date.Observation
  for observation in date_weather.observations:
    print("Date:",observation.date_pretty)
    print("Temp:",observation.temp_f)


问:
pyspark throws TypeError: textFile() missing 1 required positional argument: 'name'
I googled this problem, yet no direct answer related to spark-2.2.0-bin-hadoop2.7. I am trying to read a text file from local directory, but I always get TypeError that name argument is missing. This is the code in jupyter notebook with Python3:

```<code>from pyspark import SparkContext as sc
data = sc.textFile("/home/bigdata/test.txt")
</code>```

When I run the cell, I get this error:

```<code>TypeError                                 Traceback (most recent call last)
  <ipython-input-7-2a326e5b8f8c> in <module>()
  1 from pyspark import SparkContext as sc
  ----> 2 data = sc.textFile("/home/bigdata/test.txt")
  TypeError: textFile() missing 1 required positional argument: 'name'
</code>```

Your help is appreciated.

答:
You are calling the textFile() instance method

```<code>def textFile(self, name, minPartitions=None, use_unicode=True):
</code>```

like it was a static method which results into "/home/bigdata/test.txt" string being used for the self value leaving name argument not specified, hence the error.

Create an instance of the SparkContext class:

```<code>from pyspark import SparkConf
from pyspark.context import SparkContext

sc = SparkContext.getOrCreate(SparkConf().setMaster("local[*]"))
data = sc.textFile("/home/bigdata/test.txt")
</code>```

Body:
I googled this problem, yet no direct answer related to spark-2.2.0-bin-hadoop2.7. I am trying to read a text file from local directory, but I always get TypeError that name argument is missing. This is the code in jupyter notebook with Python3:

from pyspark import SparkContext as sc
data = sc.textFile("/home/bigdata/test.txt")

When I run the cell, I get this error:

TypeError                                 Traceback (most recent call last)
  <ipython-input-7-2a326e5b8f8c> in <module>()
  1 from pyspark import SparkContext as sc
  ----> 2 data = sc.textFile("/home/bigdata/test.txt")
  TypeError: textFile() missing 1 required positional argument: 'name'

Your help is appreciated.

Body:
You are calling the textFile() instance method

def textFile(self, name, minPartitions=None, use_unicode=True):

like it was a static method which results into "/home/bigdata/test.txt" string being used for the self value leaving name argument not specified, hence the error.

Create an instance of the SparkContext class:

from pyspark import SparkConf
from pyspark.context import SparkContext

sc = SparkContext.getOrCreate(SparkConf().setMaster("local[*]"))
data = sc.textFile("/home/bigdata/test.txt")


问:
a simple regexp validator
How do a I create a validator, which has these simple rules. An expression is valid if

it must start with a letter

it must end with a letter

it can contain a dash (minus sign), but not at start or end of the expression

答:
```<code>/^[A-Za-z]+(-?[A-Za-z]+)?$/
</code>```

this seems like what you want.

^ = match the start position

^[A-Za-z]+ = start position is followed by any at least one or more letters.

-? = is there zero or one hyphens (use "*" if there can be multiple hyphens in a row).

[A-Za-z]+ = hyphen is followed by one or more letters

(-?[A-Za-z]+)? = for the case that there is a single letter.

$= match the end position in the string.

OwnerDisplayName: new-to-rails

Title: a simple regexp validator

Body:
/^[A-Za-z]+(-?[A-Za-z]+)?$/

this seems like what you want.

^ = match the start position

^[A-Za-z]+ = start position is followed by any at least one or more letters.

-? = is there zero or one hyphens (use "*" if there can be multiple hyphens in a row).

[A-Za-z]+ = hyphen is followed by one or more letters

(-?[A-Za-z]+)? = for the case that there is a single letter.

$= match the end position in the string.

OwnerDisplayName: gnomed

LastEditorDisplayName: gnomed


问:
0x80071C57 Error Connecting to Service Fabric Cluster
I'm trying to deploy my application or connect to a Service Fabric cluster, but I get the following error: Could Not connect to cluster: System.Fabric.FabricException: An error occurred during this operation.  Please check the trace logs for more details. ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80071C57

答: This occurred because I did not have the correct client certificate installed on my dev box. Once I installed it, I was able to connect to the cluster in PowerShell and deploy apps in Visual Studio.</p>


问:
how to disconnect the webcam in webcam.js?
Does anyone know how can I disconnect the webcam in webcam.js?

I'm using Webcam.attach(webcam.js) to connect to the webcam. However, I try to use webcam.reset() to disconnect the webcam and it's seem not working. The webcam is still on and the tab of the browser show webcam is connected (red dot showing on the tab).

Does anyone know how can I disconnect it in webcam.js?

答:
I've tried Webcam.reset( '#my_camera' ) with no problem.

Tested on: https://pixlcore.com/demos/webcamjs/demos/basic.html

Did you check for console errors?


问:
Clean up N+1 queries in Rails relations
I have a GET method that gets called when a calendar page loads:

```<code>def get_events
  @events.select {|event| event.task.present? }.each do |event|
    target_contact = event.task.primary_contact
    owner = event.task.task_followers.where(owner: true).first.follower
    events << { id: event.id, title: event.title, contact: target_contact, owner: owner }
  end
  render json: events.to_json
end
</code>```

I have millions of events and I am seeing a ton of N+1 queries, as it loads individual events and relations. I know Rails provides an includes method to eliminate such queries. But the includes method just takes symbol arguments:

```<code>Event.includes(:task)
</code>```

And I do not think it is possible to build my json response using includes method.

Here are the relations:

```<code>class Event < ActiveRecord::Base
  belongs_to :task
end

class Task < ActiveRecord::Base
  has_many :task_followers, dependent: :destroy
end
</code>```

Any ideas?

答:
You can load nested associations like this:</p>

```<code>Event.includes(task: [task_followers: :follower])
</code>```

Title: Clean up N+1 queries in Rails relations

Body:
I have a GET method that gets called when a calendar page loads:

def get_events
  @events.select {|event| event.task.present? }.each do |event|
    target_contact = event.task.primary_contact
    owner = event.task.task_followers.where(owner: true).first.follower
    events << { id: event.id, title: event.title, contact: target_contact, owner: owner }
  end
  render json: events.to_json
end

I have millions of events and I am seeing a ton of N+1 queries, as it loads individual events and relations. I know Rails provides an includes method to eliminate such queries. But the includes method just takes symbol arguments:

Event.includes(:task)

And I do not think it is possible to build my json response using includes method.

Here are the relations:

class Event < ActiveRecord::Base
  belongs_to :task
end

class Task < ActiveRecord::Base
  has_many :task_followers, dependent: :destroy
end

Any ideas?

Body:
You can load nested associations like this:

Event.includes(task: [task_followers: :follower])


问:
Unable to locate new folder on mapped drive
I had create a macro that auto upload the current workbook to sharepoint apon triggering the macro.
The macro was successful, uploading the file to sharepoint folder that was mapped to the drive.

However, the macro only success if the SharePoint folder is created way before time. Eg. maybe 1 day in advanced.

If the folder is newly created, it would not be able to upload to the folder as Sorry there's no such folder.

If I go to the drive on window explorer, I would be able to see the newly created folder.
I also tried copy the file path shown on the msg box and type in window explorer, it directs me to the folder with no issues.

Is there a way I can speed up the process and why does this happens?

Macro IF statement

```<code>If Dir(spPath) = "" Then
    MsgBox "Sorry there's no such folder. Folder Path: " & vbNewLine & vbNewLine & spPath & ""
    Call UnMapDrive(drive)
    Exit Sub
    ElseIf Not Dir(spPath & fileName) = "" Then
    MsgBox("File Already Exist!!!")
    ElseIf Dir(spPath & fileName) = "" Then
    FolderCreate (path)
    ThisWorkbook.SaveCopyAs copyPath & fileName
    Call FileCopy(path & fileName, spPath & fileName)
    MsgBox "File Successfully uploaded to SharePoint."
    Kill (path) & "*.*"
    RmDir path
    Call UnMapDrive(drive)
End If
</code>```

答:
Change

```<code>If Dir(spPath) = "" Then
</code>```

to

```<code>If Dir(spPath, vbDirectory) = "" Then
</code>```

Until someone puts a file into the directory (perhaps a day after the directory is created), your code is not seeing any files there (because there aren't any).  By adding vbDirectory it will look for the directory itself.

Body:
I had create a macro that auto upload the current workbook to sharepoint apon triggering the macro.
The macro was successful, uploading the file to sharepoint folder that was mapped to the drive.

However, the macro only success if the SharePoint folder is created way before time. Eg. maybe 1 day in advanced.

If the folder is newly created, it would not be able to upload to the folder as Sorry there's no such folder.

If I go to the drive on window explorer, I would be able to see the newly created folder.
I also tried copy the file path shown on the msg box and type in window explorer, it directs me to the folder with no issues.

Is there a way I can speed up the process and why does this happens?

Macro IF statement

If Dir(spPath) = "" Then
    MsgBox "Sorry there's no such folder. Folder Path: " & vbNewLine & vbNewLine & spPath & ""
    Call UnMapDrive(drive)
    Exit Sub
    ElseIf Not Dir(spPath & fileName) = "" Then
    MsgBox("File Already Exist!!!")
    ElseIf Dir(spPath & fileName) = "" Then
    FolderCreate (path)
    ThisWorkbook.SaveCopyAs copyPath & fileName
    Call FileCopy(path & fileName, spPath & fileName)
    MsgBox "File Successfully uploaded to SharePoint."
    Kill (path) & "*.*"
    RmDir path
    Call UnMapDrive(drive)
End If

Body:
Change

If Dir(spPath) = "" Then

to

If Dir(spPath, vbDirectory) = "" Then

Until someone puts a file into the directory (perhaps a day after the directory is created), your code is not seeing any files there (because there aren't any).  By adding vbDirectory it will look for the directory itself.


问:
VideoCapture Does Not Work in Anaconda
I am using ubuntu 14.04, and have anaconda python installed. I used conda install opencv and conda install cv2 to install opencv. However I am unable to use the VideoCapture at all (I need to process videos frames by frames). I need to use anaconda for the rest of the project.

Here is my code:

```<code>import cv2
import os
capture = cv2.VideoCapture('/home/Downloads/data/zfH2XdRcH14.mp4')
while not capture.isOpened():
    print 'noob'
while True:
    ret, frame = capture.read()
    cv2.imwrite('~/Downloads/data/pic.png',frame)
    cv2.imshow('Video', frame)
    count += 1
    print count
</code>```

The code keeps printing noob. I have checked the location multiple times and it is correct. I have no clue what the issue is and I have been stuck on this for hours.

答:
ffmpeg is not present in default conda channel.

You need to download opencv from conda-forge channel which contains latest and additional packages and dependencies for video processing. Try the following:

```<code>conda install -c conda-forge ffmpeg
conda install -c conda-forge opencv
</code>```

Here -c tells which channel to use. In our case we need 'conda-forge'.

Title: VideoCapture Does Not Work in Anaconda

Body:
I am using ubuntu 14.04, and have anaconda python installed. I used conda install opencv and conda install cv2 to install opencv. However I am unable to use the VideoCapture at all (I need to process videos frames by frames). I need to use anaconda for the rest of the project.

Here is my code:

import cv2
import os
capture = cv2.VideoCapture('/home/Downloads/data/zfH2XdRcH14.mp4')
while not capture.isOpened():
    print 'noob'
while True:
    ret, frame = capture.read()
    cv2.imwrite('~/Downloads/data/pic.png',frame)
    cv2.imshow('Video', frame)
    count += 1
    print count

The code keeps printing noob. I have checked the location multiple times and it is correct. I have no clue what the issue is and I have been stuck on this for hours.

Body:
ffmpeg is not present in default conda channel.

You need to download opencv from conda-forge channel which contains latest and additional packages and dependencies for video processing. Try the following:

conda install -c conda-forge ffmpeg
conda install -c conda-forge opencv

Here -c tells which channel to use. In our case we need 'conda-forge'.

ContentLicense: CC BY-SA 4.0


问:
Mysql database not showing the current date for NOW() function
I am using the NOW() with insert query so that I can get the currentTime when the query is triggered. But I get a time of 12 hours back in the database. How can I get the current Time ? Please help.</p>

答:
Perform this query right after you've been connected to the database:

```<code>SET time_zone = '+05:30';
</code>```

Where it is your valid timezone offset in the quotes.

Body:
Perform this query right after you've been connected to the database:

SET time_zone = '+05:30';

Where it is your valid timezone offset in the quotes.


问:
Drawing QR code with Qt in native C/C++
I am successfully drawing and displaying the QrCode on a QLabel, but it's not recognised when I scan it. Here is the code I used - I made a small class with a static function:

```<code>void QrCodeDrawer::paintQR(QPainter &painter, const QSize sz, const QString &data, QColor fg)
{
    char *str=data.toUtf8().data();
    // NOTE: At this point you will use the API to get the encoding and format you want, instead of my hardcoded stuff:
    QrCode qr = QrCode::encodeText(str, QrCode::Ecc::HIGH);
    const int s=qr.size>0?qr.size:1;
    const double w=sz.width();
    const double h=sz.height();
    const double aspect=w/h;
    const double size=((aspect>1.0)?h:w);
    const double scale=size/(s+2);
    // NOTE: For performance reasons my implementation only draws the foreground parts in supplied color.
    // It expects background to be prepared already (in white or whatever is preferred).
    painter.setPen(Qt::NoPen);
    painter.setBrush(fg);
    for(int y=0; y<s; y++) {
        for(int x=0; x<s; x++) {
            const int color=qr.getModule(x, y);  // 0 for white, 1 for black
            if(0x0!=color) {
                const double rx1=(x+1)*scale, ry1=(y+1)*scale;
                QRectF r(rx1, ry1, scale, scale);
                painter.drawRects(&r,1);
            }
        }
    }
}
</code>```

And called it here:

```<code>QPixmap map(400,400);
QPainter painter(&map);
QrCodeDrawer::paintQR(painter,QSize(400,400),"Hello World", QColor("white"));
ui.qrCode->setPixmap(map);
</code>```

I gave "Hello World" as input string and here is the code I get:

I got the source code from here.

答:
I used the same sample but had problems with garbage QR codes until I realised str can be a dangling pointer. I changed my code to this and it worked fine:

```<code>void QrCodeDrawer::paintQR(QPainter &painter, const QSize sz, const QString &data, QColor fg)
{
    // NOTE: At this point you will use the API to get the encoding and format you want, instead of my hardcoded stuff:
    QrCode qr = QrCode::encodeText(data.toUtf8().constData(), QrCode::Ecc::HIGH);
</code>```

Title: Drawing QR code with Qt in native C/C++

Body:
I am successfully drawing and displaying the QrCode on a QLabel, but it's not recognised when I scan it. Here is the code I used - I made a small class with a static function:

void QrCodeDrawer::paintQR(QPainter &painter, const QSize sz, const QString &data, QColor fg)
{
    char *str=data.toUtf8().data();
    // NOTE: At this point you will use the API to get the encoding and format you want, instead of my hardcoded stuff:
    QrCode qr = QrCode::encodeText(str, QrCode::Ecc::HIGH);
    const int s=qr.size>0?qr.size:1;
    const double w=sz.width();
    const double h=sz.height();
    const double aspect=w/h;
    const double size=((aspect>1.0)?h:w);
    const double scale=size/(s+2);
    // NOTE: For performance reasons my implementation only draws the foreground parts in supplied color.
    // It expects background to be prepared already (in white or whatever is preferred).
    painter.setPen(Qt::NoPen);
    painter.setBrush(fg);
    for(int y=0; y<s; y++) {
        for(int x=0; x<s; x++) {
            const int color=qr.getModule(x, y);  // 0 for white, 1 for black
            if(0x0!=color) {
                const double rx1=(x+1)*scale, ry1=(y+1)*scale;
                QRectF r(rx1, ry1, scale, scale);
                painter.drawRects(&r,1);
            }
        }
    }
}

And called it here:

QPixmap map(400,400);
QPainter painter(&map);
QrCodeDrawer::paintQR(painter,QSize(400,400),"Hello World", QColor("white"));
ui.qrCode->setPixmap(map);

I gave "Hello World" as input string and here is the code I get:

I got the source code from here.

Body:
I used the same sample but had problems with garbage QR codes until I realised str can be a dangling pointer. I changed my code to this and it worked fine:

void QrCodeDrawer::paintQR(QPainter &painter, const QSize sz, const QString &data, QColor fg)
{
    // NOTE: At this point you will use the API to get the encoding and format you want, instead of my hardcoded stuff:
    QrCode qr = QrCode::encodeText(data.toUtf8().constData(), QrCode::Ecc::HIGH);


问:
Error while integrating spring with hibernate
I'm trying to integrate spring with hibernate but i get this error:

[2017-10-06 05:26:14,475] Artifact spring-mvc-hibernate-example:war: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDaoImp': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.boraji.tutorial.spring.config.AppConfig: Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution. Please see server.log for more details.

Here are some files:

pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.boraji.tutorial.spring</groupId>
  <artifactId>spring-mvc-hibernate-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <properties>
    <failOnMissingWebXml>false</failOnMissingWebXml>
  </properties>
  <dependencies>
    <!-- Spring MVC Dependency -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>

    <!-- Spring ORM -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>

    <!-- Mysql Connector -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.6</version>
    </dependency>

    <!-- Hibernate ORM -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.10.Final</version>
    </dependency>

    <!-- Hibernate-C3P0 Integration -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-c3p0</artifactId>
      <version>5.2.10.Final</version>
    </dependency>

    <!-- c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>

    <!-- Hibernate Validator -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>5.4.1.Final</version>
    </dependency>

    <!-- JSTL Dependency -->
    <dependency>
      <groupId>javax.servlet.jsp.jstl</groupId>
      <artifactId>javax.servlet.jsp.jstl-api</artifactId>
      <version>1.2.1</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!-- Servlet Dependency -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- JSP Dependency -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate</artifactId>
      <version>3.5.4-Final</version>
    </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.8.0-alpha2</version>
      </dependency>
  </dependencies>

</project>
</code>```

Initializer:

```<code>public class MyWebAppInitializer
      extends AbstractAnnotationConfigDispatcherServletInitializer {

   @Override
   protected Class<?>[] getRootConfigClasses() {
      return new Class[] { AppConfig.class };
   }

   @Override
   protected Class<?>[] getServletConfigClasses() {
      return new Class[] { WebConfig.class };
   }

   @Override
   protected String[] getServletMappings() {
      return new String[] { "/" };
   }
}
</code>```

application config:

```<code>@Configuration
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.boraji.tutorial.spring.dao"),
      @ComponentScan("com.boraji.tutorial.spring.service") })
public class AppConfig {

   @Autowired
   private Environment env;

   @Bean
   public LocalSessionFactoryBean getSessionFactory() {
      LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();

      Properties props = new Properties();
      // Setting JDBC properties
      props.put(DRIVER, env.getProperty("mysql.driver"));
      props.put(URL, env.getProperty("mysql.url"));
      props.put(USER, env.getProperty("mysql.user"));
      props.put(PASS, env.getProperty("mysql.password"));

      // Setting Hibernate properties
      props.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
      props.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));
      props.put(DIALECT, env.getProperty("hibernate.dialect"));

      // Setting C3P0 properties
      props.put(C3P0_MIN_SIZE,
            env.getProperty("hibernate.c3p0.min_size"));
      props.put(C3P0_MAX_SIZE,
            env.getProperty("hibernate.c3p0.max_size"));
      props.put(C3P0_ACQUIRE_INCREMENT,
            env.getProperty("hibernate.c3p0.acquire_increment"));
      props.put(C3P0_TIMEOUT,
            env.getProperty("hibernate.c3p0.timeout"));
      props.put(C3P0_MAX_STATEMENTS,
            env.getProperty("hibernate.c3p0.max_statements"));

      factoryBean.setHibernateProperties(props);
      factoryBean.setAnnotatedClasses(User.class);
      return factoryBean;
   }

   @Bean
   public HibernateTransactionManager getTransactionManager() {
      HibernateTransactionManager transactionManager = new HibernateTransactionManager();
      transactionManager.setSessionFactory(getSessionFactory().getObject());
      return transactionManager;
   }
}
</code>```

db.properties:

```<code># MySQL properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost/test
mysql.user=root
mysql.password=root

# Hibernate propert[2017-10-06 05:26:14,475] Artifact spring-mvc-hibernate-example:war: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDaoImp': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.boraji.tutorial.spring.config.AppConfig: Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution. Please see server.log for more details.ies
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQLDialect

#C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150
</code>```

UserDao:

```<code>@Repository
public class UserDaoImp implements UserDao {

   @Autowired
   private SessionFactory sessionFactory;

   public void save(User user) {
      sessionFactory.getCurrentSession().save(user);
   }

   public List<User> list() {
      @SuppressWarnings("unchecked")
      TypedQuery<User> query = sessionFactory.getCurrentSession().createQuery("from User");
      return query.getResultList();
   }

}
</code>```

I saw lots of similar problems here but it didn't help. What could go wrong in my application?

答:
DRIVER, URL, USER and PASS are all static fields. Make sure you imported all of them. Plus, make sure you imported the spring Environment (not the hibernate).</p>

```<code>import static org.hibernate.cfg.Environment.*;
import org.springframework.core.env.Environment;
</code>```

Body:
I'm trying to integrate spring with hibernate but i get this error:

[2017-10-06 05:26:14,475] Artifact spring-mvc-hibernate-example:war: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDaoImp': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.boraji.tutorial.spring.config.AppConfig: Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution. Please see server.log for more details.

Here are some files:

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.boraji.tutorial.spring</groupId>
  <artifactId>spring-mvc-hibernate-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <properties>
    <failOnMissingWebXml>false</failOnMissingWebXml>
  </properties>
  <dependencies>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.6</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.10.Final</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-c3p0</artifactId>
      <version>5.2.10.Final</version>
    </dependency>

    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>5.4.1.Final</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp.jstl</groupId>
      <artifactId>javax.servlet.jsp.jstl-api</artifactId>
      <version>1.2.1</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate</artifactId>
      <version>3.5.4-Final</version>
    </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.8.0-alpha2</version>
      </dependency>
  </dependencies>

</project>

Initializer:

public class MyWebAppInitializer
      extends AbstractAnnotationConfigDispatcherServletInitializer {

   @Override
   protected Class<?>[] getRootConfigClasses() {
      return new Class[] { AppConfig.class };
   }

   @Override
   protected Class<?>[] getServletConfigClasses() {
      return new Class[] { WebConfig.class };
   }

   @Override
   protected String[] getServletMappings() {
      return new String[] { "/" };
   }
}

application config:

@Configuration
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.boraji.tutorial.spring.dao"),
      @ComponentScan("com.boraji.tutorial.spring.service") })
public class AppConfig {

   @Autowired
   private Environment env;

   @Bean
   public LocalSessionFactoryBean getSessionFactory() {
      LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();

      Properties props = new Properties();
      // Setting JDBC properties
      props.put(DRIVER, env.getProperty("mysql.driver"));
      props.put(URL, env.getProperty("mysql.url"));
      props.put(USER, env.getProperty("mysql.user"));
      props.put(PASS, env.getProperty("mysql.password"));

      // Setting Hibernate properties
      props.put(SHOW_SQL, env.getProperty("hibernate.show_sql"));
      props.put(HBM2DDL_AUTO, env.getProperty("hibernate.hbm2ddl.auto"));
      props.put(DIALECT, env.getProperty("hibernate.dialect"));

      // Setting C3P0 properties
      props.put(C3P0_MIN_SIZE,
            env.getProperty("hibernate.c3p0.min_size"));
      props.put(C3P0_MAX_SIZE,
            env.getProperty("hibernate.c3p0.max_size"));
      props.put(C3P0_ACQUIRE_INCREMENT,
            env.getProperty("hibernate.c3p0.acquire_increment"));
      props.put(C3P0_TIMEOUT,
            env.getProperty("hibernate.c3p0.timeout"));
      props.put(C3P0_MAX_STATEMENTS,
            env.getProperty("hibernate.c3p0.max_statements"));

      factoryBean.setHibernateProperties(props);
      factoryBean.setAnnotatedClasses(User.class);
      return factoryBean;
   }

   @Bean
   public HibernateTransactionManager getTransactionManager() {
      HibernateTransactionManager transactionManager = new HibernateTransactionManager();
      transactionManager.setSessionFactory(getSessionFactory().getObject());
      return transactionManager;
   }
}

db.properties:

# MySQL properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost/test
mysql.user=root
mysql.password=root

# Hibernate propert[2017-10-06 05:26:14,475] Artifact spring-mvc-hibernate-example:war: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDaoImp': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.boraji.tutorial.spring.config.AppConfig: Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution. Please see server.log for more details.ies
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQLDialect

#C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150

UserDao:

@Repository
public class UserDaoImp implements UserDao {

   @Autowired
   private SessionFactory sessionFactory;

   public void save(User user) {
      sessionFactory.getCurrentSession().save(user);
   }

   public List<User> list() {
      @SuppressWarnings("unchecked")
      TypedQuery<User> query = sessionFactory.getCurrentSession().createQuery("from User");
      return query.getResultList();
   }

}

I saw lots of similar problems here but it didn't help. What could go wrong in my application?

Body:
DRIVER, URL, USER and PASS are all static fields. Make sure you imported all of them. Plus, make sure you imported the spring Environment (not the hibernate).

import static org.hibernate.cfg.Environment.*;
import org.springframework.core.env.Environment;


问:
nHibernate generated this odd bit of SQL; did SQLS consume it as is?
As a result of the following LINQ:

```<code>plans
  .Where(p => p.Attributes.Any(a => a.Attribute.Product.Type == callType) &&
    call.StartTime < p.EndDate.GetValueOrDefault(System.Data.SqlTypes.SqlDateTime.MaxValue.Value) &&
    call.StartTime > p.StartDate.GetValueOrDefault(System.Data.SqlTypes.SqlDateTime.MinValue.Value))
</code>```

Plans are something like mobile phone plans. Let's say there's a base price of $1 per minute for international calls, and that contract has null start and end times because it's the base. A special plan for december is created, starting on teh 1st and ending on the last day of the month. This plan should override the base (and it will later, with a .OrderBy endtime-starttime [i.e. the shorter a plan the more overriding it is] + .First, but that's not interesting to me right now) but it should only apply to calls made in Dec, hence the two clauses that ensure we only look for plans that support the call type, and have a start/end date that straddles the time the call was made

This translates to the following SQL according to the output window debug from nHibernate:

```<code>and
  (exists
    (
      ..blah blah blah..
      where product7_.Type=?
    )
  ) and ?<coalesce(plan4_.EndDate, ?) and ?>coalesce(plan4_.StartDate, ?)
</code>```

I get the EXISTS (blahblahblah) as that's derived from the p.Any(), but what's the funky SQL in the angle brackets?

it looks like ) and ?<coalesce(plan4_.EndDate, ?) and ?>coalesce(plan4_.StartDate, ?) should be (in regular SQL syntax)

```<code>and call.starttime BETWEEN COALESCE(plan.StartDate, '1753-01-01') AND COALESCE(plan.EndDate, '9999-12-31')
</code>```

Does SQLServer do something with it as output by nHibernate, or is some other part of nHibernate responsible for expanding this to something more like my "regular" SQL? (nhibernate runs in sqlserver2008 mode, but the target is azure)

答:
The answer is there's no funky SQL in angle-brackets :)

Look closer, those are the < (lesser-than) and > (greater-than) operators in your query which are also supported in SQL.
The lack of spaces is confusing you.

The ? symbol is a common placeholder for the positional parameters in your query as those are not sent inline with the SQL text (in this case, the value of call.StartTime and the max/min date values).

You can interpret it as:

```<code>and :startTime < coalesce(plan4_.EndDate, :sqlTimeMaxValue) and :startTime > coalesce(plan4_.StartDate, :sqlTimeMinValue)
</code>```

Hope that helps!

Body:
As a result of the following LINQ:

plans
  .Where(p => p.Attributes.Any(a => a.Attribute.Product.Type == callType) &&
    call.StartTime
 p.StartDate.GetValueOrDefault(System.Data.SqlTypes.SqlDateTime.MinValue.Value))

Plans are something like mobile phone plans. Let's say there's a base price of $1 per minute for international calls, and that contract has null start and end times because it's the base. A special plan for december is created, starting on teh 1st and ending on the last day of the month. This plan should override the base (and it will later, with a .OrderBy endtime-starttime [i.e. the shorter a plan the more overriding it is] + .First, but that's not interesting to me right now) but it should only apply to calls made in Dec, hence the two clauses that ensure we only look for plans that support the call type, and have a start/end date that straddles the time the call was made

This translates to the following SQL according to the output window debug from nHibernate:

and
  (exists
    (
      ..blah blah blah..
      where product7_.Type=?
    )
  ) and ?<coalesce(plan4_.EndDate, ?) and ?>coalesce(plan4_.StartDate, ?)

I get the EXISTS (blahblahblah) as that's derived from the p.Any(), but what's the funky SQL in the angle brackets?

it looks like ) and ?<coalesce(plan4_.EndDate, ?) and ?>coalesce(plan4_.StartDate, ?) should be (in regular SQL syntax)

and call.starttime BETWEEN COALESCE(plan.StartDate, '1753-01-01') AND COALESCE(plan.EndDate, '9999-12-31')

Does SQLServer do something with it as output by nHibernate, or is some other part of nHibernate responsible for expanding this to something more like my "regular" SQL? (nhibernate runs in sqlserver2008 mode, but the target is azure)

Body:
The answer is there's no funky SQL in angle-brackets :)

Look closer, those are the < (lesser-than) and > (greater-than) operators in your query which are also supported in SQL.
The lack of spaces is confusing you.

The ? symbol is a common placeholder for the positional parameters in your query as those are not sent inline with the SQL text (in this case, the value of call.StartTime and the max/min date values).

You can interpret it as:

and :startTime < coalesce(plan4_.EndDate, :sqlTimeMaxValue) and :startTime > coalesce(plan4_.StartDate, :sqlTimeMinValue)

Hope that helps!


问:
C - Exception thrown: read access violation
I'm new to programming and I just recently started learning C.

Every week we have "labs" where we have 90 mins to finish the given tasks and so far every week I get the same error "Exception thrown: read access violation." My question is, what does it mean? I can't seem to figure out what it actually means and how to solve it. Every week I spend half of the given time just trying to figure out what's  wrong. I would really appreciate if someone explained to me what to do/what to look for when I get this error.

Once the error was gone after I fixed in my code some passing of a pointer/address (not sure which one but it was wrong). When I fixed that, the error was gone.

Another time the error was gone after I noticed that one of my loops doesn't stop where it should it just went on to very high numbers (no, not forever, I don't know why). When I fixed the loop the error was gone.

I hope it's clear what I'm trying to ask but I will include my current problem but I don't think it's really necessary to look at. Thanks in advance for any help!

This time I tried to write a task at home and once again I got the same error but I haven't yet figured out what is wrong. The task was to:

Write function:

int find_next_word(const char *string, int startIndex, int *end);

which will search string for the first word, starting at startIndex,
  return the index of its first character. A word is a nonempty sequence
  of alphanumeric characters, surrounded by other non-alphanumeric
  characters, beginning or end of the string (use function
  is_alphanumeric to classify characters). Function should also search
  for a first character after the word (possibly the null terminating
  character) and store its index in the variable pointed to by end.

is_alphanumeric is a function from a previous task which I wrote and is included in the code; it works.

```<code>#include <stdio.h>
#include <stdlib.h>

int is_alfanumeric(char c);
int find_next_word(const char* str, int start, int* end);

void main(void)
{
    /********Part 1********/
    puts("********Part 1********");
    char c = (char)getchar();
    if (is_alfanumeric(c))
        printf("%c is a letter or a number\n", c);
    else
        printf("%c is neither a letter nor a number\n", c);

    /********Part 2********/
    puts("********Part 2********\n");
    char str[] = "  ThhHhis is MmmMy,\t tTesttt string \t \n";
    printf("Original string:\n[%s]\n", str);
    int end;
    int start = find_next_word(str, 0, &end);
    printf("First word start: %d, end: %d\n", start, end);
    start = find_next_word(str, end, &end);
    printf("Second word start: %d, end: %d\n", start, end);
    system("pause");
}

int is_alfanumeric(char c) {
    if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')
        return 1;
    else
        return 0;
}
int find_next_word(const char* str, int start, int* end) {
    int i = start;
    for (; is_alfanumeric(str[i]); i++);
    for (; !is_alfanumeric(str[i]) && str[i] != '\0'; i++);
    return i;
    for (; is_alfanumeric(str[i]); i++);
    *end = i;
}
</code>```

答:
You're running past yourself with your loops. In your first loop, you run straight to the end
of the char array. (Remmember, C doesn't have "strings", it has character arrays.) Then, in your
second loop, you get an access violation because you're trying to index past the end of the array. Try this:</p>

```<code>int find_next_word(const char *str, int start, int *end) {
    int i = start;
    int r = 0;

    for (; str[i] != '\0'; i++) {

        /* You want the FIRST character that satisfies the conditions */
        if (is_alfanumeric(str[i]) {
            r = i;
            break;
        }
    }

    if (r > start) {

        /* If r is greater than start, you know you found a character
           before the end of the array, so now you can increment
           your cursor until you find a non-alfanumeric character,
           or you run out of array. */

        for (; !is_alfanumeric(str[i]); i++);
    }
    *end = i;
    return r;
}
</code>```

Body:
I'm new to programming and I just recently started learning C.

Every week we have "labs" where we have 90 mins to finish the given tasks and so far every week I get the same error "Exception thrown: read access violation." My question is, what does it mean? I can't seem to figure out what it actually means and how to solve it. Every week I spend half of the given time just trying to figure out what's  wrong. I would really appreciate if someone explained to me what to do/what to look for when I get this error.

Once the error was gone after I fixed in my code some passing of a pointer/address (not sure which one but it was wrong). When I fixed that, the error was gone.

Another time the error was gone after I noticed that one of my loops doesn't stop where it should it just went on to very high numbers (no, not forever, I don't know why). When I fixed the loop the error was gone.

I hope it's clear what I'm trying to ask but I will include my current problem but I don't think it's really necessary to look at. Thanks in advance for any help!

This time I tried to write a task at home and once again I got the same error but I haven't yet figured out what is wrong. The task was to:

Write function:

int find_next_word(const char *string, int startIndex, int *end);

which will search string for the first word, starting at startIndex,
  return the index of its first character. A word is a nonempty sequence
  of alphanumeric characters, surrounded by other non-alphanumeric
  characters, beginning or end of the string (use function
  is_alphanumeric to classify characters). Function should also search
  for a first character after the word (possibly the null terminating
  character) and store its index in the variable pointed to by end.

is_alphanumeric is a function from a previous task which I wrote and is included in the code; it works.

#include <stdio.h>
#include <stdlib.h>

int is_alfanumeric(char c);
int find_next_word(const char* str, int start, int* end);

void main(void)
{
    /********Part 1********/
    puts("********Part 1********");
    char c = (char)getchar();
    if (is_alfanumeric(c))
        printf("%c is a letter or a number\n", c);
    else
        printf("%c is neither a letter nor a number\n", c);

    /********Part 2********/
    puts("********Part 2********\n");
    char str[] = "  ThhHhis is MmmMy,\t tTesttt string \t \n";
    printf("Original string:\n[%s]\n", str);
    int end;
    int start = find_next_word(str, 0, &end);
    printf("First word start: %d, end: %d\n", start, end);
    start = find_next_word(str, end, &end);
    printf("Second word start: %d, end: %d\n", start, end);
    system("pause");
}

int is_alfanumeric(char c) {
    if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')
        return 1;
    else
        return 0;
}
int find_next_word(const char* str, int start, int* end) {
    int i = start;
    for (; is_alfanumeric(str[i]); i++);
    for (; !is_alfanumeric(str[i]) && str[i] != '\0'; i++);
    return i;
    for (; is_alfanumeric(str[i]); i++);
    *end = i;
}

Body:
You're running past yourself with your loops. In your first loop, you run straight to the end
of the char array. (Remmember, C doesn't have "strings", it has character arrays.) Then, in your
second loop, you get an access violation because you're trying to index past the end of the array. Try this:

int find_next_word(const char *str, int start, int *end) {
    int i = start;
    int r = 0;

    for (; str[i] != '\0'; i++) {

        /* You want the FIRST character that satisfies the conditions */
        if (is_alfanumeric(str[i]) {
            r = i;
            break;
        }
    }

    if (r > start) {

        /* If r is greater than start, you know you found a character
           before the end of the array, so now you can increment
           your cursor until you find a non-alfanumeric character,
           or you run out of array. */

        for (; !is_alfanumeric(str[i]); i++);
    }
    *end = i;
    return r;
}


问:
Not able to run a selected suiteXmlFile via maven surefire plugin
I have a pretty simple test project setup where I have multiple suiteXmlFiles. The pom looks as follows:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>testautomation</groupId>
<artifactId>testautomation</artifactId>
<version>0.0.1-SNAPSHOT</version>

 <properties>
    <log4j.version>2.8.2</log4j.version>
    <selenium.version>2.53.0</selenium.version>
    <testng.version>6.10</testng.version>
    <relevantcodes.version>2.41.1</relevantcodes.version>
    <aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
    <aws-java-sdk-dynamodb.version>1.11.139</aws-java-sdk-dynamodb.version>
    <rest-assured.verison>2.9.1-SNAPSHOT</rest-assured.verison>
    <json-path.version>2.9.0</json-path.version>
    <json.version>20160810</json.version>
    <xml-path.version>2.9.0</xml-path.version>
    <json-schema-validator.verison>2.9.0</json-schema-validator.verison>
    <poi.verison>3.15</poi.verison>
    <poi-ooxml.verison>3.15</poi-ooxml.verison>
    <poi-ooxml-schemas.version>3.15</poi-ooxml-schemas.version>
    <poi-scratchpad.version>3.2-FINAL</poi-scratchpad.version>
    <jackson-databind.version>2.8.5</jackson-databind.version>
    <maven.compiler.plugin.version>3.6.1</maven.compiler.plugin.version>
    <opencsv>3.10</opencsv>
    <java.version>1.8</java.version>
    <!-- <maven.jar.plugin.version>3.0.2</maven.jar.plugin.version> -->
    <maven.jar.plugin.version>2.6</maven.jar.plugin.version>
    <maven-install-plugin.version>2.5.2</maven-install-plugin.version>

     <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
     <!--<maven-surefire-plugin.version>2.12</maven-surefire-plugin.version> -->
    <skipTests>false</skipTests>
     <sometest>src/test/resources/testngxmls/sometest/test1.xml</sometest>
    <smoketest>src/test/resources/testngxmls/smoketest/test2.xml</smoketest>

</properties>

<build>
    <!-- <sourceDirectory>src</sourceDirectory> -->
    <plugins>

     <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven.compiler.plugin.version}</version>
            <inherited>true</inherited>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>${maven.jar.plugin.version}</version>
            <inherited>true</inherited>
            <executions>
                <execution>
                    <goals>
                        <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <version>${maven-install-plugin.version}</version>
            <executions>
                <execution>
                    <id>default-install</id>
                    <phase>install</phase>
                    <goals>
                        <goal>install</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>${maven-surefire-plugin.version}</version>
             <configuration>
                <skipTests>${skipTests}</skipTests>
                <suiteXmlFiles>
                    <xmlFile>${sometest}</xmlFile>
                    <xmlFile>${smoketest}</xmlFile>
                </suiteXmlFiles>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>${selenium.version}</version>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>${testng.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>${log4j.version}</version>
    </dependency>

    <dependency>
        <groupId>com.relevantcodes</groupId>
        <artifactId>extentreports</artifactId>
        <version>${relevantcodes.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>${poi.verison}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>${poi-ooxml.verison}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>${poi-ooxml-schemas.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>${poi-scratchpad.version}</version>
    </dependency>

    <!--adding only required jars of AWS -->

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-lambda-java-core</artifactId>
        <version>${aws-lambda-java-core.version}</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-dynamodb</artifactId>
        <version>${aws-java-sdk-dynamodb.version}</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>com.jayway.restassured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>${rest-assured.verison}</version>
    </dependency>

    <dependency>
        <groupId>com.jayway.restassured</groupId>
        <artifactId>json-path</artifactId>
        <version>${json-path.version}</version>
    </dependency>

    <dependency>
        <groupId>com.jayway.restassured</groupId>
        <artifactId>xml-path</artifactId>
        <version>${xml-path.version}</version>
    </dependency>

    <dependency>
        <groupId>com.jayway.restassured</groupId>
        <artifactId>json-schema-validator</artifactId>
        <version>${json-schema-validator.verison}</version>
        <!-- <scope>test</scope> -->
        <scope>compile</scope>
    </dependency>

    <dependency>
         <groupId>com.opencsv</groupId>
         <artifactId>opencsv</artifactId>
         <version>${opencsv}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson-databind.version}</version>
    </dependency>

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>${json.version}</version>
    </dependency>

    <dependency>

        <groupId>com.google.inject</groupId>
        <artifactId>guice</artifactId>
        <version>3.0</version>
    </dependency>

     <!-- <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-text</artifactId>
        <version>1.1</version>
    </dependency> -->
</dependencies>

<repositories>
    <repository>
        <id>sonatype</id>
        <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        <snapshots />
    </repository>
</repositories>
</code>```

With this pom.xml. I have been trying to use mvn command line to run selected suites independently, however it keeps executing all the suiteXmlFiles. The command I have used are as follows:

When I run this command $ mvn -e clean test -Dsurefire.xmlFile=sometest it runs sometest suite and then also runs all tests in smoketest. Similar observations with all the commands listed below.

$ mvn -e clean test -Dsurefire.xmlFiles=sometest

I have even tried changing the xmlFile to suiteXmlFile and file tags and running the respective commands:

$ mvn -e clean test -Dsurefire.suiteXmlFile=sometest
$ mvn -e clean test -Dsurefire.suiteXmlFiles=sometest

$ mvn -e clean test -Dsurefire.suiteXmlFile=sometest
$ mvn -e clean test -Dsurefire.suiteXmlFiles=sometest

Is there a way these tests can be run independently sticking to the suiteXmlFiles. This looks like a straightforward feature and it is puzzling why it would be so difficult to get this up and running.

答:
Seems working fine with testng-6.13.1 and maven-surefire-plugin 2.20. Check you artifact versions or you have to pass the correct file path to Dsurefire.suiteXmlFile option.

MVN Command:

```<code> mvn test -Dsurefire.suiteXmlFiles=src/test/resources/testXml1.xml
</code>```

Output for Test Suite 1:

```<code>[INFO] Running TestSuite
This is TestNG-Test-Suite-First Example
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.345 s - in TestSuite
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
</code>```

MVN Command:

```<code> mvn test -Dsurefire.suiteXmlFiles=src/test/resources/testXml2.xml
</code>```

Output for Test Suite 2:

```<code>[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running TestSuite
@BeforeTest
This is TestNG-Test-Suite-Second Example
@AfterTest

[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.399 s - in TestSuite
[INFO]
</code>```

Project Setup

pom.xml

```<code> <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.13.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20</version>
                    <configuration>
                        <suiteXmlFiles>
                            <suiteXmlFile>src/test/resources/testXmlAll.xml</suiteXmlFile>
                            <suiteXmlFile>src/test/resources/testXml1.xml</suiteXmlFile>
                            <suiteXmlFile>src/test/resources/testXml2.xml</suiteXmlFile>
                        </suiteXmlFiles>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</code>```

testXml1.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="test1">
    <test name="test1">
        <classes>
            <class name="TestNgSuiteFirstTest"/>
        </classes>
    </test>
</suite>
</code>```

testXml2.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="test2">
    <test name="test2">
        <classes>
            <class name="TestNgSuiteSecondTest"/>
        </classes>
    </test>
</suite>
</code>```

Pass the suite file as parameter

This is just a workaround to pass the suit file as parameter

Configure property variable to point to each suite file.

```<code><properties>
   <test1SuiteFile>${project.basedir}/src/test/resources/testXml1.xml</test1SuiteFile>
        <test2SuiteFile>${project.basedir}/src/test/resources/testXml2.xml</test2SuiteFile>
        <!-- Default suites -->
        <testAllSuiteFile>${project.basedir}/src/test/resources/testXmlAll.xml</testAllSuiteFile>
        <suiteFile>${testAllSuiteFile}</suiteFile>
    </properties>
</code>```

Update plugin:

```<code> <configuration>
     <suiteXmlFiles>
          <suiteXmlFile>${suiteFile}</suiteXmlFile>
      </suiteXmlFiles>
  </configuration>
</code>```

Pass the file name as parameter in  command line

```<code>mvn clean test
mvn test -DsuiteFile=${test2SuiteFile}
mvn test -DsuiteFile=${test1SuiteFile},${test2SuiteFile}
</code>```

Otherwise define configuration as follows and pass single file:

```<code>[INFO] Running TestSuite
This is TestNG-Test-Suite-First Example
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.345 s - in TestSuite
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
</code>```0

Body:
I have a pretty simple test project setup where I have multiple suiteXmlFiles. The pom looks as follows:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>testautomation</groupId>
<artifactId>testautomation</artifactId>
<version>0.0.1-SNAPSHOT</version>

 <properties>
    <log4j.version>2.8.2</log4j.version>
    <selenium.version>2.53.0</selenium.version>
    <testng.version>6.10</testng.version>
    <relevantcodes.version>2.41.1</relevantcodes.version>
    <aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
    <aws-java-sdk-dynamodb.version>1.11.139</aws-java-sdk-dynamodb.version>
    <rest-assured.verison>2.9.1-SNAPSHOT</rest-assured.verison>
    <json-path.version>2.9.0</json-path.version>
    <json.version>20160810</json.version>
    <xml-path.version>2.9.0</xml-path.version>
    <json-schema-validator.verison>2.9.0</json-schema-validator.verison>
    <poi.verison>3.15</poi.verison>
    <poi-ooxml.verison>3.15</poi-ooxml.verison>
    <poi-ooxml-schemas.version>3.15</poi-ooxml-schemas.version>
    <poi-scratchpad.version>3.2-FINAL</poi-scratchpad.version>
    <jackson-databind.version>2.8.5</jackson-databind.version>
    <maven.compiler.plugin.version>3.6.1</maven.compiler.plugin.version>
    <opencsv>3.10</opencsv>
    <java.version>1.8</java.version>

    <maven.jar.plugin.version>2.6</maven.jar.plugin.version>
    <maven-install-plugin.version>2.5.2</maven-install-plugin.version>

     <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>

    <skipTests>false</skipTests>
     <sometest>src/test/resources/testngxmls/sometest/test1.xml</sometest>
    <smoketest>src/test/resources/testngxmls/smoketest/test2.xml</smoketest>

</properties>

<build>

    <plugins>

     <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven.compiler.plugin.version}</version>
            <inherited>true</inherited>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>${maven.jar.plugin.version}</version>
            <inherited>true</inherited>
            <executions>
                <execution>
                    <goals>
                        <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <version>${maven-install-plugin.version}</version>
            <executions>
                <execution>
                    <id>default-install</id>
                    <phase>install</phase>
                    <goals>
                        <goal>install</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>${maven-surefire-plugin.version}</version>
             <configuration>
                <skipTests>${skipTests}</skipTests>
                <suiteXmlFiles>
                    <xmlFile>${sometest}</xmlFile>
                    <xmlFile>${smoketest}</xmlFile>
                </suiteXmlFiles>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>${selenium.version}</version>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>${testng.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>${log4j.version}</version>
    </dependency>

    <dependency>
        <groupId>com.relevantcodes</groupId>
        <artifactId>extentreports</artifactId>
        <version>${relevantcodes.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>${poi.verison}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>${poi-ooxml.verison}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>${poi-ooxml-schemas.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>${poi-scratchpad.version}</version>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-lambda-java-core</artifactId>
        <version>${aws-lambda-java-core.version}</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-dynamodb</artifactId>
        <version>${aws-java-sdk-dynamodb.version}</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>com.jayway.restassured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>${rest-assured.verison}</version>
    </dependency>

    <dependency>
        <groupId>com.jayway.restassured</groupId>
        <artifactId>json-path</artifactId>
        <version>${json-path.version}</version>
    </dependency>

    <dependency>
        <groupId>com.jayway.restassured</groupId>
        <artifactId>xml-path</artifactId>
        <version>${xml-path.version}</version>
    </dependency>

    <dependency>
        <groupId>com.jayway.restassured</groupId>
        <artifactId>json-schema-validator</artifactId>
        <version>${json-schema-validator.verison}</version>

        <scope>compile</scope>
    </dependency>

    <dependency>
         <groupId>com.opencsv</groupId>
         <artifactId>opencsv</artifactId>
         <version>${opencsv}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson-databind.version}</version>
    </dependency>

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>${json.version}</version>
    </dependency>

    <dependency>

        <groupId>com.google.inject</groupId>
        <artifactId>guice</artifactId>
        <version>3.0</version>
    </dependency>

</dependencies>

<repositories>
    <repository>
        <id>sonatype</id>
        <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        <snapshots />
    </repository>
</repositories>

With this pom.xml. I have been trying to use mvn command line to run selected suites independently, however it keeps executing all the suiteXmlFiles. The command I have used are as follows:

When I run this command $ mvn -e clean test -Dsurefire.xmlFile=sometest it runs sometest suite and then also runs all tests in smoketest. Similar observations with all the commands listed below.

$ mvn -e clean test -Dsurefire.xmlFiles=sometest

I have even tried changing the xmlFile to suiteXmlFile and file tags and running the respective commands:

$ mvn -e clean test -Dsurefire.suiteXmlFile=sometest
$ mvn -e clean test -Dsurefire.suiteXmlFiles=sometest

$ mvn -e clean test -Dsurefire.suiteXmlFile=sometest
$ mvn -e clean test -Dsurefire.suiteXmlFiles=sometest

Is there a way these tests can be run independently sticking to the suiteXmlFiles. This looks like a straightforward feature and it is puzzling why it would be so difficult to get this up and running.

Body:
Seems working fine with testng-6.13.1 and maven-surefire-plugin 2.20. Check you artifact versions or you have to pass the correct file path to Dsurefire.suiteXmlFile option.

MVN Command:

 mvn test -Dsurefire.suiteXmlFiles=src/test/resources/testXml1.xml

Output for Test Suite 1:

[INFO] Running TestSuite
This is TestNG-Test-Suite-First Example
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.345 s - in TestSuite
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

MVN Command:

 mvn test -Dsurefire.suiteXmlFiles=src/test/resources/testXml2.xml

Output for Test Suite 2:

[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running TestSuite
@BeforeTest
This is TestNG-Test-Suite-Second Example
@AfterTest

[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.399 s - in TestSuite
[INFO]

Project Setup

pom.xml

 <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.13.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20</version>
                    <configuration>
                        <suiteXmlFiles>
                            <suiteXmlFile>src/test/resources/testXmlAll.xml</suiteXmlFile>
                            <suiteXmlFile>src/test/resources/testXml1.xml</suiteXmlFile>
                            <suiteXmlFile>src/test/resources/testXml2.xml</suiteXmlFile>
                        </suiteXmlFiles>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

testXml1.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="test1">
    <test name="test1">
        <classes>
            <class name="TestNgSuiteFirstTest"/>
        </classes>
    </test>
</suite>

testXml2.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="test2">
    <test name="test2">
        <classes>
            <class name="TestNgSuiteSecondTest"/>
        </classes>
    </test>
</suite>

Pass the suite file as parameter

This is just a workaround to pass the suit file as parameter

Configure property variable to point to each suite file.

<properties>
   <test1SuiteFile>${project.basedir}/src/test/resources/testXml1.xml</test1SuiteFile>
        <test2SuiteFile>${project.basedir}/src/test/resources/testXml2.xml</test2SuiteFile>
        <!-- Default suites -->
        <testAllSuiteFile>${project.basedir}/src/test/resources/testXmlAll.xml</testAllSuiteFile>
        <suiteFile>${testAllSuiteFile}</suiteFile>
    </properties>

Update plugin:

 <configuration>
     <suiteXmlFiles>
          <suiteXmlFile>${suiteFile}</suiteXmlFile>
      </suiteXmlFiles>
  </configuration>

Pass the file name as parameter in  command line

mvn clean test
mvn test -DsuiteFile=${test2SuiteFile}
mvn test -DsuiteFile=${test1SuiteFile},${test2SuiteFile}

Otherwise define configuration as follows and pass single file:

mvn test -DsuiteFile=testXml1.xml

   <configuration>
             <suiteXmlFile>${project.basedir}/src/test/resources/${suiteFile}
                            </suiteXmlFile>
  </suiteXmlFiles>
</configuration>