问:
ASPX extension not showing when browsing site from VS2013 IDE
i have created a web site with VS2013 IDE and my .net framework version is 4.5.

i select default webform template with no authentication and IDE generate project with many code and aspx file.

when i run my code from IDE then aspx extension is not showing. i comment this code in RouteConfig.cs file

```<code> //var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
//routes.EnableFriendlyUrls(settings);
</code>```

but still aspx extension is not showing. so tell me what i need to change as a result aspx extension should be shown.

答:
Doing that is enough to remove friendly URLs for me, you do also have to edit your Site.Master etc to change the links from ~/About to ~/About.aspx for example.

Otherwise, check for other URL rewriting as described in Scott Gu's blog: https://weblogs.asp.net/scottgu/tip-trick-url-rewriting-with-asp-net

Body:
i have created a web site with VS2013 IDE and my .net framework version is 4.5.

i select default webform template with no authentication and IDE generate project with many code and aspx file.

when i run my code from IDE then aspx extension is not showing. i comment this code in RouteConfig.cs file

 //var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
//routes.EnableFriendlyUrls(settings);

but still aspx extension is not showing. so tell me what i need to change as a result aspx extension should be shown.


来源: stackexchange

问:
Adding images side by side in pdf using itextsharp
I am writing some data to the pdf using itextsharp. I am adding 2 images. I used this code:

```<code> iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(System.Windows.Forms.Application.StartupPath + "\\t.jpg");
 iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(System.Windows.Forms.Application.StartupPath + "\\teiasLogo.jpg");
 pdfDocCreatePDF.Add(img);
 pdfDocCreatePDF.Add(img2);
</code>```

I want to see them like that :

As a result I don't want new line ( \n ) between the images, I want spaces. How can I do that? Thanks..

答:
```<code> PdfPTable resimtable = new PdfPTable(2); // two colmns create tabble
 resimtable.WidthPercentage = 100f;//table %100 width
 iTextSharp.text.Image imgsag = iTextSharp.text.Image.GetInstance(Application.StartupPath+"/sagkulak.jpg");
iTextSharp.text.Image imgsol = iTextSharp.text.Image.GetInstance(Application.StartupPath + "/sagkulak.jpg");
resimtable.AddCell(imgsag);//Table One colmns added first image
resimtable.AddCell(imgsol);//Table two colmns added second image
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing some data to the pdf using itextsharp. I am adding 2 images. I used this code:

 iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(System.Windows.Forms.Application.StartupPath + "\\t.jpg");
 iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(System.Windows.Forms.Application.StartupPath + "\\teiasLogo.jpg");
 pdfDocCreatePDF.Add(img);
 pdfDocCreatePDF.Add(img2);

I want to see them like that :

As a result I don't want new line ( \n ) between the images, I want spaces. How can I do that? Thanks..


问:
Select/Apply Styles to specific character with Javascript
When I write code instead of using camelCase or seperate_with_underscore I separate my class names with custom unicode chars. Such as this:

sideNavܢheaderܢtext

So if I have a class with a specific state modifier I will write it like so:

sideNavܢheaderܢtextᆞbold

These are not css selectors this is just my naming convention. Now for my question.

I am using the atom text editor and sometimes I want to be able to hide these special characters. I can use javascript to select things in Atom, but is it possible to use javascript to literally select a single character?

Then I can use that selection to apply a "display:none" style to it?

Like:

```<code>var a = document.getElementByChar("a");
a.style.display = "none";
</code>```

Any help or ideas would be appreciated!

Update: I don't want to actually remove the characters. Just "hide" them from view. The naming convention I use is actually much more complex than this and I use these special characters to define all sorts of patterns in my document.

However sometimes I only care about certain selectors and I want the others to temporarily go away.

答:
If I'm understanding your question correctly, in JavaScript you can:

Get the entire string from the className:

const string = document.querySelector(".sideNavܢheaderܢtext").textContent

Find the location of the character you want to modify. For example:

string.indexOf('a').

Wrap the character with a span (plenty of ways to do that - check out this one).

Add class to span and style with CSS.

ContentLicense: CC BY-SA 4.0

Body:
When I write code instead of using camelCase or seperate_with_underscore I separate my class names with custom unicode chars. Such as this:

sideNavܢheaderܢtext

So if I have a class with a specific state modifier I will write it like so:

sideNavܢheaderܢtextᆞbold

These are not css selectors this is just my naming convention. Now for my question.

I am using the atom text editor and sometimes I want to be able to hide these special characters. I can use javascript to select things in Atom, but is it possible to use javascript to literally select a single character?

Then I can use that selection to apply a "display:none" style to it?

Like:

var a = document.getElementByChar("a");
a.style.display = "none";

Any help or ideas would be appreciated!

Update: I don't want to actually remove the characters. Just "hide" them from view. The naming convention I use is actually much more complex than this and I use these special characters to define all sorts of patterns in my document.

However sometimes I only care about certain selectors and I want the others to temporarily go away.


问:
Why does Internet Explorer and Edge output new Date() data into database differently than other browsers?
I found a way to add a date as a time stamp when a user submits a message with my web application. Every thing works perfectly but when I use new Date(); to have its value store in a MySQL database, Internet Explorer
and Edge just inputs the data like this â€Ž12â€Ž:â€Ž14â€Ž â€ŽPM but it suppose to look something like this 12:33 PM.

In other words different browsers input it perfectly in the database so I know my code isn't wrong but Edge and Explorer don't store the data properly so what's going on here? And how can I get Edge and Explorer to store the time data like how the other browsers do perfectly? And this is a screenshot of the database.

The method I'm using to store data into the database works perfectly with all different kinds of data like strings, numeric etc.. and all different browsers but edge and explorer can't store JavaScript new Date() value properly.

Here is a method on how I'm getting a time stamp and generating values to be use in the server side code.

message.js

```<code>//Get message date
function message_date() {

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();

if(dd<10) {
    dd = '0'+dd
}

if(mm<10) {
    mm = '0'+mm
}

today = mm + '/' + dd + '/' + yyyy;
var today;
return today;
}

var message_date_stamp = message_date();  // this will grab you the return value from message_date();

//Get user send message time
var timez = new Date();
timez = timez.toLocaleString('en-US', { hour: 'numeric',minute:'numeric', hour12: true });
var get_time = timez;

$(document).ready(function(){
$("#send").click(function(){
var conversation_id = $("#conversation_id").val();
var user_id = $("#user_id").val();
var member_name = $("#member_name").val();
var message = $("#message").val();
var status= $("#status").val();
var sender_id= $("#sender_id").val();
var receiver_id= $("#receiver_id").val();
var photo_link = $("#photo_link").val();
var hyper_link = $("#hyper_link").val();
var date = message_date_stamp;
var time = get_time;

// Returns successful data submission message when the entered information is stored in database.
var dataString = 'conversation_id='+ conversation_id + '&user_id=' + user_id + '&member_name='+ member_name + '&message='+ message + '&status='+ status + '&sender_id='+ sender_id + '&receiver_id='+ receiver_id + '&photo_link='+ photo_link + '&hyper_link='+ hyper_link + '&time='+ time + '&date='+ date;

    //AJAX code to submit form.
    $.ajax({
    type: "POST",
    url: "send_message_data.php",
    data: dataString
    });
    });
    });
</code>```

This is how I'm storing the data into the database in PHP just know that the value of new Date() is generated from a previous page and in PHP it's represented by PHP's variable call $time.

send_message_data.php

```<code><?php
//Credentials
$db_servername = "localhost";
$db_username = "1234u";
$db_password = "1234";
$db_name = "1234db";

$connect = mysqli_connect($db_servername, $db_username, $db_password, $db_name);

//Form values
$conversation_id = $_POST['conversation_id'];
$user_id = $_POST['user_id'];
$member_name= $_POST['member_name'];
$message= $_POST['message'];
$status= $_POST['status'];
$sender_id= $_POST['sender_id'];
$receiver_id= $_POST['receiver_id'];

$date= $_POST['date'];

//FOR STACK OVER FLOW USERS $time is how I'm storing this into the data base
$time= $_POST['time'];

$photo_link= $_POST['photo_link'];
$hyper_link= $_POST['hyper_link'];

//SECURITY

//Basic character escaping.
$conversation_id = htmlspecialchars($conversation_id);
$member_name = htmlspecialchars($member_name);
$message = htmlspecialchars($message);
$photo_link = htmlspecialchars($photo_link);
$hyper_link = htmlspecialchars($hyper_link);

//OTHER FEATURES

//Prevent MYSQLI injection.
$conversation_id = mysqli_real_escape_string($connect, $conversation_id);
$member_name = mysqli_real_escape_string($connect, $member_name);
$message = mysqli_real_escape_string($connect, $message);
$photo_link = mysqli_real_escape_string($connect, $photo_link );
$hyper_link = mysqli_real_escape_string($connect, $hyper_link);

//Removes tags combat the following injections HTML, JAVA-SCRIPT, PHP.
$conversation_id = filter_var($conversation_id, FILTER_SANITIZE_STRING);
$member_name = filter_var($member_name, FILTER_SANITIZE_STRING);
$message = filter_var($message, FILTER_SANITIZE_STRING);
$photo_link = filter_var($photo_link, FILTER_SANITIZE_STRING);
$hyper_link = filter_var($hyper_link, FILTER_SANITIZE_STRING);

$query = "INSERT INTO messages_x1(conversation_id,user_id,member_name,message,status,sender_id,receiver_id,photo_link,hyper_link,date,time) values ('$conversation_id','$user_id','$member_name','$message','$status','$sender_id','$receiver_id','$photo_link','$hyper_link','$date','$time')";

$run = $connect->query($query);

if($run) {
echo "Form Submitted succesfully";
}

?>
</code>```

And one last thing I read that it has nothing to do with the code but I read some where that mentions Explorer and Edge have problems on interacting with JavaScript's new Date() poorly in certain situations. I just want a solution to bypass Explorer and Edge limitations.

答:
No offense to the people that said it was my code that had errors. But I always knew it wasn't my code that was causing this. I was right I found out that different browsers will tend to structure your code differently in your database. So for any future readers wondering why their code is treated and inserted differently in the data base then you know why. Here is proof starting from internet explore to chrome and to safari Iphone.

Screen shot

The good news is that internet explore version of the time is outputting the time in a human readable way but sadly it's structure of the time differs in the data base.

Body:
I found a way to add a date as a time stamp when a user submits a message with my web application. Every thing works perfectly but when I use new Date(); to have its value store in a MySQL database, Internet Explorer
and Edge just inputs the data like this â€Ž12â€Ž:â€Ž14â€Ž â€ŽPM but it suppose to look something like this 12:33 PM.

In other words different browsers input it perfectly in the database so I know my code isn't wrong but Edge and Explorer don't store the data properly so what's going on here? And how can I get Edge and Explorer to store the time data like how the other browsers do perfectly? And this is a screenshot of the database.

The method I'm using to store data into the database works perfectly with all different kinds of data like strings, numeric etc.. and all different browsers but edge and explorer can't store JavaScript new Date() value properly.

Here is a method on how I'm getting a time stamp and generating values to be use in the server side code.

message.js

//Get message date
function message_date() {

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();

if(dd<10) {
    dd = '0'+dd
}

if(mm<10) {
    mm = '0'+mm
}

today = mm + '/' + dd + '/' + yyyy;
var today;
return today;
}

var message_date_stamp = message_date();  // this will grab you the return value from message_date();

//Get user send message time
var timez = new Date();
timez = timez.toLocaleString('en-US', { hour: 'numeric',minute:'numeric', hour12: true });
var get_time = timez;

$(document).ready(function(){
$("#send").click(function(){
var conversation_id = $("#conversation_id").val();
var user_id = $("#user_id").val();
var member_name = $("#member_name").val();
var message = $("#message").val();
var status= $("#status").val();
var sender_id= $("#sender_id").val();
var receiver_id= $("#receiver_id").val();
var photo_link = $("#photo_link").val();
var hyper_link = $("#hyper_link").val();
var date = message_date_stamp;
var time = get_time;

// Returns successful data submission message when the entered information is stored in database.
var dataString = 'conversation_id='+ conversation_id + '&user_id=' + user_id + '&member_name='+ member_name + '&message='+ message + '&status='+ status + '&sender_id='+ sender_id + '&receiver_id='+ receiver_id + '&photo_link='+ photo_link + '&hyper_link='+ hyper_link + '&time='+ time + '&date='+ date;

    //AJAX code to submit form.
    $.ajax({
    type: "POST",
    url: "send_message_data.php",
    data: dataString
    });
    });
    });

This is how I'm storing the data into the database in PHP just know that the value of new Date() is generated from a previous page and in PHP it's represented by PHP's variable call $time.

send_message_data.php

<?php
//Credentials
$db_servername = "localhost";
$db_username = "1234u";
$db_password = "1234";
$db_name = "1234db";

$connect = mysqli_connect($db_servername, $db_username, $db_password, $db_name);

//Form values
$conversation_id = $_POST['conversation_id'];
$user_id = $_POST['user_id'];
$member_name= $_POST['member_name'];
$message= $_POST['message'];
$status= $_POST['status'];
$sender_id= $_POST['sender_id'];
$receiver_id= $_POST['receiver_id'];

$date= $_POST['date'];

//FOR STACK OVER FLOW USERS $time is how I'm storing this into the data base
$time= $_POST['time'];

$photo_link= $_POST['photo_link'];
$hyper_link= $_POST['hyper_link'];

//SECURITY

//Basic character escaping.
$conversation_id = htmlspecialchars($conversation_id);
$member_name = htmlspecialchars($member_name);
$message = htmlspecialchars($message);
$photo_link = htmlspecialchars($photo_link);
$hyper_link = htmlspecialchars($hyper_link);

//OTHER FEATURES

//Prevent MYSQLI injection.
$conversation_id = mysqli_real_escape_string($connect, $conversation_id);
$member_name = mysqli_real_escape_string($connect, $member_name);
$message = mysqli_real_escape_string($connect, $message);
$photo_link = mysqli_real_escape_string($connect, $photo_link );
$hyper_link = mysqli_real_escape_string($connect, $hyper_link);

//Removes tags combat the following injections HTML, JAVA-SCRIPT, PHP.
$conversation_id = filter_var($conversation_id, FILTER_SANITIZE_STRING);
$member_name = filter_var($member_name, FILTER_SANITIZE_STRING);
$message = filter_var($message, FILTER_SANITIZE_STRING);
$photo_link = filter_var($photo_link, FILTER_SANITIZE_STRING);
$hyper_link = filter_var($hyper_link, FILTER_SANITIZE_STRING);

$query = "INSERT INTO messages_x1(conversation_id,user_id,member_name,message,status,sender_id,receiver_id,photo_link,hyper_link,date,time) values ('$conversation_id','$user_id','$member_name','$message','$status','$sender_id','$receiver_id','$photo_link','$hyper_link','$date','$time')";

$run = $connect->query($query);

if($run) {
echo "Form Submitted succesfully";
}

?>

And one last thing I read that it has nothing to do with the code but I read some where that mentions Explorer and Edge have problems on interacting with JavaScript's new Date() poorly in certain situations. I just want a solution to bypass Explorer and Edge limitations.


问:
How do I get a random number from numbers available?
I have a table that I am trying to get a random number from:

```<code>//Fruits
id  |  FruitName
----------------
2   |  Banana
3   |  Apple
4   |  Orange
6   |  Grape
7   |  Plum
8   |  Lime
10  |  Kiwi
</code>```

The problem is because of the inconsistencies (note: ids 1, 5, and 9 are missing), writing the following statement will not work (even if written properly):

Random.Next(someLinq.id).First(), (samelinq.id).Last())

How would I get a random number from the numbers available?

答:
How about something like this?</p>

```<code>// get the count
var count = context.Fruits.Count();
// generate a random fruit index
var random = new Random().Next(count);
// skip by random
var randomFruit = context.Fruits
                         .Skip(random)
                         .Take(1)
                         .FirstOrDefault();
</code>```

Body:
I have a table that I am trying to get a random number from:

//Fruits
id  |  FruitName
----------------
2   |  Banana
3   |  Apple
4   |  Orange
6   |  Grape
7   |  Plum
8   |  Lime
10  |  Kiwi

The problem is because of the inconsistencies (note: ids 1, 5, and 9 are missing), writing the following statement will not work (even if written properly):

Random.Next(someLinq.id).First(), (samelinq.id).Last())

How would I get a random number from the numbers available?

Body:
How about something like this?

// get the count
var count = context.Fruits.Count();
// generate a random fruit index
var random = new Random().Next(count);
// skip by random
var randomFruit = context.Fruits
                         .Skip(random)
                         .Take(1)
                         .FirstOrDefault();


问:
How to start a new line of an array of squares with CSS
I'm trying to create a 'grid' of squares using CSS. So far I've tried:

.square {
  display: block;
  float: left;
  border: 1px solid black;
  width: 50px;
  height: 50px;
  margin: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>

<div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div></code>```

However, this simply display 6 squares in a row. I'd like to have two rows of 3 squares each, however. Why do the encompassing divs not have the 'normal' behavior that they are displayed beneath each other?

答:
Something like this?

<!DOCTYPE html>

1

2

3

4

5

6

```

Body:
I'm trying to create a 'grid' of squares using CSS. So far I've tried:

.square {
  display: block;
  float: left;
  border: 1px solid black;
  width: 50px;
  height: 50px;
  margin: 30px;
}

However, this simply display 6 squares in a row. I'd like to have two rows of 3 squares each, however. Why do the encompassing divs not have the 'normal' behavior that they are displayed beneath each other?

Body:
Something like this?

<!DOCTYPE html>
<html>
<head>
<style>

.square-wrapper {
width: 276px;
}
.square {
    display: inline-block;
    float: left;
    border: 1px solid black;
    width: 30px;
    height: 50px;
    margin: 30px;
}
</style>
</head>
<body>

<div class="square-wrapper">
<div class="square">1</div>
<div class="square">2</div>
<div class="square">3</div>
</div>

<div class="square-wrapper">
<div class="square">4</div>
<div class="square">5</div>
<div class="square">6</div>
</div>

</body>
</html>


问:
check if in GMT, then convert to local time in in GMT - R - looping
I've found a million posts about converting from GMT to local time, but not one that first checks if the date-time is in GMT, and then converting it to its representative local time. As folks are suggesting a duplicate,  I am looking to convert from GMT to local time, but more importantly, specifically want to check whether or not a conversion needs to be made. I'm using lubridate, dplyr, zoo, and stringr.

Take this example data (my data is in a larger data frame of nums and POSXIct formats):

for store 1000, the df dataframe has the column Time:

```<code>Time<-c("2017-02-02 06:05:00 GMT", "2017-02-04 00:06:10 GMT", "2017-02-05 00:06:15 GMT")
df<-as.data.frame(Time)
</code>```

time_zone_info is as follows:

```<code>x<-1000
timezone<-"US/Eastern"
time_zone_info<-cbind(x,timezone)
time_zone_info<-as.data.frame(time_zone_info)
</code>```

my current attempt is below:

```<code>correct_to_local_time<-function(df){
    if("GMT" %in% df$Time){
        df$Time<-as.POSIXct(df$Time, tz ="GMT",usetz=TRUE)
        df$Time<-with_tz(df$Time,tz=time_zone_info$timezone)
        }
    else{
           as.POSIXct(df$Time)}
}
correct_to_local_time(df)
</code>```

which gives me the following which is computationally incorrect (it should be 1:05:00EDT, 01:10:00EDT, etc., but it did change the GMT to EDT, so I'm quite confused...):

```<code>Time
2017-02-02 06:05:00 EDT
2017-02-02 06:10:00 EDT
2017-02-02 06:10:00 EDT
</code>```

Ideally I'd like something like:

```<code> Local Time
2017-02-02 01:05:00 EDT
2017-02-04 01:10:00 EDT
2017-02-05 01:15:00 EDT
</code>```

Once a conversion from GMT to EDT or MST is made, are daylight savings accounted for?

Thanks in advance ya'll

答:
The package lubridate probably can help you.

```<code> require(lubridate)

dfTime<-c("2017-02-02 06:05:00 GMT",
          "2017-02-04 00:06:00 New_York",
          "2017-02-05 00:06:00 US/Mountain")
dfStore <-c(1000, 2000, 3000)
dftimeZone<-c("US/Eastern", "US/Eastern", "US/Mountain")

time_zone_info <- data.frame(Store = dfStore,
                             Time = dfTime,
                             Timezone = dftimeZone,
                             stringsAsFactors = FALSE)
</code>```

First, check that all your time zones are within your system's recognized list of time zones. (I wasn't sure.)

```<code>all(time_zone_info$Timezone %in% OlsonNames())
</code>```

Ok, good.

Next, convert your character string of times into POSIXct. I like the lubridate function "ymd_hms" here because it's so flexible. You can also set what the time zone was for that, too, using the argument "tz". This returns the time IN YOUR CURRENT TIME ZONE. For example, I'm in Seattle, so this returns the equivalent time in PST for me. I'm pretty sure lubridate accounts for daylight savings time. (I'm having difficulty getting this to sapply and thus opting for a "for" loop. I'm sure someone else could make this happen without that, though.)

```<code>time_zone_info$Time2 <- as.POSIXct(NA)
for(i in 1:nrow(time_zone_info)){
      time_zone_info$Time2[i] <- ymd_hms(time_zone_info$Time[i],
                                         tz = time_zone_info$Timezone[i])
}
</code>```

Everything in time_zone_info$Time2 will be in the same time zone, and I believe that's by design for making easy comparisons. It's hard to get R to make multiple time zones in the same column of a data.frame.

Body:
I've found a million posts about converting from GMT to local time, but not one that first checks if the date-time is in GMT, and then converting it to its representative local time. As folks are suggesting a duplicate,  I am looking to convert from GMT to local time, but more importantly, specifically want to check whether or not a conversion needs to be made. I'm using lubridate, dplyr, zoo, and stringr.

Take this example data (my data is in a larger data frame of nums and POSXIct formats):

for store 1000, the df dataframe has the column Time:

Time<-c("2017-02-02 06:05:00 GMT", "2017-02-04 00:06:10 GMT", "2017-02-05 00:06:15 GMT")
df<-as.data.frame(Time)

time_zone_info is as follows:

x<-1000
timezone<-"US/Eastern"
time_zone_info<-cbind(x,timezone)
time_zone_info<-as.data.frame(time_zone_info)

my current attempt is below:

correct_to_local_time<-function(df){
    if("GMT" %in% df$Time){
        df$Time<-as.POSIXct(df$Time, tz ="GMT",usetz=TRUE)
        df$Time<-with_tz(df$Time,tz=time_zone_info$timezone)
        }
    else{
           as.POSIXct(df$Time)}
}
correct_to_local_time(df)

which gives me the following which is computationally incorrect (it should be 1:05:00EDT, 01:10:00EDT, etc., but it did change the GMT to EDT, so I'm quite confused...):

Time
2017-02-02 06:05:00 EDT
2017-02-02 06:10:00 EDT
2017-02-02 06:10:00 EDT

Ideally I'd like something like:

 Local Time
2017-02-02 01:05:00 EDT
2017-02-04 01:10:00 EDT
2017-02-05 01:15:00 EDT

Once a conversion from GMT to EDT or MST is made, are daylight savings accounted for?

Thanks in advance ya'll

Body:
The package lubridate probably can help you.

 require(lubridate)

dfTime<-c("2017-02-02 06:05:00 GMT",
          "2017-02-04 00:06:00 New_York",
          "2017-02-05 00:06:00 US/Mountain")
dfStore <-c(1000, 2000, 3000)
dftimeZone<-c("US/Eastern", "US/Eastern", "US/Mountain")

time_zone_info <- data.frame(Store = dfStore,
                             Time = dfTime,
                             Timezone = dftimeZone,
                             stringsAsFactors = FALSE)

First, check that all your time zones are within your system's recognized list of time zones. (I wasn't sure.)

all(time_zone_info$Timezone %in% OlsonNames())

Ok, good.

Next, convert your character string of times into POSIXct. I like the lubridate function "ymd_hms" here because it's so flexible. You can also set what the time zone was for that, too, using the argument "tz". This returns the time IN YOUR CURRENT TIME ZONE. For example, I'm in Seattle, so this returns the equivalent time in PST for me. I'm pretty sure lubridate accounts for daylight savings time. (I'm having difficulty getting this to sapply and thus opting for a "for" loop. I'm sure someone else could make this happen without that, though.)

time_zone_info$Time2 <- as.POSIXct(NA)
for(i in 1:nrow(time_zone_info)){
      time_zone_info$Time2[i] <- ymd_hms(time_zone_info$Time[i],
                                         tz = time_zone_info$Timezone[i])
}

Everything in time_zone_info$Time2 will be in the same time zone, and I believe that's by design for making easy comparisons. It's hard to get R to make multiple time zones in the same column of a data.frame.


问:
NDK support with different Product Flavour
I want different string value from ndk library.
as i have two flavor demo and live I want value "hello I am from  demo " for demo flavor and for live flavor  i want "hello I am from live "

Here is my java file code

```<code>public class MainActivity extends AppCompatActivity {
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Example of a call to a native method
    TextView tv = (TextView) findViewById(R.id.sample_text);
    tv.setText(stringFromJNI());
}

/**
 * A native method that is implemented by the 'native-lib' native library,
 * which is packaged with this application.
 */
public native String stringFromJNI();
</code>```

}

Here is my cpp file code

```<code>#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring JNICALL
Java_com_de_demo_ndk2_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "hello I am from  demo";
    return env->NewStringUTF(hello.c_str());
}
</code>```

this is my build.gradle file

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.de.demo.ndk2"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        flavorDimensions "default"
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {

        demo
                {
                    // applicationId "com.readwhere.whitelabel.test"
                    //applicationId "com.android.rwstaging"
                    applicationId "com.android.demo"
                    versionName "2.1"
                    dimension "default"

                    externalNativeBuild {
                        cmake {

                            targets "native-lib-demo","my-executible-                   demo"

                        }}

                }
        live
                {
                    // applicationId "com.readwhere.whitelabel.test"
                    //applicationId "com.android.rwstaging"
                    applicationId "com.android.live"
                    versionName "2.1"
                    dimension "default"

                }}
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}
</code>```

I have paste same cpp file in demo folder as well as in main folder
but could achieve my task. Any help would be appreciate
this are some refrence links

https://developer.android.com/studio/projects/gradle-external-native-builds.html

How to set CmakeLists path in product flavor for each Android ABI?

答:
Probably, the minimal code to achieve your goal at compile time is to set cppFLags per flavor:

```<code>productFlavors {
  demo {
    applicationId "com.android.demo"
    versionName "2.1"
    dimension "default"

    externalNativeBuild.cmake {
      cppFlags '-DDEMO'
    }
  }
  live {
     applicationId "com.android.live"
     versionName "2.1"
     dimension "default"
    externalNativeBuild.cmake {
      cppFlags '-DLIVE'
    }
  }
}
</code>```

and in your cpp file

```<code>#ifdef DEMO
  std::string hello = "hello I am from demo";
#endif
#ifdef LIVE
  std::string hello = "hello I am from live";
#endif
</code>```

Or you can use stingify pattern as in this answer.

Naturally, your conditional compilation is not limited to string variation.

Body:
I want different string value from ndk library.
as i have two flavor demo and live I want value "hello I am from  demo " for demo flavor and for live flavor  i want "hello I am from live "

Here is my java file code

public class MainActivity extends AppCompatActivity {
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Example of a call to a native method
    TextView tv = (TextView) findViewById(R.id.sample_text);
    tv.setText(stringFromJNI());
}

/**
 * A native method that is implemented by the 'native-lib' native library,
 * which is packaged with this application.
 */
public native String stringFromJNI();

}

Here is my cpp file code

#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring JNICALL
Java_com_de_demo_ndk2_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "hello I am from  demo";
    return env->NewStringUTF(hello.c_str());
}

this is my build.gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.de.demo.ndk2"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        flavorDimensions "default"
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {

        demo
                {
                    // applicationId "com.readwhere.whitelabel.test"
                    //applicationId "com.android.rwstaging"
                    applicationId "com.android.demo"
                    versionName "2.1"
                    dimension "default"

                    externalNativeBuild {
                        cmake {

                            targets "native-lib-demo","my-executible-                   demo"

                        }}

                }
        live
                {
                    // applicationId "com.readwhere.whitelabel.test"
                    //applicationId "com.android.rwstaging"
                    applicationId "com.android.live"
                    versionName "2.1"
                    dimension "default"

                }}
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

I have paste same cpp file in demo folder as well as in main folder
but could achieve my task. Any help would be appreciate
this are some refrence links

https://developer.android.com/studio/projects/gradle-external-native-builds.html

How to set CmakeLists path in product flavor for each Android ABI?

Body:
Probably, the minimal code to achieve your goal at compile time is to set cppFLags per flavor:

productFlavors {
  demo {
    applicationId "com.android.demo"
    versionName "2.1"
    dimension "default"

    externalNativeBuild.cmake {
      cppFlags '-DDEMO'
    }
  }
  live {
     applicationId "com.android.live"
     versionName "2.1"
     dimension "default"
    externalNativeBuild.cmake {
      cppFlags '-DLIVE'
    }
  }
}

and in your cpp file

#ifdef DEMO
  std::string hello = "hello I am from demo";
#endif
#ifdef LIVE
  std::string hello = "hello I am from live";
#endif

Or you can use stingify pattern as in this answer.

Naturally, your conditional compilation is not limited to string variation.


问:
Showing Div via CSS selector within a UL
I want to build CSS drop down menus.

I want to solve the problem of too long drop down items in UL. So I want to use DIV within a UL.

If you run this example, heading 3 will show you drop down UL items. I want the same for Heading 2 link. Because I put that UL in a DIV. So how can I do it?

CSS Code:

```<code>li{
    list-style: none;
    float: left;
}

li ul {
    display: none;
    background-color: #69f;
}

li:hover > div#mDiv {
    display: block;
}

.menuDiv{
    display: none;
}

li:hover > ul {
    display: block;
}
</code>```

Markup:

```<code><ul>
  <li><a href="#">Heading 1</a></li>
  <li><a href="#">Heading 2</a>
    <div class = "menuDiv" id = "mDiv">
        <ul>
          <li><a href="#">Subitem 1</a></li>
          <li><a href="#">Subitem 2</a></li>
          <li><a href="#">Subitem 3</a></li>
        </ul>
    </div>
  </li>
  <li><a href="#">Heading 3</a>
    <ul>
      <li><a href="#">Subitem 4</a></li>
      <li><a href="#">Subitem 5</a></li>
      <li><a href="#">Subitem 6</a></li>
    </ul>
  </li>
  </ul>
</code>```

答:
Get rid of the > combinator so the inner uls get picked up whether they're in a containing div or not:

```<code>li:hover ul {
    display: block;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to build CSS drop down menus.

I want to solve the problem of too long drop down items in UL. So I want to use DIV within a UL.

If you run this example, heading 3 will show you drop down UL items. I want the same for Heading 2 link. Because I put that UL in a DIV. So how can I do it?

CSS Code:

li{
    list-style: none;
    float: left;
}

li ul {
    display: none;
    background-color: #69f;
}

li:hover > div#mDiv {
    display: block;
}

.menuDiv{
    display: none;
}

li:hover > ul {
    display: block;
}

Markup:

Heading 1

Heading 2

Subitem 1

Subitem 2

Subitem 3

Heading 3

Subitem 4

Subitem 5

Subitem 6

Body:
Get rid of the > combinator so the inner uls get picked up whether they're in a containing div or not:

li:hover ul {
    display: block;
}


答:
I'm not familiar with Atom. Are each of these selectors within dom elements in Atom?

If all of your selectors existed within  then you could do something like this...

```<code>$('span.selector').each(function(elm){
    $(elm).text($(elm).text().split('ܢ').join('<b style="display:none;">ܢ</b>'));
});
</code>```

Title: Select/Apply Styles to specific character with Javascript

Body:
I'm not familiar with Atom. Are each of these selectors within dom elements in Atom?

If all of your selectors existed within <span class="selector"> then you could do something like this...

$('span.selector').each(function(elm){
    $(elm).text($(elm).text().split('ܢ').join('<b style="display:none;">ܢ</b>'));
});


问:
fs.writeFile in a promise, asynchronous-synchronous stuff
I need some help with my code. I'm new at Node.js and have a lot of trouble with it.

What I'm trying to do:

Fetch a .txt with Amazon products (ASINs) ;

Fetch all products using the amazon-product-api package;

Save each product in a .json file.

My code is not working. I think I messed up with this asynchronous-synchronous stuff - help me!

```<code>var amazon = require('amazon-product-api');
var fs = require('fs');

var client = amazon.createClient({
    awsId: "XXX",
    awsSecret: "XXX",
    awsTag: "888"
});

var array = fs.readFileSync('./test.txt').toString().split('\n');
for (var i = 1; i < array.length; i++) {
     var ASIN = array[i];

    client.itemLookup({
            domain: 'webservices.amazon.de',
            responseGroup: 'Large',
            idType: 'ASIN',
            itemId: ASIN
        })
        .then(function(results) {
            fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("JSON saved");
                }
            })

            return results;

        }).catch(function(err) {
            console.log(err);
        });
};
</code>```

答:
say

```<code>const util = require('util')
const fs_writeFile = util.promisify(fs.writeFile)
</code>```

https://nodejs.org/api/util.html#util_util_promisify_original

this is less prone to bugs than the top-voted answer

Body:
I need some help with my code. I'm new at Node.js and have a lot of trouble with it.

What I'm trying to do:

Fetch a .txt with Amazon products (ASINs) ;

Fetch all products using the amazon-product-api package;

Save each product in a .json file.

My code is not working. I think I messed up with this asynchronous-synchronous stuff - help me!

var amazon = require('amazon-product-api');
var fs = require('fs');

var client = amazon.createClient({
    awsId: "XXX",
    awsSecret: "XXX",
    awsTag: "888"
});

var array = fs.readFileSync('./test.txt').toString().split('\n');
for (var i = 1; i < array.length; i++) {
     var ASIN = array[i];

    client.itemLookup({
            domain: 'webservices.amazon.de',
            responseGroup: 'Large',
            idType: 'ASIN',
            itemId: ASIN
        })
        .then(function(results) {
            fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("JSON saved");
                }
            })

            return results;

        }).catch(function(err) {
            console.log(err);
        });
};

Body:
say

const util = require('util')
const fs_writeFile = util.promisify(fs.writeFile)

https://nodejs.org/api/util.html#util_util_promisify_original

this is less prone to bugs than the top-voted answer


问:
ARM template to create ASA job with javascript UDAs
I have a stream analytics job which uses a number of javascript UDFs and UDAs. I would like to be able to deploy this using an Azure resource manager template.

The documentation at https://learn.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-function seems rather outdated and only describes Scalar functions, which I assume means UDFs.

Are there any documentation or examples showing how to create UDAs using an ARM template?

答:
If you have created a job with UDA already, use PowerShell command Get-AzureRMStreamAnalyticsJob to retrieve the job definition and you will find out how UDA is defined.

https://learn.microsoft.com/en-us/azure/stream-analytics/stream-analytics-monitor-and-manage-jobs-use-powershell


问:
How to remove unused objects after matching with another array?
I have an array of objects and another array of names like the following:

array of objects as file info objects

```<code>[
  { fieldname: 'banner', path: 'banner_img_path' },
  { fieldname: 'logo'  , path: 'logo_img_path'   },
  { fieldname: 'random', path: 'random_img_path' }
]
</code>```

and here is my array of names

```<code>['banner', 'logo']
</code>```

So how can i match or mapping those two variables! note that after mapping or matching, all not used objects should be deleted from the original array of objects?? i need to get object like that

```<code>{
  banner: banner_img_path,
  logo  : logo_img_path
}
</code>```

I'm able to do matching but i was stuck with erasing those not used objects.

Note: May be this question is duplicated but only because i don't know what is the name of this operation!
so please forgive me.

答:
There is a simple solution by using functional native JavaScript functions.

const obj = [
  { fieldname: 'banner', path: 'banner_img_path' },
  { fieldname: 'logo', path: 'logo_img_path' },
  { fieldname: 'random', path: 'random_img_path' },
  { fieldname: 'other', path: 'random_img_path' }
];

const names = ['banner', 'logo'];

obj.map((o, i) => {
 let match = false;
  names.some((item) => {
   if (item === o.fieldname) {
     match = true;
     return true;
    }
  });
  if (!match) {
   delete obj[i];
  }
});

for (let o in obj) {
 document.querySelector('p').innerHTML += obj[o].fieldname + '
';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p></p></code>```

Body:
I have an array of objects and another array of names like the following:

array of objects as file info objects

[
  { fieldname: 'banner', path: 'banner_img_path' },
  { fieldname: 'logo'  , path: 'logo_img_path'   },
  { fieldname: 'random', path: 'random_img_path' }
]

and here is my array of names

['banner', 'logo']

So how can i match or mapping those two variables! note that after mapping or matching, all not used objects should be deleted from the original array of objects?? i need to get object like that

{
  banner: banner_img_path,
  logo  : logo_img_path
}

I'm able to do matching but i was stuck with erasing those not used objects.

Note: May be this question is duplicated but only because i don't know what is the name of this operation!
so please forgive me.

Body:
There is a simple solution by using functional native JavaScript functions.

const obj = [
  { fieldname: 'banner', path: 'banner_img_path' },
  { fieldname: 'logo', path: 'logo_img_path' },
  { fieldname: 'random', path: 'random_img_path' },
  { fieldname: 'other', path: 'random_img_path' }
];

const names = ['banner', 'logo'];

obj.map((o, i) => {
 let match = false;
  names.some((item) => {
   if (item === o.fieldname) {
     match = true;
     return true;
    }
  });
  if (!match) {
   delete obj[i];
  }
});

for (let o in obj) {
 document.querySelector('p').innerHTML += obj[o].fieldname + '<br>';
}

<p></p>


问:
trying to draw a sprite onto canvas but I am missing something

window.onload = function(){
  theVideo();
  playVideo();
  Move();
  Draw();
};
let objectInfo = {
    canvas: null,
    context: null,
    // Number of sprites
    numberOfFrames: 16,
    image: null,
    imageWidth: 128,
    imageHeight: 192,
    frameIndex: 0,
    frameWidth: 0,
    // Animation interval (ms)
    msInterval: 1000,
    x: 10,
    y: 10,
};
const imageFile = "shaggy.png";
 function Draw(){
  objectInfo.context.drawImage(myImage, shift, 0, frameWidth, frameHeight, 120, 25, frameWidth, frameHeight);
 }
//image setup
window.onload= function () {

    // Canvas setup
    objectInfo.canvas = document.querySelector("#myCanvas");
    objectInfo.context = objectInfo.canvas.getContext("2d");

    // Image setup
    objectInfo.image = new Image();
    objectInfo.image.onload = function() {

        // The this object refers to image because within image onload event handler
        objectInfo.imageWidth = this.width;
        objectInfo.imageHeight = this.height;

        // Calculate framewidth (size of each sprite)
        objectInfo.frameWidth = objectInfo.imageWidth / objectInfo.numberOfFrames;
    };
    // Load image
    objectInfo.image.src = imageFile;

};

var xPos = 0;
var yPos = 0;

//move image
function Move(e){
  //right
  if(e.keyCode==39){
      xPos+=5;
  }
  //left
  if(e.keyCode==37){
      xPos-=5;
  }
  //up
   if(e.keyCode==38){
      yPos-=5;
   }
   //down
    if(e.keyCode==40){
      yPos+=5;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <title>Sprite</title>
    <meta charset="utf-8">
    <meta name="author" content="Peyton">
    <meta name="description" content="115">
    <link rel= 'stylesheet' href="p4.css">
    <script src="p4.js"> </script>
      <style>canvas { border: 1px solid black; }</style>
<body>
    <canvas width= "1300" height= "600" id= "myCanvas">

    <video id="video" controls >
        <source src="ScoobyDooV.mp4"/>
        <source src="ScoobyDooV.ogv"/>
    </video>

    </canvas>
    </body>

    </html>
    <nav>
    </nav>
    <main id="#wrapper"><br>

    </main>
</body>
</html></code>```

I'm really new to coding and am not sure what I am missing to call my sprite and draw the first image onto the canvas. I later have to call each measurement of my sprite and assign to a function keydown event to make it look like its walking each direction so if I could get any guidance on that too that would be great.

答: You are defining window.onload twice, only one out of your two callbacks will be executed

Body:
window.onload = function(){
  theVideo();
  playVideo();
  Move();
  Draw();
};
let objectInfo = {
    canvas: null,
    context: null,
    // Number of sprites
    numberOfFrames: 16,
    image: null,
    imageWidth: 128,
    imageHeight: 192,
    frameIndex: 0,
    frameWidth: 0,
    // Animation interval (ms)
    msInterval: 1000,
    x: 10,
    y: 10,
};
const imageFile = "shaggy.png";
 function Draw(){
  objectInfo.context.drawImage(myImage, shift, 0, frameWidth, frameHeight, 120, 25, frameWidth, frameHeight);
 }
//image setup
window.onload= function () {

    // Canvas setup
    objectInfo.canvas = document.querySelector("#myCanvas");
    objectInfo.context = objectInfo.canvas.getContext("2d");

    // Image setup
    objectInfo.image = new Image();
    objectInfo.image.onload = function() {

        // The this object refers to image because within image onload event handler
        objectInfo.imageWidth = this.width;
        objectInfo.imageHeight = this.height;

        // Calculate framewidth (size of each sprite)
        objectInfo.frameWidth = objectInfo.imageWidth / objectInfo.numberOfFrames;
    };
    // Load image
    objectInfo.image.src = imageFile;

};

var xPos = 0;
var yPos = 0;

//move image
function Move(e){
  //right
  if(e.keyCode==39){
      xPos+=5;
  }
  //left
  if(e.keyCode==37){
      xPos-=5;
  }
  //up
   if(e.keyCode==38){
      yPos-=5;
   }
   //down
    if(e.keyCode==40){
      yPos+=5;
    }
}

<!DOCTYPE html>

    <title>Sprite</title>
    <meta charset="utf-8">
    <meta name="author" content="Peyton">
    <meta name="description" content="115">
    <link rel= 'stylesheet' href="p4.css">

    <canvas width= "1300" height= "600" id= "myCanvas">

    <video id="video" controls >
        <source src="ScoobyDooV.mp4"/>
        <source src="ScoobyDooV.ogv"/>
    </video>

    </canvas>

I'm really new to coding and am not sure what I am missing to call my sprite and draw the first image onto the canvas. I later have to call each measurement of my sprite and assign to a function keydown event to make it look like its walking each direction so if I could get any guidance on that too that would be great.


答:
It's because of float: left.

Option 1:

Use display:inline-block instead of float:left:

.square {
    display: inline-block;
    border: 1px solid black;
    width: 50px;
    height: 50px;
    margin: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>

<div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>

<div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>

</body>
</html></code>```

Option 2
Use clearfix in parent div:

.square {
    display: block;
    float: left;
    border: 1px solid black;
    width: 50px;
    height: 50px;
    margin: 30px;
}
.parent{
    clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>

<div class="parent">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>

<div class="parent">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>

</body>
</html></code>```

Title: How to start a new line of an array of squares with CSS

Body:
It's because of float: left.

Option 1:

Use display:inline-block instead of float:left:

.square {
    display: inline-block;
    border: 1px solid black;
    width: 50px;
    height: 50px;
    margin: 30px;
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>

<div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>

</body>
</html>

Option 2
Use clearfix in parent div:

.square {
    display: block;
    float: left;
    border: 1px solid black;
    width: 50px;
    height: 50px;
    margin: 30px;
}
.parent{
    clear: both;
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<div class="parent">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>

<div class="parent">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>

</body>
</html>


问:
A network-related or instance-specific error occurred while establishing a connection to SQL Server
```<code>A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
</code>```

when i upload my site on webserver and connect with remote sqlserver2005 using connection string....

```<code><connectionStrings>
    <remove name="ConnectionString"/>
    <add name="ConnectionString" connectionString="Data Source=69.16.253.19,1433;Initial Catalog=vb_usa;Persist Security Info=True;User ID=username;Password=password" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</code>```

it produces the following errr --
you can see error in my webpage :

http://vbi.volvobusesindia.com

it shows an error above ..

i m using aspnetdb.mdf in my website in APP_Data Folder... features i use in my website is Login Control, Password recovery, signup control...

答: On that remote machine (63.15.223.19), the SQL services are not running. You can go to that machine and try to run "net start mssqlserver" from command prompt.</p>

Body:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

when i upload my site on webserver and connect with remote sqlserver2005 using connection string....

<connectionStrings>
    <remove name="ConnectionString"/>
    <add name="ConnectionString" connectionString="Data Source=69.16.253.19,1433;Initial Catalog=vb_usa;Persist Security Info=True;User ID=username;Password=password" providerName="System.Data.SqlClient"/>
  </connectionStrings>

it produces the following errr --
you can see error in my webpage :

http://vbi.volvobusesindia.com

it shows an error above ..

i m using aspnetdb.mdf in my website in APP_Data Folder... features i use in my website is Login Control, Password recovery, signup control...


问:
How to colorize Segoe MDL2 Icons in WPF?
I am looking for a way to add colour to Segoe MDL2 icons. The glyphs in my application are currently TextBlock resources, defined like this:

```<code><TextBlock x:Key="PenSymbol" x:Shared="False" FontFamily="Segoe MDL2 Assets" Text="" FontSize="16" TextOptions.TextRenderingMode="Grayscale"/>
</code>```

The effect I'm after is the one in the left 3 icons:

This is a screenshot of the toolbar in Window 10 Sketchpad (after applying the Creators update).

Edit: I know how to change the text colour, I am trying to figure out how to get the "partial fill"-effect (blue, black and yellow in the screenshot).

Edit2: It is necessary to display 2 different glyphs to achieve this effect. The glyphs necessary for the background were added to the Segoe MDL2 font in the last update. Thanks to mm8 for pointing me in the right direction.

XAML:

```<code><Style x:Key="SymbolText" TargetType="{x:Type TextBlock}">
    <Setter Property="FontSize" Value="16"/>
    <Setter Property="UseLayoutRounding" Value="True"/>
    <Setter Property="TextAlignment" Value="Center"/>
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="FontFamily" Value="Segoe MDL2 Assets"/>
    <Setter Property="TextOptions.TextRenderingMode" Value="Grayscale"/>
</Style>

<StackPanel Orientation="Horizontal">
    <Grid Margin="4">
        <TextBlock Text="" Style="{StaticResource SymbolText}" Foreground="OrangeRed"/>
        <TextBlock Text="" Style="{StaticResource SymbolText}"/>
    </Grid>
    <Grid Margin="4">
        <TextBlock Text="" Style="{StaticResource SymbolText}" Foreground="LightGreen"/>
        <TextBlock Text="" Style="{StaticResource SymbolText}"/>
    </Grid>
    <Grid Margin="4">
        <TextBlock Text="" Style="{StaticResource SymbolText}" Foreground="LightBlue"/>
        <TextBlock Text="" Style="{StaticResource SymbolText}"/>
    </Grid>
</StackPanel>
</code>```

Result:

答:
You can put one gliph over another and colorize it this way. Example:

```<code><Grid>
    <FontIcon Foreground="#f8d876" FontFamily="Segoe MDL2 Assets" Glyph="" />
    <FontIcon  FontFamily="Segoe MDL2 Assets" Glyph="" />
</Grid>
</code>```

Result:

Body:
I am looking for a way to add colour to Segoe MDL2 icons. The glyphs in my application are currently TextBlock resources, defined like this:

<TextBlock x:Key="PenSymbol" x:Shared="False" FontFamily="Segoe MDL2 Assets" Text="" FontSize="16" TextOptions.TextRenderingMode="Grayscale"/>

The effect I'm after is the one in the left 3 icons:

This is a screenshot of the toolbar in Window 10 Sketchpad (after applying the Creators update).

Edit: I know how to change the text colour, I am trying to figure out how to get the "partial fill"-effect (blue, black and yellow in the screenshot).

Edit2: It is necessary to display 2 different glyphs to achieve this effect. The glyphs necessary for the background were added to the Segoe MDL2 font in the last update. Thanks to mm8 for pointing me in the right direction.

XAML:

<StackPanel Orientation="Horizontal">
    <Grid Margin="4">
        <TextBlock Text="" Style="{StaticResource SymbolText}" Foreground="OrangeRed"/>
        <TextBlock Text="" Style="{StaticResource SymbolText}"/>
    </Grid>
    <Grid Margin="4">
        <TextBlock Text="" Style="{StaticResource SymbolText}" Foreground="LightGreen"/>
        <TextBlock Text="" Style="{StaticResource SymbolText}"/>
    </Grid>
    <Grid Margin="4">
        <TextBlock Text="" Style="{StaticResource SymbolText}" Foreground="LightBlue"/>
        <TextBlock Text="" Style="{StaticResource SymbolText}"/>
    </Grid>
</StackPanel>

Result:

Body:
You can put one gliph over another and colorize it this way. Example:

<Grid>
    <FontIcon Foreground="#f8d876" FontFamily="Segoe MDL2 Assets" Glyph="&#xE8D5;" />
    <FontIcon  FontFamily="Segoe MDL2 Assets" Glyph="&#xE8B7;" />
</Grid>

Result:


问:
Join one table to two separate one-to-many tables
I have three tables, like so:

```<code>projects
| id | name       |
|----|------------|
| 1  | enterprise |
| 2  | discovery  |

widgets
| project_id | name            |
|------------|-----------------|
| 1          | saucer section  |
| 1          | pylons          |
| 2          | spinning saucer |
| 2          | angular pylons  |

sprockets
| project_id | name        |
|------------|-------------|
| 1          | engineering |
| 1          | bridge      |
| 1          | mess        |
| 2          | engineering |
| 2          | bridge      |
| 2          | mess        |
</code>```

What I am trying to write is a query that gives me exactly ten results: essentially one for each row in widgets and sprockets, that looks like this:

```<code>result
| project_name | widget_name     | sprocket_name |
|--------------|-----------------|---------------|
| enterprise   | saucer section  | null          |
| enterprise   | pylons          | null          |
| enterprise   | null            | engineering   |
| enterprise   | null            | bridge        |
| enterprise   | null            | mess          |
| discovery    | spinning saucer | null          |
| discovery    | angular pylons  | null          |
| discovery    | null            | engineering   |
| discovery    | null            | bridge        |
| discovery    | null            | mess          |
</code>```

Instead, my joins are combining to return 12 rows. Adding a group by seems to reduce it too much.

I've tried something like the following, but the joins are multiplied:

```<code>select
  p.name as project_name,
  w.name as widget_name,
  s.name as sprocket_name
from
  projects as p
left join widgets w on p.id = w.project_id
left join sprockets s on p.id = s.project_id;
</code>```

The answers I've found mostly focus on redesigning the database, however that is not an option for me. How can I write a join to return the above ten rows from this dataset?

答:
Use a UNION of joins with each table.

```<code>SELECT p.name AS project_name, w.name AS widget_name, NULL AS sprocket_name
FROM projects AS p
INNER JOIN widgets AS w ON p.id = w.project_id

UNION ALL

SELECT p.name AS project_name, NULL AS widget_name, s.name AS sprocket_name
FROM projects AS p
INNER JOIN sprockets AS s ON p.id = s.project_id
</code>```

Body:
I have three tables, like so:

projects
| id | name       |
|----|------------|
| 1  | enterprise |
| 2  | discovery  |

widgets
| project_id | name            |
|------------|-----------------|
| 1          | saucer section  |
| 1          | pylons          |
| 2          | spinning saucer |
| 2          | angular pylons  |

sprockets
| project_id | name        |
|------------|-------------|
| 1          | engineering |
| 1          | bridge      |
| 1          | mess        |
| 2          | engineering |
| 2          | bridge      |
| 2          | mess        |

What I am trying to write is a query that gives me exactly ten results: essentially one for each row in widgets and sprockets, that looks like this:

result
| project_name | widget_name     | sprocket_name |
|--------------|-----------------|---------------|
| enterprise   | saucer section  | null          |
| enterprise   | pylons          | null          |
| enterprise   | null            | engineering   |
| enterprise   | null            | bridge        |
| enterprise   | null            | mess          |
| discovery    | spinning saucer | null          |
| discovery    | angular pylons  | null          |
| discovery    | null            | engineering   |
| discovery    | null            | bridge        |
| discovery    | null            | mess          |

Instead, my joins are combining to return 12 rows. Adding a group by seems to reduce it too much.

I've tried something like the following, but the joins are multiplied:

select
  p.name as project_name,
  w.name as widget_name,
  s.name as sprocket_name
from
  projects as p
left join widgets w on p.id = w.project_id
left join sprockets s on p.id = s.project_id;

The answers I've found mostly focus on redesigning the database, however that is not an option for me. How can I write a join to return the above ten rows from this dataset?

Body:
Use a UNION of joins with each table.

SELECT p.name AS project_name, w.name AS widget_name, NULL AS sprocket_name
FROM projects AS p
INNER JOIN widgets AS w ON p.id = w.project_id

UNION ALL

SELECT p.name AS project_name, NULL AS widget_name, s.name AS sprocket_name
FROM projects AS p
INNER JOIN sprockets AS s ON p.id = s.project_id


答:
you have to clear your floatting elements

https://css-tricks.com/all-about-floats/

Clearing the Float

Float's sister property is clear. An element that has the clear property set on it will not move up adjacent to the float like the float desires, but will move itself down past the float....

.square {
  display: block;
  float: left;
  border: 1px solid black;
  width: 50px;
  height: 50px;
  margin: 30px;
}
body>div {overflow:hidden;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>

<div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div></code>```

Body:
I'm trying to create a 'grid' of squares using CSS. So far I've tried:

.square {
  display: block;
  float: left;
  border: 1px solid black;
  width: 50px;
  height: 50px;
  margin: 30px;
}

However, this simply display 6 squares in a row. I'd like to have two rows of 3 squares each, however. Why do the encompassing divs not have the 'normal' behavior that they are displayed beneath each other?

Body:
you have to clear your floatting elements

https://css-tricks.com/all-about-floats/

Clearing the Float

Float's sister property is clear. An element that has the clear property set on it will not move up adjacent to the float like the float desires, but will move itself down past the float....

.square {
  display: block;
  float: left;
  border: 1px solid black;
  width: 50px;
  height: 50px;
  margin: 30px;
}
body>div {overflow:hidden;}

<div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>

<div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>


问:
Wrong Calculation by User-Defined SQL-Function
I have a function defined by

```<code>CREATE OR REPLACE FUNCTION public.div(dividend INTEGER, divisor INTEGER)
    RETURNS INTEGER
    LANGUAGE 'sql'
    IMMUTABLE
    LEAKPROOF
    STRICT
    SECURITY DEFINER
    PARALLEL SAFE
    AS $BODY$
        SELECT ($1 + $2/2) / $2;
    $BODY$;
</code>```

It should calculate a commercial rounded result. Most of the times, it does the job. I don't know why, but select div(5, 3) gives me the correct answer while it doesn't when one parameter is calculated by an aggregate, e.g. select div(sum(val), 3) from (select 1 as val UNION SELECT 4) list is sufficient to trigger that.
How can I fix div? I don't want to cast every input.

BTW, using SELECT (cast($1 as integer) + cast($2 as integer)/2) / cast($2 as integer); as the definition of div didn't help.

答:
Change the name of the function.

The function div(numeric, numeric) is a builtin Postgres function and there is an ambiguity which function you want to call:

```<code>select div(5, 3)           -- calls your function public.div(integer, integer)
select div(5::bigint, 3)   -- calls pg_catalog.div(numeric, numeric)
</code>```

In the second case the arguments have to be resolved and the system function is chosen as first.

Note that the function sum(integer) gives bigint as a result.

Body:
I have a function defined by

CREATE OR REPLACE FUNCTION public.div(dividend INTEGER, divisor INTEGER)
    RETURNS INTEGER
    LANGUAGE 'sql'
    IMMUTABLE
    LEAKPROOF
    STRICT
    SECURITY DEFINER
    PARALLEL SAFE
    AS $BODY$
        SELECT ($1 + $2/2) / $2;
    $BODY$;

It should calculate a commercial rounded result. Most of the times, it does the job. I don't know why, but select div(5, 3) gives me the correct answer while it doesn't when one parameter is calculated by an aggregate, e.g. select div(sum(val), 3) from (select 1 as val UNION SELECT 4) list is sufficient to trigger that.
How can I fix div? I don't want to cast every input.

BTW, using SELECT (cast($1 as integer) + cast($2 as integer)/2) / cast($2 as integer); as the definition of div didn't help.

Body:
Change the name of the function.

The function div(numeric, numeric) is a builtin Postgres function and there is an ambiguity which function you want to call:

select div(5, 3)           -- calls your function public.div(integer, integer)
select div(5::bigint, 3)   -- calls pg_catalog.div(numeric, numeric)

In the second case the arguments have to be resolved and the system function is chosen as first.

Note that the function sum(integer) gives bigint as a result.


问:
java - How to upgrade project from gwt 2.5.0 to gwt 2.8.2
I am trying to upgrade my GWT application, which is using GWT 2.5.0 and JDK 6, so I am wondering if any one can help me figuring out the impact or the thinks that should be upgraded.

Thanks in advance.

答:
Um...  Upgrade your jars to 2.8.2, and (ideally) set your java language level to 1.8 (and enjoy using lambdas).

If there are compilation errors, fix them, but there probably won't be, as the gwt project generally avoids making backwards incompatible changes.

Instead of listing everything that could go wrong but probably won't it would be better to just update to 2.8.2, and if any errors appear, hop over to the gwtproject gitter and ask about any specific problem you are having.

https://gitter.im/gwtproject/gwt


问:
Hibernate 5.2.10: Unable to perform unmarshalling

Edit 5: Solved

The main problem was that I've used JDK 9, where the JAXB APIs are no longer on on the default class path. Here is link where I've found solution.

I used hibernate version 4.3.6 from example tutorial and everything've worked good, but when I update version to 5.2.10 I have problem (I know that code responsible for getSessionFactory is different so I changed it).

My first function:

```<code>private static SessionFactory getSessionFactory(){
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
    return sessionFactory;
}
</code>```

And my function in 5.2.10 version:

```<code>private static SessionFactory getSessionFactory(){

    StandardServiceRegistry registry;
    SessionFactory sessionFactory;
    registry = new StandardServiceRegistryBuilder().configure().build();

    MetadataSources sources = new MetadataSources(registry);

    Metadata metadata = sources.getMetadataBuilder().build();

    sessionFactory = metadata.getSessionFactoryBuilder().build();
    return sessionFactory;

}
</code>```

Exception:

Exception in thread "main"
  org.hibernate.internal.util.config.ConfigurationException: Unable to
  perform unmarshalling at line number 0 and column 0 in RESOURCE
  hibernate.cfg.xml. Message: null

and hibernate.cfg.xml

```<code><?xml version="1.0" encoding="utf-8"?>
        <!DOCTYPE hibernate-configuration SYSTEM

"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL94Dialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/postgres</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">123</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="show_sql">false</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="com.example.Item"/>
    </session-factory>
</hibernate-configuration>
</code>```

Where is the problem? I've tried everything.

Edit: pom.xml

```<code>  <?xml version="1.0" encoding="UTF-8"?>
<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>pl.example</groupId>
<artifactId>example</artifactId>
<version>1.0-SNAPSHOT</version>

<build>
    <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.1.4</version>
    </dependency>

    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
    </dependency>

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

Edit 2

```<code>public class HibernateUtil {
    private static final SessionFactory sessionFactory;
static {
    try {
        StandardServiceRegistry standardRegistry =
                new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata metaData =
                new MetadataSources(standardRegistry).getMetadataBuilder().build();
        sessionFactory = metaData.getSessionFactoryBuilder().build();
    } catch (Throwable th) {

        System.err.println("Enitial SessionFactory creation failed" + th);
        throw new ExceptionInInitializerError(th);

    }
}
public static SessionFactory getSessionFactory() {

    return sessionFactory;

}
</code>```

}

```<code>@Entity
@Table(name = "employee")
public class Employee implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="emp_name")
    private String empName;

    @Column(name="emp_address")
    private String empAddress;

    @Column(name="emp_mobile_nos")
    private String empMobileNos;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public String getEmpAddress() {
        return empAddress;
    }

    public void setEmpAddress(String empAddress) {
        this.empAddress = empAddress;
    }

    public String getEmpMobileNos() {
        return empMobileNos;
    }

    public void setEmpMobileNos(String empMobileNos) {
        this.empMobileNos = empMobileNos;
    }

}
</code>```

Testing class.

```<code>  public class Test{
    public static void main(String[] args) throws Exception {

        SessionFactory sessFact = HibernateUtil.getSessionFactory();
        Session session = sessFact.getCurrentSession();
        org.hibernate.Transaction tr = session.beginTransaction();
        Employee emp = new Employee();
        emp.setEmpName("Deepak Kumar");
        emp.setEmpMobileNos("000000");
        emp.setEmpAddress("Delhi - India");
        session.save(emp);
        tr.commit();
        System.out.println("Successfully inserted");
        sessFact.close();
    }

}
</code>```

Edit 3

```<code>lis 17, 2017 11:54:50 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
lis 17, 2017 11:54:50 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
lis 17, 2017 11:54:50 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
Enitial SessionFactory creation failedorg.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
Exception in thread "main" java.lang.ExceptionInInitializerError
    at pl.lostandfound.HibernateUtil.<clinit>(HibernateUtil.java:31)
    at pl.lostandfound.Test.main(Test.java:13)
Caused by: org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
    at pl.lostandfound.HibernateUtil.<clinit>(HibernateUtil.java:24)
    ... 1 more
Caused by: javax.xml.bind.JAXBException
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:241)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:477)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:656)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:599)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
    ... 5 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    at javax.xml.bind.ContextFinder.safeLoadClass(ContextFinder.java:594)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:239)
    ... 9 more
</code>```

Edit 4

```<code>    log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Enitial SessionFactory creation failedorg.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
Exception in thread "main" java.lang.ExceptionInInitializerError
</code>```

答:
I would certainly first fix the ClassNotFound Exception (java.lang.ClassNotFoundException:com.sun.xml.internal.bind.v2.ContextFactory). This indicated that a class that needed to be loaded is not present...

Maybe adding the following dependency would fix your problem:

```<code><dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.3.0</version>
</dependency>
</code>```

Most recent version taken from here: https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl

If the ClassNotFound exception is still there...I would look more closely what version of JAXB hibernate is using. A very nice way to analyze your dependencies are the following two commands:

```<code>mvn clean dependency:analyze
</code>```

and

```<code>mvn clean dependency:tree
</code>```

For Edit4: check following answers:

ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml] in project root folder

Location of hibernate.cfg.xml in project?

Body:
Edit 5: Solved

The main problem was that I've used JDK 9, where the JAXB APIs are no longer on on the default class path. Here is link where I've found solution.

I used hibernate version 4.3.6 from example tutorial and everything've worked good, but when I update version to 5.2.10 I have problem (I know that code responsible for getSessionFactory is different so I changed it).

My first function:

private static SessionFactory getSessionFactory(){
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
    return sessionFactory;
}

And my function in 5.2.10 version:

private static SessionFactory getSessionFactory(){

    StandardServiceRegistry registry;
    SessionFactory sessionFactory;
    registry = new StandardServiceRegistryBuilder().configure().build();

    MetadataSources sources = new MetadataSources(registry);

    Metadata metadata = sources.getMetadataBuilder().build();

    sessionFactory = metadata.getSessionFactoryBuilder().build();
    return sessionFactory;

}

Exception:

Exception in thread "main"
  org.hibernate.internal.util.config.ConfigurationException: Unable to
  perform unmarshalling at line number 0 and column 0 in RESOURCE
  hibernate.cfg.xml. Message: null

and hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
        <!DOCTYPE hibernate-configuration SYSTEM

"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL94Dialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/postgres</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">123</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="show_sql">false</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="com.example.Item"/>
    </session-factory>
</hibernate-configuration>

Where is the problem? I've tried everything.

Edit: pom.xml

  <?xml version="1.0" encoding="UTF-8"?>
<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>pl.example</groupId>
<artifactId>example</artifactId>
<version>1.0-SNAPSHOT</version>

<build>
    <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.1.4</version>
    </dependency>

    <dependency>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
    </dependency>

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

Edit 2

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
static {
    try {
        StandardServiceRegistry standardRegistry =
                new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata metaData =
                new MetadataSources(standardRegistry).getMetadataBuilder().build();
        sessionFactory = metaData.getSessionFactoryBuilder().build();
    } catch (Throwable th) {

        System.err.println("Enitial SessionFactory creation failed" + th);
        throw new ExceptionInInitializerError(th);

    }
}
public static SessionFactory getSessionFactory() {

    return sessionFactory;

}

}

@Entity
@Table(name = "employee")
public class Employee implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="emp_name")
    private String empName;

    @Column(name="emp_address")
    private String empAddress;

    @Column(name="emp_mobile_nos")
    private String empMobileNos;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public String getEmpAddress() {
        return empAddress;
    }

    public void setEmpAddress(String empAddress) {
        this.empAddress = empAddress;
    }

    public String getEmpMobileNos() {
        return empMobileNos;
    }

    public void setEmpMobileNos(String empMobileNos) {
        this.empMobileNos = empMobileNos;
    }

}

Testing class.

  public class Test{
    public static void main(String[] args) throws Exception {

        SessionFactory sessFact = HibernateUtil.getSessionFactory();
        Session session = sessFact.getCurrentSession();
        org.hibernate.Transaction tr = session.beginTransaction();
        Employee emp = new Employee();
        emp.setEmpName("Deepak Kumar");
        emp.setEmpMobileNos("000000");
        emp.setEmpAddress("Delhi - India");
        session.save(emp);
        tr.commit();
        System.out.println("Successfully inserted");
        sessFact.close();
    }

}

Edit 3

lis 17, 2017 11:54:50 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
lis 17, 2017 11:54:50 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
lis 17, 2017 11:54:50 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
Enitial SessionFactory creation failedorg.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
Exception in thread "main" java.lang.ExceptionInInitializerError
    at pl.lostandfound.HibernateUtil.<clinit>(HibernateUtil.java:31)
    at pl.lostandfound.Test.main(Test.java:13)
Caused by: org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
    at pl.lostandfound.HibernateUtil.<clinit>(HibernateUtil.java:24)
    ... 1 more
Caused by: javax.xml.bind.JAXBException
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:241)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:477)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:656)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:599)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
    ... 5 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    at javax.xml.bind.ContextFinder.safeLoadClass(ContextFinder.java:594)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:239)
    ... 9 more

Edit 4

    log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Enitial SessionFactory creation failedorg.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
Exception in thread "main" java.lang.ExceptionInInitializerError

Body:
I would certainly first fix the ClassNotFound Exception (java.lang.ClassNotFoundException:com.sun.xml.internal.bind.v2.ContextFactory). This indicated that a class that needed to be loaded is not present...

Maybe adding the following dependency would fix your problem:

<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.3.0</version>
</dependency>

Most recent version taken from here: https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl

If the ClassNotFound exception is still there...I would look more closely what version of JAXB hibernate is using. A very nice way to analyze your dependencies are the following two commands:

mvn clean dependency:analyze

and

mvn clean dependency:tree

For Edit4: check following answers:

ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml] in project root folder

Location of hibernate.cfg.xml in project?


问:
Changing .gitconfig location on Windows
By default on Windows Git places global .gitconfig in c:\documents and settings\user\

How can I change that position so .gitconfig is stored in c:\my_configuration_files\?

Can it be done at all?

答:
As someone who has been interested in this for a VERY LONG TIME. See from the manual:

$XDG_CONFIG_HOME/git/config - Second user-specific configuration file. If $XDG_CONFIG_HOME is not set or empty, $HOME/.config/git/config will be used. Any single-valued variable set in this file will be overwritten by whatever is in ~/.gitconfig. It is a good idea not to create this file if you sometimes use older versions of Git, as support for this file was added fairly recently.

Which was only recently added. This dump is from 2.15.0.

Works for me.

Title: Changing .gitconfig location on Windows