问:
How to minimize duplicate queries
Suppose I have two datasets.

In QlikView, if I try to include these in a load using a query like the following:

```<code>sql select marriage_id, primary_person_id, seconary_person_id, marriage_start_date, marriage_end_date from marriage_table;

sql select person_id as primary_person_id, person_id as seconary_person_id, first_name, middle_name, last_name, date_of_birth from person_table;
</code>```

I will get an error about how I could be leading myself to have inaccurate data, as QlikView has two potential paths to get to PERSON_TABLE. Which makes sense, but I really really hate the idea of duplicating the selects and tables like the following.

```<code>sql select marriage_id, primary_person_id, seconary_person_id, marriage_start_date, marriage_end_date from marriage_table;

sql select person_id as primary_person_id, first_name, middle_name, last_name, date_of_birth from person_table;

sql select person_id as seconary_person_id, first_name, middle_name, last_name, date_of_birth from person_table;
</code>```

Is there a better way to deal with this that I'm missing?

答:
What you are showing in that figure is called "circular reference" (I think Qlikview calls it "Synthetic Key") and it is something that you should really try to avoid since it may make your app, not crash, but show incorrect results (which is worse).
In my opinion you have two options:

Op1 - Duplicate your PERSON_TABLE so that PRIMARY_PERSON_ID will be linked to PERSON_TABLE_1 and SECONDARY_PERSON_ID will be linked to PERSON_TABLE_2.

```<code>PERSON_TABLE_1:
SQL SELECT person_id as primary_person_id,
first_name as first_name_1,
middle_name as middle_name_1,
last_name as last_name_1,
date_of_birth as date_of_birth_1
FROM person_table

PERSON_TABLE_2:
SQL SELECT person_id as secondary_person_id,
first_name as first_name_2,
middle_name as middle_name_2,
last_name as last_name_2,
date_of_birth as date_of_birth_2
FROM person_table
</code>```

The problem with this option is that you have to choose different alias for each field, which is usually not very convenient depending on the type of analysis you do in your app.

Op2: Create a unique MARRIAGE_TABLE already including the data of the two people. For that you can create a SQL query with two JOINS (I will only use first and middle names for simplicity, but you can add all the other fields)

```<code>SELECT T1.*, T2.first_name as first_name_1, T2.middle_name as middle_name_1,
T3.first_name as first_name_2, T3.middle_name as middle_name_2
FROM MARRIAGE_TABLE AS T1
LEFT JOIN PERSON_TABLE AS T2 ON Q1.primary_person_id = T2.person_id
LEFT JOIN PERSON_TABLE AS T3 ON Q1.secondary_person_id = T3.person_id
</code>```

which will result in a unique table with the following columns:

```<code>MARRIAGE_ID PRIMARY_PERSON_ID SECONDARY_PERSON_ID MARRIAGE_START_DATE MARRIAGE_END_DATE FIRST_NAME_1 MIDDLE_NAME_1 FIRST_NAME_2 MIDDLE_NAME_2
</code>```

Title: How to minimize duplicate queries

Body:
Suppose I have two datasets.

In QlikView, if I try to include these in a load using a query like the following:

sql select marriage_id, primary_person_id, seconary_person_id, marriage_start_date, marriage_end_date from marriage_table;

sql select person_id as primary_person_id, person_id as seconary_person_id, first_name, middle_name, last_name, date_of_birth from person_table;

I will get an error about how I could be leading myself to have inaccurate data, as QlikView has two potential paths to get to PERSON_TABLE. Which makes sense, but I really really hate the idea of duplicating the selects and tables like the following.

sql select marriage_id, primary_person_id, seconary_person_id, marriage_start_date, marriage_end_date from marriage_table;

sql select person_id as primary_person_id, first_name, middle_name, last_name, date_of_birth from person_table;

sql select person_id as seconary_person_id, first_name, middle_name, last_name, date_of_birth from person_table;

Is there a better way to deal with this that I'm missing?

Body:
What you are showing in that figure is called "circular reference" (I think Qlikview calls it "Synthetic Key") and it is something that you should really try to avoid since it may make your app, not crash, but show incorrect results (which is worse).
In my opinion you have two options:

Op1 - Duplicate your PERSON_TABLE so that PRIMARY_PERSON_ID will be linked to PERSON_TABLE_1 and SECONDARY_PERSON_ID will be linked to PERSON_TABLE_2.

PERSON_TABLE_1:
SQL SELECT person_id as primary_person_id,
first_name as first_name_1,
middle_name as middle_name_1,
last_name as last_name_1,
date_of_birth as date_of_birth_1
FROM person_table

PERSON_TABLE_2:
SQL SELECT person_id as secondary_person_id,
first_name as first_name_2,
middle_name as middle_name_2,
last_name as last_name_2,
date_of_birth as date_of_birth_2
FROM person_table

The problem with this option is that you have to choose different alias for each field, which is usually not very convenient depending on the type of analysis you do in your app.

Op2: Create a unique MARRIAGE_TABLE already including the data of the two people. For that you can create a SQL query with two JOINS (I will only use first and middle names for simplicity, but you can add all the other fields)

SELECT T1.*, T2.first_name as first_name_1, T2.middle_name as middle_name_1,
T3.first_name as first_name_2, T3.middle_name as middle_name_2
FROM MARRIAGE_TABLE AS T1
LEFT JOIN PERSON_TABLE AS T2 ON Q1.primary_person_id = T2.person_id
LEFT JOIN PERSON_TABLE AS T3 ON Q1.secondary_person_id = T3.person_id

which will result in a unique table with the following columns:

MARRIAGE_ID PRIMARY_PERSON_ID SECONDARY_PERSON_ID MARRIAGE_START_DATE MARRIAGE_END_DATE FIRST_NAME_1 MIDDLE_NAME_1 FIRST_NAME_2 MIDDLE_NAME_2


来源: stackexchange

问:
MS SQL Trigger needed for Update a row, then delete from other table
i am looking for a trigger for ms sql. I have one table dbo.item, and another table dbo.ean. In frontend i edit this table, and once it is finished, i want to get a number from dbo.ean added to dbo.item. Once it got edited, it should be deleted from dbo.ean, so it is not used a second time.Furthermore a condition is, if the sku is like '%%%%W'....

Table design:

dbo.item

sku              name                            ean
5510W       testproduct 1
5511W       testproduct 2
5512W       testproduct 3
5513W       testproduct 4
5514W       testproduct 5

dbo.ean

ean
111111
222222
333333
444444
555555

I've used the search function, but my knowledge of sql is rather small :D, so any help or hints are highly appreciated,

答:
On SqlServer There are two tables for triggers (inserted/deleted) that are a view of changes applied on original table.

You Can use a trigger like this:
Create Trigger tr_ondelete on item After delete as

Delete from ean where ean Is in (select ean from deleted)

ContentLicense: CC BY-SA 3.0


问:
Swifty way to get value associated with another in struct
I have a CustomColors struct which contains static lets that define primary and secondary colors for my app.

```<code>struct CustomColors {

    static let orangePrimary = UIColor(r: 255, g: 110, b: 64, a: 1)
    static let orangeSecondary = UIColor(r: 230, g: 74, b: 25, a: 1)

    static let bluePrimary = UIColor(r: 24, g: 255, b: 255, a: 1)
    static let blueSecondary = UIColor(r: 18, g: 191, b: 191, a: 1)

    static let yellowPrimary = UIColor(r: 255, g: 255, b: 0, a: 1)
    static let yellowSecondary = UIColor(r: 255, g: 193, b: 7, a: 1)
}
</code>```

Because secondary colors are completely dependent from the primary ones, I am looking for a way to build a data structure (in the swiftiest way) that would allow me to call for example: CustomColors.bluePrimary.secondary to get the blueSecondary color.

I feel I am missing something pretty basic here as I cannot seem to see how I could do this in the most simple way.

Thanks in advance for your help !

答:
Try this way:

```<code>struct CustomColors {
    public class Color: UIColor {
        private var _secondary:UIColor?

        var secondary:UIColor? {
            get {
                return _secondary
            }
        }

        func setSecondary(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> Color {
            _secondary = UIColor(red: red, green: green, blue: blue, alpha: alpha)
            return self
        }

    }

    static let orangeColor = Color(red: 255, green: 110, blue: 64, alpha: 1).setSecondary(red: 230, green: 74, blue: 25, alpha: 1)

    static let blueColor = Color(red: 24, green: 255, blue: 255, alpha: 1).setSecondary(red: 18, green: 255, blue: 255, alpha: 1)

    static let yellowColor = Color(red: 255, green: 255, blue: 0, alpha: 1).setSecondary(red: 255, green: 193, blue: 7, alpha: 1)

}

CustomColors.orangeColor.secondary
</code>```

It's more flexible way to implement what you want, I guess :)

Body:
I have a CustomColors struct which contains static lets that define primary and secondary colors for my app.

struct CustomColors {

    static let orangePrimary = UIColor(r: 255, g: 110, b: 64, a: 1)
    static let orangeSecondary = UIColor(r: 230, g: 74, b: 25, a: 1)

    static let bluePrimary = UIColor(r: 24, g: 255, b: 255, a: 1)
    static let blueSecondary = UIColor(r: 18, g: 191, b: 191, a: 1)

    static let yellowPrimary = UIColor(r: 255, g: 255, b: 0, a: 1)
    static let yellowSecondary = UIColor(r: 255, g: 193, b: 7, a: 1)
}

Because secondary colors are completely dependent from the primary ones, I am looking for a way to build a data structure (in the swiftiest way) that would allow me to call for example: CustomColors.bluePrimary.secondary to get the blueSecondary color.

I feel I am missing something pretty basic here as I cannot seem to see how I could do this in the most simple way.

Thanks in advance for your help !

Body:
Try this way:

struct CustomColors {
    public class Color: UIColor {
        private var _secondary:UIColor?

        var secondary:UIColor? {
            get {
                return _secondary
            }
        }

        func setSecondary(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> Color {
            _secondary = UIColor(red: red, green: green, blue: blue, alpha: alpha)
            return self
        }

    }

    static let orangeColor = Color(red: 255, green: 110, blue: 64, alpha: 1).setSecondary(red: 230, green: 74, blue: 25, alpha: 1)

    static let blueColor = Color(red: 24, green: 255, blue: 255, alpha: 1).setSecondary(red: 18, green: 255, blue: 255, alpha: 1)

    static let yellowColor = Color(red: 255, green: 255, blue: 0, alpha: 1).setSecondary(red: 255, green: 193, blue: 7, alpha: 1)

}

CustomColors.orangeColor.secondary

It's more flexible way to implement what you want, I guess :)


问:
Dynamically loading webpack common chunks in browser (with requirejs)
I'm trying to create a Webpack bundle with some "vendor" dependencies (React, lodash, ...) and use them in my web app.

The issue I have, is that I don't want to add my vendor.js file as a

答: You can use webpack built-in code-splitting - require.ensure or import().


问:
Eclipse Mars JavaScript Editor not recognizing errors
Somehow i can enter anything i want in a .js file but there are no errors nor warnings (syntax highlighting works tough) recognized.

I have no exludes or something.

Also i remember having the option to convert a project into a javascript project but this option is also gone.

my .project

```<code><?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>JavaScriptProject</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.wst.validation.validationbuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.wst.jsdt.core.jsNature</nature>
    </natures>
</projectDescription>
</code>```

Anyone knows what could be the reason for this?

Update:

I have configured Tern ESLint for validation (and converted the project to a tern project) but also Tern ESlint is also showing no errors or warnings. My Guess is that somewhere there must be a setting which deavtivated the JavaScript code validation for JSDT and / or Tern but in the settings and project settings i have checked all i can find regarding validation...

答:
Open your .project file and check if your project has the "jsdt nature".
As described as in "Edit 4" in the Question section of this post: how-to-ignore-node-shebang-error-in-eclipse

In the answer sections there is quite some information too.

I also recommend to add 'eslint' with the --fix option as an External Tool Configuration .

Body:
Somehow i can enter anything i want in a .js file but there are no errors nor warnings (syntax highlighting works tough) recognized.

I have no exludes or something.

Also i remember having the option to convert a project into a javascript project but this option is also gone.

my .project

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>JavaScriptProject</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.wst.validation.validationbuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.wst.jsdt.core.jsNature</nature>
    </natures>
</projectDescription>

Anyone knows what could be the reason for this?

Update:

I have configured Tern ESLint for validation (and converted the project to a tern project) but also Tern ESlint is also showing no errors or warnings. My Guess is that somewhere there must be a setting which deavtivated the JavaScript code validation for JSDT and / or Tern but in the settings and project settings i have checked all i can find regarding validation...


问:
Array showing error on tbody
This is my code, I don't know whats wrong with this piece of code.

```<code>var tst= this.apptDataTable.find("tbody:last")
</code>```

am getting value but when i add

```<code>var tst= this.apptDataTable.find("tbody:last")[0]
</code>```

It's showing undefined.

Please help me to solve this

答:
I dont know why you add the index [0]?

And :last select SINGLE element which is the last one.

Title: Array showing error on tbody

Body:
This is my code, I don't know whats wrong with this piece of code.

var tst= this.apptDataTable.find("tbody:last")

am getting value but when i add

var tst= this.apptDataTable.find("tbody:last")[0]

It's showing undefined.

Please help me to solve this


问:
Open image in modal (link in one div img in another)
I have a dot-front that when hovered over it flips and shows a dot-back with a link. If I click the link it should open a modal with a preview image.
I think that the problem is in the jquery where I wrote closest and find, but I don't know how to fix it.

$(function() {
  $('.pop').on('click', function() {
    console.log("pop");
    $('#imagepreview').attr('src', $('#modal-icon01').closest(".div-img").find('.front img').attr('src'));
    $('#imagemodal').modal('show');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.div-img {
  display: inline-block;
  height: 200px;
  width: 200px;
  cursor: pointer;
}

.div-img img {
  object-fit: cover;
  width: 240px;
  margin-left: -20px;
}

.div-img span {
  display: table-cell;
  vertical-align: middle;
  height: 200px;
}

.div-img > .front {
  position: absolute;
  transform: perspective( 600px) rotateY( 0deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img > .back {
  position: absolute;
  transform: perspective( 600px) rotateY( 180deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img:hover > .front {
  transform: perspective( 600px) rotateY( -180deg);
}

.div-img:hover > .back {
  transform: perspective( 600px) rotateY( 0deg);
}</code>```

    Pizza Hut Delivery
(De ce Pizza Hut)

        <button type="button" class="close" data-dismiss="modal">×Close</button>

```

答:
Here is the working code. Bootstrap includes were missing. And secondly, seems some of the HTML is missing in your question as I can't find this ID modal-icon01.

Try the below code and let me know:

$('.pop').on('click', function() {
  console.log("pop");
  $('#imagemodal').modal('show');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.div-img {
  display: inline-block;
  height: 200px;
  width: 200px;
  cursor: pointer;
}

.div-img img {
  object-fit: cover;
  width: 240px;
  margin-left: -20px;
}

.div-img span {
  display: table-cell;
  vertical-align: middle;
  height: 200px;
}

.div-img>.front {
  position: absolute;
  transform: perspective( 600px) rotateY( 0deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img>.back {
  position: absolute;
  transform: perspective( 600px) rotateY( 180deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img:hover>.front {
  transform: perspective( 600px) rotateY( -180deg);
}

.div-img:hover>.back {
  transform: perspective( 600px) rotateY( 0deg);
}</code>```

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

    Pizza Hut Delivery
(De ce Pizza Hut)

        <button type="button" class="close" data-dismiss="modal">×Close</button>

```

Body:
I have a dot-front that when hovered over it flips and shows a dot-back with a link. If I click the link it should open a modal with a preview image.
I think that the problem is in the jquery where I wrote closest and find, but I don't know how to fix it.

$(function() {
  $('.pop').on('click', function() {
    console.log("pop");
    $('#imagepreview').attr('src', $('#modal-icon01').closest(".div-img").find('.front img').attr('src'));
    $('#imagemodal').modal('show');
  });
});

.div-img {
  display: inline-block;
  height: 200px;
  width: 200px;
  cursor: pointer;
}

.div-img img {
  object-fit: cover;
  width: 240px;
  margin-left: -20px;
}

.div-img span {
  display: table-cell;
  vertical-align: middle;
  height: 200px;
}

.div-img > .front {
  position: absolute;
  transform: perspective( 600px) rotateY( 0deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img > .back {
  position: absolute;
  transform: perspective( 600px) rotateY( 180deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img:hover > .front {
  transform: perspective( 600px) rotateY( -180deg);
}

.div-img:hover > .back {
  transform: perspective( 600px) rotateY( 0deg);
}

    Pizza Hut Delivery
(De ce Pizza Hut)

        <button type="button" class="close" data-dismiss="modal">×Close</button>

Body:
Here is the working code. Bootstrap includes were missing. And secondly, seems some of the HTML is missing in your question as I can't find this ID modal-icon01.

Try the below code and let me know:

$('.pop').on('click', function() {
  console.log("pop");
  $('#imagemodal').modal('show');
});

.div-img {
  display: inline-block;
  height: 200px;
  width: 200px;
  cursor: pointer;
}

.div-img img {
  object-fit: cover;
  width: 240px;
  margin-left: -20px;
}

.div-img span {
  display: table-cell;
  vertical-align: middle;
  height: 200px;
}

.div-img>.front {
  position: absolute;
  transform: perspective( 600px) rotateY( 0deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img>.back {
  position: absolute;
  transform: perspective( 600px) rotateY( 180deg);
  backface-visibility: hidden;
  height: 200px;
  width: 200px;
  -webkit-transition: transform 0.7s linear;
  -moz-transition: transform 0.7s linear;
  transition: transform 0.7s linear;
  background: #0f1013;
  border: solid 1px black;
  -moz-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  -webkit-box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  box-shadow: 0px 5px 25px rgba(0, 0, 0, 1), inset 0 0px 50px rgba(0, 0, 0, 1);
  overflow: hidden;
  border-radius: 150px;
}

.div-img:hover>.front {
  transform: perspective( 600px) rotateY( -180deg);
}

.div-img:hover>.back {
  transform: perspective( 600px) rotateY( 0deg);
}

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<div class="div-img">
  <div class="back">
    <center><span><a class="pop" data-toggle="modal" data-target="#myModal" href="#">Pizza Hut Delivery<br>(De ce Pizza Hut)</a></span></center>
  </div>
  <div class="front">
    <center><img src="http://patyshibuya.com.br/wp-content/uploads/2014/04/04.jpg" style="width: 400px; height: 264px;"></center>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <img src="" id="imagepreview" style="width: 100%;">
      </div>
    </div>
  </div>
</div>


问:
std::stod does not give the exact number output
I have a string that I want to convert to a double using std::stod. However, the output of std::stod is not what I would expect. For example, if my string is 6.1, the output of std::stod is 6.0999999999999996.

Is there anything I can do to either make it so std::stod returns 6.1 or  to convert the 6.099...6 to 6.1?

答:
Nope. std::stod returns a double, and on most implementations, a double is a binary floating point type.

That will not have an exact representation of 6.1.

If you need 6.1 exactly, then consider using an integral type with an appropriate scaling factor, or use a decimal type from a 3rd party library.

See Is floating point math broken?


问:
Rewriting example.com/section.php?username=xyz to example.com/xyz/section
Using the following htaccess, I have been able to rewrite example.com/profile.php?username=xyz to example.com/xyz,

```<code>RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?user=$1
</code>```

Adding the following to the above,

```<code>RewriteRule ^([a-zA-Z0-9_-]+)/section$ section.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/section/$ section.php?user=$1
</code>```

did not resolve example.com/section.php?username=xyz to example.com/xyz/section.

Am I doing something wrong here?

答:
First of all: The manner of speaking would rather be the opposite: The rules you showed are to rewrite requests like /xyz internally to /profile.php?username=xyz and not vice versa.

Now if you want to rewrite requests like /xyz/section internally to /section.php?username=xyz where section and xyz are variable, try these rules:

```<code>RewriteRule ^([a-zA-Z0-9_-]+)/?$ profile.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/([^/]+)/?$ $2.php?user=$1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using the following htaccess, I have been able to rewrite example.com/profile.php?username=xyz to example.com/xyz,

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?user=$1

Adding the following to the above,

RewriteRule ^([a-zA-Z0-9_-]+)/section$ section.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/section/$ section.php?user=$1

did not resolve example.com/section.php?username=xyz to example.com/xyz/section.

Am I doing something wrong here?

Body:
First of all: The manner of speaking would rather be the opposite: The rules you showed are to rewrite requests like /xyz internally to /profile.php?username=xyz and not vice versa.

Now if you want to rewrite requests like /xyz/section internally to /section.php?username=xyz where section and xyz are variable, try these rules:

RewriteRule ^([a-zA-Z0-9_-]+)/?$ profile.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/([^/]+)/?$ $2.php?user=$1

ContentLicense: CC BY-SA 2.5


问:
Access denied for user 'root'@'localhost' (using password: YES) using MAMP
I am new to php and can't seem to solve this issue that I have.
Basically I want to build a data base and access it on my website.
I downloaded MAMP on my mac to run the site locally until I publish my site.
I made a database using phpmyadmin.
The database is a table that consists of 5 rows and 4 columns (but will increase in the future).
The following is my code to connect to database called hello:

```<code><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hello";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "connected to database";
}
?>
</code>```

However I get this error as it seems that I cannot connect to the database.

```<code>Connection failed: Access denied for user 'root'@'localhost' (using password: YES)
</code>```

I have tried different things like adding in a space for the password or setting it to root but they don't seem to work.
I dont understand how there is a password set on the database when I never set one.

答:
I dont understand how there is a password set on the database when I never set one.

Because MAMP sets one by default.

Their documentation also tells you how to change it:

Open the Mac OS Terminal Application located in your /Applications/Utilities directory.

Enter the following command line: /Applications/MAMP/Library/bin/mysqladmin -u root -p password
  [NewPassword]

Replace [NewPassword] with your new password.

Please bear in mind that you also have to change the phpMyAdmin configuration and probably your own php scripts to use the newly
  created MySQL password. For changing the phpMyAdmin configuration edit
  the following file and update the password. /Applications/MAMP/bin/phpMyAdmin/config.inc.php

… don't write applications that log in as root though. Create a new user with just as many permissions as they need.

Body:
I am new to php and can't seem to solve this issue that I have.
Basically I want to build a data base and access it on my website.
I downloaded MAMP on my mac to run the site locally until I publish my site.
I made a database using phpmyadmin.
The database is a table that consists of 5 rows and 4 columns (but will increase in the future).
The following is my code to connect to database called hello:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hello";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "connected to database";
}
?>

However I get this error as it seems that I cannot connect to the database.

Connection failed: Access denied for user 'root'@'localhost' (using password: YES)

I have tried different things like adding in a space for the password or setting it to root but they don't seem to work.
I dont understand how there is a password set on the database when I never set one.


问:
Set scroll position to top in new page using barba.js
I use the code from barba.js documentation as below to switch between pages.

```<code>var FadeTransition = Barba.BaseTransition.extend({
    start: function() {
        Promise
            .all([this.newContainerLoading, this.fadeOut()])
            .then(this.fadeIn.bind(this));
    },

    fadeOut: function() {
        return $(this.oldContainer).animate({ opacity: 0 }).promise();
    },

    fadeIn: function() {
        var _this = this;
        var $el = $(this.newContainer);

        $(this.oldContainer).hide();

        $el.css({
        visibility : 'visible',
        opacity : 0
        });
        $el.animate({ opacity: 1 }, 400, function() {
        _this.done();
        });
    }
});

Barba.Pjax.getTransition = function() {
    return FadeTransition;
};
</code>```

The problem is that the scroll position retained in the new page.
I tried to add $(window).scrollTop(0); inside fadeIn function, but this gives unwanted scroll when pressing back button. How can it be solved?

The following is the behavior after adding $(window).scrollTop(0);

in page A, scroll down and press link to page B. Page B enters and has scroll position at top

press back button, page B scroll to the position of page A and then fades out

page A enters and has scroll position at top

scroll down and press forward button. Page A scroll to top and then fades out

page B enters and has scroll position at top

The following is the expected behavior:

in page A, scroll down and press link to page B. Page B enters and has scroll position at top

press back button, page B fades out without scrolling

page A enters and has scroll position as step 1

答:
```<code>  fadeIn: function() {

    $(window).scrollTop(0); // scroll to top here

    var _this = this;
    var $el = $(this.newContainer);

    $(this.oldContainer).hide();

    $el.css({
      visibility : 'visible',
      opacity : 0
    });

    $el.animate({ opacity: 1 }, 400, function() {
      /**
       * Do not forget to call .done() as soon your transition is finished!
       * .done() will automatically remove from the DOM the old Container
       */

      _this.done();
    });
</code>```

Body:
I use the code from barba.js documentation as below to switch between pages.

var FadeTransition = Barba.BaseTransition.extend({
    start: function() {
        Promise
            .all([this.newContainerLoading, this.fadeOut()])
            .then(this.fadeIn.bind(this));
    },

    fadeOut: function() {
        return $(this.oldContainer).animate({ opacity: 0 }).promise();
    },

    fadeIn: function() {
        var _this = this;
        var $el = $(this.newContainer);

        $(this.oldContainer).hide();

        $el.css({
        visibility : 'visible',
        opacity : 0
        });
        $el.animate({ opacity: 1 }, 400, function() {
        _this.done();
        });
    }
});

Barba.Pjax.getTransition = function() {
    return FadeTransition;
};

The problem is that the scroll position retained in the new page.
I tried to add $(window).scrollTop(0); inside fadeIn function, but this gives unwanted scroll when pressing back button. How can it be solved?

The following is the behavior after adding $(window).scrollTop(0);

in page A, scroll down and press link to page B. Page B enters and has scroll position at top

press back button, page B scroll to the position of page A and then fades out

page A enters and has scroll position at top

scroll down and press forward button. Page A scroll to top and then fades out

page B enters and has scroll position at top

The following is the expected behavior:

in page A, scroll down and press link to page B. Page B enters and has scroll position at top

press back button, page B fades out without scrolling

page A enters and has scroll position as step 1


问:
Is there a way to automatically strip leading space from Apache commons-cli option value?
Consider the following example:

```<code>import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class ApacheCommonsCliWhitespaceTest {

  public static void main(String[] args) throws ParseException {
    Options options = new Options();
    Option option = new Option("t", "test", true, "test description");
    options.addOption(option);

    CommandLineParser parser = new DefaultParser();

    String[] parameters = new String[1];

    parameters[0] = "-t ping";
    CommandLine result = parser.parse(options, parameters);
    System.out.println("*" + result.getOptionValue("t") + "*");

    parameters[0] = "-test ping";
    result = parser.parse(options, parameters);
    System.out.println("*" + result.getOptionValue("t") + "*");
  }
}
</code>```

The result will be

```<code>* ping*
* ping*
</code>```

Is there really no way to remove the leading space automatically? I would have expected that to be a common use case.

答:
Try </p>

```<code>result.getOptionValue("t").trim()
</code>```

Body:
Consider the following example:

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class ApacheCommonsCliWhitespaceTest {

  public static void main(String[] args) throws ParseException {
    Options options = new Options();
    Option option = new Option("t", "test", true, "test description");
    options.addOption(option);

    CommandLineParser parser = new DefaultParser();

    String[] parameters = new String[1];

    parameters[0] = "-t ping";
    CommandLine result = parser.parse(options, parameters);
    System.out.println("*" + result.getOptionValue("t") + "*");

    parameters[0] = "-test ping";
    result = parser.parse(options, parameters);
    System.out.println("*" + result.getOptionValue("t") + "*");
  }
}

The result will be

* ping*
* ping*

Is there really no way to remove the leading space automatically? I would have expected that to be a common use case.

Body:
Try

result.getOptionValue("t").trim()


问:
How to avoid generating duplicate numbers using RandomStringUtils.random of Apache Commons Jar
I am using Apache Commons Lang3 package class RandomStringUtils. After generating some numbers, RandomStringUtils.randomNumeric is generating duplicate numbers in an infinite loop. How can I prevent this from happening?

Here is my code:

```<code>quantity = 100000
insertedNum = 0;
length = 9;
String[] numGen = new String[100];
idx = 1;

while (insertedNum < quantity) {
    String random=RandomStringUtils.randomNumeric(length);
    numGen[idx - 1] = random;
    if (idx == 100) {
        insertedNum += DB Code. If unique constraint error then discard batch return 0 else execute batch return inserted count.
        idx = 1;
        numGen = new String[100];
    }
    else
        idx++;
    }
}
</code>```

答:
A cumbersome approach would be to keep regenerating random strings till you find that you have encountered a unique random string that is not already contained in your array. All you have to do is check whether the newly generated random string is already in the array or not

```<code>quantity = 100000
insertedNum = 0;
length = 9;
String[] numGen = new String[100];
idx = 0;
String random = "";
while (insertedNum < quantity) {
            random=RandomStringUtils.randomNumeric(length);
            while( isAlreadyInArray( numGen , random ) )
            {
                //regenerate a random string
                random = RandomStringUtils.randomNumeric( length );
            }
            // Add it to your array, and increment it by one
            numGen[idx] = random;
            idx = (idx + 1) % numGen.length;
            // In this case, the array got populated to completion
            if (idx == 0) {
                System.out.println( java.util.Arrays.toString( numGen ) );
                //clear the batch set
                insertedNum += DB Code. If unique constraint error then discard batch return 0 else execute batch return inserted count.
                numGen = new String[100];
            }
        }
</code>```

And here is the helper method isAlreadyInArray( String[] array , String someVal )

```<code>public boolean isAlreadyInArray( String[] mData , String strToCheck )
{
    for( int x = 0; x < mData.length; x++ )
    {
        if( mData[x] != null && mData[x].equalsIgnoreCase( strToCheck ) )
        {
            return true;
        }
    }
    return false;
}
</code>```

Please run this sample, and if it fails to help, then certainly we can re-iterate over the problem :)

Body:
I am using Apache Commons Lang3 package class RandomStringUtils. After generating some numbers, RandomStringUtils.randomNumeric is generating duplicate numbers in an infinite loop. How can I prevent this from happening?

Here is my code:

quantity = 100000
insertedNum = 0;
length = 9;
String[] numGen = new String[100];
idx = 1;

while (insertedNum < quantity) {
    String random=RandomStringUtils.randomNumeric(length);
    numGen[idx - 1] = random;
    if (idx == 100) {
        insertedNum += DB Code. If unique constraint error then discard batch return 0 else execute batch return inserted count.
        idx = 1;
        numGen = new String[100];
    }
    else
        idx++;
    }
}

Body:
A cumbersome approach would be to keep regenerating random strings till you find that you have encountered a unique random string that is not already contained in your array. All you have to do is check whether the newly generated random string is already in the array or not

quantity = 100000
insertedNum = 0;
length = 9;
String[] numGen = new String[100];
idx = 0;
String random = "";
while (insertedNum < quantity) {
            random=RandomStringUtils.randomNumeric(length);
            while( isAlreadyInArray( numGen , random ) )
            {
                //regenerate a random string
                random = RandomStringUtils.randomNumeric( length );
            }
            // Add it to your array, and increment it by one
            numGen[idx] = random;
            idx = (idx + 1) % numGen.length;
            // In this case, the array got populated to completion
            if (idx == 0) {
                System.out.println( java.util.Arrays.toString( numGen ) );
                //clear the batch set
                insertedNum += DB Code. If unique constraint error then discard batch return 0 else execute batch return inserted count.
                numGen = new String[100];
            }
        }

And here is the helper method isAlreadyInArray( String[] array , String someVal )

public boolean isAlreadyInArray( String[] mData , String strToCheck )
{
    for( int x = 0; x < mData.length; x++ )
    {
        if( mData[x] != null && mData[x].equalsIgnoreCase( strToCheck ) )
        {
            return true;
        }
    }
    return false;
}

Please run this sample, and if it fails to help, then certainly we can re-iterate over the problem :)


问:
Migration :: Jboss 6.0 eap toWildfly 10.01+Java 8- java.security.NoSuchProviderException: JCE cannot authenticate the provider BC
I am getting below error when I deploy ear on wildfly 10.

I have used latest jar(bcprov-jdk16-1.46.jar and bcmail-jdk16-1.46.jar) but not worked.

```<code>13:46:35,654 ERROR [stderr] (ServerService Thread Pool -- 76) java.security.NoSuchProviderException: JCE cannot authenticate the provider BC
13:46:35,654 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JceSecurity.getInstance(JceSecurity.java:100)
13:46:35,669 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.SecretKeyFactory.getInstance(SecretKeyFactory.java:204)
13:46:35,669 ERROR [stderr] (ServerService Thread Pool -- 76)   at com.generic.util.EncryptionUtils.getKey(EncryptionUtils.java:165)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at com.generic.util.EncryptionUtils.initializeDecryptionCipher(EncryptionUtils.java:230)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at com.generic.util.EncryptionUtils.isEncrypted(EncryptionUtils.java:93)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at com.generic.system.SystemStartup.loadDefaulBSettings(SystemStartup.java:286)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at com.generic.system.SystemStartup.startUp(SystemStartup.java:120)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at sample.servlets.tartup.init(Startup.java:187)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor.init(RunAsLifecycleInterceptor.java:78)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:103)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:250)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.ManagedServlet.createServlet(ManagedServlet.java:133)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.DeploymentManagerImpl$2.call(DeploymentManagerImpl.java:546)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.DeploymentManagerImpl$2.call(DeploymentManagerImpl.java:517)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
13:46:35,716 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
13:46:35,716 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
13:46:35,716 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
13:46:35,716 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
13:46:35,716 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.DeploymentManagerImpl.start(DeploymentManagerImpl.java:559)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:101)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at java.util.concurrent.FutureTask.run(FutureTask.java:266)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at java.lang.Thread.run(Thread.java:748)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at org.jboss.threads.JBossThread.run(JBossThread.java:320)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76) Caused by: java.lang.SecurityException: Cannot verify jar:vfs:/E:/myprj/wildfly-10.1.0.Final/bin/content/myapp.ear/lib/tik
a-app-1.4.jar!/
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JarVerifier.verifySingleJar(JarVerifier.java:446)
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JarVerifier.verifyJars(JarVerifier.java:361)
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JarVerifier.verify(JarVerifier.java:289)
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JceSecurity.verifyProviderJar(JceSecurity.java:159)
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JceSecurity.getVerificationResult(JceSecurity.java:185)
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JceSecurity.getInstance(JceSecurity.java:97)
</code>```

答:
There are two workarounds.

You create a modul with the libs (bcprov-jdk16-1.46.jar,bcmail-jdk16-1.46.jar) and import it in your jboss-deployment-structure.xml

You add the jars in the jboss-deployment-structure.xml as resource with the option use-physical-code-source="true" Example:
<resource-root path="/lib/bcprov-jdk16-1.46.jar" use-physical-code-source="true"/>

Body:
I am getting below error when I deploy ear on wildfly 10.

I have used latest jar(bcprov-jdk16-1.46.jar and bcmail-jdk16-1.46.jar) but not worked.

13:46:35,654 ERROR [stderr] (ServerService Thread Pool -- 76) java.security.NoSuchProviderException: JCE cannot authenticate the provider BC
13:46:35,654 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JceSecurity.getInstance(JceSecurity.java:100)
13:46:35,669 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.SecretKeyFactory.getInstance(SecretKeyFactory.java:204)
13:46:35,669 ERROR [stderr] (ServerService Thread Pool -- 76)   at com.generic.util.EncryptionUtils.getKey(EncryptionUtils.java:165)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at com.generic.util.EncryptionUtils.initializeDecryptionCipher(EncryptionUtils.java:230)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at com.generic.util.EncryptionUtils.isEncrypted(EncryptionUtils.java:93)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at com.generic.system.SystemStartup.loadDefaulBSettings(SystemStartup.java:286)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at com.generic.system.SystemStartup.startUp(SystemStartup.java:120)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at sample.servlets.tartup.init(Startup.java:187)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor.init(RunAsLifecycleInterceptor.java:78)
13:46:35,685 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:103)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:250)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.ManagedServlet.createServlet(ManagedServlet.java:133)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.DeploymentManagerImpl$2.call(DeploymentManagerImpl.java:546)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.DeploymentManagerImpl$2.call(DeploymentManagerImpl.java:517)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
13:46:35,700 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
13:46:35,716 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
13:46:35,716 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
13:46:35,716 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
13:46:35,716 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
13:46:35,716 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at io.undertow.servlet.core.DeploymentManagerImpl.start(DeploymentManagerImpl.java:559)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:101)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at java.util.concurrent.FutureTask.run(FutureTask.java:266)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at java.lang.Thread.run(Thread.java:748)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76)   at org.jboss.threads.JBossThread.run(JBossThread.java:320)
13:46:35,732 ERROR [stderr] (ServerService Thread Pool -- 76) Caused by: java.lang.SecurityException: Cannot verify jar:vfs:/E:/myprj/wildfly-10.1.0.Final/bin/content/myapp.ear/lib/tik
a-app-1.4.jar!/
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JarVerifier.verifySingleJar(JarVerifier.java:446)
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JarVerifier.verifyJars(JarVerifier.java:361)
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JarVerifier.verify(JarVerifier.java:289)
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JceSecurity.verifyProviderJar(JceSecurity.java:159)
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JceSecurity.getVerificationResult(JceSecurity.java:185)
13:46:35,747 ERROR [stderr] (ServerService Thread Pool -- 76)   at javax.crypto.JceSecurity.getInstance(JceSecurity.java:97)


问:
Remove border in HorizontalPanel of GWT
My previous programmer developed web UI using GWT's UI Binder like below. The problem is that there is border showing exactly like table.
Is there way I can explicitly specify the border=none to HorizontalPanel. I tried add class=noborder after defining noborder in the .css. It returned error HorizontalPanel can't use 'class'. Could anyone help this out?</p>

```<code><g:HorizontalPanel>
<g:Anchor ui:field="A"/>
<g:HTML ui:field="B" />
<g:Anchor ui:field="C" />
<g:HTML ui:field="D" />
</g:HorizontalPanel>
</code>```

答:
instead of </p>

```<code>class="noborder"
</code>```

<p>try </p>

```<code>addStyleName="noborder"
</code>```

Title: Remove border in HorizontalPanel of GWT

Body:
My previous programmer developed web UI using GWT's UI Binder like below. The problem is that there is border showing exactly like table.
Is there way I can explicitly specify the border=none to HorizontalPanel. I tried add class=noborder after defining noborder in the .css. It returned error HorizontalPanel can't use 'class'. Could anyone help this out?

<g:HorizontalPanel>
<g:Anchor ui:field="A"/>
<g:HTML ui:field="B" />
<g:Anchor ui:field="C" />
<g:HTML ui:field="D" />
</g:HorizontalPanel>

Body:
instead of

class="noborder"

try

addStyleName="noborder"


问:
Why passing the load factor on specifying the access order on the constructor?
I was wondering why when does the constructor of a LinkedHashMap that the client code can specify if is access ordered expect a loadFactor?
Is there any particular reason for this design instead of using a default factor?

答:
Sometimes things "just happen". Beyond that:

When designing a library API, you have to balance simplicity and "feature count". Meaning: of course you could create a huge number of constructors, allowing to set all flags as you want them. But that would lead to a high number of constructors. And that is typically not what you want.

In that sense: if you are really willing to touch the insertion order flag for linked hash maps ... then you are already taking a "very special route". And then the creators of the API (probably) decided to give you one special constructor, instead of a higher number.


问:
Export the content of a SQL Server table to a CSV without using xp_cmdshell
I need to export the content of a Table into a file CSV.

I tried to use the execution of a xp_cmdshell from a stored procedure but it doesn't work because this component is turned off as part of the security configuration for this server.

Do you know others way to write a file from a stored procedure?

答:
Here are a couple of methods you can try :

1. Using BCP

syntax :

```<code>bcp "SELECT * FROM Database.dbo.input" queryout C:\output.csv -c -t',' -T -S .\SQLEXPRESS
</code>```

microsoft document : BCP Utility

2. Second Method(for excel, but should work for csv too) :

```<code>Insert into OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
</code>```

For this, you need to enable adhoc distributed queries by following command :

```<code>EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
</code>```

you might encounter a link server error. So you should refer : this stack overflow solution

Body:
Here are a couple of methods you can try :

1. Using BCP

syntax :

bcp "SELECT * FROM Database.dbo.input" queryout C:\output.csv -c -t',' -T -S .\SQLEXPRESS

microsoft document : BCP Utility

2. Second Method(for excel, but should work for csv too) :

Insert into OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable

For this, you need to enable adhoc distributed queries by following command :

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO

you might encounter a link server error. So you should refer : this stack overflow solution


问:
Kite Dataset map-reduce
I am trying to do map-reduce with kite-dataset api.

I have followed below urls to refer.

https://community.cloudera.com/t5/Kite-SDK-includes-Morphlines/Map-Reduce-with-Kite/td-p/22165

https://github.com/kite-sdk/kite/blob/master/kite-data/kite-data-mapreduce/src/test/java/org/kitesdk/data/mapreduce/TestMapReduce.java

My code snippet as below

```<code>public class MapReduce {

    private static final String sourceDatasetURI = "dataset:hive:test_avro";

    private static final String destinationDatasetURI = "dataset:hive:test_parquet";

    private static class LineCountMapper
            extends Mapper<GenericData.Record, Void, Text, IntWritable> {
        @Override
        protected void map(GenericData.Record record, Void value,
                           Context context)
                throws IOException, InterruptedException {
            System.out.println("Record is "+record);
            context.write(new Text(record.get("index").toString()), new IntWritable(1));
        }
    }

    private Job createJob() throws Exception {
        System.out.println("Inside Create Job");
        Job job = new Job();
        job.setJarByClass(getClass());

       Dataset<GenericData.Record> inputDataset = Datasets.load(sourceDatasetURI, GenericData.Record.class);
       Dataset<GenericData.Record> outputDataset = Datasets.load(destinationDatasetURI, GenericData.Record.class);

        DatasetKeyInputFormat.configure(job).readFrom(inputDataset).withType(GenericData.Record.class);

        job.setMapperClass(LineCountMapper.class);
        DatasetKeyOutputFormat.configure(job).writeTo(outputDataset).withType(GenericData.Record.class);

        job.waitForCompletion(true);

        return job;
    }

    public static void main(String[] args) throws Exception {
        MapReduce httAvroToParquet = new MapReduce();
        httAvroToParquet.createJob();
    }
}
</code>```

I am using HDP 2.3.2 box ,creating assembly jar and submitting my application through spark-submit.

I am getting below error when I submit my application.

```<code>2015-12-18 04:09:07,156 WARN [main] org.apache.hadoop.hdfs.shortcircuit.DomainSocketFactory: The short-circuit local reads feature cannot be used because libhadoop cannot be loaded.
2015-12-18 04:09:07,282 INFO [main] org.apache.hadoop.mapreduce.v2.app.MRAppMaster: OutputCommitter set in config null
2015-12-18 04:09:07,333 WARN [main] org.kitesdk.data.spi.Registration: Not loading URI patterns in org.kitesdk.data.spi.hive.Loader
2015-12-18 04:09:07,334 INFO [main] org.apache.hadoop.service.AbstractService: Service org.apache.hadoop.mapreduce.v2.app.MRAppMaster failed in state INITED; cause: org.apache.hadoop.yarn.exceptions.YarnRuntimeException: org.kitesdk.data.DatasetNotFoundException: Unknown dataset URI: hive://{}:9083/default/test_parquet. Check that JARs for hive datasets are on the classpath.
org.apache.hadoop.yarn.exceptions.YarnRuntimeException: org.kitesdk.data.DatasetNotFoundException: Unknown dataset URI: hive://{}:9083/default/test_parquet. Check that JARs for hive datasets are on the classpath.
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$1.call(MRAppMaster.java:478)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$1.call(MRAppMaster.java:458)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.callWithJobClassLoader(MRAppMaster.java:1560)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.createOutputCommitter(MRAppMaster.java:458)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.serviceInit(MRAppMaster.java:377)
    at org.apache.hadoop.service.AbstractService.init(AbstractService.java:163)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$4.run(MRAppMaster.java:1518)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.initAndStartAppMaster(MRAppMaster.java:1515)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.main(MRAppMaster.java:1448)
Caused by: org.kitesdk.data.DatasetNotFoundException: Unknown dataset URI: hive://{}:9083/default/test_parquet. Check that JARs for hive datasets are on the classpath.
    at org.kitesdk.data.spi.Registration.lookupDatasetUri(Registration.java:109)
    at org.kitesdk.data.Datasets.load(Datasets.java:103)
    at org.kitesdk.data.Datasets.load(Datasets.java:165)
    at org.kitesdk.data.mapreduce.DatasetKeyOutputFormat.load(DatasetKeyOutputFormat.java:510)
    at org.kitesdk.data.mapreduce.DatasetKeyOutputFormat.getOutputCommitter(DatasetKeyOutputFormat.java:473)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$1.call(MRAppMaster.java:476)
    ... 11 more
</code>```

I am not getting what's wrong ? Is there any class-path problem ? If yes then where do I set it ?

答:
You effectively have a classpath problem

Your project is missing org.kitesdk:kite-data-hive

You can

Add this jar to your fat jar before submitting it to Spark

Tells Spark to add it to your classpath when you submit

Title: Kite Dataset map-reduce

Body:
I am trying to do map-reduce with kite-dataset api.

I have followed below urls to refer.

https://community.cloudera.com/t5/Kite-SDK-includes-Morphlines/Map-Reduce-with-Kite/td-p/22165

https://github.com/kite-sdk/kite/blob/master/kite-data/kite-data-mapreduce/src/test/java/org/kitesdk/data/mapreduce/TestMapReduce.java

My code snippet as below

public class MapReduce {

    private static final String sourceDatasetURI = "dataset:hive:test_avro";

    private static final String destinationDatasetURI = "dataset:hive:test_parquet";

    private static class LineCountMapper
            extends Mapper<GenericData.Record, Void, Text, IntWritable> {
        @Override
        protected void map(GenericData.Record record, Void value,
                           Context context)
                throws IOException, InterruptedException {
            System.out.println("Record is "+record);
            context.write(new Text(record.get("index").toString()), new IntWritable(1));
        }
    }

    private Job createJob() throws Exception {
        System.out.println("Inside Create Job");
        Job job = new Job();
        job.setJarByClass(getClass());

       Dataset<GenericData.Record> inputDataset = Datasets.load(sourceDatasetURI, GenericData.Record.class);
       Dataset<GenericData.Record> outputDataset = Datasets.load(destinationDatasetURI, GenericData.Record.class);

        DatasetKeyInputFormat.configure(job).readFrom(inputDataset).withType(GenericData.Record.class);

        job.setMapperClass(LineCountMapper.class);
        DatasetKeyOutputFormat.configure(job).writeTo(outputDataset).withType(GenericData.Record.class);

        job.waitForCompletion(true);

        return job;
    }

    public static void main(String[] args) throws Exception {
        MapReduce httAvroToParquet = new MapReduce();
        httAvroToParquet.createJob();
    }
}

I am using HDP 2.3.2 box ,creating assembly jar and submitting my application through spark-submit.

I am getting below error when I submit my application.

2015-12-18 04:09:07,156 WARN [main] org.apache.hadoop.hdfs.shortcircuit.DomainSocketFactory: The short-circuit local reads feature cannot be used because libhadoop cannot be loaded.
2015-12-18 04:09:07,282 INFO [main] org.apache.hadoop.mapreduce.v2.app.MRAppMaster: OutputCommitter set in config null
2015-12-18 04:09:07,333 WARN [main] org.kitesdk.data.spi.Registration: Not loading URI patterns in org.kitesdk.data.spi.hive.Loader
2015-12-18 04:09:07,334 INFO [main] org.apache.hadoop.service.AbstractService: Service org.apache.hadoop.mapreduce.v2.app.MRAppMaster failed in state INITED; cause: org.apache.hadoop.yarn.exceptions.YarnRuntimeException: org.kitesdk.data.DatasetNotFoundException: Unknown dataset URI: hive://{}:9083/default/test_parquet. Check that JARs for hive datasets are on the classpath.
org.apache.hadoop.yarn.exceptions.YarnRuntimeException: org.kitesdk.data.DatasetNotFoundException: Unknown dataset URI: hive://{}:9083/default/test_parquet. Check that JARs for hive datasets are on the classpath.
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$1.call(MRAppMaster.java:478)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$1.call(MRAppMaster.java:458)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.callWithJobClassLoader(MRAppMaster.java:1560)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.createOutputCommitter(MRAppMaster.java:458)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.serviceInit(MRAppMaster.java:377)
    at org.apache.hadoop.service.AbstractService.init(AbstractService.java:163)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$4.run(MRAppMaster.java:1518)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.initAndStartAppMaster(MRAppMaster.java:1515)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.main(MRAppMaster.java:1448)
Caused by: org.kitesdk.data.DatasetNotFoundException: Unknown dataset URI: hive://{}:9083/default/test_parquet. Check that JARs for hive datasets are on the classpath.
    at org.kitesdk.data.spi.Registration.lookupDatasetUri(Registration.java:109)
    at org.kitesdk.data.Datasets.load(Datasets.java:103)
    at org.kitesdk.data.Datasets.load(Datasets.java:165)
    at org.kitesdk.data.mapreduce.DatasetKeyOutputFormat.load(DatasetKeyOutputFormat.java:510)
    at org.kitesdk.data.mapreduce.DatasetKeyOutputFormat.getOutputCommitter(DatasetKeyOutputFormat.java:473)
    at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$1.call(MRAppMaster.java:476)
    ... 11 more

I am not getting what's wrong ? Is there any class-path problem ? If yes then where do I set it ?


问:
Could not find or load main class (classname) in Scala Intellij
I am learning Scala and while writing some programs. I am getting following

```<code>> error:could not find or load main class Animal
</code>```

I am getting this error even if I delete the class or rename the class.
I am creating this program inside src->main->scala->Animal(package)->Animal(class).

I tried to search for solutions on Google and on this site but that did not help me. Please let  me know what I am missing. I am running this program on Intellij.

I am getting this error for other programs as well.

```<code>package Animal

class Animal {
def a:Int = 10
  println(a)
}
</code>```

答:
Perhaps you have previously written an application whose main method was in the Animal object. Either delete the run configuration that points to this class or make Animal an application by making it an object with a main method, e.g.:

```<code>package Animal

object Animal {

  def a: Int = 10

  def main(args: Array[String]): Unit =
    println(a)

}
</code>```

You can also use the App trait and skip the definition of the main method, than you could edit your code as follows.

```<code>package Animal

object Animal extends App {

  def a: Int = 10

  println(a)

}
</code>```

Body:
I am learning Scala and while writing some programs. I am getting following

> error:could not find or load main class Animal

I am getting this error even if I delete the class or rename the class.
I am creating this program inside src->main->scala->Animal(package)->Animal(class).

I tried to search for solutions on Google and on this site but that did not help me. Please let  me know what I am missing. I am running this program on Intellij.

I am getting this error for other programs as well.

package Animal

class Animal {
def a:Int = 10
  println(a)
}

Body:
Perhaps you have previously written an application whose main method was in the Animal object. Either delete the run configuration that points to this class or make Animal an application by making it an object with a main method, e.g.:

package Animal

object Animal {

  def a: Int = 10

  def main(args: Array[String]): Unit =
    println(a)

}

You can also use the App trait and skip the definition of the main method, than you could edit your code as follows.

package Animal

object Animal extends App {

  def a: Int = 10

  println(a)

}


问:
not getting correct data format in json while using ajax call
i have written a get api and i want to show some records in data table, while im getting records in json im getting date values like this "/Date(1498849454000)/".
How to get date value in "2017-04-11 02:09" in this format.
data is stored correctly "2017-04-11 02:09:17.000".
data type - datetime

sample data

```<code>{"data":[{"updtd_date":"\/Date(1498849454000)\/","usecase":"watertank","id":1026,"sms":"Alert: Tank is Full  at 01/07/2017 12:33:51 AM ]"},
</code>```

code

```<code>     <script>
            $(document).ready(function () {
                $('#myTable').DataTable({
                    "ajax": {
                        "url": "url",
                        "type": "GET",
                        "datatype": "json"
                    },
                    "columns" : [
                        { "data": "updtd_date", "autoWidth": true },
                        { "data": "usecase", "autoWidth": true },
                        { "data": "id", "autoWidth": true },
                        { "data": "sms", "autoWidth": true }
                        ]
                });
            });
        </script>

        <table id="myTable">
                <thead>
                    <tr>
                        <th>Time</th>
                        <th>Use Case</th>
                        <th>Sl no</th>
                        <th>SMS</th>
                    </tr>
                </thead>
            </table>
</code>```

controller

```<code>   public ActionResult getSMS()
        {
            using (smartpondEntities dc = new smartpondEntities())
            {
                var data = dc.sms.OrderByDescending(a => a.id).ToList();
                return Json(new { data = data }, JsonRequestBehavior.AllowGet);
            }

        }
</code>```

答:
if your date is displayed as Date(1498849454000) then it is a time stamp

```<code>$timestamp = //assign your date here after json decode
$timestamp = preg_replace( '/[^0-9]/', '', $timestamp);
$date = date("Y-m-d H:i:s", $timestamp / 1000);
</code>```

this will transform timestamp (divided by 1000 cause of JS date) to a human-readable format.
hope this helps.

Body:
i have written a get api and i want to show some records in data table, while im getting records in json im getting date values like this "/Date(1498849454000)/".
How to get date value in "2017-04-11 02:09" in this format.
data is stored correctly "2017-04-11 02:09:17.000".
data type - datetime

sample data

{"data":[{"updtd_date":"\/Date(1498849454000)\/","usecase":"watertank","id":1026,"sms":"Alert: Tank is Full  at 01/07/2017 12:33:51 AM ]"},

code

                        Time
                        Use Case
                        Sl no
                        SMS

controller

   public ActionResult getSMS()
        {
            using (smartpondEntities dc = new smartpondEntities())
            {
                var data = dc.sms.OrderByDescending(a => a.id).ToList();
                return Json(new { data = data }, JsonRequestBehavior.AllowGet);
            }

        }

Body:
if your date is displayed as Date(1498849454000) then it is a time stamp

$timestamp = //assign your date here after json decode
$timestamp = preg_replace( '/[^0-9]/', '', $timestamp);
$date = date("Y-m-d H:i:s", $timestamp / 1000);

this will transform timestamp (divided by 1000 cause of JS date) to a human-readable format.
hope this helps.


问:
Access every Flask array elements and Display to html with JavaScript
I'm a beginner in python and flask, so i want to ask on how can i access the flask array, increments its array index and display it in html by using JavaScript. I managed to access only one of its array and display it but i failed in incrementing its index to access each of its element. Below is part of my code :

Python/Flask

```<code>@app.route('/Table',methods=['GET', 'POST'])
def showtable():
incr1=0
incr2=0

form = InputForm2(request.form)
session['stemp'] = form.istemp.data
stemp = session['stemp']
session['etemp'] = form.ietemp.data
etemp = session['etemp']
session['stp1'] = form.istp1.data
stp1 = session['stp1']

session['spress'] = form.ispress.data
spress = session['spress']
session['epress'] = form.iepress.data
epress = session['epress']
session['stp2'] = form.istp2.data
stp2 = session['stp2']

incr1 = (etemp - stemp) / stp1
incr2 = (epress - spress) / stp2

tps = np.arange(stemp,etemp,incr1)

for i in range(0,len(tps)):
    tps[i] = tps[i].tolist()

i=0

return render_template('table.html',stemp=stemp,etemp=etemp,incr1=incr1,stp1=stp1,spress=spress,epress=epress,incr2=incr2,
                       tps=tps,i=i)
</code>```

HTML/JavaScript

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAAfJAAAAJDIxMDc1NWExLTczODgtNDBhOS1iZmYwLWRmOTZjZjc2NzVhYQ.png">

    <link rel="stylesheet" type="text/css" href="http://docs.handsontable.com/pro/bower_components/handsontable-pro/dist/handsontable.full.min.css">

    <title>Invigour Tool</title>

    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Invigour Energy

Dashboard

PVT Tool

Help

          <form class="navbar-form navbar-right">
            <input type="text" class="form-control" placeholder="Search...">
          </form>

Overview (current)

          <form method="POST" class="form" id="fm3">

Output Data for Basic Input

Copyright © Invigour Energy 2016

            </form>

```

Please guide me.Thanks.

答:
Have a closer look at this javascript code you wrote:

```<code>for( i ; i < yyy; i++) {
    //alert(i);
    //alert('{{ (tps[i]) }}'):
    var t = '{{ (tps[i]) }}';
    data.push(
          {temp:t, press:999 } );
     //xyz = '{{ (tps[0 + 1]) }}';
     for(t;t<yyy;t++)
           t = '{{ (tps[i+1]) }}'
  }
</code>```

Do you see the problem here? You're probably thinking youre incrementing your i, but there are two i s and they are quite bit different. The i in tps[i] gets evaluted by jinja on the server. The i in the javascript for loop gets evaluated the browser on the client. Jinja will evaluate tps at i and hard codes that in the javascript code.

If you want to send a python array to your javascript, here are two ways. You can write the whole array at once like this:

```<code>var tps_array = JSON.parse('{{ tps | safe }}');
</code>```

and then iterate the array with javascript.

Alternatively, you can write a route that returns your list, and ajax that route on your page load to get the array. That way if the array is huge, your page will not take forever to load.

Body:
I'm a beginner in python and flask, so i want to ask on how can i access the flask array, increments its array index and display it in html by using JavaScript. I managed to access only one of its array and display it but i failed in incrementing its index to access each of its element. Below is part of my code :

Python/Flask

@app.route('/Table',methods=['GET', 'POST'])
def showtable():
incr1=0
incr2=0

form = InputForm2(request.form)
session['stemp'] = form.istemp.data
stemp = session['stemp']
session['etemp'] = form.ietemp.data
etemp = session['etemp']
session['stp1'] = form.istp1.data
stp1 = session['stp1']

session['spress'] = form.ispress.data
spress = session['spress']
session['epress'] = form.iepress.data
epress = session['epress']
session['stp2'] = form.istp2.data
stp2 = session['stp2']

incr1 = (etemp - stemp) / stp1
incr2 = (epress - spress) / stp2

tps = np.arange(stemp,etemp,incr1)

for i in range(0,len(tps)):
    tps[i] = tps[i].tolist()

i=0

return render_template('table.html',stemp=stemp,etemp=etemp,incr1=incr1,stp1=stp1,spress=spress,epress=epress,incr2=incr2,
                       tps=tps,i=i)

HTML/JavaScript

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAAfJAAAAJDIxMDc1NWExLTczODgtNDBhOS1iZmYwLWRmOTZjZjc2NzVhYQ.png">

    <link rel="stylesheet" type="text/css" href="http://docs.handsontable.com/pro/bower_components/handsontable-pro/dist/handsontable.full.min.css">

    <title>Invigour Tool</title>

    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Invigour Energy

Dashboard

PVT Tool

Help

          <form class="navbar-form navbar-right">
            <input type="text" class="form-control" placeholder="Search...">
          </form>

Overview (current)

          <form method="POST" class="form" id="fm3">

Output Data for Basic Input

Copyright © Invigour Energy 2016

            </form>

Please guide me.Thanks.

Body:
Have a closer look at this javascript code you wrote:

for( i ; i < yyy; i++) {
    //alert(i);
    //alert('{{ (tps[i]) }}'):
    var t = '{{ (tps[i]) }}';
    data.push(
          {temp:t, press:999 } );
     //xyz = '{{ (tps[0 + 1]) }}';
     for(t;t<yyy;t++)
           t = '{{ (tps[i+1]) }}'
  }

Do you see the problem here? You're probably thinking youre incrementing your i, but there are two i s and they are quite bit different. The i in tps[i] gets evaluted by jinja on the server. The i in the javascript for loop gets evaluated the browser on the client. Jinja will evaluate tps at i and hard codes that in the javascript code.

If you want to send a python array to your javascript, here are two ways. You can write the whole array at once like this:

var tps_array = JSON.parse('{{ tps | safe }}');

and then iterate the array with javascript.

Alternatively, you can write a route that returns your list, and ajax that route on your page load to get the array. That way if the array is huge, your page will not take forever to load.


问:
i want to select data from table according to date in codeigniter
My question is that.
there is data in table with different dates in created column where i manually enter date in format yyyy/mm/dd with help of insert data
i want to fetch data according to date in array.

and most important the date should be displayed only once and data similar to that date should be displayed in following array

for example
data of 2017/07/04 should be displayed on in one array
data of 2017/07/03 should be displayed in one array

```
{date:2017/07/04}{{id=4,name=abc,created=2017/07/04},{id=5,name=def,created=2017/07/04}}
```

答:
Although the question is very limited - I think you're after something like this:

```<code>$array = array();
foreach ($result->result_array() as $row){
    $array[$row['DATE']][] = array('id'=>$row['ID'],'name'=>$row['NAME'],'created'=>$row['DATE']);
}
</code>```

Obviously you need to replace the capitalised field names with your DB references.

Should you then want it JSON encoded use json_encode($array);

Body:
My question is that.
there is data in table with different dates in created column where i manually enter date in format yyyy/mm/dd with help of insert data
i want to fetch data according to date in array.

and most important the date should be displayed only once and data similar to that date should be displayed in following array

for example
data of 2017/07/04 should be displayed on in one array
data of 2017/07/03 should be displayed in one array

{date:2017/07/04}{{id=4,name=abc,created=2017/07/04},{id=5,name=def,created=2017/07/04}}

Body:
Although the question is very limited - I think you're after something like this:

$array = array();
foreach ($result->result_array() as $row){
    $array[$row['DATE']][] = array('id'=>$row['ID'],'name'=>$row['NAME'],'created'=>$row['DATE']);
}

Obviously you need to replace the capitalised field names with your DB references.

Should you then want it JSON encoded use json_encode($array);


问:
How to use fscanf to read from file and find the matched record with the user input
I want to read the user input and verify if it is match with the "user.txt" record, if it match then it will prompt the user an error message,but the data read by the scanf will always turn into random number,here's the code.Sorry for my English as i'm not a native English speaker                    </p>

```<code>                int day,month,year;
                char name[15];

                printf("Enter your name\n");
                scanf(" %[^\n]s",name);
                printf("Enter you birthday(dd/mm/yyyy)\n");
                scanf("%d%*[-/]%d%*[-/]%d",&day,&month,&year);
                printf("Enter your contact number (60-)\n");
                scanf("%d",&contactNumber);
                printf("Enter your postcode\n");
                scanf("%d",&postcode);

                char x [30];
                int y,z,w,d;
                int duplicateContactNum [15];
                int checkSentinel=0;

                filepointer=fopen("user.txt","r");
                if(filepointer==NULL){
                //Not exist,Print exception message
                printf("Exception Occur: Error writing text into the text file");

                }
                while(!feof(filepointer))
                {
                    fscanf(filepointer,"%s;%d/%d/%d;%d;%d\n",x,&y,&z,&w,&duplicateContactNum,&d);
                    if(strcmp(contactNumber,duplicateContactNum)==0)
                    {
                        checkSentinel++;
                        break;
                    }

                }
                if(checkSentinel!=0)
                {
                    rewind(filepointer);
                    printf("You have entered a duplicated entry\n");
                    fclose(filepointer);
                }
                else
                {
                    rewind(filepointer);
                    fclose(filepointer);
                    filepointer=fopen("user.txt","a");
                    fprintf(filepointer,"%s;%d/%d/%d;%d;%d\n",name,day,month,year,contactNumber,postcode);
                    fclose(filepointer);
                }
</code>```

答:
You have one error in the initial format string, and you do not test the return value of the scanf calls, so the all return errors but you are not warned about it.

```<code>            printf("Enter your name\n");
            if (1 != scanf(" %[^\n]",name)) {  // no s after [] format
                fprintf(stderr, "Error reading name\n");
                return 1;
            }
            printf("Enter you birthday(dd/mm/yyyy)\n");
            if (3 != scanf("%d%*[-/]%d%*[-/]%d",&day,&month,&year)) {
                ...
            }
            printf("Enter your contact number (60-)\n");
            if (1 != scanf("%d",&contactNumber)) {
                ...
            }
            printf("Enter your postcode\n");
            if (1 != scanf("%d",&postcode)) {
                ...
            }
</code>```

Remember: Always test input functions

Body:
I want to read the user input and verify if it is match with the "user.txt" record, if it match then it will prompt the user an error message,but the data read by the scanf will always turn into random number,here's the code.Sorry for my English as i'm not a native English speaker

                int day,month,year;
                char name[15];

                printf("Enter your name\n");
                scanf(" %[^\n]s",name);
                printf("Enter you birthday(dd/mm/yyyy)\n");
                scanf("%d%*[-/]%d%*[-/]%d",&day,&month,&year);
                printf("Enter your contact number (60-)\n");
                scanf("%d",&contactNumber);
                printf("Enter your postcode\n");
                scanf("%d",&postcode);

                char x [30];
                int y,z,w,d;
                int duplicateContactNum [15];
                int checkSentinel=0;

                filepointer=fopen("user.txt","r");
                if(filepointer==NULL){
                //Not exist,Print exception message
                printf("Exception Occur: Error writing text into the text file");

                }
                while(!feof(filepointer))
                {
                    fscanf(filepointer,"%s;%d/%d/%d;%d;%d\n",x,&y,&z,&w,&duplicateContactNum,&d);
                    if(strcmp(contactNumber,duplicateContactNum)==0)
                    {
                        checkSentinel++;
                        break;
                    }

                }
                if(checkSentinel!=0)
                {
                    rewind(filepointer);
                    printf("You have entered a duplicated entry\n");
                    fclose(filepointer);
                }
                else
                {
                    rewind(filepointer);
                    fclose(filepointer);
                    filepointer=fopen("user.txt","a");
                    fprintf(filepointer,"%s;%d/%d/%d;%d;%d\n",name,day,month,year,contactNumber,postcode);
                    fclose(filepointer);
                }

Body:
You have one error in the initial format string, and you do not test the return value of the scanf calls, so the all return errors but you are not warned about it.

            printf("Enter your name\n");
            if (1 != scanf(" %[^\n]",name)) {  // no s after [] format
                fprintf(stderr, "Error reading name\n");
                return 1;
            }
            printf("Enter you birthday(dd/mm/yyyy)\n");
            if (3 != scanf("%d%*[-/]%d%*[-/]%d",&day,&month,&year)) {
                ...
            }
            printf("Enter your contact number (60-)\n");
            if (1 != scanf("%d",&contactNumber)) {
                ...
            }
            printf("Enter your postcode\n");
            if (1 != scanf("%d",&postcode)) {
                ...
            }

Remember: Always test input functions


问:
Counting in how many rows do a pair of values occur
my data frame looks like this:

```<code>Index   V1  v2  v3  v4  v5  v6

 1      a    b  c   d    e  f

 2      b    c  d   e
 3      a    b  c   f    g
 4      a    c  f   d    g
 5      b    c  d   g    h  i
 .      .    .  .   .    .  .
 .      .    .  .   .    .  .
</code>```

I need to iterate through each row in the data frame and pick up pairs that appear together, and count them. For example a and b appears in row index 1 and 3, so count = 2.

Data frame has 6 columns excluding index and 554 rows. 6 variables in each row out of a possible 11.

First step would be to do the pair of a and b.

Then to do all combinations. eg. a+c, a+d, a+e... b+c, b+d...

I've used table(apply(df,1,function(x) paste(sort(x), collapse='-')))
and
count(df) from the plyr package but the output was freq of a+b, a+b+c.... b+c, b+c+d.

I need freq of all pairs. So the freq of a+b = (freq of a+b) + (freq of a+b+c) + (freq of a+b+c+d) and so on

In excel, I've tried COUNTIF. Such that COUNTIF(column1,a,column2,b), but a and b aren't always in columns 1 and 2 respectively.

Also tried COUNTIF(df,a,df,b) but that gave me a huge number.

Can be done in either r or excel. Although I think it would be faster in R.

答:
Using an example random data,
let's assume that the data frame is in C5:H558.

Define a name str as

```<code>=$C$5:$C$558&$D$5:$D$558&$E$5:$E$558&$F$5:$F$558&$G$5:$G$558&$H$5:$H$558
</code>```

Enter the symbols in L5:V5 as well as in K6:K16.

Enter this counting formula

```<code>=IF(CODE($K7)>CODE(L$5),SUMPRODUCT(1-N(ISERROR(FIND($K7,str))+N(ISERROR(FIND(L$5,str)))>0)),"")
</code>```

in L6 and copy it to fill the rest of the table L6:V16.

Body:
my data frame looks like this:

Index   V1  v2  v3  v4  v5  v6

 1      a    b  c   d    e  f

 2      b    c  d   e
 3      a    b  c   f    g
 4      a    c  f   d    g
 5      b    c  d   g    h  i
 .      .    .  .   .    .  .
 .      .    .  .   .    .  .

I need to iterate through each row in the data frame and pick up pairs that appear together, and count them. For example a and b appears in row index 1 and 3, so count = 2.

Data frame has 6 columns excluding index and 554 rows. 6 variables in each row out of a possible 11.

First step would be to do the pair of a and b.

Then to do all combinations. eg. a+c, a+d, a+e... b+c, b+d...

I've used table(apply(df,1,function(x) paste(sort(x), collapse='-')))
and
count(df) from the plyr package but the output was freq of a+b, a+b+c.... b+c, b+c+d.

I need freq of all pairs. So the freq of a+b = (freq of a+b) + (freq of a+b+c) + (freq of a+b+c+d) and so on

In excel, I've tried COUNTIF. Such that COUNTIF(column1,a,column2,b), but a and b aren't always in columns 1 and 2 respectively.

Also tried COUNTIF(df,a,df,b) but that gave me a huge number.

Can be done in either r or excel. Although I think it would be faster in R.

Body:
Using an example random data,
let's assume that the data frame is in C5:H558.

Define a name str as

=$C$5:$C$558&$D$5:$D$558&$E$5:$E$558&$F$5:$F$558&$G$5:$G$558&$H$5:$H$558

Enter the symbols in L5:V5 as well as in K6:K16.

Enter this counting formula

=IF(CODE($K7)>CODE(L$5),SUMPRODUCT(1-N(ISERROR(FIND($K7,str))+N(ISERROR(FIND(L$5,str)))>0)),"")

in L6 and copy it to fill the rest of the table L6:V16.


问:
NumPy array initialization (fill with identical values)
I need to create a NumPy array of length n, each element of which is v.

Is there anything better than:

```<code>a = empty(n)
for i in range(n):
    a[i] = v
</code>```

I know zeros and ones would work for v = 0, 1. I could use v * ones(n), but it <s>won't work when v is None, and also</s> would be much slower.

答:
I had  np.array(n * [value]) in mind, but apparently that is slower than all other suggestions for large enough n. The best in terms of readability and speed is

np.full(n, 3.14)
```
<p>Here is full comparison with perfplot (a pet project of mine).</p>
<p><img src="https://i.stack.imgur.com/YNe6v.png" alt="enter image description here" /></p>
<p>The two <code>empty</code> alternatives are still the fastest (with NumPy 1.12.1). <code>full</code> catches up for large arrays.</p>
<hr />
<p>Code to generate the plot:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import perfplot

def empty_fill(n):
    a = np.empty(n)
    a.fill(3.14)
    return a

def empty_colon(n):
    a = np.empty(n)
    a[:] = 3.14
    return a

def ones_times(n):
    return 3.14 * np.ones(n)

def repeat(n):
    return np.repeat(3.14, (n))

def tile(n):
    return np.repeat(3.14, [n])

def full(n):
    return np.full((n), 3.14)

def list_to_array(n):
    return np.array(n * [3.14])

perfplot.show(
    setup=lambda n: n,
    kernels=[empty_fill, empty_colon, ones_times, repeat, tile, full, list_to_array],
    n_range=[2 ** k for k in range(27)],
    xlabel="len(a)",
    logx=True,
    logy=True,
)
</code>```

Body:
I need to create a NumPy array of length n, each element of which is v.

Is there anything better than:

a = empty(n)
for i in range(n):
    a[i] = v

I know zeros and ones would work for v = 0, 1. I could use v * ones(n), but it <s>won't work when v is None, and also</s> would be much slower.

Body:
I had  np.array(n * [value]) in mind, but apparently that is slower than all other suggestions for large enough n. The best in terms of readability and speed is

np.full(n, 3.14)

Here is full comparison with perfplot (a pet project of mine).

The two empty alternatives are still the fastest (with NumPy 1.12.1). full catches up for large arrays.

Code to generate the plot:

import numpy as np
import perfplot

def empty_fill(n):
    a = np.empty(n)
    a.fill(3.14)
    return a

def empty_colon(n):
    a = np.empty(n)
    a[:] = 3.14
    return a

def ones_times(n):
    return 3.14 * np.ones(n)

def repeat(n):
    return np.repeat(3.14, (n))

def tile(n):
    return np.repeat(3.14, [n])

def full(n):
    return np.full((n), 3.14)

def list_to_array(n):
    return np.array(n * [3.14])

perfplot.show(
    setup=lambda n: n,
    kernels=[empty_fill, empty_colon, ones_times, repeat, tile, full, list_to_array],
    n_range=[2 ** k for k in range(27)],
    xlabel="len(a)",
    logx=True,
    logy=True,
)


问:
Oracle update query using partition
I have following sample data in Oracle v.12 database

```<code>ID | NAME   | DML_TYPE  | FND_FILESEQNO | FND_FILERBA

---------------------------------------------------------

1  | name1a | insert    | 1             | 1

1  | name1b | update    | 1             | 2

2  | name2a | insert    | 2             | 1

2  | name2b | update    | 2             | 2

....

....

....
</code>```

I want following 2 transactions to happen

delete old records (FND_FILESEQNO + FND_FILERBA) partition by 'ID' column

update latest record DML_TYPE = 'insert'

So eventually, if I query this table, I should get following result...

```<code>ID | NAME   | DML_TYPE  | FND_FILESEQNO | FND_FILERBA

---------------------------------------------------------

1  | name1b | insert    | 1             | 2

2  | name2b | insert    | 2             | 2
</code>```

Many thanks

答:
Try This:-</p>

```<code>MERGE INTO STACTOVER a
USING (  SELECT * FROM (
      SELECT   STACTOVER.*,Row_Number() OVER(PARTITION BY ID ORDER BY ID)rn
FROM  STACTOVER)WHERE rn>1
  )b
ON
(a.ID = b.ID)
WHEN MATCHED THEN
  UPDATE SET a.dml_type = 'insert'
  DELETE WHERE a.NAME != b.NAME ;
</code>```

Title: Oracle update query using partition

Body:
I have following sample data in Oracle v.12 database

ID | NAME   | DML_TYPE  | FND_FILESEQNO | FND_FILERBA

---------------------------------------------------------

1  | name1a | insert    | 1             | 1

1  | name1b | update    | 1             | 2

2  | name2a | insert    | 2             | 1

2  | name2b | update    | 2             | 2

....

....

....

I want following 2 transactions to happen

delete old records (FND_FILESEQNO + FND_FILERBA) partition by 'ID' column

update latest record DML_TYPE = 'insert'

So eventually, if I query this table, I should get following result...

ID | NAME   | DML_TYPE  | FND_FILESEQNO | FND_FILERBA

---------------------------------------------------------

1  | name1b | insert    | 1             | 2

2  | name2b | insert    | 2             | 2

Many thanks

Body:
Try This:-

MERGE INTO STACTOVER a
USING (  SELECT * FROM (
      SELECT   STACTOVER.*,Row_Number() OVER(PARTITION BY ID ORDER BY ID)rn
FROM  STACTOVER)WHERE rn>1
  )b
ON
(a.ID = b.ID)
WHEN MATCHED THEN
  UPDATE SET a.dml_type = 'insert'
  DELETE WHERE a.NAME != b.NAME ;