date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/19 | 519 | 1,841 | <issue_start>username_0: I am building a web application and I am using Dropwizard 1.3.0, which has a dependency on jetty-io 9.4.8. This dependency has conflicts with another package (dropwizard-websocket-jee7-bundle 2.0.0), because it seem to fetch the wrong version number.
I looked into tha package, and found the method that has been renamed in [9.4.x - AbstractWebSocketConnection.java](https://github.com/eclipse/jetty.project/blob/jetty-9.4.x/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/io/AbstractWebSocketConnection.java#L647) from [9.3.x - AbstractWebSocketConnection.java](https://github.com/eclipse/jetty.project/blob/jetty-9.3.x/jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/io/AbstractWebSocketConnection.java#L761). The issue is that even though in Gradle the dependency tree shows I fetched 9.4.8 (the new one which I need), I still get the older, 9.3.x java file which causes the conflicts. I tried to Invalidate Caches / Restart and rebuild the whole project, but I seem to get the outdated file all the time.
What are the possible solutions for this?<issue_comment>username_1: Try forcing a particular version in your build.gradle
Example here: <https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html>
Upvotes: 0 <issue_comment>username_2: If your bad class are imported by a transitive dependency, try to exclude explicit the transitive dependency.
For example if your required library is 'my.group:requiredLibrary:2.0.0' and there are another version in 'my.group:someDependency:0.1.5' you can do like this:
```
dependencies{
compile 'my.group:requiredLibrary:2.0.0'
compile ('my.group:someDependency:0.1.5'){
exclude group: 'my.group' module:'requiredLibrary'
}
}
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 1,086 | 3,708 | <issue_start>username_0: how do i remove the text li created in the JavaScript.
the li was created in the javascript and on click on each button in front of them it should only remove that li and not all
```js
function addBook() {
var userInput = document.getElementById('books').value;
if (userInput === "") {
alert("Please Enter A Text");
return false;
}
var book = document.getElementById('addBook');
var list = document.getElementById('addBook').children;
var check = -1;
var btn = document.createElement('button');
btn.innerHTML = 'X';
(list.length === 0) && book.insertAdjacentHTML('beforeend', '- ' + userInput + 'x
');
for (var k = 0; k < list.length; k++) {
console.log(list[k].innerText);
if (list[k].innerText === userInput + "x") {
check = 1;
break;
}
}
(check === -1) && book.insertAdjacentHTML('beforeend', '- ' + userInput + 'x
');
}
function removeParent(e) {
var book = document.getElementById('addBook').children;
book.parentNode.parentNode.removeChild(e.parentNode);
}
```
```html
### Favourite Books
Enter Book's name:
Add Book
### Hoobies
```<issue_comment>username_1: `book` is not an `Element`, instead it is a **list of `Element`s**
Simple use `e` instead of `book`
```
function removeParent(e) {
e.parentNode.parentNode.removeChild(e.parentNode);
}
```
**Demo**
```js
function addBook() {
var userInput = document.getElementById('books').value;
if (userInput === "") {
alert("Please Enter A Text");
return false;
}
var book = document.getElementById('addBook');
var list = document.getElementById('addBook').children;
var check = -1;
var btn = document.createElement('button');
btn.innerHTML = 'X';
(list.length === 0) && book.insertAdjacentHTML('beforeend', '- ' + userInput + 'x
');
for (var k = 0; k < list.length; k++) {
console.log(list[k].innerText);
if (list[k].innerText === userInput + "x") {
check = 1;
break;
}
}
(check === -1) && book.insertAdjacentHTML('beforeend', '- ' + userInput + 'x
');
}
function removeParent(e) {
e.parentNode.parentNode.removeChild(e.parentNode);
}
```
```html
### Favourite Books
Enter Book's name:
Add Book
### Hoobies
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Modify the removeParent function like this:
```
function removeParent(e) {
var book = document.getElementById('addBook');
book.removeChild(e.parentNode);
}
```
```js
function addBook() {
var userInput = document.getElementById('books').value;
if (userInput === "") {
alert("Please Enter A Text");
return false;
}
var book = document.getElementById('addBook');
var list = document.getElementById('addBook').children;
var check = -1;
var btn = document.createElement('button');
btn.innerHTML = 'X';
(list.length === 0) && book.insertAdjacentHTML('beforeend', '- ' + userInput + 'x
');
for (var k = 0; k < list.length; k++) {
console.log(list[k].innerText);
if (list[k].innerText === userInput + "x") {
check = 1;
break;
}
}
(check === -1) && book.insertAdjacentHTML('beforeend', '- ' + userInput + 'x
');
}
function removeParent(e) {
var book = document.getElementById('addBook');
book.removeChild(e.parentNode);
}
```
```html
### Favourite Books
Enter Book's name:
Add Book
### Hoobies
```
Upvotes: 0 <issue_comment>username_3: you simply need to use the "e" parameter it's directly pointing on your element that was clicked :
```
x
```
h
```
function removeParent(e) {
e.parentNode.parentNode.removeChild(e.parentNode);
}
```
Upvotes: 0 |
2018/03/19 | 804 | 2,940 | <issue_start>username_0: is there any way to change button style (colvis, copy, print, excel) in angularjs datatables.
```
vm.dtOptions = DTOptionsBuilder.newOptions().withButtons([
'colvis',
'copy',
'print',
'excel'
]);
```
Only way I can do this is directly in source code, but this is not good way.
here is solution with jquery, but this doesn't have any effect in DOM
```
$('#myTable').DataTable( {
buttons: {
buttons: [
{ extend: 'copy', className: 'copyButton' },
{ extend: 'excel', className: 'excelButton' }
]
}
} );
```
css
```
.copyButton {
background-color: red
}
.excelButton{
background-color: red
}
```
Thank you<issue_comment>username_1: Simply replace a button identifier with a literal and add `className` :
```js
.withButtons([
'colvis',
{ extend: 'copy', className: 'copyButton' },
'print',
{ extend: 'excel', className: 'excelButton' }
]);
```
This works for a "clean" setup, but you are probably including all default stylesheets there is.
DataTables use by default an tag and style it to look like a button through a `.dt-button` class which have a lot of pseudo class styling for `:hover` and so on. This makes it complicated to change for example the background, you'll need additional hackish CSS.
Also, DataTables itself already injects unique classes for each button type like `.buttons-excel` which you could take benefit of.
I will suggest you completely reset the default behaviour through the [`dom`](https://datatables.net/reference/option/buttons.dom) option:
```js
.withButtons({
dom: {
button: {
tag: 'button',
className: ''
}
},
buttons: [
'colvis',
'copy',
'print',
'excel'
]
})
```
Now you can style for example `.buttons-excel` nicely from scratch :
```css
.buttons-excel {
background-color: red;
color: white;
border: 1px outset;
}
.buttons-excel:hover {
background-color: pink;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: If you are working with the bootstrap 4 taste of DataTables the buttons automatically have class btn-secondary.
Using the dom option you lose the bootstrap design altogether.
You can however add classes like so:
```
myTable = $('#myTableId').DataTable({
buttons: [
{ extend: 'colvis', className: 'btn-outline-secondary' },
{ extend: 'excel', className: 'btn-outline-secondary' }
]});
```
But for me this didn't change the button design because the btn-secondary was still there. So I removed it manually afterwords.
```
setTimeout(function () {
$oTable.buttons().container().addClass('ml-2').appendTo('#myTableId_length'); //attach buttons to table length choser
$oTable.buttons().container().find('.btn').removeClass('btn-secondary'); //remove class btn secondary
}, 500);
```
This is wrapped in a time-out to make sure, everything has been rendered before.
Upvotes: 0 |
2018/03/19 | 436 | 1,234 | <issue_start>username_0: I needed to fetch first block in "*.*" string (i.e '\*') in shell script. I found that instead of printing the string it is displaying list of all file in current directory.
How overcome this issue?
main purpose is change string "asterisk.asterick" (this read from /etc/rsyslog.conf) to "\*.debug", here first field i need keep as it is, only second field needs to change.
```
root@xyz-node:/tmp# ccvv=*.*
root@xyz-node:/tmp# echo ccvv
ccvv
root@xyz-node:/tmp# echo $ccvv
new_script.sh rsyslog.conf rsyslog.confe tmp.8R7bE0tYbg
root@xyz-node:/tmp#
root@xyz-node:/tmp#
root@xyz-node:/tmp# echo $ccvv|cut -d "." -f1
new_script
```<issue_comment>username_1: As i understand it...
```
$ echo "*.*"
*.*
$ ccvv="*.*"
$ echo $ccvv
*.*
```
Or?
Upvotes: 1 <issue_comment>username_2: Actually you have to quote variable itself.
`echo "$ccvv"`
Upvotes: 2 <issue_comment>username_3: You could use `sed`'s substitution:
```
sed -i.bak 's/\([a-zA-Z0-9*]\+\.\).*/\1debug/g' InputFile
```
Here `.bak` will create a backup file named `InputFile.bak` before doing the replacement.
Example input:
```
some text
*.conf
some text
some.text
```
Output:
```
some text
*.debug
some text
some.debug
```
Upvotes: 0 |
2018/03/19 | 403 | 1,169 | <issue_start>username_0: On my homepage I have a set of tabs. When I click on the + icon, a new page (AddReportPage) is being pushed (this.navCtrl.push(AddReportPage)).
On this new page I want to display a new set of tabs with different icons and different functions(see image 2).
But when I use the ion-tabs, they're not being displayed...
These tabs have to execute functions with ionSelect.
Do you have a solution?
1.
[](https://i.stack.imgur.com/pd52q.jpg)
2.
[](https://i.stack.imgur.com/luxER.png)<issue_comment>username_1: As i understand it...
```
$ echo "*.*"
*.*
$ ccvv="*.*"
$ echo $ccvv
*.*
```
Or?
Upvotes: 1 <issue_comment>username_2: Actually you have to quote variable itself.
`echo "$ccvv"`
Upvotes: 2 <issue_comment>username_3: You could use `sed`'s substitution:
```
sed -i.bak 's/\([a-zA-Z0-9*]\+\.\).*/\1debug/g' InputFile
```
Here `.bak` will create a backup file named `InputFile.bak` before doing the replacement.
Example input:
```
some text
*.conf
some text
some.text
```
Output:
```
some text
*.debug
some text
some.debug
```
Upvotes: 0 |
2018/03/19 | 383 | 1,317 | <issue_start>username_0: I have a document in solr which is already indexed and stored like
```
{
"title":"<NAME>",
"url":"http://harrypotter.com",
"series":[
"sorcer's stone",
"Goblin of fire",
]
}
```
My requirement is,during query time when I try to retrieve the document
it should concatenate 2 fields in to and give the output like
```
{
"title":"<NAME>",
"url":"http://harrypotter.com",
"series":[
"sorcer's stone",
"Goblin of fire",
],
"title_url":"<NAME>,http://harrypotter.com"
}
```
I know how to do it during index time by using URP but I'm not able to understand how to achieve this during query time.Could anyone please help me with this.Any sample code for reference would be a great help to me.Thanks for your time.<issue_comment>username_1: concat function is available in solr7:
```
http://localhost:8983/solr/col/query?...&fl=title,url,concat(title,url)
```
if you are in an older solr, how difficult is to do this on the client side?
Upvotes: 2 <issue_comment>username_2: To concat you can use `concat(field1, field2)`.
There are many other functions to manipulate data while retrieving.
You can see that [here](https://lucene.apache.org/solr/guide/7_1/function-queries.html#concat-function).
Upvotes: 1 |
2018/03/19 | 857 | 3,746 | <issue_start>username_0: I tried creating an object in PHP for PHPMailer to be used in development enviroments.
```
class Configuration
function __construct()
{
// creating an object for configuration, setting the configuration options and then returning it.
return $config = (object) array(
'DevEnv' => true, // DevEnv setting is used to define if PHPMailer should use a dev mail address to send to or not.
'ReceiverEmail' => '<EMAIL>', // Set the develop enviroment email.
'ReceiverName' => 'name' // Set the develop enviroment email name.
);
}
}
```
Then I call the class in another controller:
```
protected $configuration;
function __construct()
{
$this->configuration = new Configuration();
}
function SendInfoMail()
{
foreach($this->configuration as $config) {
var_dump($config);
if ($config->DevEnv == true) {
// do stuff
}else{
// do stuff
}
}
```
for some reason, it just dumps an empty object. I also tried using
```
var_dump($config->ReceiverEmail);
```<issue_comment>username_1: Constructors do not work that way. They do not have a return value β <http://php.net/manual/en/language.oop5.decon.php>
`new ClassA` always returns an instance of that class.
Upvotes: 2 [selected_answer]<issue_comment>username_2: You are using constructor incorrectly. See this working example:
```
class Configuration {
protected $configuration;
function __construct() {
// creating an object for configuration, setting the configuration options and then returning it.
$this->configuration = (object) array(
'DevEnv' => true, // DevEnv setting is used to define if PHPMailer should use a dev mail address to send to or not.
'ReceiverEmail' => '<EMAIL>', // Set the develop enviroment email.
'ReceiverName' => 'name' // Set the develop enviroment email name.
);
}
}
class Class2 {
//protected $configuration;
function __construct() {
$this->configuration = new Configuration();
}
function SendInfoMail() {
var_dump($this->configuration);
foreach($this->configuration as $config) {
if ($config->DevEnv == true) {
// do stuff
}else{
// do stuff
}
}
}
}
$t = new Class2();
$t->SendInfoMail();
```
Upvotes: 1 <issue_comment>username_3: You have instance of Configuration class. Instead of that, try to add new method let's say "getProperties()".
```
class Configuration
function getProperties()
{
// creating an object for configuration, setting the configuration options and then returning it.
return $config = (object) array(
'DevEnv' => true, // DevEnv setting is used to define if PHPMailer should use a dev mail address to send to or not.
'ReceiverEmail' => '<EMAIL>', // Set the develop enviroment email.
'ReceiverName' => 'name' // Set the develop enviroment email name.
);
}
}
```
So you can call it wherever you want:
```
protected $configuration;
function __construct()
{
$this->configuration = new Configuration();
}
function SendInfoMail()
{
foreach($this->configuration->getProperties() as $config) {
var_dump($config);
if ($config->DevEnv == true) {
// do stuff
}else{
// do stuff
}
}
```
Upvotes: 2 |
2018/03/19 | 1,269 | 4,444 | <issue_start>username_0: I want to make a query in sql-server which can make the following output as like column \_B from column\_A.Columns are varchar type.
```
Column_A column_B
karim,karim,rahim,masud,raju,raju karim,rahim,masud,raju
jon,man,jon,kamal,kamal jon,man,kamal
c,abc,abc,pot c,abc,pot
```<issue_comment>username_1: First of all: You were told in comments alread, that this is a very bad design (violating 1.NF)! If you have the slightest chance to change this, you really should... **Never store more than one value within one cell!**
If you have to stick with this (or in order to repair this mess), you can go like this:
This is the simplest approach I can think of: Transform the CSV to an XML and call `XQuery`-function `distinct-values()`
```
DECLARE @tbl TABLE(ColumnA VARCHAR(MAX));
INSERT INTO @tbl VALUES
('karim,karim,rahim,masud,raju,raju')
,('jon,man,jon,kamal,kamal')
,('c,abc,abc,pot');
WITH Splitted AS
(
SELECT ColumnA
,CAST('' + REPLACE(ColumnA,',','') + '' AS XML) AS TheParts
FROM @tbl
)
SELECT ColumnA
,TheParts.query('distinct-values(/x/text())').value('.','varchar(250)') AS ColumnB
FROM Splitted;
```
The result
```
ColumnA ColumnB
karim,karim,rahim,masud,raju,raju karim rahim masud raju
jon,man,jon,kamal,kamal jon man kamal
c,abc,abc,pot c abc pot
```
UPDATE Keep the commas
----------------------
```
WITH Splitted AS
(
SELECT ColumnA
,CAST('' + REPLACE(ColumnA,',','') + '' AS XML) AS TheParts
FROM @tbl
)
SELECT ColumnA
,STUFF(
(TheParts.query
('
for $x in distinct-values(/x/text())
return {concat(",", $x)}
').value('.','varchar(250)')),1,1,'') AS ColumnB
FROM Splitted;
```
The result
```
ColumnB
karim,rahim,masud,raju
jon,man,kamal
c,abc,pot
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: SQL remove duplicates from comma separated string:
--------------------------------------------------
Pseudocode: Make a postgresql function that receives as input the comma delimited string, and creates another array in memory. Split the string on comma, trim whitespace and enumerate each item, if the item doesn't appear in the new list, then add it. Finally flatten the new array to string and return.
```
drop function if exists remove_duplicates_from_comma_separated_string(text);
CREATE or replace FUNCTION remove_duplicates_from_comma_separated_string(arg1 text)
RETURNS text language plpgsql AS $$ declare
item text;
split_items text[];
ret_items text[];
ret_val text;
BEGIN
--split your string on commas and trim whitespace
split_items := string_to_array(ltrim(arg1), ',');
--enumerate each item, if it doesn't exist in the new array then add it.
FOREACH item IN ARRAY split_items LOOP
if ( item::text = ANY(ret_items)) then
else
--append this unique item into ret_items
select array_append(ret_items, ltrim(item)) into ret_items;
end if;
END LOOP;
--flatten the final array to a text with comma delimiter
SELECT array_to_string(ret_items, ',', '*') into ret_val;
return ret_val;
END; $$;
```
So now we can invoke the function on a table thustly:
```
drop table if exists foo_table;
create table foo_table(name text);
insert into foo_table values('karim,karim,rahim,masud,raju,raju');
insert into foo_table values('jon,man,jon,kamal,kamal');
insert into foo_table values('jon,man,kamal');
insert into foo_table values('c,abc,poty');
insert into foo_table values('c,abc,abc,kotb');
select remove_duplicates_from_comma_separated_string(name) from foo_table;
```
Which prints:
```
βββββββββββββββββββββββββββββββββββββββββββββββββ
β remove_duplicates_from_comma_separated_string β
βββββββββββββββββββββββββββββββββββββββββββββββββ€
β karim,rahim,masud,raju β
β jon,man,kamal β
β jon,man,kamal β
β c,abc,poty β
β c,abc,kotb β
βββββββββββββββββββββββββββββββββββββββββββββββββ
```
Code smell haaax factor: 9.5 of 10. Construction crew watches the novice programmer bang in a nail with the $90 sql brand pipe wrench, everyone rolls their eyes.
Upvotes: 0 |
2018/03/19 | 560 | 1,554 | <issue_start>username_0: I have a dataframe that contains some duplicates, around 100 of them, the data is displayed like this:
```
Data V1 V2 V3 V4
Cellulomonas uda 0.2 0.0 0.0 0.1
Cellulomonas uda 0.0 0.1 0.3 0.1
```
But I would like to find all the duplicates in the dataframe and add them together, to give this:
```
Data V1 V2 V3 V4
Cellulomonas uda 0.2 0.1 0.3 0.2
```
Is there a function in dplyr which could help with this? Or even a way to add the rows together in Excel and just manually deleting one of the duplicates would be fine.<issue_comment>username_1: You can take the sum of V values for each `Data` value :
```
df1 <- read.table(text="Data V1 V2 V3 V4
'Cellulomonas uda' 0.2 0.0 0.0 0.1
'Cellulomonas uda' 0.0 0.1 0.3 0.1",h=T,string=F)
library(dplyr)
df1 %>% group_by(Data) %>% summarize_all(sum)
# # A tibble: 1 x 5
# Data V1 V2 V3 V4
#
# 1 Cellulomonas uda 0.2 0.1 0.3 0.2
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: With base R we could use `aggregate`:
```
aggregate(. ~ Data, df1, sum)
Data V1 V2 V3 V4
1 Cellulomonas uda 0.2 0.1 0.3 0.2
```
And with `data.table` I think we could do:
```
library(data.table)
dt[, lapply(.SD, sum), by = Data]
Data V1 V2 V3 V4
1 Cellulomonas uda 0.2 0.1 0.3 0.2
```
Upvotes: 2 |
2018/03/19 | 570 | 1,524 | <issue_start>username_0: I've done this RLE code a while back and I seem to be blind on what is going on wrong. The expected output of encode() should be 'a1b2c3' but instead I'm getting the value 'None'.
```
def encode(text):
if not text:
return ""
else:
last_char = text[0]
max_index = len(text)
i = 1
while i < max_index and last_char == text[i]:
i += 1
return last_char + str(i) + encode(text[i:])
print(encode("abbccc"))
def decode(text):
if not text:
return ""
else:
char = text[0]
quantity = text[1]
return char * int(quantity) + decode(text[2:])
print(decode("a1b2c3"))
```
Regards<issue_comment>username_1: You can take the sum of V values for each `Data` value :
```
df1 <- read.table(text="Data V1 V2 V3 V4
'Cellulomonas uda' 0.2 0.0 0.0 0.1
'Cellulomonas uda' 0.0 0.1 0.3 0.1",h=T,string=F)
library(dplyr)
df1 %>% group_by(Data) %>% summarize_all(sum)
# # A tibble: 1 x 5
# Data V1 V2 V3 V4
#
# 1 Cellulomonas uda 0.2 0.1 0.3 0.2
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: With base R we could use `aggregate`:
```
aggregate(. ~ Data, df1, sum)
Data V1 V2 V3 V4
1 Cellulomonas uda 0.2 0.1 0.3 0.2
```
And with `data.table` I think we could do:
```
library(data.table)
dt[, lapply(.SD, sum), by = Data]
Data V1 V2 V3 V4
1 Cellulomonas uda 0.2 0.1 0.3 0.2
```
Upvotes: 2 |
2018/03/19 | 965 | 3,512 | <issue_start>username_0: I want to make "camera follow" effect on feature while its moves along path.
The feature is moved using `requestAnimationFrame`, here is the example code:
```
var lastFrame = +new Date;
var updateSlider = function () {
var now = +new Date, deltaTime = now - lastFrame;
trackValue += deltaTime;
self.move(trackValue);
lastFrame = now;
self.Timer = requestAnimationFrame(updateSlider);
};
updateSlider();
.move = function (timestamp) {
var point = LineString.getCoordinateAtM(timestamp);
if(point) Feature.setCoordinate(point);
this.followCamera();
};
```
I tried a few options of centering the view. And it works, but the problem is that the map jitters. Need help on getting rid of the jitter.
See this OL example - <http://openlayers.org/en/latest/examples/geolocation-orientation.html>, to see map jitters, press "Simulate"
```
.followCamera = function() {
var extent = Feature.getGeometry().getExtent();
A) view.set('center', ol.extent.getCenter(extent);
B) view.setCenter(ol.extent.getCenter(extent);
C) view.animate({center: ol.extent.getCenter(extent)});
D) view.fit(extent) <- Not usable in my case, because i want to zoom in/out manually
};
```
Also you can try this example (taken from ol examples) - <https://jsfiddle.net/32z45kLo/5/> - try with and without `setCenter` part at `moveFeature` function (`line 152`)
Here is the video - <https://youtu.be/L96HgWZi6Lo><issue_comment>username_1: I think the problem is that you are creating and drawing a new feature to `vectorContext` at each frame animation.
Instead you should create a feature and add it into a `vectorLayer` once, and then modify its geometry at each frame animation.
```
//here you define the pinpoint feature and add it to the vectorLayer
var feature = new ol.Feature();
feature.setStyle(styles.geoMarker);
vectorLayer.getSource().addFeature(feature);
var moveFeature = function(event) {
var vectorContext = event.vectorContext;
var frameState = event.frameState;
if (animating) {
var elapsedTime = frameState.time - now;
// here the trick to increase speed is to jump some indexes
// on lineString coordinates
var index = Math.round(speed * elapsedTime / 1000);
if (index >= routeLength) {
stopAnimation(true);
return;
}
var currentPoint = new ol.geom.Point(routeCoords[index]);
//here you modify the feature geometry instead of creating a new feature
feature.setGeometry(currentPoint);
map.getView().setCenter(routeCoords[index]);
}
// tell OpenLayers to continue the postcompose animation
map.render();
};
```
working demo without jitter:
<https://jsfiddle.net/32z45kLo/80/>
Upvotes: 2 <issue_comment>username_2: The problem is that points on the lines are not equidistant thus the position jump from one to another but nothing inbeetween.
Look at this example to calculate points on the line: <http://viglino.github.io/ol-ext/examples/animation/map.featureanimation.path.html>
Using a [ol.featureAnimation.Path](https://github.com/Viglino/ol-ext/blob/master/src/featureanimation/Path.js), if you have to move the map on position change, just listen to the change event on the animated feature to get its current position:
```
geoMarker.on('change', function() {
map.getView().setCenter(geoMarker.getGeometry().getCoordinates());
});
```
You can see a working example with your code here: <https://jsfiddle.net/Viglino/nhrwynzs/>
Upvotes: 2 |
2018/03/19 | 1,148 | 3,070 | <issue_start>username_0: Given my list of dictionaries
```
dict_nomi = [
{'first_name': 'Luca', 'last_name': 'Rossi'},
{'first_name': 'Stefano', 'last_name': '<NAME>'},
{'first_name': 'Luca', 'last_name': 'Bianchi'},
{'first_name': 'Luca', 'last_name': 'Rossi'},
]
```
I'd like to count the occurrences of values not by one key, but by multiple keys (two, in this case).
```
def count_names(dict_nomi):
names = Counter(v['first_name'] for v in dict_nomi if v.get('first_name'))
for names, count in names.most_common():
print(names, count)
count_names(dict_nomi)
```
This gives me:
```
('Luca', 3)
('Stefano', 1)
```
But how can I get something like
```
('<NAME>', 2)
('<NAME>', 1)
('<NAME>', 1)
```
this?
Thanks.<issue_comment>username_1: ```
def count_names(dict_nomi):
names = Counter("{} {}".format(v['first_name'], v['last_name']) for v in dict_nomi if v.get('first_name') and v.get('last_name'))
for names, count in names.most_common():
print(names, count)
return names
names = count_names(dict_nomi)
```
Upvotes: 1 <issue_comment>username_2: What about just:
```
from collections import Counter
dict_nomi = [
{'first_name': 'Luca', 'last_name': 'Rossi'},
{'first_name': 'Stefano', 'last_name': '<NAME>'},
{'first_name': 'Luca', 'last_name': 'Bianchi'},
{'first_name': 'Luca', 'last_name': 'Rossi'},
]
c = Counter(' '.join((d['first_name'], d['last_name'])) for d in dict_nomi)
print(c)
```
Output:
```
Counter({'<NAME>': 2, '<NAME>': 1, '<NAME>': 1})
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: ```
dict_nomi = [
{'first_name': 'Luca', 'last_name': 'Rossi'},
{'first_name': 'Stefano', 'last_name': '<NAME>'},
{'first_name': 'Luca', 'last_name': 'Bianchi'},
{'first_name': 'Luca', 'last_name': 'Rossi'},
]
res = {}
for i in dict_nomi: #Iterate over your dict
val = "{0} {1}".format(i["first_name"], i["last_name"])
if val not in res: #Check if key in res
res[val] = 1 #Else create and add count
else:
res[val] += 1 #Increment count
print(res)
```
**Output:**
```
{'<NAME>': 1, '<NAME>': 2, '<NAME>': 1}
```
Upvotes: 0 <issue_comment>username_4: ```
from collections import Counter
Counter([d['first_name'] + ' ' + d['last_name'] for d in dict_nomi])
out: Counter({'<NAME>': 2, '<NAME>': 1, '<NAME>': 1})
```
Upvotes: 1 <issue_comment>username_5: For this you can use the Counter Dict from **`collections`** module in python.
```
from collections import Counter as cnt
dict_nomi = [
{'first_name': 'Luca', 'last_name': 'Rossi'},
{'first_name': 'Stefano', 'last_name': '<NAME>'},
{'first_name': 'Luca', 'last_name': 'Bianchi'},
{'first_name': 'Luca', 'last_name': 'Rossi'},
]
cnt_dict = cnt(' '.join((dic['first_name'], dic['last_name'])) for dic in dict_nomi)
final_res = [(i,j,) for i,j in cnt_dict.iteritems()]
```
Output
```
[('<NAME>', 1), ('<NAME>', 2), ('<NAME>', 1)]
```
Let me know if this solves your problem
Upvotes: 0 |
2018/03/19 | 2,079 | 7,094 | <issue_start>username_0: I am getting 'TypeError: Cannot convert undefined or null to object' while trying to access the length of json object in nodejs.
Following is how my data looks like:
```js
{
"college": [
{
"colleges": [],
"department": [
1,
2,
3
],
"general_course": [],
"id": 1,
"name": "College of the Arts",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1919"
},
{
"colleges": [],
"department": [
4,
5,
6
],
"general_course": [],
"id": 2,
"name": "College of Communications",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1920"
},
{
"colleges": [],
"department": [
7,
12
],
"general_course": [],
"id": 3,
"name": "College of Education",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1921"
},
{
"colleges": [],
"department": [
13,
17,
19
],
"general_course": [],
"id": 4,
"name": "College of Engineering and Computer Science",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1922"
},
{
"colleges": [],
"department": [
20,
26,
27
],
"general_course": [],
"id": 5,
"name": "College of Health and Human Development",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1923"
},
{
"colleges": [],
"department": [
28,
29,
32,
48
],
"general_course": [],
"id": 6,
"name": "College of Humanities and Social Sciences",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1924"
},
{
"colleges": [],
"department": [
52,
57
],
"general_course": [],
"id": 7,
"name": "College of Natural Sciences and Mathematics",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1925"
},
{
"colleges": [],
"department": [
58,
59,
63
],
"general_course": [],
"id": 8,
"name": "Mihaylo College of Business and Economics",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1926"
}
]
}
```
**Step 1** - Parsing it into nodejs:
```
let colleges = JSON.parse(data)
```
**Step 2** - Saving it into the dialogflow app data:
```
app.data.collegeData = data;
```
**Step 3** - Accessing the length:
```
let collegeLength = Object.keys(app.data.collegeData.college).length;
```
Getting following error in firebase console:
>
> TypeError: Cannot convert undefined or null to object
>
>
>
**Update:**
Here is the code:
```js
if ( app.data.collegeData === undefined ){
app.data.collegeData = [];
}
**Step 1 =>**
showColleges(college);
**Step 2 =>**
function showColleges(collegeName){
if (app.data.collegeData.length === 0){
getCollegeData().then(buildSingleCollegeResponse(collegeName))
.catch(function (err){
console.log('No college data')
console.log(err)
});
}
else{
buildSingleCollegeResponse(collegeName);
}
}
**Step 3 =>**
function getCollegeData(){
console.log('Inside get College Data')
return requestAPI(URL)
.then(function (data) {
let colleges = JSON.parse(data)
if (colleges.hasOwnProperty('college')){
saveData(colleges)
}
return null;
})
.catch(function (err) {
console.log('No college data')
console.log(err)
});
}
**Step 4 =>**
function saveData(data){
app.data.collegeData = data;
console.log(app.data.collegeData)
}
**Step 5 =>**
function buildSingleCollegeResponse(collegeName){
let responseToUser, text;
//console.log('Data is -> '+ Object.keys(app.data.collegeData.college).length);
//console.log('Length is -> '+ app.data.collegeData.college.length);
console.log('Count is -> '+app.data.collegeCount);
let collegeLength = Object.keys(app.data.collegeData.college).length;
if ( collegeLength === 0){
responseToUser = 'No colleges available at this time';
text = 'No colleges available at this time';
}
else if ( app.data.collegeCount < collegeLength ){
for ( var i = 1; i <= collegeLength; i++)
{
console.log('All Colleges:: '+app.data.collegeData.college[i])
let coll = app.data.collegeData.college[i]
let name = coll.name
console.log('checkCollegeExist => College Name:: '+ name)
console.log('checkCollegeExist => Parameter => College Name:: '+collegeName)
if(String(name).valueOf() === String(collegeName).valueOf()){
responseToUser = 'Yes! CSUF has '+collegeName;
text = 'Yes! CSUF has '+collegeName;
}else{
responseToUser = 'CSUF does not teach ' +collegeName+' currently';
text = 'CSUF does not teach ' +collegeName+' currently';
}
}
}
else{
responseToUser = 'No more colleges';
}
if (requestSource === googleAssistantRequest) {
sendGoogleResponse(responseToUser);
} else {
sendResponse(text);
}
}
```<issue_comment>username_1: You haven't mentioned what value `app.data` holds before issuing `app.data.collegeData = data;`
If `app.data` is undefined you should try `app.data = {collegeData: data}`
Or else negating what app stores. Following works
```
app = {};
app.data = {};
app.data.collegeData = data;
app.data.collegeData.college.length
```
You don't need to do the following
```
let collegeLength = Object.keys(app.data.collegeData.college).length;
```
**Update**: Refer to <https://jsfiddle.net/dmxuum79/3/>
Upvotes: 0 <issue_comment>username_2: This is the culprit:
```
getCollegeData().then(buildSingleCollegeResponse(collegeName))
```
That **calls** `buildSingleCollegeResponse(collegeName)` and then passes its *return value* into `then`, just like `foo(bar())` **calls** `bar` and passes its return value into `foo`.
You wanted to pass a functon to `then`:
```
getCollegeData().then(() => buildSingleCollegeResponse(collegeName))
// An arrow function ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
---
Note that now that it's clear from the updated question that `app.data.collegeData.college` is an *array*, there's no need for `Object.keys`. Change:
```
let collegeLength = Object.keys(app.data.collegeData.college).length;
```
to simply
```
let collegeLength = app.data.collegeData.college.length;
```
Arrays have a `length` property (whereas non-array objects don't, by default).
Upvotes: 3 [selected_answer] |
2018/03/19 | 592 | 1,948 | <issue_start>username_0: I have 2 columns in gridview I want to check if the column is null then the column will hidden .. I used many ways but I can't get the right result
here is my code
```
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[8].Text == "")
{
e.Row.Cells[8].Visible = false;
e.Row.Cells[9].Visible = false;
}
}
```
I'm tried also to check equal null word but the same problem The columns not hidden<issue_comment>username_1: You haven't mentioned what value `app.data` holds before issuing `app.data.collegeData = data;`
If `app.data` is undefined you should try `app.data = {collegeData: data}`
Or else negating what app stores. Following works
```
app = {};
app.data = {};
app.data.collegeData = data;
app.data.collegeData.college.length
```
You don't need to do the following
```
let collegeLength = Object.keys(app.data.collegeData.college).length;
```
**Update**: Refer to <https://jsfiddle.net/dmxuum79/3/>
Upvotes: 0 <issue_comment>username_2: This is the culprit:
```
getCollegeData().then(buildSingleCollegeResponse(collegeName))
```
That **calls** `buildSingleCollegeResponse(collegeName)` and then passes its *return value* into `then`, just like `foo(bar())` **calls** `bar` and passes its return value into `foo`.
You wanted to pass a functon to `then`:
```
getCollegeData().then(() => buildSingleCollegeResponse(collegeName))
// An arrow function ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
---
Note that now that it's clear from the updated question that `app.data.collegeData.college` is an *array*, there's no need for `Object.keys`. Change:
```
let collegeLength = Object.keys(app.data.collegeData.college).length;
```
to simply
```
let collegeLength = app.data.collegeData.college.length;
```
Arrays have a `length` property (whereas non-array objects don't, by default).
Upvotes: 3 [selected_answer] |
2018/03/19 | 674 | 2,297 | <issue_start>username_0: When I use `resolveAttribute()` to find out a color value of `?attr/colorControlNormal`, I got `236`:
```
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = typedValue.data;
// 236
```
---
But when I use an XML layout with the following `TextView` element:
```
```
...and the following Java code:
```
View textView = findViewById(R.id.textView);
int color = ((TextView) textView).getCurrentTextColor();
// -1979711488
```
I got a color value of `-1979711488`
---
Why those results vary? I expected to get same color values, but they are not.
The second approach (I believe) returns a correct color value. Why is my first approach wrong?
I would prefer to obtain the color value of `?attr/colorControlNormal` without a need of using actual element. How can I do that?<issue_comment>username_1: I believe instead of this:
```
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = typedValue.data;
```
You should do this:
```
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = ContextCompat.getColor(this, typedValue.resourceId)
```
Upvotes: 7 [selected_answer]<issue_comment>username_2: It's correct I think, check with it
HEX
```
Integer intColor = -1979711488138;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);
```
or
```
int color = getCurrentTextColor();
int a = Color.alpha(color);
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
```
Upvotes: 1 <issue_comment>username_3: Using Kotlin you can do the following to get the color:
```
val color = TypedValue().let {
requireContext().theme.resolveAttribute(R.attr.colorControlNormal, it, true)
requireContext().getColor(it.resourceId)
}
```
Upvotes: 1 <issue_comment>username_4: In Kotlin, according to @username_1 answer, to do it you could do something like this:
```
val typedValue = TypedValue()
theme.resolveAttribute(com.google.android.material.R.attr.colorControlNormal, typedValue, true)
val color = ContextCompat.getColor(this, typedValue.resourceId)
```
Upvotes: 0 |
2018/03/19 | 395 | 1,548 | <issue_start>username_0: I am working on android Tv, In our Fragment there the two Horizontal Recyclerview, when I scroll First Recyclerview using D-pad in Right direction, it scrolls well and when I come to last focus item of its Recycler view, Focus automatically goes down to second Recycler view item.
How to prevent this?
```
xml version="1.0" encoding="utf-8"?
```<issue_comment>username_1: try setting the `focusable` attribute of the `recyclerview` to `false`
```
recyclerview.setFocusable(false);
```
Upvotes: 0 <issue_comment>username_2: It might be late but for any one still looking for solution:
You should write your own logic while searching for next focus happens and supply the last view as next focus item if in the end of list OR you may modify the logic according to your needs. For Ex:
```
override fun onInterceptFocusSearch(focused: View?, direction: Int): View? {
val position = getPosition(focused)
val count = itemCount
lastKnownPosition = position
return if (position == count - 1 && direction == View.FOCUS_RIGHT) {
focused
} else {
super.onInterceptFocusSearch(focused, direction)
}
}
```
And this method will be part of your layout manager.
Upvotes: 3 <issue_comment>username_3: I am posting this answer very late , but there is one way you can do it is , in Adapter class check if the item is first , and set the nextFocusLeftId to itself.
for example.
itemview.setnextFocusLeftId(itemview.gedId)
do the same for the last element of the recycler view.
Upvotes: -1 |
2018/03/19 | 1,252 | 2,946 | <issue_start>username_0: I am learning C++ and came upon this problem while trying to use a formula to calculate the current.

And I got: `0.628818` where the answer should be:
>
> f=200 Hz
>
>
> R=15 Ohms
>
>
> C=0.0001 (100Β΅F)
>
>
> L=0.01476 (14.76mH)
>
>
> E = 15 V
>
>
> Answer: I = 0.816918A (calculated)
>
>
>
Below is my code:
```
#include
#include
int main()
{
const double PI = 3.14159;
double r = 15;
double f = 200;
double c = 0.0001;
double l = 0.01476;
double e = 15;
double ans = e / std::sqrt(std::pow(r, 2) + (std::pow(2 \* PI\*f\*l - (1.0 / 2.0 \* PI\*f\*c), 2)));
std::cout << "I = " << ans << "A" << std::endl;
}
```
I have read about truncation errors and tried to use 1.0/2.0 but doesn't seem to work either.<issue_comment>username_1: Truncation error refers to using only the first N terms of an infinite series to estimate a value. So the answer to your question is "No." You might find the following to be of some interest however....
```
#include
#include
#include
using namespace std;
template
T fsqr(T x) { return x \* x; }
// Numerically stable and non-blowuppy way to calculate
// sqrt(a\*a+b\*b)
template
T pythag(T a, T b) {
T absA = fabs(a);
T absB = fabs(b);
if (absA > absB)
{
return absA\*sqrt(1.0 + fsqr(absB / absA));
} else if (0 == absB) {
return 0;
} else {
return absB\*sqrt(1.0 + fsqr(absA / absB));
}
}
int main () {
double e, r, f, l, c, ans;
const double PI = 3.14159265358972384626433832795028841971693993751058209749445923078164062862089986280348253421170;
cout << "Insert value for resistance: " << endl;
cin >> r ;
cout << "Insert value for frequency: " << endl;
cin >> f;
cout << "Insert value for capacitance: " << endl;
cin >> c;
cout << "Insert value for inductance: " << endl;
cin >> l;
cout << "Insert value for electromotive force (voltage): " << endl;
cin >> e;
ans = e / pythag(r, 2\*PI\*f\*l - (1/(2\*PI\*f\*c)) );
cout << "I = " << ans << "A" << endl;
system("pause");
return 0;
}
```
Just kidding about all that PI.
Upvotes: 1 <issue_comment>username_2: The main problem is multiplying Β½ by ΟfC instead of dividing, here:
```
(1.0 / 2.0 * PI*f*c)
```
This sort of problem is best avoided by using suitable named values (that also allows you to use faster and more precise `x*x` instead of `std::pow(x,2)`).
You can also remove some of that arithmetic by using the standard hypotenuse function instead of squaring and sqrting inline:
```
double ans = e / std::hypot(r, (2*PI*f*l - 0.5/PI/f/c));
```
---
```
#include
#include
int main()
{
static constexpr double PI = 4 \* std::atan(1);
double r = 15; // ohm
double f = 200; // hertz
double c = 0.0001; // farad
double l = 0.01476; // henry
double e = 15; // volt
double current = e / std::hypot(r, (2 \* PI\*f\*l - 0.5/PI/f/c));
std::cout << "I = " << current << "A" << std::endl;
}
```
Upvotes: 0 |
2018/03/19 | 515 | 1,727 | <issue_start>username_0: I have an array of objects and when I try to access to it, I get an error saying:
>
> TypeError: Cannot set property 'ID' of undefined
>
>
>
My code is the following:
```
export class Carimplements OnInit {
pieces: Piece[] = [];
test(pos){
this.pieces[pos].ID = "test";
}
}
```
being Piece an object
```
export class Piece{
ID: string;
doors: string;
}
```
I call to `test(pos)` from the HTML with a valid position.
I guess that I am trying to access to the position X of an array that has not been initialized. How could I do it? Is it possible to create a constructor?<issue_comment>username_1: * Correct syntax for defining array types in TypeScript is this:
```
pieces: Piece[] = [];
```
* The error is a runtime error. When you run your app you have an empty array `pieces` (but the variable still initialized with `[]`) but you call `test(whatever)` which tries to access an array element `whatever` that doesn't exist.
You can do for example this:
```
pieces: Piece[] = [{
ID: '1',
doors: 'foo'
}];
```
and then test this method with `test(0)`.
Upvotes: 5 [selected_answer]<issue_comment>username_2: You can try the following method
```
test(pos){
if(pos < this.pieces.length)
this.pieces[pos].ID = "test";
else
// throw error
}
```
Upvotes: 0 <issue_comment>username_3: How about this?
```
export class Carimplements OnInit {
pieces: Piece[] = [];
test(pos){
this.pieces[pos] = {ID: "test"};
}
}
```
Upvotes: 1 <issue_comment>username_4: ```
let pieces: Piece[] = [];
//initialize object before assigning value
test(pos){
this.pieces[pos] = new Piece();
this.pieces[pos].ID = "test";
}
```
Upvotes: 1 |
2018/03/19 | 941 | 2,338 | <issue_start>username_0: I have imported the first three columns of a .csv file named as *Time, Test 1* and *Test 2* in my python program.
```
import pandas as pd
fields = ['Time', 'Time 1', 'Time 2']
df=pd.read_csv('file.csv', skipinitialspace=True, usecols=fields)
```
[Here](https://i.stack.imgur.com/zNAGx.jpg) is the file which I imported in the program.
[](https://i.stack.imgur.com/hvIpt.jpg)
How can I make a function which finds the mean/average of the values in the **Test 1** column between a given time limit? The time limits (starting and end values) are to be taken as the parameters in the function.
e.g., I want to find the average of the values in the column **Test 1** from 0.50 seconds to 4.88 seconds. The limits (0.50 and 4.88) would be the function's parameter.<issue_comment>username_1: I think need [`between`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html) for boolen mask, filter by [`boolean indexing`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing) and get `mean`:
```
def custom_mean(x,y):
return df.loc[df['Time'].between(x,y), 'Test 1'].mean()
```
**Sample**:
```
df = pd.DataFrame({'Time':[0.0, 0.25, 0.5, 0.68, 0.94, 1.25, 1.65, 1.88, 2.05, 2.98, 3.45, 3.99, 4.06, 4.68, 4.88, 5.06, 6.0],
'Test 1':np.random.randint(10, size=17)})
```
---
```
print (df)
Test 1 Time
0 3 0.00
1 6 0.25
2 5 0.50
3 4 0.68
4 8 0.94
5 9 1.25
6 1 1.65
7 7 1.88
8 9 2.05
9 6 2.98
10 8 3.45
11 0 3.99
12 5 4.06
13 0 4.68
14 9 4.88
15 6 5.06
16 2 6.00
def custom_mean(x,y):
return df.loc[df['Time'].between(x,y), 'Test 1'].mean()
print (custom_mean(0.50, 1.0))
5.666666666666667
#verify
print (df.loc[df['Time'].between(0.50, 1.0), 'Test 1'])
2 5
3 4
4 8
Name: Test 1, dtype: int32
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use the `between` mask and `mean`, `std` function from numpy library.
For example: this line of code will estimate the mean of the `Test 1` while it was taken between time 0.0 and 5.0:
```
np.mean(df[df['Time'].between(0.0, 5.0)]['Test 1'])
```
Upvotes: 0 |
2018/03/19 | 717 | 2,651 | <issue_start>username_0: How can I update my state value inside child component in this property `{this.state.username}` using of this function `this.messageSubmit` and how can I re-render the child render for displaying changed state values. Please help me anyone how can I update my state value inside and chat box because I'm new to **reactjs**
This is my child component `chatting.js`
```
import React from "react";
export class Chatting extends React.Component{
constructor(props){
super(props);
this.state={
username: 'shiva'
}
this.messageSubmit=this.messageSubmit.bind(this);
this.messageTextBox=this.messageTextBox.bind(this);
}
messageTextBox(event){
this.setState=({
username :event.target.value
})
}
messageSubmit(){
console.log(this.setState.username);
}
render(){
return(
Flush to the bottom right. Uses .btm-right only.
Flush to the bottom right. Uses .btm-right only.
{this.setState.username}
Flush to the bottom right. Uses .btm-right only.
)
}
}
```
This is my parent class
```
import React from "react";
import {render} from "react-dom";
import {Default} from "./component/Default";
import {Chatting} from "./component/Chatting";
import {BrowserRouter as Router,Route,Link,Switch } from 'react-router-dom';
// import Background from '../images/person_img.png';
class App extends React.Component{
constructor(){
super();
}
render(){
return(
[*person*
dgfg](/chattting)
);
}
}
render(,document.getElementById('app'));
```
<issue_comment>username_1: `setState` is a function.
You should write:
```
this.setState({
username: event.target.value
});
```
Also, instead of
```
console.log(this.setState.username);
```
You should write
```
console.log(this.state.username);
```
And, again, instead of:
```
{this.setState.username}
```
You should write
```
{this.state.username}
```
Upvotes: 1 <issue_comment>username_2: In addition to the syntax corrections by @Rahamin, couple of pointers to your code -
1. Calling `setState` in the render function directly shouldn't be used, as it'll go into an infinite recursive function call stack. You'll probably be thrown an error of `Maximum update depth exceeded`.
2. Also, using `console.log`directly in the function that sets the state won't give you the desired output as they are queued and updated. It's best to include such `console.log` statements in the render itself.
3. Lastly, please post questions with good formatted code :)
Upvotes: 0 |
2018/03/19 | 152 | 656 | <issue_start>username_0: I want to migrate wordpress to new host and new domain.
Could you please let me know why I have this message?
"Apache is functioning normally"
<https://preloved-bazaar.stilgut.pl/>
How to fix it?<issue_comment>username_1: Because your are using a SSL Certificate and there are pages linked with http or you have not installed and configured your SSL certificate correctcly.
Upvotes: -1 <issue_comment>username_2: Install all in one migration plugin on your WordPress create a backup file of your WordPress and upload it on your domain WordPress plugin it would automatically migrate your file to the specified domain
Upvotes: 0 |
2018/03/19 | 657 | 2,038 | <issue_start>username_0: I would like to access a json child using Angular2, here is what I tried:
**my json :**
```
orderList=
{
"ref1": {
"Id": "57987"
"order": [
{
"amount": 4900,
"parent": "CIDPT8AO"
}
]
}
}
```
**in the view:**
```
| {{order[0]}} | // NOT OKAY
```
I would like to access "Id" and "parent", any idea?<issue_comment>username_1: First of all: you're missing a , after the "Id" line.
You're trying to access a JSON object like an array. Not sure if that works with Angular... If the error is not solved by adding the , I mentioned above, try declaring your orderList as an array.
If you're bound to this format you could do it like that:
```
orderListValues = Object.keys(orderList).map(function(_) { return j[_]; })
```
Then you should be able to access the values like that:
```
| {{order.Id}} |
```
Example:
```js
orderList = {
"ref1": {
"Id": "57987",
"order": [
{
"amount": 4900,
"parent": "CIDPT8AO"
}
]
}
};
orderListValues = Object.keys(orderList).map(function(_) { return orderList[_]; });
console.log(orderListValues);
```
Upvotes: 1 <issue_comment>username_2: Your orderList is an object, you need
```
| {{order}} |
```
Upvotes: 0 <issue_comment>username_3: **You can try this approach :**
**HTML**
```
| |
| --- |
| {{order.Id}} |
```
**Component**
```
var orderList=
{
"ref1": {
"Id": "57987",
"order": [
{
"amount": 4900,
"parent": "CIDPT8AO"
}
]
}
};
var obj = orderList[Object.keys(orderList)[0]];
```
Upvotes: 0 <issue_comment>username_4: NgForOf provides several exported values that can be aliased to local variables, for example:
**index: number** -> The index of the current item in the iterable.
**first: boolean** -> True when the item is the first item in the iterable.
```
| {{order.id}} |
{{order.parent}} |
```
<https://angular.io/api/common/NgForOf>
Upvotes: 0 |
2018/03/19 | 710 | 2,337 | <issue_start>username_0: ```
Async.each(asd, (items, callback) => {
req.models.aswdf.find({id: items.id}, function (err, result){
category.push(result[0].asd);
});
callback();
}, (err) => {
if (err)
next(err, null);
});
return done(null, {displayName: people[0].fullName(),id: people[0].id, email: people[0].email, role: category});
```
i am working with nodejs and i want to implement async for-each. I am passing asd as array of object and calling another method to get data from mysql but it is not working properly it enters the loop and get out of it and call done method.
I want to first execute the loop and the call the done method.<issue_comment>username_1: First of all: you're missing a , after the "Id" line.
You're trying to access a JSON object like an array. Not sure if that works with Angular... If the error is not solved by adding the , I mentioned above, try declaring your orderList as an array.
If you're bound to this format you could do it like that:
```
orderListValues = Object.keys(orderList).map(function(_) { return j[_]; })
```
Then you should be able to access the values like that:
```
| {{order.Id}} |
```
Example:
```js
orderList = {
"ref1": {
"Id": "57987",
"order": [
{
"amount": 4900,
"parent": "CIDPT8AO"
}
]
}
};
orderListValues = Object.keys(orderList).map(function(_) { return orderList[_]; });
console.log(orderListValues);
```
Upvotes: 1 <issue_comment>username_2: Your orderList is an object, you need
```
| {{order}} |
```
Upvotes: 0 <issue_comment>username_3: **You can try this approach :**
**HTML**
```
| |
| --- |
| {{order.Id}} |
```
**Component**
```
var orderList=
{
"ref1": {
"Id": "57987",
"order": [
{
"amount": 4900,
"parent": "CIDPT8AO"
}
]
}
};
var obj = orderList[Object.keys(orderList)[0]];
```
Upvotes: 0 <issue_comment>username_4: NgForOf provides several exported values that can be aliased to local variables, for example:
**index: number** -> The index of the current item in the iterable.
**first: boolean** -> True when the item is the first item in the iterable.
```
| {{order.id}} |
{{order.parent}} |
```
<https://angular.io/api/common/NgForOf>
Upvotes: 0 |
2018/03/19 | 1,814 | 6,678 | <issue_start>username_0: I've spent a long time trying to figure this out to no avail. I've read a lot about passing back HtmlResponse and using selenium middleware but have struggled to understand how to structure the code and implement into my solution.
Here is my spider code:
```
import scrapy
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
count = 0
class ContractSpider(scrapy.Spider):
name = "contracts"
def start_requests(self):
urls = [
'https://www.contractsfinder.service.gov.uk/Search/Results',
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def __init__(self):
self.driver = webdriver.Firefox()
self.driver.get("https://www.contractsfinder.service.gov.uk/Search/Results")
elem2 = self.driver.find_element_by_name("open")
elem2.click()
sleep(5)
elem = self.driver.find_element_by_name("awarded")
elem.click()
sleep(5)
elem3 = self.driver.find_element_by_id("awarded_date")
elem3.click()
sleep(5)
elem4 = self.driver.find_element_by_name("awarded_from")
elem4.send_keys("01/03/2018")
elem4.send_keys(Keys.RETURN)
sleep(5)
elem5 = self.driver.find_element_by_name("awarded_to")
elem5.send_keys("16/03/2018")
elem5.send_keys(Keys.RETURN)
sleep(5)
elem6 = self.driver.find_element_by_name("adv_search")
self.driver.execute_script("arguments[0].scrollIntoView(true);", elem6)
elem6.send_keys(Keys.RETURN)
def parse(self, response):
global count
count += 1
strcount = str(count)
page = self.driver.get(response.url)
filename = strcount+'quotes-%s.html' % page
with open(filename, 'wb') as f:
f.write(response.body)
self.log('Saved file %s' % filename)
for a in response.css('a.standard-paginate-next'):
yield response.follow(a, callback=self.parse)
```
The selenium part is working in that firefox is called, various java interactions are taking place and a final page of results is loaded.
The scrapy part of the code seems to be working (in that it finds the next button of the selenium loaded firefox webdriver and clicks through - I can see this by watching the webdriver firefox itself) - however, the actual scraping taking place (which is saving down HTML onto my c:\ drive) is scraping the URL '<https://www.contractsfinder.service.gov.uk/Search/Results>' separately and without the selenium induced java interactions from the firefox webdriver.
I think I understand some of the reasons as to why this isn't working as I want it to, for example in the start\_requests I'm referring to the original URL which means that the selenium loaded page is not used by the spider, but every time I've tried to create a response back from the webdriver by using a wide variety of different methods from reading stackoverflow, I get a variety of errors as my understanding isn't good enough - thought i'd post a version where the selenium & scrapy elements are doing something, but please can someone explain and show me the best approach to linking the 2 elements together ie, once selenium has finished - use the firefox webdriver loaded page and pass it to scrapy to do its stuff? Any feedback much appreciated.<issue_comment>username_1: As you said, scrapy opens your initial url, not the page modified by Selenium.
If you want to get page from Selenium, you should use driver.page\_source.encode('utf-8') (encoding is not compulsory). You can also use it with scrapy Selector:
```
response = Selector(text=driver.page_source.encode('utf-8'))
```
After it work with response as you used to.
**EDIT:**
I would try something like this (notice, I haven't tested the code):
```
import scrapy
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
count = 0
class ContractSpider(scrapy.Spider):
name = "contracts"
def start_requests(self):
urls = [
'https://www.contractsfinder.service.gov.uk/Search/Results',
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def __init__(self):
driver = webdriver.Firefox()
# An implicit wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any element
# (or elements) not immediately available.
driver.implicitly_wait(5)
@staticmethod
def get__response(url):
self.driver.get("url")
elem2 = self.driver.find_element_by_name("open")
elem2.click()
elem = self.driver.find_element_by_name("awarded")
elem.click()
elem3 = self.driver.find_element_by_id("awarded_date")
elem3.click()
elem4 = self.driver.find_element_by_name("awarded_from")
elem4.send_keys("01/03/2018")
elem4.send_keys(Keys.RETURN)
elem5 = self.driver.find_element_by_name("awarded_to")
elem5.send_keys("16/03/2018")
elem5.send_keys(Keys.RETURN)
elem6 = self.driver.find_element_by_name("adv_search")
self.driver.execute_script("arguments[0].scrollIntoView(true);", elem6)
elem6.send_keys(Keys.RETURN)
return self.driver.page_source.encode('utf-8')
def parse(self, response):
global count
count += 1
strcount = str(count)
# Here you got response from webdriver
# you can use selectors to extract data from it
selenium_response = Selector(text=self.get_selenium_response(response.url))
...
```
Upvotes: 2 <issue_comment>username_2: Combine the solution from [@Alex K](https://stackoverflow.com/users/5372300/alex-k) and others, here is my tested code:
```
import scrapy
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
...
def __init__(self, name=None, **kwargs):
super(MySpider, self).__init__(name, **kwargs)
self.driver = webdriver.Chrome()
@staticmethod
def get_selenium_response(driver, url):
driver.get(url)
# in case of explicit amount of time
# time.sleep(5)
# in case of wait until element been found
try:
def find(driver):
table_el = driver.find_element_by_xpath('//*[@id="table_el"]')
if table_el:
return table_el
else:
return False
element = WebDriverWait(driver, 5).until(find)
return driver.page_source.encode('utf-8')
except:
driver.quit()
def parse(self, response):
response = scrapy.Selector(
text=self.get_selenium_response(self.driver, response.url))
# ...parse response as normally
```
Upvotes: 1 |
2018/03/19 | 966 | 3,853 | <issue_start>username_0: I have the following code
```
public static void main(String[] args) {
new Thread() {
public void run() {
try {
employee1();
} catch (Exception e) {
Logger.LogServer(e);
}
finally {
Logger.LogServer("empployee1 records inserted");
}
}
}.start();
new Thread() {
public void run() {
try {
employee2();
} catch (Exception e) {
Logger.LogServer(e);
}
finally {
Logger.LogServer("employee2 records inserted");
}
}
}.start();
}
```
I want to wait for both the treads to finish execution and then exit the application with `System.exit(0);`. How can i achieve this?
Can someone please assist me.<issue_comment>username_1: You would need to use `join()` on both threads.
As per the [official documentation](https://docs.oracle.com/javase/tutorial/essential/concurrency/join.html):
>
> The **join** method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,
> `t.join()` causes the current thread to pause execution until t's thread terminates.
>
>
>
```
public static void main(String[] args) {
Thread t1 = new Thread() {
public void run() {
...
}
};
Thread t2 = new Thread() {
public void run() {
...
}
};
t1.start();
t2.start();
t1.join();
t2.join();
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
Thread t1 = ...
Thread t2 = ...
t1.join();
t2.join();
System.exit(0);
```
You need to catch InterruptedException or mark main as throwing it as well.
Upvotes: 1 <issue_comment>username_3: You can use [.join()](https://docs.oracle.com/javase/tutorial/essential/concurrency/join.html) that will block until the thread has finished executing.
```
Thread t = new Thread() {
public void run() {
try {
employee1();
} catch (Exception e) {
Logger.LogServer(e);
}
finally {
Logger.LogServer("empployee1 records inserted");
}
}
}.start();
Thread t2 = new Thread() {
public void run() {
try {
employee2();
} catch (Exception e) {
Logger.LogServer(e);
}
finally {
Logger.LogServer("employee2 records inserted");
}
}
}.start();
t.join();t2.join();
System.exit(0);
```
Upvotes: 0 <issue_comment>username_4: if you want to terminated the flow use `System.exit(0)`
or
You can simply keep references to all the threads somewhere (like a list) and then use the references later.
```
List appThreads = new ArrayList();
```
Every time you start a thread:
Thread thread = new Thread(new MyRunnable());
appThreads.add(thread);
Then when you want to signal termination (not via stop I hope :D) you have easy access to the threads you created.
You can alternatively use an ExecutorService and call shutdown when you no longer need it:
```
ExecutorService exec = Executors.newFixedThreadPool(10);
...
exec.submit(new MyRunnable());
...
exec.shutdown();
```
This is better because you shouldn't really create a new thread for each task you want to execute, unless it's long running I/O or something similar.
Upvotes: 0 <issue_comment>username_5: Note that you should not create Threads directly. Use an `ExecutorService` to start asynchronous tasks:
```
ExecutorService executor = Executors.newFixedThreadPoolExecutor(4);
executor.submit(() -> employee1());
executor.submit(() -> employee2());
executor.shutdown();
executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
// all tasks are finished now
```
Upvotes: 0 |
2018/03/19 | 1,128 | 4,712 | <issue_start>username_0: I am working on an angular 4 Application, writing Unit Cases, I am facing below Problem.
**component.ts**
```
ngOnInit() {
this.service.getData().subscribe(res => {
console.log(res);
this.data= JSON.parse(res._body);
this.addFormControls();
},
error => {
console.log(error);
});
}
```
**component.spec.ts**
```
describe('component', () => {
let userRolesService: LayoutService;
const modulesData = {
'moduleName':'Info'
}
class MockUserRolesService {
public getModulesData() {
return modulesData;
}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
providers:[ {provide: LayoutService, useClass: MockUserRolesService } ]
})
.compileComponents();
}));
beforeEach(() => {
userRolesService = TestBed.get(LayoutService);
});
afterEach(() => {
userRolesService = null;
component = null;
});
it('should fetch module data', () => {
userRolesService.getData().subscribe(
result => {
expect(result).toBeTruthy();
}
);
});
});
```
Updated the code for mock services file.Could you please help me some one to make it work. Used Mock service and test Bed Framework. Could you please some one help me..................................................................................................................................................................................................................................................................................................................................................<issue_comment>username_1: I don't know what you tried to mock, but that's not how you mock a service.
I will use the `useValue` instead of the `useClass`, but you can adapt it if you want.
Your test is testing a subscription to an observable, and you return ... Nothing.
```
class MockUserRolesService {
public getModulesData() {
return modulesData;
}
}
```
You're testing `getData` and I don't see it anywhere in your mock.
Here is how you mock your service.
```
const serviceMock = {
provide: LayoutService,
useValue: {
getData: Observable.of(/* any value you want */)
}
};
TestBed.configureTestingModule({
providers:[ {provide: LayoutService, useValue: serviceMock } ]
})
```
**EDIT** In unit testing, you test if your features (components, services) work as expected. let's take your `ngOnInit` function for instance :
```
this.service.getData().subscribe(res => {
console.log(res);
this.data= JSON.parse(res._body);
this.addFormControls();
}
```
Given how you wrote it, your tests should cover this cases :
* Does my component call `getData` on the service ?
* On success, does my component store the data returned by the service ?
* Does the console display the data ?
* Is the method `addFormControls` called ?
If you want to test that, you should create this mock :
```
useValue: {
getData: Observable.of({
'_body': 'my data'
})
}
```
Now, you must make your test.
Since you have an asynchronous call (with an Observable), then you should subscribe to the call, then call. Here is how it's done.
```
it('should call the getData function of the service and store the data', () => {
// Spy on your service to see if it has been called, and let him process
spyOn(component['service'], 'getData').and.callThrough();
// Array notation avoid scope issues (if your variable is protected or private)
component['service'].getData().subscribe(response => {
expect(component['service'].getData).toHaveBeenCalled();
// Since you store the data in the data variable, check if it's equal to your mock value
expect(component.data).toEqual('my data');
});
});
```
If you want to test all cases :
```
it('should call the getData function of the service and store the data', () => {
spyOn(component['service'], 'getData').and.callThrough();
spyOn(component, 'addFormControls');
spyOn(console, 'log');
component['service'].getData().subscribe(response => {
expect(component['service'].getData).toHaveBeenCalled();
expect(component.data).toEqual('my data');
expect(console.log).toHaveBeenCalledWith(response);
expect(component.addFormControls).toHaveBeenCalled();
});
});
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: I got a similar issue but inside a map
>
> undefined is not a constructor evaluating arr.uniorgs
>
>
>
so this:
```
this.arr.map(aux => aux.uniorgs)
```
i changed to:
```
this.arr.map(aux => aux['uniorgs'])
```
Upvotes: 0 |
2018/03/19 | 1,593 | 6,150 | <issue_start>username_0: I am learning react-router and I need help in the following problem:
I am iterating through an array of strings called nameArr. I would like to create a list of clickable links of the strings using react-router so that each link will navigate though a route defined in route.js.
The array nameArr is populated from the response created by a server.
The following code focuses on creating a list and applying it to the JSX.
```
var React = require('react');
var Router = require('react-router');
var createReactClass = require('create-react-class');
var Link = Router.Link;
var request = require('superagent'); //Superagent is an AJAX API used in Node.
var classComp = createReactClass({
request.post('/getdata')
.end(function (err, res) {
if (err || !res.ok) {
console.log('Oh no! err');
} else {
var response = JSON.parse(res.text);
var i;
var pathArr = [];
var nameArr = [];
for (i = 0; i < response.length; i++) {
pathArr[i] = response[i].videourl;
nameArr[i] = response[i].name;
}
var displayItem = "";
for (var m in nameArr) {
displayItem += "### " + nameArr[m].toString() + "
";
}
displayItem += "";
document.getElementById("vdlist").innerHTML = displayItem;
}
render: function () {
return (
{this.display()}
Videos
======
);
}
});
```
When I run the application, the List is generated but the links are not showing. That is no action happens when I click the links. Please suggest how I can approach this problem in a better way.
Thanks a lot!<issue_comment>username_1: A more idiomatic way of doing this:
```
render: function () {
return (
Videos
======
{nameArr.map(name => (
### {name.toString()}
))}
);
}
```
FYI you can't use JSX-only elements (like ) in `.innerHTML`.
EDIT[Explanation]:
React is built to make it easier to manage dynamic web pages, and essentially replaces the need to use things like `.innerHTML`. If you're using React and find yourself trying to use `.innerHTML` it is most likely you're going in the wrong direction.
Any capitalised element you can be sure is not an original HTML element but is instead a React component. If that's the case then the appropriate place to use it is within a JSX block (or possibly directly as a React component, if you prefer). So , and any other tag beginning with a capitable letter.
What I've done is added a block of JavaScript to your `.render` JSX that maps over the `nameArr` array and generates the code you were trying to generate from your `.display` method. As you can see, you can insert arbitrary JavaScript into JSX by putting it between `{}` braces.
EDIT[to answer updated question]:
Your `nameArr` variable is only available in the `.end()` function for the request you're making so of course you don't have access to it in the `render` function. React provides a feature exactly for this case! React state! You can read up more about [State and Lifecycle](https://reactjs.org/docs/state-and-lifecycle.html).
In this case all you need to do is initialise some state for your class and then update it when you receive new data. The way you initialise state using the pre-ES6 style you're using is by adding a `getInitialState` key to your `createReactClass` argument:
```
getInitialState: function() {
return { nameArr: [] };
},
```
In this case I've initialised `nameArr` to be an empty array. Then in your `render` function you can refer to `this.state.nameArr`:
```
render: function () {
return (
Videos
======
{this.state.nameArr.map(name => (
### {name.toString()}
))}
);
}
```
Once you do this if we don't update it anywhere, it will always be empty. To update it, we call `this.setState({ ... })`. This is how it would work with your request call:
```
request.post('/getdata')
.end(function (err, res) {
var response;
var i;
var nameArr = [];
if (err || !res.ok) {
console.log('Oh no! err');
// NOTE: You should probably set an error in state here:
// this.setState({ error: '...' });
} else {
var response = JSON.parse(res.text);
// NOTE: .map is an easier way to extract the name here
nameArr = response.map(function (p) { return p.name });
// This is where you update your React state.
this.setState({ nameArr: nameArr });
}
});
```
Once you've done this, your React class should update quickly and efficiently. This is the power of React and hopefully you can see that this is much easier than attempting to build HTML all over again. Instead you can just rely on one `render` method.
Upvotes: 1 <issue_comment>username_2: As already mentioned in the comment by username_1, you try to access a dom element in the render function. This is never a good idea and shouldn't ever be done.
It is also not the correct way in React to access the dom directly since you will loose some powerful tools of react, like the virtual dom.
A better way would be to use JSX. And by JSX, I mean real JSX. There is a difference between a string that "looks" like JSX and actual JSX. What you try to do is to create a string with JSX inside. Then you add this string into the dom - using the innerHTML property. However, your JSX won't really be handled as JSX. It will just handle it like HTML - and there is no element in HTML. That's why you can't see the items.
Instead do it like this:
```
import React, { Component } from 'react';
import { Link } from 'react-router-dom'; // You need to use react-router-dom here
class VideoList extends Component {
constructor(props) {
super(props);
this.nameArr = ['name1', 'name2'];
}
getVideos() {
// This creates a JSX element for every name in the list.
return this.nameArr.map(name => ### {name}
);
}
render() {
return (
Videos
======
{this.getVideos()}
);
}
}
```
Upvotes: 2 <issue_comment>username_3: You could try an Anchor and then Link component as:
```
{`${crew.name}`}
```
Upvotes: 0 |
2018/03/19 | 444 | 1,472 | <issue_start>username_0: So I performed a sentiment analysis using tidy principles. I would like to plot the results in a comparison cloud (positive VS negative sentiments).
This is my code:
```
library(reshape2)
library(tidytext)
dtm_tidy %>%
filter()
dtm_tidy %>%
inner_join(get_sentiments("bing"),by=c(term="word")) %>%
count(term, sentiment, sort=TRUE) %>%
acast(term ~ sentiment, value.var = "n", fill = 0) %>%
comparison.cloud(colors = c("darkred", "darkgreen"), max.words=300, scale = c(0.3, 0.3), random.order=FALSE, rot.per=0.25, title.size = 1)
```
However, something seems to go wrong, because the titles (positive & negative) are not shown or rendered. I already changed scales and title.size but nothing could solve this issue.
Anybody an idea?<issue_comment>username_1: I found the answer to my problem: if this issue occurs to you, use the `fixed.asp=TRUE`command. Something like this:
```
comparison.cloud(colors = c("darkred", "darkgreen"), max.words=300, scale = c(0.3, 0.3), random.order=FALSE, rot.per=0.25,fixed.asp=TRUE,title.size = 1)
```
This should do the trick! :)
Upvotes: 1 <issue_comment>username_2: I had a similar problem -- the titles were being cutoff on the top and the bottom of the rendered plot when I tried to save it as a pdf.
I was able to get the correct plot output by using "Portrait" orientation instead of "Landscape." I'm not sure why that fixed the issue but it did when saving it as a pdf or an image.
Upvotes: 2 |
2018/03/19 | 321 | 1,137 | <issue_start>username_0: I am using Angular 4 and I want to play video.My code is given below
```
```
When I am using this it's showing me an error
Error parsing header X-XSS-Protection: 1; mode=block; report=: insecure reporting URL for secure page at character position 22. The default protections will be applied.
NTEznm0vuzU:1 Error parsing header X-XSS-Protection: 1; mode=block; report=<https://www.google.com/appserve/security-bugs/log/youtube>: insecure reporting URL for secure page at character position 22. The default protections will be applied.
please anyone help me.<issue_comment>username_1: you can create like the following way.This will work
```
**\*\*title\*\***
```
Upvotes: 0 <issue_comment>username_2: What you need is a domSanitizer of angular.
In your HTML,
```
```
and in your component's .ts file:
```
//import the needed class.
import { DomSanitizer } from '@angular/platform-browser';
// Add the dependency.
constructor(private _domSanitizer: DomSanitizer){
}
getSafeURL(){
return _domService.bypassSecurityTrustResourceUrl(' Your youtube url');
}
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 518 | 1,836 | <issue_start>username_0: ```
line = "Hello, world"
sc.parallelize(list(line)).collect()
```
I obtain the following error
`TypeError: parallelize() missing 1 required positional argument: 'c'`
I also have an other issue when creating a dataframe from a list of strings with only one column:
```
from pyspark.sql.types import *
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
schema = StructType([StructField("name", StringType(), True)])
df3 = sqlContext.createDataFrame(fuzzymatchIntro, schema)
df3.printSchema()
```
I obtain the following error:
```
----> 3 sqlContext = SQLContext(sc)
AttributeError: type object 'SparkContext' has no attribute '_jsc'
```
Thank you in advance<issue_comment>username_1: Looking at your comment above, **you seem to have initialized `sparkContext` in a wrong way** as you have done
>
> `from pyspark.context import SparkContext
> from pyspark.sql.session import SparkSession
> sc = SparkContext
> spark = SparkSession.builder.appName("DFTest").getOrCreate()`
>
>
>
The correct way would be
```
from pyspark.sql.session import SparkSession
spark = SparkSession.builder.appName("DFTest").getOrCreate()
sc = spark.sparkContext
```
**And `spark` object can do the work of `sqlContext`**
Upvotes: 1 <issue_comment>username_2: I tried above suggestion in my pyspark in windows using the Jupyter terminal and it has worked. Please find my sample code below which worked for me
```
import findspark
findspark.init()
import pyspark
from pyspark.sql.session import SparkSession
spark = SparkSession.builder.appName("DFTest").getOrCreate()
sc = spark.sparkContext
words = sc.parallelize(["scala","java","hadoop","spark","akka","spark vs
hadoop","pyspark","pyspark and spark"])
counts = words.count()
print("Number of elements in RDD -> %i" % (counts))
```
Upvotes: 0 |
2018/03/19 | 755 | 3,087 | <issue_start>username_0: I'm defining the Swagger specification of a REST service to be implemented. Since the response document represents a tree-like structure where several nodes repeat multiple times, I'd like to define them in the beginning of a document and then reference them by means of JSON Pointer notation.
So the response document should look like this:
```
{
"definitions": {
"organizations": [
{ "id": 101, "name": "Org 1" },
...
],
"clusters": [
{ "id": 201, "name": "Cluster 1" },
...
],
"plants": [
{ "id": 301 }
]
},
"plants_hierarchy": {
"relations": [
{
"cluster": { "$ref", "#/definitions/clusters/1" },
"organization": { "$ref", "#/definitions/organizations/123" },
"plants": [
{ "$ref": "#/definitions/plants/234" },
...
]
},
...
]
}
}
```
The plant objects inside #/plants\_hierarchy/relations/plants should be represented as JSON Pointer and not as the original objects in order to keep the size of the document small.
My question is how should I express the JSON Pointer in the Swagger YAML document?<issue_comment>username_1: YAML provides [anchors and aliases](http://www.yaml.org/spec/1.2/spec.html#id2765878), which cover your use-case exactly:
```
definitions:
organizations:
- &my_organization
id: 101
name: Org 1
clusters:
- &my_cluster
id: 201
name: Cluster 1
plants:
- &my_plant
id: 301
plants_hierarchy:
relations:
- cluster: *my_cluster
organization: *my_organization
plants:
- *my_plant
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: First of all, why don't you just include the data inline? Using JSON References/JSON Pointers in actual API responses is a rather unusal scenario, and it would require your API clients to use a JSON Reference resolution library to calculate those references. Most languages/frameworks have JSON libraries, but JSON Reference resolution libraries are rare. If all data is inline, then it's trivial to access it - e.g. simply use `response.plants_hierarchy.relations[0].cluster.name`. But hiding data behind JSON References makes things a lot more complicated for the clients.
Anyway, if you are sure this is what you want to do, then the `$ref` property can be defined a simple `string` property, possibly with a `pattern`.
```yaml
swagger: '2.0'
...
definitions:
JsonReference:
type: object
properties:
'$ref':
type: string
pattern: '^#'
example: '#/definitions/something/1'
Relation:
type: object
properties:
cluster:
$ref: '#/definitions/JsonReference'
organization:
$ref: '#/definitions/JsonReference'
plants:
type: array
items:
$ref: '#/definitions/JsonReference'
```
Upvotes: 2 |
2018/03/19 | 1,747 | 6,229 | <issue_start>username_0: I have a multidimensional array in the following format :
```
array (
0 =>
array (
'manual' => 1,
'cancelled' => 1,
'expired' => 1,
'earned' => 1,
'user' =>
array (
'user1' => 1,
'user2' => 1,
'user3' => 1,
'user4' => 1,
),
'transfer' =>
array (
'transfer1' =>
array (
'key1' => 1,
'key2' => 1,
'key3' => 1,
),
'transfer2' =>
array (
'key5' => 1,
'key6' => 1,
'key7' => 1,
),
),
'date' => '2018-03-07',
),
1 =>
array (
'manual' => 1,
'cancelled' => 1,
'expired' => 1,
'earned' => 1,
'user' =>
array (
'user1' => 1,
'user2' => 1,
'user3' => 1,
'user4' => 1,
),
'transfer' =>
array (
'transfer1' =>
array (
'key1' => 1,
'key2' => 1,
'key3' => 1,
),
'transfer2' =>
array (
'key5' => 1,
'key6' => 1,
'key7' => 1,
),
),
'date' => '2018-03-08',
),
```
)I need to calculate the sum of the array values with same index. So the total array should be as the following
```
Array
(
[total] => Array
(
[manual] => 2
[cancelled] => 2
[expired] => 2
[earned] => 2
[user] => Array
(
[user1] => 2
[user2] => 2
[user3] => 2
[user4] => 2
)
[transfer] => Array
(
[transfer1] => Array
(
[key1] => 2
[key2] => 2
[key3] => 2
)
[transfer2] => Array
(
[key5] => 2
[key6] => 2
[key7] => 2
)
)
```
That is the total should have the same format except date, but it needs to show the total sum of the value. How can this be done in PHP ? I have used the following code
```
$final = array_shift($input);
foreach ($final as $key => &$value){
$value += array_sum(array_column($input, $key));
}
unset($value);
var_dump($final);
```
where `$input` is considered as the first array and `$final` is total. I think this only work with single indexes.<issue_comment>username_1: You can use recursive function which walk through all you "tree".
There
If element is array create same in result array and run function for each key.
If it has a number, just add value to result.
Here is a SAMPLE
```
php
// Array with data
$arr=array(array('manual'=1,'cancelled'=>1,'expired'=>1,'earned'=>1,'user'=>array('user1'=>1,'user2'=>1,'user3'=>1,'user4'=>1,),'transfer'=>array('transfer1'=>array('key1'=>1,'key2'=>1,'key3'=>1,),'transfer2'=>array('key5'=>1,'key6'=>1,'key7'=>1,)),'date'=>'2018-03-07',),array('manual'=>1,'cancelled'=>1,'expired'=>1,'earned'=>1,'user'=>array('user1'=>1,'user2'=>1,'user3'=>1,'user4'=>1,),'transfer'=>array('transfer1'=>array('key1'=>2,'key2'=>2,'key3'=>2,),'transfer2'=>array('key5'=>2,'key6'=>2,'key7'=>2,)),'date'=>'2018-03-08',));
//Init result array
$res=array('total'=>array());
foreach ($arr as $key=>$val) {
//Run it for each element and store result to $res['total']
countTotal($res['total'],$val);
}
//Show result
print_r($res);
/*
* Count totals for branch of array
* @param $res - reference to branch of result array
* @param $arr - branch of data array
*/
function countTotal(&$res,$arr) {
foreach ($arr as $key=>$val) {
if (is_array($val)) {
//it's array. Create "branch" in $res and run countTotal() to calc total for it
if (!isset($res[$key])) $res[$key]=array();
countTotal($res[$key],$val);
} else if (is_numeric($val)) {
// it's number. Create "leaf" if need and add value.
if (!isset($res[$key])) $res[$key]=0;
$res[$key]+=$val;
}
}
}
```
As you see it use reference to branch of result array for accumulating totals
Results
```
Array
(
[total] => Array
(
[manual] => 2
[cancelled] => 2
[expired] => 2
[earned] => 2
[user] => Array
(
[user1] => 2
[user2] => 2
[user3] => 2
[user4] => 2
)
[transfer] => Array
(
[transfer1] => Array
(
[key1] => 3
[key2] => 3
[key3] => 3
)
[transfer2] => Array
(
[key5] => 3
[key6] => 3
[key7] => 3
)
)
)
)
```
*In second "transfer" I have used "2" so it's "3" in sum*
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can write the recursive function like the following:
```
function array_sum_recursive_assoc($array, &$result = [])
{
$keys = array_keys($array[0] ?? []);
foreach ($keys as $key) {
foreach (($column = array_column($array, $key)) as $value) {
if (is_array($value)) {
$result[$key] = [];
array_sum_recursive_assoc($column, $result[$key]);
continue 2;
}
// In this case date safe guard.
if (!is_numeric($value)) {
continue;
}
$result[$key] = ($result[$key] ?? 0) + $value;
}
}
return $result;
}
var_dump(array_sum_recursive_assoc($array));
```
Here is [the demo](http://sandbox.onlinephpfunctions.com/code/8b6ba7cc173e3197966ae3cd93ce402dc78a7063).
Upvotes: 1 |
2018/03/19 | 425 | 1,321 | <issue_start>username_0: Using this code inside my `validation.php`, I was able to translate the translate the values of the `edit_type`-field:
```
'values' => [
'edit_type' => [
'1' => 'Intern',
'2' => 'Kunde'
],
'every_day' => [
'true' => 'ausgewΓ€hlt',
'false' => 'nicht ausgewΓ€hlt'
]
],
```
But for some reason, the same logic does not work for the `every_day` field. I assume it has something to do with the values being booleans.
This is usually used with `required_if` inside the validation, in the case of `every_day` I use `required_unless` which should not make a difference.
Any idea how I can accomplish this?<issue_comment>username_1: Try this. I think this will help
```
'values' => [
'edit_type' => [
'1' => 'Intern',
'2' => 'Kunde'
],
'every_day' => [
true => 'ausgewΓ€hlt',
false => 'nicht ausgewΓ€hlt'
]
],
```
Upvotes: 0 <issue_comment>username_2: As explained [here](https://stackoverflow.com/a/37179857)
>
> ... in PHP, the boolean value true is displayed as 1 and the boolean value false is displayed as the empty string (i.e. nothing is displayed)
>
>
>
So, you can map boolean values like this
```
'values' => [
'every_day' => [
'1' => 'ausgewΓ€hlt',
'' => 'nicht ausgewΓ€hlt',
],
],
```
Upvotes: 1 |
2018/03/19 | 997 | 3,406 | <issue_start>username_0: I am trying to update single object inside an array that exist inside another array (nested array) but what happen that all records are removed and the new records are inserted instead
this is the structure I am using:
```
"summary_mark" : [
{
"target_id" : "5aa27e77967c552b10ea725b",
"primitives" : [
{
"primitive" : "B",
"test_count" : NumberInt(3),
"right_test_count" : NumberInt(3),
"mark" : NumberInt(66)
},
{
"primitive" : "T",
"test_count" : NumberInt(3),
"right_test_count" : NumberInt(3),
"mark" : NumberInt(66)
},
{
"primitive" : "H",
"test_count" : NumberInt(3),
"right_test_count" : NumberInt(3),
"mark" : NumberInt(66)
}
]
}
],
```
what i am trying to do is changing one of the records inside the primitives array.
actually i am trying to update the record using this function:
```
$testCount = ++$primitiveSummaryMark['test_count'];
$update['summary_mark.$.primitives'][$primKey]['primitive'] = $answer->primitive_value;
$update['summary_mark.$.primitives'][$primKey]['test_count'] = $testCount;
if ($answer->result != 0) {
$rightAnswersCount = ++$primitiveSummaryMark['right_test_count'];
$update['summary_mark.$.primitives'][$primKey]['right_test_count'] = $rightAnswersCount;
} else {
$rightAnswersCount = $primitiveSummaryMark['right_test_count'];
}
if ($testCount < $level_tests_amount->tests_count[$target_level]) {
$totalTestCount = $level_tests_amount->tests_count[$target_level];
} else {
$totalTestCount = $testCount;
}
$primitiveTargetMark = ($rightAnswersCount * 100) / $totalTestCount;
$update['summary_mark.$.primitives'][$primKey]['mark'] = $primitiveTargetMark;
```
where I am performing some logic then run this query:
```
MyClass::raw()
->findOneAndUpdate([
'course' => $this->first()->course,
'summary_mark.target_id' => $data->target_id,
],
['$set' => $update]);
```
the input is something like this:
```
{"data":{ "target_id":"5aa27e77967c552b10ea725b","question":"5aa141b6c8af28381079e9c7", "answers":[{"primitive_value":"B","result":1,"elpassed_time":20,"distructor":""},{"primitive_value":"T","result":1,"elpassed_time":3,"distructor":""}]}}
```
what I expect to see is the records with primitives (B,T,H) but i get (B,T) cause those which they are updated i cause of the input<issue_comment>username_1: Try this. I think this will help
```
'values' => [
'edit_type' => [
'1' => 'Intern',
'2' => 'Kunde'
],
'every_day' => [
true => 'ausgewΓ€hlt',
false => 'nicht ausgewΓ€hlt'
]
],
```
Upvotes: 0 <issue_comment>username_2: As explained [here](https://stackoverflow.com/a/37179857)
>
> ... in PHP, the boolean value true is displayed as 1 and the boolean value false is displayed as the empty string (i.e. nothing is displayed)
>
>
>
So, you can map boolean values like this
```
'values' => [
'every_day' => [
'1' => 'ausgewΓ€hlt',
'' => 'nicht ausgewΓ€hlt',
],
],
```
Upvotes: 1 |
2018/03/19 | 544 | 1,826 | <issue_start>username_0: Very new to HTML and JS combined with Bootstrap.
I use the Cyborg-theme and I use the Nav tabs in my HTML-file.
The problem that I'm getting is that whenever I click on a tab, I want that tab to become the "active" tab. But that doesn't work, instead the only tab that I set to active in the HMTL is the one tab that stays active.
The tabs changes so I get the right information displayed. It's just this little detail that has me very frustrated. Any ideas?
My HTML:
```js
$(".nav li").on("click", function() {
$("nav li").removeClass("active");
$(this).addClass("active");
});
```
```html
* [About](#about)
* [Top tracks](#toptracks)
* [Something](#something)
${artist.bio.content}
${this.tracks.map(track => `* ${track['name']}
`).join('')}
Something in here ...
```<issue_comment>username_1: Just replace your code inside click event:
```
$("nav li").removeClass("active");
```
to:
```
$(".nav li").removeClass("active");
___^__
```
as in your HTML code, you have a `.nav` class and not the `nav` element and hence the active class is never removed from the initial tab.
Also, add the `active` class to first `li`, not to the link inside it in your HTML
Code:
```js
$(".nav li").on("click", function() {
$(".nav li").removeClass("active");
$(this).addClass("active");
});
```
```html
* [About](#about)
* [Top tracks](#toptracks)
* [Something](#something)
${artist.bio.content}
${this.tracks.map(track => `
* ${track['name']}
`).join('')}
Something in here ...
```
Upvotes: 0 <issue_comment>username_2: If you are using `bootstrap` no need for custom `js` , it automatically add active to the `li`s
```html
* [About](#about)
* [Top tracks](#toptracks)
* [Something](#something)
ghgfhfg
5555
Something in here ...
```
Upvotes: 2 |
2018/03/19 | 1,701 | 4,804 | <issue_start>username_0: I am trying to make a menu from the left with slideout animation. But it does not load the animation, it is not closing or opening, it is staying as normal menu.
This is my code, as follows
* javascript
* -css
* -html :
```js
$(document).ready(function(){
$(".fa-times").click(function(){
$(".sidebar-menu").addClass("hide-menu");
$(".toggle-menu").addClass("opacity-one");
});
$(".fa-times").click(function(){
$(".sidebar-menu").removeClass("hide-menu");
$(".toggle-menu").removeClass("opacity-one");
});
})
```
```css
*{
margin: 0;
padding: 0;
list-style: none;
text-decoration: none;
}
.fa-times{
right: 10px;
top: 10px;
opacity: 0.7;
cursor: pointer;
position: absolute;
color: white;
transition: all 0.2s ease-in-out;
}
.fa-times:hover{
opacity: 1;
}
.sidebar-menu{
position: fixed;
width: 250px;
margin-left: 0px;
overflow: hidden;
height: 100vh;
max-height: 100vh;
background-color: rgba(17,17,17,0.9);
opacity: 0.9;
transition: all 0.3s ease-in-out;
}
.hide-menu{
margin-left: -250px;
transition: all 0.3s ease-in-out;
}
.toggle-menu{
position: fixed;
padding: 15px 20px 15px 15px;
margin-top: 70px;
color: white;
cursor: pointer;
background-color: #648B79;
opacity: 0;
z-index: 10000;
font-size: 2em;
transition: all 0.2s ease-in-out;
}
.opacity-one{
opacity: 1;
transition: all 0.2s ease-in-out;
}
.toggle-menu:hover{
background-color: #FE4365;
transition: all 0.2s ease-in-out;
}
.boxed-item{
font-family: 'Open Sans';
font-weight: 200;
padding: 10px 20px;
display: inline-block;
border: solid 2px white;
box-sizing: border-box;
font-size: 29px;
color: white;
text-align: center;
margin-top: 70px;
}
.logo-bold{
font-weight: 800;
}
.logo-title{
color: white;
font-family: 'Open Sans';
font-weight: 200;
font-size: 20px;
text-align: center;
padding: 5px 0;
}
.menu-close{
color: #D8D8D8;
position: absolute;
right: 8px;
opacity: 0.7;
top: 6px;
font-size: 1.1em;
transition: all 0.3s ease-in-out;
cursor: pointer;
}
.menu-close:hover{
color: #FE4365;
opacity: 1;
transition: all 0.2s ease-in-out;
}
.navigation-section{
margin: 20px 0;
display: block;
width: 200px;
margin-left: 25px;
}
.navigation-item{
font-weight: 200;
font-family: 'Open Sans';
color: white;
padding: 12px 0px;
box-sizing: border-box;
font-size: 14px;
color: #D8D8D8;
border-bottom: solid 1px #D8D8D8;
transition: all 0.3s ease-in-out;
cursor: pointer;
}
.navigation-item:hover{
color: white;
transition: all 0.3s ease-in-out;
}
.boxed-item-smaller{
font-size: 12px;
color: #D8D8D8;
width: 200px;
transition: all 0.3s ease-in-out;
cursor: pointer;
border-width: 1px;
margin: 0 0 20px 0;
}
.boxed-item-smaller:hover{
background-color: white;
color: #111;
transition: all 0.3s ease-in-out;
}
.hide-menu{
margin-left: -250px;
}
.opacity-one{
opacity: 1;
transform: all 0.3s ease-in-out;
}
```
```html
Coffee note
Coffe . note
============
Manage Your Time
----------------
* HOME
* DASHBOARD
* WEEKLY TO-DO
* SKILLS
* INTERESTS
* PORTFOLIO
* CONTACT
[SIGN UP
=============](#)
```
I cannot undestand where exactly is the problem and why. In the code there might be some confusing things because I tried many "solutions"and things to fix it but without any result. I will be glad if there is somebody to tell me where is my mistake and how I can fix it..Thank you for your time!<issue_comment>username_1: You added two click-events, one adding a class and the other removing it again. So clicking wont change anything. Here is how you should do it:
```
var hide = false;
$(document).ready(function(){
$(".fa-times").click(function(){
if (!hide) {
hide = true;
$(".sidebar-menu").addClass("hide-menu");
$(".toggle-menu").addClass("opacity-one");
} else {
hide = false;
$(".sidebar-menu").removeClass("hide-menu");
$(".toggle-menu").removeClass("opacity-one");
}
});
})
```
Upvotes: 1 <issue_comment>username_2: I fixed the code for you
also you can use `toggleClass` since your already working with `jquery` instead of `addClass` and `removeClass`
```
$(".fa-bars").on("click",function(){
$(".sidebar-menu").toggleClass("hide-menu");
$(".toggle-menu").toggleClass("opacity-one");
});
$(".fa-times").on("click",function(){
$(".sidebar-menu").toggleClass("hide-menu");
$(".toggle-menu").toggleClass("opacity-one");
});
```
here is the code pen link <https://codepen.io/anon/pen/jzVeXP>
Upvotes: 1 [selected_answer] |
2018/03/19 | 2,064 | 5,756 | <issue_start>username_0: I can't find anything in the documentation.
If I do a git pull, am I guaranteed that the underlying file, resulting of the merge, is atomically written?
Some more context about what I am trying to achieve:
I have some scripts that periodically do a git pull and I need to know if I can rely on the state of the files being valid during a pull.
We are basically using git as a deployment tool. We never have merge conflicts by design. On the remote end, a job constantly pulls every x seconds, and other jobs read the files. What could happen is that we open a file while it's being pulled by git, and the contents of the file are not what we are expecting.
This is unless git is smart enough to use some atomic swap on the underlying OS (RedHat in this case)<issue_comment>username_1: The short answer is *no*.
It's worth considering that `git pull` isn't about files at all, it's about *commits*. Files are just a side effect. :-) The pull operation is just `git fetch` (obtain commits) followed by a second Git command, usually `git merge`. The merge step merges *commits*. This has a side effect of merging files as well, if the operation is not a fast-forward instead of a merge; and then when the merge or fast-forward is complete, Git does a `git checkout` of the resulting commit.
So this really boils down to: *Is `git checkout` atomic at the OS level?* The answer is a very loud *no:* it's not atomic in any way. Individual files written in the work-tree are written one at a time, using OS-level `write` calls, which are not atomic. Files that need to be created or deleted are done one at a time. Git *does* use the index, which indexes (i.e., keeps tabs on) the work-tree, to minimize the number of files removed, created, or rewritten-in-place. Git also locks against other *Git* operations, and makes the Git-level transaction appear atomicβbut anything working outside Git, that does not cooperate with Git's locking system, will be able to see the changes as they occur.
Upvotes: 4 [selected_answer]<issue_comment>username_2: On the `git checkout` part of `git pull`, see [username_1](https://stackoverflow.com/users/1256452/username_1)'s [answer](https://stackoverflow.com/a/49366413/6309).
On the `git fetch` part of `git pull`, there is an [--`atomic` flag](https://git-scm.com/docs/git-fetch#Documentation/git-fetch.txt---atomic), Git 2.36 (Q2 2022) clarifies it.
"[`git fetch`](https://github.com/git/git/blob/851d2f0ab123c8fa33bbdc8e5a325e0c8b2c5d9c/Documentation/git-fetch.txt)"([man](https://git-scm.com/docs/git-fetch)) can make two separate fetches, but ref updates coming from them were in two separate ref transactions under "`--atomic`", which has been corrected with Git 2.36 (Q2 2022).
See [commit 583bc41](https://github.com/git/git/commit/583bc419235cedc6a2ba12593f058a9f812b9594), [commit b3a8046](https://github.com/git/git/commit/b3a804663c4682f6df55dd6703f8f8af9a7c6ab5), [commit 4f2ba2d](https://github.com/git/git/commit/4f2ba2d06a7dd7e84e105a2779a7f07549d04231), [commit 62091b4](https://github.com/git/git/commit/62091b4c87a199c172556f15c5662c6c3679e9cd), [commit 2983cec](https://github.com/git/git/commit/2983cec0f26b7409ccc2dd5710b40ff4809cd4b1), [commit efbade0](https://github.com/git/git/commit/efbade066083eb0a8ccee5a8290cd3fc834705f3), [commit 2a0cafd](https://github.com/git/git/commit/2a0cafd464709cfa22fe7249290c644a2a26c520) (17 Feb 2022) by [<NAME> (`pks-t`)](https://github.com/pks-t).
(Merged by [<NAME> -- `gitster` --](https://github.com/gitster) in [commit 851d2f0](https://github.com/git/git/commit/851d2f0ab123c8fa33bbdc8e5a325e0c8b2c5d9c), 13 Mar 2022)
>
> [`fetch`](https://github.com/git/git/commit/2a0cafd464709cfa22fe7249290c644a2a26c520): increase test coverage of fetches
> ------------------------------------------------------------------------------------------------------------------------
>
>
> Signed-off-by: <NAME>
>
>
>
>
> When using `git fetch` with the `--atomic` flag, the expectation is that either all of the references are updated, or alternatively none are in case the fetch fails.
>
>
> While we already have tests for this, we do not have any tests which exercise atomicity either when pruning deleted refs or when backfilling tags.
>
> This gap in test coverage hides that we indeed don't handle atomicity correctly for both of these cases.
>
>
> Add test cases which cover these testing gaps to demonstrate the broken behaviour.
>
>
>
---
Warning:
With Git 2.36 (Q2 2022), revert the "deletion of a ref should not trigger transaction events for loose and packed ref backends separately" that regresses the behaviour when a ref is not modified since it was packed.
See [commit 4315986](https://github.com/git/git/commit/43159864b62202b7a887b65e562fba9f45f5cd2e), [commit 347cc1b](https://github.com/git/git/commit/347cc1b11dc1082d217a5221fd074e8fb984cdc3), [commit c6da34a](https://github.com/git/git/commit/c6da34a610e58f7e58042b5ed24a19bd2c18e928) (13 Apr 2022) by [<NAME> (`gitster`)](https://github.com/gitster).
(Merged by [<NAME> -- `gitster` --](https://github.com/gitster) in [commit 4027e30](https://github.com/git/git/commit/4027e30c5395c9c1aeea85e99f51ac62f5148145), 14 Apr 2022)
>
> [`4027e30c53`](https://github.com/git/git/commit/4027e30c5395c9c1aeea85e99f51ac62f5148145):Merge branch 'jc/revert-ref-transaction-hook-changes'
> ------------------------------------------------------------------------------------------------------------------------------------------------
>
>
>
>
> Revert "fetch: increase test coverage of fetches"
>
> Revert "Merge branch 'ps/avoid-unnecessary-hook-invocation-with-packed-refs'"
>
>
>
Upvotes: 1 |
2018/03/19 | 674 | 2,679 | <issue_start>username_0: I'm working on a Unity game that's to be exported as an iOS project and built with Xcode. We've got an existing Jenkins setup that does the job for me at a click of a button, but recently I've been asked to add WebTrends to my project.
The manual process for that is as follows:
* Copy over a podfile, a pre-made webtrends.plist file, and the pods folder (so I don't have to download that over again).
* Do a `pod install` on the project directory.
* Open xcworkspace file and build as normal.
So I went to Jenkins Plugin Manager, and installed (without restarting) CocoaPods Jenkins Integration. This, however, unhelpfully added a Build Step called Update CocoaPods. Upon adding that to my Build Steps and running it, it resulted in the following:
```
[workspace] $ pod repo update
Build step 'Update CocoaPods' marked build as failure
Archiving artifacts
Finished: FAILURE
```
The documentation wasn't very helpful either, only saying that, currently, this has no advantage over running an execute shell script. So I did just that, and added a `pod install` to the Build Step, which resulted in the following:
```
/Users/Shared/Jenkins/tmp/afesefgwedc.sh: line 26: pod: command not found
Build step 'Execute shell' marked build as failure
Archiving artifacts
Finished: FAILURE
```
So clearly pod was not installed. I don't have the credentials or the rights to install it myself, I would have thought installing CocoaPods via Jenkins would have done it. And even if I did, there's that previous error to contend with. I could try to reboot the server, but that's a last resort.
Has anyone successfully integrated pods with Jenkins? What else could I try, or what else did I miss?
I'm quite new at Jenkins, so I apologize in advance if this seems lacking. I would be happy to provide other information if requested.<issue_comment>username_1: If you want to install pod , you need to write following command in **Execute shell** of **Build** phase.
```
/usr/local/bin/pod install
```
Because for installing pod, you need to give path for executable pod file. And with above command in execute shell helping you for install the pod.
*Note - Jenkins looked in a workspace whether pod is installed or not. If there is already installed pod on your workspace, jenkins not installed it again. And if not then it installing pod.*
[](https://i.stack.imgur.com/cPYzD.png)
Upvotes: 2 <issue_comment>username_2: It depends where you have cocoapods installed, try this:
`which pod`
Which will display where's the pod command located:
`/Users/HomeDir/.rbenv/shims/pod`
Upvotes: 0 |
2018/03/19 | 479 | 1,736 | <issue_start>username_0: Generally I want to write `.js` files with typescript instead of Flow. I configured the webpack to use `ts-loader` on js extension, and that works just fine. I use `checkJs` on tsconfig file and it check the js file fine.
However, VS Code shows an error the error on js files:
>
> Type annotations can only be used in TypeScript files.
>
>
>
[](https://i.stack.imgur.com/rG9Y2.png)
How can I make that error go away in VS Code?<issue_comment>username_1: You should use .ts, not .js files for TypeScript code in order to get full IDE and other tooling support. The compiler will transform your .ts files into .js.
Upvotes: 2 <issue_comment>username_2: You cannot use typescript type declarations in js files. (Even with checkJS enabled)
On JS files you have to use JSDoc annotations.
```
/** @type {number} */
var x;
```
Typescript would check these for you.
But I guess what you're looking for is a .ts file
Upvotes: 3 <issue_comment>username_3: Yes you generally should use the correct file extension but you can force VS Code to treat JS files as TypeScript by [setting](https://code.visualstudio.com/docs/getstarted/settings):
```
"files.associations": {
"*.js": "typescript"
}
```
Upvotes: 2 <issue_comment>username_4: Since Typescript 3 is out, and the work they have done allowing it to be combined with babel 7, it makes sense now for many programmers to have typescript in `.js` files.
Currently I have added the following vscode settings :
```
"files.associations": {
"*.js": "typescript"
},
```
And restarted VSCode, and it works for me.
Hopefully vscode will provide a cleaner solution in the future.
Upvotes: 2 |
2018/03/19 | 461 | 1,620 | <issue_start>username_0: i can't display the image in my website, which is fetched from the API.
this is my image fetching/showing code.
```
this.state.filteredData.map((data,i) =>
{data.details.name}
![]()
const aStyle={
width:300,
height:360
};
```
[](https://i.stack.imgur.com/cKt9i.png)
only image box is showing.<issue_comment>username_1: You should use .ts, not .js files for TypeScript code in order to get full IDE and other tooling support. The compiler will transform your .ts files into .js.
Upvotes: 2 <issue_comment>username_2: You cannot use typescript type declarations in js files. (Even with checkJS enabled)
On JS files you have to use JSDoc annotations.
```
/** @type {number} */
var x;
```
Typescript would check these for you.
But I guess what you're looking for is a .ts file
Upvotes: 3 <issue_comment>username_3: Yes you generally should use the correct file extension but you can force VS Code to treat JS files as TypeScript by [setting](https://code.visualstudio.com/docs/getstarted/settings):
```
"files.associations": {
"*.js": "typescript"
}
```
Upvotes: 2 <issue_comment>username_4: Since Typescript 3 is out, and the work they have done allowing it to be combined with babel 7, it makes sense now for many programmers to have typescript in `.js` files.
Currently I have added the following vscode settings :
```
"files.associations": {
"*.js": "typescript"
},
```
And restarted VSCode, and it works for me.
Hopefully vscode will provide a cleaner solution in the future.
Upvotes: 2 |
2018/03/19 | 943 | 3,493 | <issue_start>username_0: I have imported class from an external module explicitly. I can create objects of this type, but when used as a parameter i.e. Passing class type to method, the method evaluates the class as 'type'.
Using the namespace prefix is non-resolvable too. The method evaluates python base types fine i.e. passing int is evaluated as int...
test.py
```
import os
import sys
import math
import time
import traceback
import datetime
import argparse
from i_factory_type import IFactoryType
from example_factory_type import ExampleFactoryType
from factory import Factory
if __name__ == "__main__":
obj = ExampleFactoryType()
print(type(obj))
print(isinstance(obj, IFactoryType))
obj.make()
factory = Factory()
factory.register('123', ExampleFactoryType)
```
factory.py
```
'''
Polymorphic factory that creates IFactoryTypes with dispatching
'''
from i_factory_type import IFactoryType
'''
Implementation of factory
'''
class Factory:
def Factory(self):
self.registry = dict()
def register(self, i_id, i_type):
print(isinstance(i_type, IFactoryType))
print(i_type.__class__)
assert( isinstance(i_type, IFactoryType) )
self.unregister_type(i_id)
self.registry[i_id] = staticmethod(i_type)
def unregister(self, i_id):
if i_is in self.registry:
del self.registry[i_id]
def clear(self):
self.registery.clear()
def make_object(self, i_id, *i_args):
ret = None
if i_id in self.registry:
ret = self.registry[i_id](i_args)
return ret
```
example\_factory\_type.py
```
'''
Base type for factory create method
'''
from i_factory_type import IFactoryType
'''
Interface for factory creation
'''
class ExampleFactoryType(IFactoryType):
@staticmethod
def make(*i_args):
print('factory make override')
```
i\_factory\_type.py
```
'''
Base type for factory create method
'''
'''
Interface for factory creation
'''
class IFactoryType:
@staticmethod
def make(*i_args):
raise NotImplementedError('Must override factory type')
```
Output:
```
True
factory make override
False
Traceback (most recent call last):
File "test.py", line 19, in
factory.register('123', ExampleFactoryType)
File "F:\code\factory.py", line 20, in register
assert( isinstance(i\_type, IFactoryType) )
AssertionError
```<issue_comment>username_1: This assertion is wrong:
```
assert( isinstance(i_type, IFactoryType) )
```
You should instead say:
```
assert issubclass(i_type, IFactoryType)
```
An instance of `ExampleFactoryType` would be an instance of `IFactoryType`, but the class itself is not an instance of its base classes.
All python classes are instances of `type`. Even the type `type` is an instance of itself.
Maybe this helps you understand the difference between types and instances:
```
obj = ExampleFactoryType()
isinstance(obj, ExampleFactoryType) # True
isinstance(obj, IFactoryType) # True
isinstance(ExampleFactoryType, IFactoryType) # False
issubclass(ExampleFactoryType, IFactoryType) # True
isinstance(ExampleFactoryType, type) # True
isinstance(IFactoryType, type) # True
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: A class is not an instance of its superclass; `isinstance(ExampleFactoryType, IFactoryType)` will always be false. This would work for an *instance* of ExampleFactoryType (eg `obj`), but not for the class itself.
Upvotes: 0 |
2018/03/19 | 526 | 2,002 | <issue_start>username_0: I'm trying to verify a server's certificate before obtaining data from it using https. I'm assuming that after `curl_easy_perform` I should use:
```
long out = -1;
curl_easy_getinfo(curl, CURLINFO_SSL_VERIFYRESULT, &out)
```
I cannot find any documentation explaining the meaning of the value `out` is set to, except for an example on <https://curl.haxx.se/libcurl/c/CURLINFO_SSL_VERIFYRESULT.html>, which seems to be wrong (or at least contradicts my experiments).
This example suggests that the value `0` means verification failure, while any other value signifies success.
I found that `0` is actually set every time I get a response body and a sensible HTTP code (obtained using `CURLINFO_RESPONSE_CODE`), whereas other values I've received (1 and 19) always went together with HTTP code 0 and empty body.
Am I missing something obvious or is there no documentation for `CURLINFO_SSL_VERIFYRESULT`?<issue_comment>username_1: This assertion is wrong:
```
assert( isinstance(i_type, IFactoryType) )
```
You should instead say:
```
assert issubclass(i_type, IFactoryType)
```
An instance of `ExampleFactoryType` would be an instance of `IFactoryType`, but the class itself is not an instance of its base classes.
All python classes are instances of `type`. Even the type `type` is an instance of itself.
Maybe this helps you understand the difference between types and instances:
```
obj = ExampleFactoryType()
isinstance(obj, ExampleFactoryType) # True
isinstance(obj, IFactoryType) # True
isinstance(ExampleFactoryType, IFactoryType) # False
issubclass(ExampleFactoryType, IFactoryType) # True
isinstance(ExampleFactoryType, type) # True
isinstance(IFactoryType, type) # True
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: A class is not an instance of its superclass; `isinstance(ExampleFactoryType, IFactoryType)` will always be false. This would work for an *instance* of ExampleFactoryType (eg `obj`), but not for the class itself.
Upvotes: 0 |
2018/03/19 | 674 | 1,960 | <issue_start>username_0: I'm trying to write regex to check whether items within a string meet a certain criteria:
It needs to be a letter followed by a number:
```
'a' then a number 0-7
```
and
```
'b' then a number 0-6
```
For example:
* String "a7b6" should be valid, but
* String "a7b7" should be invalid (because b is followed by 7, which is out of the range 0-6), and
* String "60" should be invalid (because both items are numbers)
I have currently written:
```
[a0-7[b0-6]]+
```
but this expression also validates "a7b7" and "60".
I've also tried:
```
[a\\d&&[^8-9]]+
```
This captures "a7" and "60"; im not sure what to add in to capture the "b6" part and ignore the "60"
EDIT: To add the fact that the order of the string is not fixed, it may be "a7b6", "b3a6", or "b2a1" etc.<issue_comment>username_1: From your examples, you're searching just for
```
a[0-7]b[0-6]
```
which is an a, followed by a digit from 0 to 7, followed by b and 0 to 6.
* ab6 would be false
* a4b7 would be false
* a4 would be false
* a2b0 would be right.
To allow multiple of these, chained together, like
* a4b4a3b5
You would group them, and write
```
(a[0-7]b[0-6])+
```
Your subconstruct [b0-6] for instance means b or 0 or 1, ... or 6, not b followed by something.
I've never seen nested sets, like `[a-z[^np]]`, which might look useful sometimes (a-z, except...) - I doubt they're valid.
Upvotes: 3 [selected_answer]<issue_comment>username_2: `[β¦]` is the syntax for character classes, allowing for any one of the chracters inside. You want something a little different:
```
(a[0-7]|b[0-6])+
```
`(β¦)`is the syntax for a group.
Upvotes: 0 <issue_comment>username_3: You need to understand the meaning of [].
Now when you write [abc] it implies set definition can match the letter a or b or c.
[a0-7[b0-6]]+ would mean multiple occurrence of a/0-7 and b/0-6.
I would advice you to go through the regex documentation again.
Upvotes: 0 |
2018/03/19 | 1,024 | 2,996 | <issue_start>username_0: I am trying to use trendline in my website and wants to make it dashed but lineDashStyle is not working under trendline option . Is it possible to make trendline dashed ?<issue_comment>username_1: there are no standard chart options for modifying the trendline dash style
however, the chart can be changed manually, on the chart's `'ready'` event
the trendline will be represented by an svg element, once found,
set attribute `stroke-dasharray` to the dash style you want
```
path.setAttribute('stroke-dasharray', '5, 5');
```
(MDN web doc --> [stroke-dasharray](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray))
see following working snippet,
the trendline's color is used to find the element,
set the color with chart option --> `trendlines.n.color`
where `n` is the trendline's series index...
```js
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Date', 'Value'],
[new Date(2017, 02,10),100],
[new Date(2017, 02,21),150],
[new Date(2017, 02,28),160],
[new Date(2017, 03,07),150],
[new Date(2017, 03,14),125],
[new Date(2017, 03,23),130],
[new Date(2017, 03,31),135],
[new Date(2017, 04,07),140],
[new Date(2017, 04,26),145],
[new Date(2017, 05,03),130],
[new Date(2017, 05,10),150],
[new Date(2017, 05,17),165],
[new Date(2017, 05,25),175],
[new Date(2017, 06,05),180],
[new Date(2017, 06,12),100]
]);
var options = {
chartArea: {
bottom: 48,
height: '100%',
left: 48,
right: 16,
top: 48,
width: '100%'
},
colors: ['#c3d5bc'],
hAxis: {
format: 'M/d/yy',
slantedText: 'true'
},
height: '100%',
legend: {
alignment: 'start',
position: 'top'
},
trendlines: {
0: {
color: '#344f35',
type: 'linear'
}
},
width: '100%'
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.AreaChart(container);
// change trendline to dashed
google.visualization.events.addListener(chart, 'ready', function () {
var pathElements = container.getElementsByTagName('path');
Array.prototype.forEach.call(pathElements, function(path) {
if (path.getAttribute('stroke') === options.trendlines[0].color) {
path.setAttribute('stroke-dasharray', '5, 5');
}
});
});
chart.draw(data, options);
});
```
```html
```
note: manual changes made to the chart will not be displayed,
when using chart method --> `getImageURI` -- to produce an image of the chart
use [html2canvas](http://html2canvas.hertzen.com/) instead...
Upvotes: 3 [selected_answer]<issue_comment>username_2: Could be done with *css*, searching by color:
```
google-chart path[stroke='#f2994a'] {
stroke-dasharray: 6, 6;
}
```
Upvotes: 1 |
2018/03/19 | 736 | 2,882 | <issue_start>username_0: macOS HFS+ supports transparent filesystem-level compression. How can I enable this compression for certain files via a programmatic API? (e.g. Cocoa or C interface)
I'd like to achieve effect of `ditto --hfsCompression src dst`, but without shelling out.
To clarify: I'm asking how to make uncompressed file compressed. I'm not interested in reading or preserving existing HFS compression state.<issue_comment>username_1: I think you're asking two different questions (and might not know it).
If you're asking "How can I make arbitrary file 'A' an HFS compressed file?" the answer is, you can,'t. HFS compressed files are created by the installer and (technically[1]) only Apple can create them.
If you are asking "How can I emulate the `--hfsCompression` logic in `ditto` such that I can copy an HFS compressed file from one HFS+ volume to another HFS+ volume and preserve its compression?" the answer to that is pretty straight forward, albeit not well documented.
HFS Compressed files have a special `UF_COMPRESSED` file flag. If you see that, the data fork of the file is actually an uncompressed image of a hidden resource. The compressed version of the file is stored in a special extended attribute. It's special because it normally doesn't appear in the list of attributes when you request them (so if you just `ls -l@` the file, for example, you won't see it). To list and read this special attribute you must pass the `XATTR_SHOWCOMPRESSION` flag to both the `listxattr()` and `getxattr()` functions.
To restore a compressed file, you reverse the process: Write an empty file, then restore all of its extended attributes, specifically the special one. When you're done, set the file's `UF_COMPRESSED` flag and the uncompressed data will magically appear in its data fork.
[1] Note: It's rumored that the compressed resource of a file is just a ZIPed version of the data, possibly with some wrapper around it. I've never taken the time to experiment, but if you're intent on creating your own compressed files you could take a stab at reverse-engineering the compressed extended attribute.
Upvotes: 1 <issue_comment>username_2: The [`copyfile.c`](https://opensource.apple.com/source/copyfile/copyfile-146/copyfile.c.auto.html) file discloses some of the implementation details.
There's also a compression tool based on that: [`afsctool`](https://github.com/RJVB/afsctool).
Upvotes: 2 <issue_comment>username_3: There's [afsctool](https://github.com/RJVB/afsctool) which is an open source implementation of HFS+ compression. It was originally by hacker [brkirch](https://forums.macrumors.com/members/brkirch.2504/) (macrumors forum link, as he still visits there) but has since been expanded and improved a great deal by [@rjvb](https://stackoverflow.com/users/1460868/rjvb) who is doing amazing things with it.
Upvotes: 3 [selected_answer] |
2018/03/19 | 1,269 | 3,772 | <issue_start>username_0: one a integer list and one a string list. The integer list's length will always be a multiple of 8. I would like to put the first 8 integers from my integer list into the first element of a string list, then loop and put the next 8 into the second element of the string list and so on. I have made an attempt, I currently have an error on the Add method as string doesn't have an add extension? Also I'm not sure if the way I have done it using loops is correct, any advice would be helpful.
List1 is my integer list
List2 is my string list
```
string x = "";
for (int i = 0; i < List1.Count/8; i++) {
for(int i2 = 0; i2 < i2+8; i2+=8)
{
x = Convert.ToString(List1[i2]);
List2[i].Add(h);
}
}
```<issue_comment>username_1: You can do that by using something like that
```
var list1 = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
var list2 = new List();
for (int i = 0; i < list1.Count / 8; i++)
{
list2.Add(string.Concat(list1.Skip(i \* 8).Take(8)));
}
// list2[0] = "12345678"
// list2[1] = "910111213141516"
```
A slightly more complicated approach, which only iterates once over `list1` (would work with IEnumerable would be sth. like this:
```
var list1 = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }.AsEnumerable();
var list2 = new List();
var i = 0;
var nextValue = new StringBuilder();
foreach (var integer in list1)
{
nextValue.Append(integer);
i++;
if (i != 0 && i % 8 == 0)
{
list2.Add(nextValue.ToString());
nextValue.Clear();
}
}
// could add remaining items if count of list1 is not a multiple of 8
// if (nextValue.Length > 0)
// {
// list2.Add(nextValue.ToString());
// }
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
while (listOfintergers.Count() > 0)
{
var first8elements = listOfintergers.ConvertAll(t=>t.ToString()).Take(8);
listOfStrings.Add(string.Concat(first8elements));
listOfintergers = listOfintergers.Skip(8).ToList();
}
```
Upvotes: 0 <issue_comment>username_3: For the fun of it, you can implement your own general purpose `Batch` extension method. Good practice to understand [extension methods](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods), [enumerators](https://msdn.microsoft.com/en-us/library/78dfe2yb(v=vs.110).aspx), [iterators](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/iterators), [generics](https://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx) and c#'s [local functions](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions):
```
static IEnumerable> Batch(
this IEnumerable source,
int batchCount,
bool throwOnPartialBatch = false)
{
IEnumerable nextBatch(IEnumerator enumerator)
{
var counter = 0;
do
{
yield return enumerator.Current;
counter += 1;
} while (counter < batchCount && enumerator.MoveNext());
if (throwOnPartialBatch && counter != batchCount) //numers.Count % batchCount is not zero.
throw new InvalidOperationException("Invalid batch size.");
}
if (source == null)
throw new ArgumentNullException(nameof(source));
if (batchCount < 1)
throw new ArgumentOutOfRangeException(nameof(batchCount));
using (var e = source.GetEnumerator())
{
while (e.MoveNext())
{
yield return nextBatch(e);
}
}
}
```
Using it is rather trivial:
```
var ii = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
var ss = ii.Batch(4, true)
.Select(b => string.Join(", ", b))
```
And sure enough, the output is:
```
1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12
```
Upvotes: 1 |
2018/03/19 | 813 | 2,420 | <issue_start>username_0: I have a table like below:
```
ID | Name | Ratio | Miles
____________________________________
1 | ABC | 45 | 21
1 | ABC | 46 | 24
1 | ABC | 46 | 25
2 | PQR | 41 | 19
2 | PQR | 39 | 17
3 | XYZ | 27 | 13
3 | XYZ | 26 | 11
4 | DEF | 40 | 18
4 | DEF | 40 | 18
4 | DEF | 42 | 20
```
I want to write a query that will find an `ID` whose `Miles` value has been steadily rising.
For instance,
`Miles` values of Name 'ABC' and 'DEF' are steadily rising.
It's fine if the `Miles` value drops by up to 5% and rises again.
It should also include this Name.
I tried self join on this table but it gives me Cartesian product.
Can anyone help me with this?
I am using SQL server 2012.
Thanks in advance!<issue_comment>username_1: SQL tables represent *unordered* sets. Let me assume that you have a column that specifies the ordering. Then, you can use `lag()` and some logic:
```
select id, name
from (select t.*,
lag(miles) over (partition by id order by orderingcol) as prev_miles
from t
) t
group by id, name
having min(case when prev_miles is null or miles >= prev_miles * 0.95 then 1 else 0 end) = 1;
```
The `having` clause is simply determining if all the rows meet your specific condition.
Upvotes: 3 [selected_answer]<issue_comment>username_2: try this:
Note: 5% case is not handled here
```
create table #tmp(ID INT,Name VARCHAR(50),Ratio INT,Miles INT)
INSERT INTO #tmp
SELECT 1,'ABC',45,21
union all
SELECT 1,'ABC',46,24
union all
SELECT 1,'ABC',46,25
union all
SELECT 2,'PQR',41,19
union all
SELECT 2,'PQR',39,17
union all
SELECT 3,'XYZ',27,13
union all
SELECT 3,'XYZ',26,11
union all
SELECT 4,'DEF',40,18
union all
SELECT 4,'DEF',40,18
union all
SELECT 4,'DEF',42,21
Select *,CASE WHEN Miles<=LEAD(Miles,1,Miles) OVER(partition by ID Order by ID) THEN 1
--NEED ADD 5%condition Here
ELSE 0 END AS nextMiles
into #tmp2
from #tmp
;with cte
AS(
select * , ROW_NUMBER() OVER (partition by ID,nextMiles order by ID) rn from #tmp2
)
SELECT DISTINCT ID,Name FROM cte WHERE rn>1
Drop table #tmp
Drop table #tmp2
```
Upvotes: 0 |
2018/03/19 | 810 | 2,734 | <issue_start>username_0: I am reading excel sheet using below code but that gives blank data table.
```
public static DataTable ReadExcel(string fileName)
{
string fileExt = ".xlsx";
string conn = string.Empty;
DataTable dtexcel = new DataTable();
if (fileExt.CompareTo(".xlsx") == 0)
conn = @"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
{
try
{
OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con); //here we read data from sheet1
oleAdpt.Fill(dtexcel); //fill excel data into dataTable
}
catch(Exception ex) { }
}
return dtexcel;
}
```
It displays empty data table as below screenshot.
[](https://i.stack.imgur.com/u7CJR.png)<issue_comment>username_1: SQL tables represent *unordered* sets. Let me assume that you have a column that specifies the ordering. Then, you can use `lag()` and some logic:
```
select id, name
from (select t.*,
lag(miles) over (partition by id order by orderingcol) as prev_miles
from t
) t
group by id, name
having min(case when prev_miles is null or miles >= prev_miles * 0.95 then 1 else 0 end) = 1;
```
The `having` clause is simply determining if all the rows meet your specific condition.
Upvotes: 3 [selected_answer]<issue_comment>username_2: try this:
Note: 5% case is not handled here
```
create table #tmp(ID INT,Name VARCHAR(50),Ratio INT,Miles INT)
INSERT INTO #tmp
SELECT 1,'ABC',45,21
union all
SELECT 1,'ABC',46,24
union all
SELECT 1,'ABC',46,25
union all
SELECT 2,'PQR',41,19
union all
SELECT 2,'PQR',39,17
union all
SELECT 3,'XYZ',27,13
union all
SELECT 3,'XYZ',26,11
union all
SELECT 4,'DEF',40,18
union all
SELECT 4,'DEF',40,18
union all
SELECT 4,'DEF',42,21
Select *,CASE WHEN Miles<=LEAD(Miles,1,Miles) OVER(partition by ID Order by ID) THEN 1
--NEED ADD 5%condition Here
ELSE 0 END AS nextMiles
into #tmp2
from #tmp
;with cte
AS(
select * , ROW_NUMBER() OVER (partition by ID,nextMiles order by ID) rn from #tmp2
)
SELECT DISTINCT ID,Name FROM cte WHERE rn>1
Drop table #tmp
Drop table #tmp2
```
Upvotes: 0 |
2018/03/19 | 367 | 1,199 | <issue_start>username_0: I have the following macro which copies the values entered on the "Add Course" worksheet to cells on the "Bloggs, Joe" worksheet.
How do I change it so it uses the value from C3 in the "Add Course" worksheet instead of the hard coded "Bloggs, Joe"?
```
Sheets("Add Course").Select
Range("C4").Select
Selection.Copy
Sheets("Bloggs, Joe").Select
Range("C7").Select
ActiveSheet.Paste
```<issue_comment>username_1: Try this:
```
Sheets("Add Course").Select
Range("C4").Select
Selection.Copy
Sheets(Sheets("Add Course").Range("C3").Value).Select
Range("C7").Select
ActiveSheet.Paste
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: Learn how to avoid Select and make your code quicker, more efficient and more concise.
```
With WorkSheets("Add Course")
.Range("C4").Copy WorkSheets(.Range("C3").Value).Range("C7")
End With
```
Upvotes: 2 <issue_comment>username_3: Check out [how to avoid using `Select`](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba) and try something like this:
```
Worksheets(Worksheets("Add Course").Range("C3").Value).Range("C7").Value = Worksheets("Add Course").Range("C4").Value
```
Upvotes: 2 |
2018/03/19 | 431 | 1,629 | <issue_start>username_0: I want to output the lastname or firstname using search but only lastname is only displaying when i search firstname it does not show values... I tried using OR but it doesn't work
```
private void search_Click(object sender, EventArgs e)
{
try
{
MySqlDataAdapter ada = new MySqlDataAdapter("select * from patient where firstname OR lastname = '" + txtSearch.Text + "'", con);
DataTable dt = new DataTable();
ada.Fill(dt);
dataGridView1.DataSource = dt;
label2.Text = dataGridView1.RowCount.ToString();
result.Visible = true;
result.Text ="Showing: "+ dataGridView1.RowCount.ToString()+ " results";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
```<issue_comment>username_1: Try this:
```
Sheets("Add Course").Select
Range("C4").Select
Selection.Copy
Sheets(Sheets("Add Course").Range("C3").Value).Select
Range("C7").Select
ActiveSheet.Paste
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: Learn how to avoid Select and make your code quicker, more efficient and more concise.
```
With WorkSheets("Add Course")
.Range("C4").Copy WorkSheets(.Range("C3").Value).Range("C7")
End With
```
Upvotes: 2 <issue_comment>username_3: Check out [how to avoid using `Select`](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba) and try something like this:
```
Worksheets(Worksheets("Add Course").Range("C3").Value).Range("C7").Value = Worksheets("Add Course").Range("C4").Value
```
Upvotes: 2 |
2018/03/19 | 777 | 2,320 | <issue_start>username_0: I want to pick all the measurement values from below string and need to store into one array. I am getting this type of string from machine whoes name is "Kane". when I connected with this machine using bluetooth at that time I am getting this type of string. I am able to print this string into console. but I am not able to retrive values from this string and I want to store into an array. Can anyone please help me out. Thanks
i want to store values of [serial no,Log No,DATE,TIME,CO2,CO,CO2,CO2,CO,CO/CO2,T1,T2,DELTA] in one single array, like: [12345,0002,23/02/18,17:43:16, -0.00,0,0.00,-0.00,0,0.000,-N\F-,-N\F-,-N\F-].
here is the string which i actually get from machine and print into textview:
```
KANE458 SW19392 V1.13
SERIAL No. 12345
LOG No. 0002
DATE 23/02/18
TIME 17:43:16
------------------------
NEXT CAL 11/12/18
------------------------
COMMISSION TEST
------------------------
ANALYSER ZERO
-------------
CO2 % -0.00
CO ppm 0
FLUE INTEGRITY
--------------
CO2 % 0.00
MAX GAS FLOW
------------
CO2 % -0.00
CO ppm 0
CO/CO2 0.0000
MIN GAS FLOW
------------
CO2 % -0.00
CO ppm 0
CO/CO2 0.0000
FLOW & RETURN
-------------
T1 (null)C -N\F-
T2 (null)C -N\F-
DELTA (null)C -N\F-
```
**I want an array containing everything after the last space character from every line**<issue_comment>username_1: Try this:
```
Sheets("Add Course").Select
Range("C4").Select
Selection.Copy
Sheets(Sheets("Add Course").Range("C3").Value).Select
Range("C7").Select
ActiveSheet.Paste
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: Learn how to avoid Select and make your code quicker, more efficient and more concise.
```
With WorkSheets("Add Course")
.Range("C4").Copy WorkSheets(.Range("C3").Value).Range("C7")
End With
```
Upvotes: 2 <issue_comment>username_3: Check out [how to avoid using `Select`](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba) and try something like this:
```
Worksheets(Worksheets("Add Course").Range("C3").Value).Range("C7").Value = Worksheets("Add Course").Range("C4").Value
```
Upvotes: 2 |
2018/03/19 | 364 | 1,141 | <issue_start>username_0: Can I pass function and parameters to function as arguments?
I can pass only function and it is working
```
function wrap(foo) {
foo();
};
wrap(() => {
console.log("test")
});
```
But I want to also pass some parameters to function **wrap**. Not only function **foo**<issue_comment>username_1: Sure you can
```js
function wrap(foo, bar) {
console.log(bar);
foo();
};
wrap(() => {
console.log("test")
}, 'somebar value');
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: **You can do that:**
```js
function wrap(foo, externalMsg) {
foo(externalMsg);
};
wrap((msg) => {
console.log(msg)
}, 'Ele from SO');
```
**Even, you can initialize params with a predefined function:**
```js
function wrap(externalMsg, foo = (msg) => {
console.log(msg)
}) {
foo(externalMsg);
};
wrap('Ele from SO');
```
Upvotes: 0 <issue_comment>username_3: Yes, You can pass extra parameter in function
```
function wrap(foo, msgObj) {
foo(msgObj.msg);
};
wrap((msg) => {
console.log("test", msg)
// test, here is your extra value
},
{msg:'here is your extra value'}
);
```
Upvotes: 1 |
2018/03/19 | 906 | 2,934 | <issue_start>username_0: I have a problem with converting a varchar2 fields into a date format.
I got 2 columns with the datatyp varchar2, one is called qtime the other is called ztime. Both fields contain strings in this format (f.e. 152015 -> would be a timestamp 15:20:15).
For reporting reasons I need to convert this fields into a date format, afterwards I want to substract (qtime-ztime) the fields an convert them into the format [hh] (f.e. after the operation 01:20:00 would be -> 01). Is it possible to to this within Oracle SQL 12c? **The biggest problem for me right now is that I don't get those Strings converted into a date format.**
`select TO_DATE(qtime,'MM/DD/YYYY hh24:mi:ss')` just gives me
>
> ORA-01861:"literal does not match format string"
>
>
>
`select TO_DATE(qtime,'hh24mmss')` gives me a wrong Date
01.03.2018
`select TO_TIMESTAMP(qtime,'hh24mmss')` gives me a wrong Date
01.03.2018 **BUT** the correct time with f.e. **15:20:15**,0000000
Thank you in advance, any help is appreciated
Note: I only have reading rights on the database Oracle 12c, so I need to to this within Statements<issue_comment>username_1: >
> "The Database contains another column with the correct date for each time"
>
>
>
The missing piece of the puzzle! Concatenate the two columns to get something which can be converted to an Oracle DATE:
```
select to_date(qdate||qtime, 'yyyymmddhh24miss') as qdatetime
, to_date(zdate||ztime, 'yyyymmddhh24miss') as zdatetime
from your_table
```
Once you have done that you can perform arithmetic of the dates e.g.
```
select id
, zdatetime - qdatetime as time_diff
from ( select id
, to_date(qdate||qtime, 'yyyymmddhh24miss') as qdatetime
, to_date(zdate||ztime, 'yyyymmddhh24miss') as zdatetime
from your_table
)
```
If you want the number of hours in the difference you can include this expression in the projection of the outer query:
```
, extract( hour from (zdatetime - qdatetime) day to second) as hrs_ela
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: First off, if you are trying to convert a varchar2 into a date without specifying neither day nor month, it will default to the first day of the current month:
>
> If you specify a date value without a date, then the default date is the first day of the current month.
>
>
>
You can read up more [here](https://docs.oracle.com/database/121/NLSPG/ch4datetime.htm#GUID-4D95F6B2-8F28-458A-820D-6C05F848CA23 "here")
Also in 2nd and 3rd your example, you are using 'hh24mmss' for specifying hour, minute and second components, but do note that correct format for minutes is **'mi'** and not 'mm', which is used for months.
So the solution is to concatenate both date and time component when creating the date as the other answer suggested, tho I would recommend using a single date field as it can store the information you need.
Upvotes: 0 |
2018/03/19 | 563 | 1,558 | <issue_start>username_0: I'm in need to set a cron in crontab like, a php file should be called according to the below schedule
>
> Mon-Fri, 9:00AM to 3:30 PM every one minute
>
>
>
I tried like below,
`*/1 * * * * wget http://example.com/trail.php`
Can someone help me how to create a cron for the above requirement?
Thanks,<issue_comment>username_1: Check the manpage of cron (`man 5 crontab`). You can do a lot of things, but there's no easy and simple way to achieve what you want. Probably the easiest is to use two entries:
```
* 9-14 * * *
0-30 15 * * *
```
Upvotes: 2 <issue_comment>username_2: You can use following pattern and code
>
> Use the hash sign to prefix a comment
> =====================================
>
>
>
> ```
> # +---------------- minute (0 - 59)
> # | +------------- hour (0 - 23)
> # | | +---------- day of month (1 - 31)
> # | | | +------- month (1 - 12)
> # | | | | +---- day of week (0 - 7) (Sunday=0 or 7)
> # | | | | |
> # * * * * * command to be executed
> #--------------------------------------------------------------------------
>
> ```
>
>
```
*/1 9-14 * * 1,2,3,4,5 wget http://example.com/trail.php
0-30 15 * * 1,2,3,4,5 wget http://example.com/trail.php
```
Upvotes: 1 <issue_comment>username_3: Finally, got the obsolete solution.
```
*/1 9-14 * * 1-5 wget -O /dev/null example/alerts.php
```
`0-30 15 * * 1-5 wget -O /dev/null example/alerts.php`
making this work like a charm.
Thanks for the answering, learnt from @Smit Raval and @username_1.
Upvotes: 0 |
2018/03/19 | 619 | 1,622 | <issue_start>username_0: I have a data stream with e.g. the following values:
```
Observable.of(
[{time: 1000, a: 100},
{time: 1000, b: 100},
{time: 2000, a: 200}]
);
```
And need to merge the values based on `time` to get:
```
[{time: 1000, a: 100, b: 100},
{time: 2000, a: 200}]
```
I can use `map` and `reduce` but then I end up with a single map that I have to split somehow again. Is there a more straight forward way in RxJs?<issue_comment>username_1: I got this in the end:
```
Observable.of(
[{time: 1000, channelKey: 'a', value: 100},
{time: 1000, channelKey: 'b',value: 100},
{time: 2000, channelKey: 'a', value: 200}]
)
.flatMap(x => x)
.groupBy(v => Math.floor(v.time.getTime() / 1000), v => {
return {[v.channelKey]: v.value}
})
.flatMap((group$) => group$.reduce((acc, cur) => Object.assign(cur, acc), {time: group$.key}))
.toArray()
.subscribe((v) => {
console.log("Value: ", v)
})
```
Upvotes: 0 <issue_comment>username_2: You could just do an array `reduce` inside of a `map` operator. Might be a bit clearer than the `groupBy` and `flatMap`. This is more of a data mapping issue than an rxjs issue.
```js
Rx.Observable.of(
[{time: 1000, a: 100},
{time: 1000, b: 100},
{time: 2000, a: 200}]
).map(data => {
return data.reduce((acc, cur) => {
const index = acc.findIndex(x => x.time === cur.time);
if (index >= 0) {
acc[index] = { ...acc[index], ...cur };
} else {
acc.push(cur);
}
return acc;
}, [])
})
.subscribe(x => { console.log('result', x); });
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 829 | 2,769 | <issue_start>username_0: I have multiple strings and string-arrays inside my Model, where they're gathered inside a list. Code:
```
namespace ReinovaGrafieken.Models
{
[JsonObject(MemberSerialization.OptIn)]
public class Graphs
{
[JsonProperty]
public string Names { get; set; }
[JsonProperty]
public string[] AnswerHeaders { get; set; }
[JsonProperty]
public string[] AnswersOne { get; set; }
[JsonProperty]
public string[] AnswersTwo { get; set; }
[JsonProperty]
public string[] AnswersThree { get; set; }
[JsonProperty]
public string[] AnswersFour { get; set; }
[JsonProperty]
public string Questions { get; set; }
[JsonProperty]
public string[] AnteOrPost { get; set; }
}
}
```
But what happens when I create my Json with the following code:
```
json = JsonConvert.SerializeObject(graphData);
```
Is that the json will be filled rather strangely.
If I fill up every string([]) once, I'll get 8 times Names, AnswerHeaders, etc.
But every time only one value will be filled. The rest of the instances is empty. I know i can use
```
NullValueHandling = NullValueHandling.Ignore
```
But if I do that I can't use proper Indexes anymore, because the code will think every single Names, AnswerHeaders, etc, is a single index.
Current output:
```
"0":{
"questionName":null,
"AnswerHeaders":null,
"AnswersOne":null,
"AnswersTwo":null,
"AnswersThree":null,
"AnswersFour":null,
"Questions":"Vraag ante 11 & Vraag post 33",
"AnteOrPost":null
},
```
Expected output:
```
"0":{
"questionName": "Vraag 1",
"AnswerHeaders": "Wat vond u",
"AnswersOne": ["2", "3", "4", "5", "6"],
"AnswersTwo": ["23","34","4","3"],
"AnswersThree":["34", "34", "5", "4", "2"].
"AnswersFour":["23","3","4","3","2"],
"Questions":"Vraag ante 11 & Vraag post 33",
"AnteOrPost": "Ante"
},
```<issue_comment>username_1: Your current output:
```
"0":{
"questionName":null,
"AnswerHeaders":null,
"AnswersOne":null,
"AnswersTwo":null,
"AnswersThree":null,
"AnswersFour":null,
"Questions":"Vraag ante 11 & Vraag post 33",
"AnteOrPost":null
},
```
Means that `JsonConvert` could not convert your array to json string **OR** it means that you didn't fill your array when serializing.
Make sure your json is properly filled by filling the fields with demo data:
```
AnswerHeaders = new string[] {"one", "two", "three", "four"};
```
and check to see the value when serialized, this will be a good starting point for your inquiry.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Found the issue. I was calling the Graphs class 8 times, instead of 1 time. Resulting into 232 strings for the Json. Afterwards I didn't have to give indexes anymore, either.
Upvotes: 0 |
2018/03/19 | 759 | 2,475 | <issue_start>username_0: I need help to this select where class from wordpress database:
What I would like to achieve is to display the first 6 newcomer posts/records.
The path to the image, image name, property title, property features (How many Bedrooms and Bathroom etc. there is)
property price and property price unit (if it $ or Danish kroner etc.)
At this link [All properties](http://djsteiner.dk/NewWordpress/properties/) here you can see what i will like to achieve on my front page, just without google map and the sort list and only the 6 first post:
[All properties](http://djsteiner.dk/NewWordpress/properties/)
This are tables: wp\_wpl\_properties, wp\_wpl\_units, wp\_wpl\_items to achieve my goal so i tried to make this select query:
enter code here
```
php
global $wpdb;
$results = $wpdb-get_results
("SELECT * FROM wp_wpl_properties,wp_wpl_units,wp_wpl_items
where wp_wpl_properties.price_unit= wp_wpl_units.id and wp_wpl_properties.id= wp_wpl_items.parent_id LIMIT 6;");
foreach ( $results as $result ) {
?>
```
I have attached table files to this question, here:
[wp\_wpl\_units.pdf](http://djsteiner.dk/wp_wpl_items.pdf)
[wp\_wpl\_items.pdf](http://djsteiner.dk/wp_wpl_units.pdf)
[wp\_wpl\_properties (1).sql](http://djsteiner.dk/wp_wpl_properties%20(1).sql)
The code I've made does not make any errors.
My problem is that i get the same record displayed 3 times at the fist columns and the same at the next 3 column, hope this make sens :)
Here is a link to my frontpage: [My frontpage](http://djsteiner.dk/NewWordpress/)<issue_comment>username_1: Your current output:
```
"0":{
"questionName":null,
"AnswerHeaders":null,
"AnswersOne":null,
"AnswersTwo":null,
"AnswersThree":null,
"AnswersFour":null,
"Questions":"Vraag ante 11 & Vraag post 33",
"AnteOrPost":null
},
```
Means that `JsonConvert` could not convert your array to json string **OR** it means that you didn't fill your array when serializing.
Make sure your json is properly filled by filling the fields with demo data:
```
AnswerHeaders = new string[] {"one", "two", "three", "four"};
```
and check to see the value when serialized, this will be a good starting point for your inquiry.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Found the issue. I was calling the Graphs class 8 times, instead of 1 time. Resulting into 232 strings for the Json. Afterwards I didn't have to give indexes anymore, either.
Upvotes: 0 |
2018/03/19 | 1,063 | 4,261 | <issue_start>username_0: I've been looking for a while through documentation to find a way to accomplish this and haven't been successful yet. The basic idea is, that I have a piece of html that I load through Qt's webview. The same content can be exported to a single html file.
This file uses Libraries such as Bootstrap and jQuery. Currently I load them through CDN which works when online just fine. However, my application also needs to run offline. So I'm looking for a way to intercept loading of the Libraries in Qt and serve a locally saved file instead. I've tried installing a https QWebEngineUrlSchemeHandler, but that never seems to trigger the requestStarted method on it.
```
(PyQT example follows)
QWebEngineProfile.defaultProfile().installUrlSchemeHandler(b'https', self)
```
If I use a different text for the scheme and embed that into the page it works, so my assumption is that it doesn't work as Qt has a default handler for it already registered. But that different scheme would fail in the file export.
Anyway, back to the core question; Is there a way to intercept loading of libraries, or to change the url scheme specifically within Qt only?
Got Further with QWebEngineUrlRequestInterceptor, now redirecting https requests to my own uri, which has a uri handler. However, the request never gets through to it, because: Redirect location 'conapp://webresource/bootstrap.min.css' has a disallowed scheme for cross-origin requests.
How do I whitelist my own conapp uri scheme?
Edit: For completeness sake, it turns out back when I originally stated the question, it was impossible to accomplish with PySide 5.11 due to bugs in it. The bug I reported back then is nowadays flagged as fixed (5.12.1 I believe) so it should now be possible to accomplish this again using Qt methods, however for my own project I'll stick to jinja for now which has become a solution for many other problems.<issue_comment>username_1: The following example shows how I've done it. It uses the QWebEngineUrlRequestInterceptor to redirect content to a local server.
As an example, I intercept the stacks.css for stackoverflow and make an obvious change.
```
import requests
import sys
import threading
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage, QWebEngineProfile
from PyQt5.QtWebEngineCore import QWebEngineUrlRequestInterceptor, QWebEngineUrlRequestInfo
from http.server import HTTPServer, SimpleHTTPRequestHandler
from socketserver import ThreadingMixIn
# Set these to the address you want your local patch server to run
HOST = '127.0.0.1'
PORT = 1235
class WebEngineUrlRequestInterceptor(QWebEngineUrlRequestInterceptor):
def patch_css(self, url):
print('patching', url)
r = requests.get(url)
new_css = r.text + '#mainbar {background-color: cyan;}' # Example of some css change
with open('local_stacks.css', 'w') as outfile:
outfile.write(new_css)
def interceptRequest(self, info: QWebEngineUrlRequestInfo):
url = info.requestUrl().url()
if url == "https://cdn.sstatic.net/Shared/stacks.css?v=596945d5421b":
self.patch_css(url)
print('Using local file for', url)
info.redirect(QtCore.QUrl('http:{}:{}/local_stacks.css'.format(HOST, PORT)))
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
"""Threaded HTTPServer"""
app = QtWidgets.QApplication(sys.argv)
# Start up thread to server patched content
server = ThreadingHTTPServer((HOST, PORT), SimpleHTTPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
# Install an interceptor to redirect to patched content
interceptor = WebEngineUrlRequestInterceptor()
profile = QWebEngineProfile.defaultProfile()
profile.setRequestInterceptor(interceptor)
w = QWebEngineView()
w.load(QtCore.QUrl('https://stackoverflow.com'))
w.show()
app.exec_()
```
Upvotes: 2 <issue_comment>username_2: So, the solution I went with in the end was, first, introduce jinja templates. Then, using those the template would have variables and blocks set based on export or internal use and from there I did not need the interceptor anymore.
Upvotes: 1 [selected_answer] |
2018/03/19 | 503 | 1,488 | <issue_start>username_0: I want all text "Text here for test" to be covered in green .
Right now only the top is green.
Here is my code :
```css
.circle {
background: #00ff00;
width: 10px;
height: 10px;
border-radius: 50%;
}
```
```html
[Text here for test](https://podio.com/abccapitalinvestmentscom/labs/apps/crew-agreements/items/1229)
```<issue_comment>username_1: Just remove `height: 10px;` from `.circle` class
```css
.circle {
background: #00ff00;
width: 10px;
border-radius: 50%;
}
```
```html
[Text here for test](https://podio.com/abccapitalinvestmentscom/labs/apps/crew-agreements/items/1229)
```
Upvotes: 2 <issue_comment>username_2: Well you set height 10px on the circle and the `.circle` div contains the text. The parent div that has the bgColor will have the height of it's children. So it will cover only 10px. The text overflows because that's the default behavior.
So a simple solution would be to remove the `height:10px` from circle. Or change the HTML structure and include the text separately, not inside the `.circle` div
```css
.circle {
background: #00ff00;
width:10px;
border-radius: 50%;
}
```
```html
[Text here for test](https://podio.com/abccapitalinvestmentscom/labs/apps/crew-agreements/items/1229)
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: ```html
[Text here for test](https://podio.com/abccapitalinvestmentscom/labs/apps/crew-agreements/items/1229)
```
Upvotes: 0 |
2018/03/19 | 424 | 1,353 | <issue_start>username_0: I have a question about indexing mechanism using Solr in Java. If I create a documents and i want to find only field "name", solr will be index all fields? Or only index by field "name" in each document?<issue_comment>username_1: Just remove `height: 10px;` from `.circle` class
```css
.circle {
background: #00ff00;
width: 10px;
border-radius: 50%;
}
```
```html
[Text here for test](https://podio.com/abccapitalinvestmentscom/labs/apps/crew-agreements/items/1229)
```
Upvotes: 2 <issue_comment>username_2: Well you set height 10px on the circle and the `.circle` div contains the text. The parent div that has the bgColor will have the height of it's children. So it will cover only 10px. The text overflows because that's the default behavior.
So a simple solution would be to remove the `height:10px` from circle. Or change the HTML structure and include the text separately, not inside the `.circle` div
```css
.circle {
background: #00ff00;
width:10px;
border-radius: 50%;
}
```
```html
[Text here for test](https://podio.com/abccapitalinvestmentscom/labs/apps/crew-agreements/items/1229)
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: ```html
[Text here for test](https://podio.com/abccapitalinvestmentscom/labs/apps/crew-agreements/items/1229)
```
Upvotes: 0 |
2018/03/19 | 1,707 | 4,182 | <issue_start>username_0: Trying to learn Scala. I want to initialize a Map of Maps.
My Java code would look something like this:
**(\* Using computeIfAbsent)**
```
private static void initMap() {
mapAdd(new App("ID_A", "Site1", "app_AAA", "A_A_A_A"));
mapAdd(new App("ID_B", "Site1", "app_BBB", "B_B_B_B"));
mapAdd(new App("ID_C", "Site2", "app_CCC", "C_C_C_C"));
mapAdd(new App("ID_D", "Site2", "app_DDD", "D_D_D_D"));
}
private static void mapAdd(App app) {
map.computeIfAbsent(app.siteId, x -> new HashMap<>()).put(app.name, app);
}
```
My Scala looks like this
```
val app1 = new AppKey("ID_A", "Site1", "app_AAA", "A_A_A_A")
val app2 = new AppKey("ID_B", "Site1", "app_BBB", "B_B_B_B")
val app3 = new AppKey("ID_C", "Site2", "app_CCC", "C_C_C_C")
val app4 = new AppKey("ID_D", "Site2", "app_DDD", "D_D_D_D")
val nameToAppKey1 = mutable.Map[String, AppKey](app1.name -> app1)
nameToAppKey1 += (app2.name -> app2)
val nameToAppKey2 = mutable.Map[String, AppKey](app3.name -> app3)
nameToAppKey2 += (app4.name -> app4)
map += ("Site1" -> nameToAppKey1)
map += ("Site2" -> nameToAppKey2)
```
It looks like it's was written by a Java refugee.
What is the best practice to initialize a Map of Maps in Scala?<issue_comment>username_1: Try this, might help
```
case class AppKey(id: String, name: String, name1: String, name2: String) //whatever your case class is
val app1 = new AppKey("ID_A", "Site1", "app_AAA", "A_A_A_A")
val app2 = new AppKey("ID_B", "Site1", "app_BBB", "B_B_B_B")
val app3 = new AppKey("ID_C", "Site2", "app_CCC", "C_C_C_C")
val app4 = new AppKey("ID_D", "Site2", "app_DDD", "D_D_D_D")
List(app1, app2, app3, app4).groupBy(_.id).map {
case (id, lst) => (id, lst.find(_.id == id))
}
```
And replace `find` with `filter` to get list of values (in Map)
Result will be:
with `find`
```
res0: scala.collection.immutable.Map[String,Option[AppKey]] = Map(ID_D -> Some(AppKey(ID_D,Site2,app_DDD,D_D_D_D)), ID_A -> Some(AppKey(ID_A,Site1,app_AAA,A_A_A_A)), ID_C -> Some(AppKey(ID_C,Site2,app_CCC,C_C_C_C)), ID_B -> Some(AppKey(ID_B,Site1,app_BBB,B_B_B_B)))
```
and with `filter`
```
res0: scala.collection.immutable.Map[String,List[AppKey]] = Map(Site2 -> List(AppKey(ID_C,Site2,app_CCC,C_C_C_C), AppKey(ID_D,Site2,app_DDD,D_D_D_D)), Site1 -> List(AppKey(ID_A,Site1,app_AAA,A_A_A_A), AppKey(ID_B,Site1,app_BBB,B_B_B_B)))
```
Upvotes: 0 <issue_comment>username_2: Initialising the data...
```
//whatever your case class is
case class AppKey(id: String, site: String, appName: String, name: String)
val app1 = AppKey("ID_A", "Site1", "app_AAA", "A_A_A_A")
val app2 = AppKey("ID_B", "Site1", "app_BBB", "B_B_B_B")
val app3 = AppKey("ID_C", "Site2", "app_CCC", "C_C_C_C")
val app4 = AppKey("ID_D", "Site2", "app_DDD", "D_D_D_D")
val apps = Seq(app1, app2, app3, app4)
```
If you are trying to group the apps by Site, you can specify what you need exactly, like this:
```
Map (
"Site2" -> apps.filter(appKey => appKey.site == "Site2"),
"Site1" -> apps.filter(appKey => appKey.site == "Site1")
)
```
or do it in a one-liner:
```
apps.groupBy(_.site)
```
Both of these methods give the following output (formatted for readability):
```
Map(
Site2 -> List(AppKey(ID_C,Site2,app_CCC,C_C_C_C),AppKey(ID_D,Site2,app_DDD,D_D_D_D)),
Site1 -> List(AppKey(ID_A,Site1,app_AAA,A_A_A_A),AppKey(ID_B,Site1,app_BBB,B_B_B_B))
)
```
If you want to further group by something like ID, you can do something like this:
```
apps.groupBy(_.site).mapValues(_.groupBy(_.id))
```
which gives the following output:
```
Map(
Site2 ->
Map(
ID_D -> List(AppKey(ID_D,Site2,app_DDD,D_D_D_D)),
ID_C -> List(AppKey(ID_C,Site2,app_CCC,C_C_C_C))
),
Site1 ->
Map(
ID_A -> List(AppKey(ID_A,Site1,app_AAA,A_A_A_A)),
ID_B -> List(AppKey(ID_B,Site1,app_BBB,B_B_B_B))
)
)
```
For more complex examples, you can just keep adding `.mapValues(_.groupBy(_.{...}))`, or specifying exactly what you want to group by similar to the first example. Note that in Scala, you don't really need to specify the `new` keyword - in most scenarios, it is implied anyway (same as with semicolons).
Upvotes: 1 |
2018/03/19 | 2,020 | 5,211 | <issue_start>username_0: I am having an issue with json.loads(). When i try to decode a json string I get an error. But if I test it with a similar dummy string, it works. What can be the problem here?
Code:
```
dummy_test = """{"state":{"reported": "hum":33.1,"temp":22.3,"relay":false,"pir":10964},"desired":{"hum":33.1,"temp":22.3,"pir":10964}}}"""
def sensor_update(client, userdata, message):
print("++++++++update++++++++++")
print("###" + dummy_test + "###")
print(type(dummy_test))
sensor_bath = json.loads(dummy_test)
print("###" + message.payload + "###")
print(type(message.payload))
sensor_bath = json.loads(message.payload)
print("+++++++++++++++++++++++\n\n")
```
Output:
```
++++++++update++++++++++
###{"state":{"reported":{"hum":33.1,"temp":22.3,"relay":false,"pir":10964},"desired":{"hum":33.1,"temp":22.3,"pir":10964}}}###
###{"state":{"reported":{"hum":33.2,"temp":22.3,"relay":false,"pir":10964},"desired":{"hum":33.2,"temp":22.3,"pir":10964}}}###
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in \_\_bootstrap\_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.\_\_target(\*self.\_\_args, \*\*self.\_\_kwargs)
File "/usr/local/lib/python2.7/dist-packages/AWSIoTPythonSDK/core/protocol/internal/workers.py", line 147, in \_dispatch
self.\_dispatch\_one()
File "/usr/local/lib/python2.7/dist-packages/AWSIoTPythonSDK/core/protocol/internal/workers.py", line 154, in \_dispatch\_one
self.\_dispatch\_methods[event\_type](mid, data)
File "/usr/local/lib/python2.7/dist-packages/AWSIoTPythonSDK/core/protocol/internal/workers.py", line 237, in \_dispatch\_message
message\_callback(None, None, message) # message\_callback(client, userdata, message)
File "sensord.py", line 43, in sensor\_update
sensor\_bath = json.loads(message.payload)
File "/usr/lib/python2.7/json/\_\_init\_\_.py", line 338, in loads
return \_default\_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 369, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 121 - line 1 column 122 (char 120 - 121)
```
The first json.loads succeeds, but the second one fails.<issue_comment>username_1: Try this, might help
```
case class AppKey(id: String, name: String, name1: String, name2: String) //whatever your case class is
val app1 = new AppKey("ID_A", "Site1", "app_AAA", "A_A_A_A")
val app2 = new AppKey("ID_B", "Site1", "app_BBB", "B_B_B_B")
val app3 = new AppKey("ID_C", "Site2", "app_CCC", "C_C_C_C")
val app4 = new AppKey("ID_D", "Site2", "app_DDD", "D_D_D_D")
List(app1, app2, app3, app4).groupBy(_.id).map {
case (id, lst) => (id, lst.find(_.id == id))
}
```
And replace `find` with `filter` to get list of values (in Map)
Result will be:
with `find`
```
res0: scala.collection.immutable.Map[String,Option[AppKey]] = Map(ID_D -> Some(AppKey(ID_D,Site2,app_DDD,D_D_D_D)), ID_A -> Some(AppKey(ID_A,Site1,app_AAA,A_A_A_A)), ID_C -> Some(AppKey(ID_C,Site2,app_CCC,C_C_C_C)), ID_B -> Some(AppKey(ID_B,Site1,app_BBB,B_B_B_B)))
```
and with `filter`
```
res0: scala.collection.immutable.Map[String,List[AppKey]] = Map(Site2 -> List(AppKey(ID_C,Site2,app_CCC,C_C_C_C), AppKey(ID_D,Site2,app_DDD,D_D_D_D)), Site1 -> List(AppKey(ID_A,Site1,app_AAA,A_A_A_A), AppKey(ID_B,Site1,app_BBB,B_B_B_B)))
```
Upvotes: 0 <issue_comment>username_2: Initialising the data...
```
//whatever your case class is
case class AppKey(id: String, site: String, appName: String, name: String)
val app1 = AppKey("ID_A", "Site1", "app_AAA", "A_A_A_A")
val app2 = AppKey("ID_B", "Site1", "app_BBB", "B_B_B_B")
val app3 = AppKey("ID_C", "Site2", "app_CCC", "C_C_C_C")
val app4 = AppKey("ID_D", "Site2", "app_DDD", "D_D_D_D")
val apps = Seq(app1, app2, app3, app4)
```
If you are trying to group the apps by Site, you can specify what you need exactly, like this:
```
Map (
"Site2" -> apps.filter(appKey => appKey.site == "Site2"),
"Site1" -> apps.filter(appKey => appKey.site == "Site1")
)
```
or do it in a one-liner:
```
apps.groupBy(_.site)
```
Both of these methods give the following output (formatted for readability):
```
Map(
Site2 -> List(AppKey(ID_C,Site2,app_CCC,C_C_C_C),AppKey(ID_D,Site2,app_DDD,D_D_D_D)),
Site1 -> List(AppKey(ID_A,Site1,app_AAA,A_A_A_A),AppKey(ID_B,Site1,app_BBB,B_B_B_B))
)
```
If you want to further group by something like ID, you can do something like this:
```
apps.groupBy(_.site).mapValues(_.groupBy(_.id))
```
which gives the following output:
```
Map(
Site2 ->
Map(
ID_D -> List(AppKey(ID_D,Site2,app_DDD,D_D_D_D)),
ID_C -> List(AppKey(ID_C,Site2,app_CCC,C_C_C_C))
),
Site1 ->
Map(
ID_A -> List(AppKey(ID_A,Site1,app_AAA,A_A_A_A)),
ID_B -> List(AppKey(ID_B,Site1,app_BBB,B_B_B_B))
)
)
```
For more complex examples, you can just keep adding `.mapValues(_.groupBy(_.{...}))`, or specifying exactly what you want to group by similar to the first example. Note that in Scala, you don't really need to specify the `new` keyword - in most scenarios, it is implied anyway (same as with semicolons).
Upvotes: 1 |
2018/03/19 | 766 | 1,972 | <issue_start>username_0: I'am using SQLite DB and I have "**Date**" column that is VARCHAR
I need to extract data between 2 dates...
this is what I tried....
```
SELECT * FROM Table1 WHERE Date BETWEEN '14/03/2017 17:00:10' AND '16/03/2018 17:00:12'
SELECT * FROM Table1 WHERE strftime('%d/%m/%y %H:%M:%S', Date) BETWEEN strftime('%d/%m/%y %H:%M:%S','15/07/2016 20:00:09') AND strftime('%d/%m/%y %H:%M:%S','16/07/2017 21:00:09')
SELECT * FROM Table1 WHERE strftime('%d/%m/%y %H:%M:%S', Date) BETWEEN '2017/07/15 20:00:09' AND '2017/07/17 21:00:09'
```
Any idea what I am doing wrong ?<issue_comment>username_1: If you have a date/time column, then just do:
```
SELECT t1.*
FROM Table1 t1
WHERE t1.Date >= '2017-03-14 17:00:10' AND
t1.Date < '2018-03-16 17:00:12';
```
Use ISO/ANSI standard date formats for constants!
I strongly discourage you from using `between` with date/time values. [Here](https://sqlblog.org/2011/10/19/what-do-between-and-the-devil-have-in-common) is a blog post on the subject, which although for SQL Server applies to all databases.
Upvotes: 2 <issue_comment>username_2: You can't use SQLite's `strftime` because it's *formatting* function, it can not parse input string.
Basically you have two options:
1. try to parse string using builtin functions
2. create user defined function
If you can rely on the fixed positions, you can easily parse your string and format it back to comply with one of supported [SQLite DateTime formats](https://www.sqlite.org/lang_datefunc.html). In your case it might look like this:
```
SELECT [Date] FROM Table1 WHERE
DATETIME(printf('%04d-%02d-%02d %02d:%02d:%02d',
substr([Date], 7, 4), substr([Date], 4, 2), substr([Date], 1, 2),
substr([Date], 12, 2), substr([Date], 15, 2), substr([Date], 18, 2)))
BETWEEN '2017-07-15 20:00:05' AND '2017-07-17 21:00:09'
```
Please note you have to change also syntax of `BETWEEN` to match one of supported `DATETIME` formats.
Upvotes: 1 |
2018/03/19 | 648 | 2,243 | <issue_start>username_0: This is my **SearchForm.js**, `handleKeywordsChange` must handle input `keywords` changes
```
import React from 'react';
import ReactDOM from 'react-dom';
class SearchForm extends React.Component {
constructor(props) {
super(props)
this.state = {
keywords: '',
city: '',
date: ''
}
//this.handleChange = this.handleChange.bind(this)
//this.handleSubmit = this.handleSubmit.bind(this)
this.handleKeywordsChange = this.handleKeywordsChange.bind(this);
}
handleKeywordsChange(e) {
console.log(1);
this.setState({
value: e.target.value
});
}
render() {
return (
Keywords
City
Date
1
2
3
4
5
)
}
}
export { SearchForm }
```
The problem is input `keywords` doesn't change its value when I'm typing. What's wrong?<issue_comment>username_1: Your `handleKeywordsChange` function sets the state `value` whereas you are using `this.state.keywords` as value for input
```
handleKeywordsChange(e) {
console.log(1);
this.setState({
keywords: e.target.value
});
}
```
Upvotes: 2 <issue_comment>username_2: It should be :
```
this.setState({
keywords: e.target.value
});
```
Upvotes: 2 <issue_comment>username_3: Make a common function for changing the state for input values.
```
handleInputChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
```
Make sure you mention `name` in every `input` tag. e.g:
```
```
Upvotes: 6 [selected_answer]<issue_comment>username_4: React Hooks makes this so much easier!!!
```js
import React, {useState} from 'react'
function SearchForm () {
const [input, setInput] = useState("")
return (
setInput(e.target.value)} />
)
}
```
Upvotes: 4 <issue_comment>username_5: I believe that you need to do something like this:
```js
handleKeyWordsChange (e) {
this.setState({[e.target.name]: e.target.value});
}
```
Upvotes: 0 <issue_comment>username_6: ```
class InputKeywordCheck {
state = {
email: '',
}
handleInputChange (e) {
const {name, value } = e.target;
this.setState({[name]: value});
}
render() {
return (
)
} }
```
Upvotes: 2 |
2018/03/19 | 1,046 | 4,418 | <issue_start>username_0: I'm creating an Android app where the scenario is User Sign Up and upon clicking "Sign Up" button , the app sends data to REST API.
**activity\_sign\_up\_login.java**
```
xml version="1.0" encoding="utf-8"?
```
**SignUp.java**
```
public class SignUpLogIn extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ConnectionStatus connectionStatus = new ConnectionStatus(getApplicationContext());
if(!connectionStatus.isOnline()){
connectionStatus.displayMobileDataSettingsDialog(this, getApplicationContext());
}
setContentView(R.layout.activity_sign_up_log_in);
final TextView mobNumberTextView = (TextView) findViewById(R.id.mobNum);
final TextView passwordTextView = (TextView) findViewById(R.id.password);
Button signUp = (Button) findViewById(R.id.signUp);
final String mobNumber = mobNumberTextView.getText().toString();
final String password = <PASSWORD>TextView.getText().toString();
signUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!validateInputFields(mobNumber, password)){
Intent checkSignUpStatusIntent = new Intent(getApplicationContext(), CrossCheckSignUpService.class);
checkSignUpStatusIntent.putExtra("countryCode", countryCode);
checkSignUpStatusIntent.putExtra("confirmMobileNumber", mobNumber);
checkSignUpStatusIntent.putExtra("confirmPassword", password);
startService(checkSignUpStatusIntent);
connectionStatus.showProgress();
}
}
});
}
private boolean validateInputFields(String mobNum, String password){
StringBuffer errors = new StringBuffer();
int count = 0;
boolean hasError = false;
if(mobNum == null || mobNum.isEmpty()){
++count;
errors.append(count + ") Please enter your mobile number");
errors.append('\n');
hasError = true;
}
if(password == null || password.isEmpty()){
//cEmail field is empty
++count;
errors.append(count + ") Please enter a password");
errors.append('\n');
hasError = true;
}
if(hasError){
Toast.makeText(this, errors.toString(), Toast.LENGTH_LONG).show();
return true;
}
return false;
}
```
Inside the onClick(), the values are empty, despite user entering the values.
1. Why is that?
2. How to fix it?
Please answer inline.
PS:
I cannot remove final for textView variables above `.setOnClickListener`
[](https://i.stack.imgur.com/DRF6N.png)<issue_comment>username_1: Your `handleKeywordsChange` function sets the state `value` whereas you are using `this.state.keywords` as value for input
```
handleKeywordsChange(e) {
console.log(1);
this.setState({
keywords: e.target.value
});
}
```
Upvotes: 2 <issue_comment>username_2: It should be :
```
this.setState({
keywords: e.target.value
});
```
Upvotes: 2 <issue_comment>username_3: Make a common function for changing the state for input values.
```
handleInputChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
```
Make sure you mention `name` in every `input` tag. e.g:
```
```
Upvotes: 6 [selected_answer]<issue_comment>username_4: React Hooks makes this so much easier!!!
```js
import React, {useState} from 'react'
function SearchForm () {
const [input, setInput] = useState("")
return (
setInput(e.target.value)} />
)
}
```
Upvotes: 4 <issue_comment>username_5: I believe that you need to do something like this:
```js
handleKeyWordsChange (e) {
this.setState({[e.target.name]: e.target.value});
}
```
Upvotes: 0 <issue_comment>username_6: ```
class InputKeywordCheck {
state = {
email: '',
}
handleInputChange (e) {
const {name, value } = e.target;
this.setState({[name]: value});
}
render() {
return (
)
} }
```
Upvotes: 2 |
2018/03/19 | 617 | 2,298 | <issue_start>username_0: So I can get the values from a certain columns(customer last name and first name) from my database into my combobox in my mainform and it's already loaded when the form is opened using LoadEvent. However I have another form where I insert another row (customer lname, fname, phone, etc.) on the same table as where my column is shown on the mainform. So I decided to put a button on my mainform where I can refresh the content of my combobox when I added a customer using the other form. The problem is when I press the button to refresh it only creates a duplicate of what already is on the combobox plus the other 1 that has just been recently added. Please help.
My code:
```
SqlConnection con = new SqlConnection("Data Source=DESKTOP-39SPLT0;Initial Catalog=SalesandInventory;Integrated Security=True");
con.Open();
SqlCommand cmd1 = new SqlCommand("select clName, cName from tblCustomer", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
sda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.Items.Add(ds.Tables[0].Rows[i][0] + ", " + ds.Tables[0].Rows[i][1]);
}
con.Close();
```<issue_comment>username_1: You can just this code instead yours :
```
comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "clName";
comboBox1.DisplayMember = "cName";
```
Upvotes: 1 <issue_comment>username_2: Okay I feel silly but thanks to mjwills and moles.
```
private void btnReset_Click(object sender, EventArgs e){
comboBox1.Items.Clear();
CustomerInfo();
}
void CustomerInfo()
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-39SPLT0;Initial Catalog=SalesandInventory;Integrated Security=True");
con.Open();
SqlCommand cmd1 = new SqlCommand("select clName, cName from tblCustomer", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
sda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.Items.Add(ds.Tables[0].Rows[i][0] + ", " + ds.Tables[0].Rows[i][1]);
}
con.Close();
}
```
Upvotes: 0 |
2018/03/19 | 408 | 1,346 | <issue_start>username_0: I would like to replace some values in input files named " i\_f.xyz " using perl, where i goes from 1 to 19.
In my files, I want to change a "6" into a "C".
To do so I tried
```
perl -pi -e 's/6/C/g' ${i}_f.xyz
```
, and some other combinations but it doesn't work.
Anyone can help me please ? Thanks a lot :)<issue_comment>username_1: You can just this code instead yours :
```
comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "clName";
comboBox1.DisplayMember = "cName";
```
Upvotes: 1 <issue_comment>username_2: Okay I feel silly but thanks to mjwills and moles.
```
private void btnReset_Click(object sender, EventArgs e){
comboBox1.Items.Clear();
CustomerInfo();
}
void CustomerInfo()
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-39SPLT0;Initial Catalog=SalesandInventory;Integrated Security=True");
con.Open();
SqlCommand cmd1 = new SqlCommand("select clName, cName from tblCustomer", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
sda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.Items.Add(ds.Tables[0].Rows[i][0] + ", " + ds.Tables[0].Rows[i][1]);
}
con.Close();
}
```
Upvotes: 0 |
2018/03/19 | 1,563 | 4,702 | <issue_start>username_0: I had some problem with WordCloud code in python when try to run Arabic huge data
this my code:
```
from os import path
import codecs
from wordcloud import WordCloud
import arabic_reshaper
from bidi.algorithm import get_display
d = path.dirname(__file__)
f = codecs.open(path.join(d, 'C:/example.txt'), 'r', 'utf-8')
text = arabic_reshaper.reshape(f.read())
text = get_display(text)
wordcloud = WordCloud(font_path='arial',background_color='white', mode='RGB',width=1500,height=800).generate(text)
wordcloud.to_file("arabic_example.png")
```
And this is the error I get:
>
> Traceback (most recent call last):
>
>
> File "", line 1, in
> runfile('C:/Users/aam20/Desktop/python/codes/WordClouds/wordcloud\_True.py',
> wdir='C:/Users/aam20/Desktop/python/codes/WordClouds')
>
>
> File
> "C:\Users\aam20\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py",
> line 705, in runfile
> execfile(filename, namespace)
>
>
> File
> "C:\Users\aam20\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py",
> line 102, in execfile
> exec(compile(f.read(), filename, 'exec'), namespace)
>
>
> File
> "C:/Users/aam20/Desktop/python/codes/WordClouds/wordcloud\_True.py",
> line 28, in
> text = get\_display(text)
>
>
> File "C:\Users\aam20\Anaconda3\lib\site-packages\bidi\algorithm.py",
> line 648, in get\_display
> resolve\_implicit\_levels(storage, debug)
>
>
> File "C:\Users\aam20\Anaconda3\lib\site-packages\bidi\algorithm.py",
> line 466, in resolve\_implicit\_levels
>
>
> '%s not allowed here' % \_ch['type']
>
>
> AssertionError: RLI not allowed here
>
>
>
Can someone help resolve this issue?<issue_comment>username_1: I tried to preprocess the text with the mentioned method below! before calling reshaper and it worked for me.
```
def removeWeirdChars(text):
weirdPatterns = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
u"\U0001f926-\U0001f937"
u'\U00010000-\U0010ffff'
u"\u200d"
u"\u2640-\u2642"
u"\u2600-\u2B55"
u"\u23cf"
u"\u23e9"
u"\u231a"
u"\u3030"
u"\ufe0f"
u"\u2069"
u"\u2066"
u"\u200c"
u"\u2068"
u"\u2067"
"]+", flags=re.UNICODE)
return weirdPatterns.sub(r'', text)
```
Upvotes: 3 <issue_comment>username_2: There is a weird character in your text that `get_display()` is unable to deal with. You can find this character and add it to a list of stopwords. However it might be very painful. One shortcut is to create a dictionary with most frequent words and their frequencies and feed it to `generate_from_frequencies` fucnction:
```
wordcloud = WordCloud(font_path='arial',background_color='white', mode='RGB',width=1500,height=800).generate_from_frequencies(YOURDICT)
```
For more information check my response to [this](https://stackoverflow.com/questions/60656343/in-wordcloud-on-python-i-would-like-to-merge-two-languages) post.
Upvotes: 0 <issue_comment>username_3: Here is how you can simply generate Arabic wordCloud:
```
import arabic_reshaper
from bidi.algorithm import get_display
reshaped_text = arabic_reshaper.reshape(text)
bidi_text = get_display(reshaped_text)
wordcloud = WordCloud(font_path='NotoNaskhArabic-Regular.ttf').generate(bidi_text)
wordcloud.to_file("worCloud.png")
```
And here is a link to Google colab example: [Colab notebook](https://colab.research.google.com/drive/1OmP1TOqXq8gCPNxlLCaKGWHNJ_q3dHRu?usp=sharing)
Upvotes: 0 <issue_comment>username_4: I had similar issue, so I removed the emoji than it work just fine
```
from wordcloud import WordCloud
import arabic_reshaper
import emoji
your_txt = emoji.replace_emoji(your_txt, replace='', version=-1)
your_txt = arabic_reshaper.reshape(your_txt)
your_txt = get_display(reshaped_text)
wordcloud = WordCloud(font_path='NotoNaskhArabic-Regular.ttf').generate(your_txt)
wordcloud.to_file("ar_wordCloud.png")
```
Upvotes: 1 |
2018/03/19 | 866 | 3,226 | <issue_start>username_0: Very simply, is the following code safe/portable?
```
#include
#include
int add(int \*a, int \*b)
{
return \*a + \*b;
}
int main()
{
int x = 2;
int y = 3;
void \*ptr1 = &x
void \*ptr2 = &y
fprintf(stdout, "%d + %d = %d\n", x, y, add(ptr1, ptr2));
return EXIT\_SUCCESS;
}
```
I've compiled this with `-Wall -Werror` and `-Wextra` and received no warnings; it seems to run fine.<issue_comment>username_1: It's fine but by the skin of your teeth.
You are converting an `int*` to `void*` and that is converted back to `int*` as the pointer is passed by value into `add`.
If, for example, `add` took two pointers to `double`, say, then the behaviour of your code would be undefined.
Upvotes: 2 <issue_comment>username_2: It is safe:
[C99](https://busybox.net/~landley/c99-draft.html#6.3.2.3)
>
> A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
>
>
>
But you need to make sure your original pointer type is correct.
Upvotes: 2 <issue_comment>username_3: There's two things to consider:
1. C allows the implicit conversion from a void pointer to any other object pointer type. So it's syntactically okay to pass those arguments.
2. The type of the actual object being pointed to, and the type of the pointer the function expects, must satisfy [strict aliasing](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule) constraints, otherwise your program is in undefined behavior land.
You are okay on both points. So your program is perfectly fine.
Upvotes: 3 [selected_answer]<issue_comment>username_4: It's "safe" in that the behavior is well defined. Having a function declared as accepting `void *` is normal when it needs to deal with many different types of data; e.g. `memcpy`.
It's not *morally* safe. By passing `void *` you are making the compiler unable to check that the pointer you are passing points to memory that holds data in the form and quantity that you expect. It is then up to you to enforce this.
In your trivial example you can see that the objects are actually `int`, and everything is fine.
In general, however, where we pass `void *` to a function, we should also pass additional information describing the memory we are handing over in enough detail that the function can do its job; if we have a function that only ever deals with one type, we look long and hard at the design decisions that made us pass around `void *` values instead of that type.
For sanity's sake (and, depending on the compiler, performance), please consider also marking arguments you are not writing to as `const`.
Upvotes: 0 <issue_comment>username_5: If you know that the pointers that you cast to void \* are always to a known set of types (e.g. char, short, int, etc.), you can create a struct type consisting of a union together with a discriminant, and pass that instead, re-casting if necessary.
You can pass it as a pointer to an undefined type, just to be a bit more specific than void \*, and in that way some responsibility is taken.
Upvotes: 0 |
2018/03/19 | 1,306 | 5,073 | <issue_start>username_0: I've been battling with a simple applying a custom adapter to a listview for a few days now, hopefully, someone can help me where I'm going wrong.
I have a ListView (listViewAsItHappens) and I want to use a custom adapter to the view so I can format the look of the ListView. I have read lots of articles but none seem to appear to work as expected.
When I debug the code, it steps to the adapter but there's nothing displayed in the ListView. I'm getting no errors and it looks like all variables/objects are passing along nicely.
Any help in helping me getting the ListView to display the 3 lines of text and images will be great.
```
ListView list;
String[] itemname ={
"Whistle",
"Football",
"Card"
};
Integer[] imgid={
R.drawable.ic_whistle,
R.drawable.ic_football,
R.drawable.ic_yellowcard
};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_refscorecard, container, false);
list=(ListView) view.findViewById(R.id.listViewAsItHappens);
asItHappened adapter=new asItHappened(getActivity(), itemname, imgid);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
```
My custom adapter (asithappens\_listview is my XML layout);
```
public class asItHappened extends ArrayAdapter {
private Activity context;
private String[] eventType;
private final Integer[] imgid;
public asItHappened(Context context, String[] event, Integer[] icon) {
super(context, R.layout.asithappens\_listview);
this.eventType=event;
this.imgid=icon;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.asithappens\_listview, null,true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txtEvent);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imgEvent);
rowView.findViewById(R.id.textView1);
txtTitle.setText(eventType[position]);
imageView.setImageResource(imgid[position]);
return rowView;
}
}
```<issue_comment>username_1: You haven't overridden the `getCount()` method of the `ArrayAdapter`. You need to override it in your customer adapter class and return the size of elements that need to be displayed. Add something like this in your custom adapter class.
```
@Override
public int getCount() {
return imgid.length;
}
```
you could change the declaration of your custom adapter and extend from `ArrayAdapter`
Or to have more flexibility you can extend it from `BaseAdapter` like this, just change your custom adapter class to this.
```
public class asItHappened extends BaseAdapter {
private Activity context;
private String[] eventType;
private final Integer[] imgid;
public asItHappened(Context context, String[] event, Integer[] icon) {
this.context = context;
this.eventType=event;
this.imgid=icon;
}
@Override
public int getCount() {
return eventType.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.asithappens_listview, null,true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txtEvent);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imgEvent);
rowView.findViewById(R.id.textView1);
txtTitle.setText(eventType[position]);
imageView.setImageResource(imgid[position]);
return rowView;
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use `super constructor` where you need to pass the `string[]` on which basis it will trigger `getView` method for each `item` in `string[]` as in
```
public class asItHappened extends ArrayAdapter { //< make it string
private Activity context;
private String[] eventType;
private final Integer[] imgid;
public asItHappened(Context context, String[] event, Integer[] icon) {
super(context, R.layout.asithappens\_listview,event); //<-- pass event
this.eventType=event;
this.imgid=icon;
}
//rest of the code
}
```
Upvotes: 0 <issue_comment>username_3: You are missing an Override method
**Add this**
```
@Override
public int getCount() {
return eventType.length;
}
```
Upvotes: 0 <issue_comment>username_4: You have created the adapter but you have not added objects into it. You might want to `add()` (method of adapter) the objects into the adapter so that the count gets updated.
Alternatively you will have to implement the `getCount()` method and maybe the `getItemId()` and `getItem()` method too.
Upvotes: 0 <issue_comment>username_5: override the getcount method and return the size of array
Upvotes: 0 |
2018/03/19 | 827 | 3,293 | <issue_start>username_0: I am looking for a way through which I can parse .zip file and identify hex data and what fields they represent?
eg : In a .zip file local file header signature from initial 4 bytes, but how to identify the rest of hex and what they represent
I have goen through <https://pkware.cachefly.net/webdocs/APPNOTE/APPNOTE_6.2.0.txt> but could not track all the hex bytes<issue_comment>username_1: You haven't overridden the `getCount()` method of the `ArrayAdapter`. You need to override it in your customer adapter class and return the size of elements that need to be displayed. Add something like this in your custom adapter class.
```
@Override
public int getCount() {
return imgid.length;
}
```
you could change the declaration of your custom adapter and extend from `ArrayAdapter`
Or to have more flexibility you can extend it from `BaseAdapter` like this, just change your custom adapter class to this.
```
public class asItHappened extends BaseAdapter {
private Activity context;
private String[] eventType;
private final Integer[] imgid;
public asItHappened(Context context, String[] event, Integer[] icon) {
this.context = context;
this.eventType=event;
this.imgid=icon;
}
@Override
public int getCount() {
return eventType.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.asithappens_listview, null,true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txtEvent);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imgEvent);
rowView.findViewById(R.id.textView1);
txtTitle.setText(eventType[position]);
imageView.setImageResource(imgid[position]);
return rowView;
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use `super constructor` where you need to pass the `string[]` on which basis it will trigger `getView` method for each `item` in `string[]` as in
```
public class asItHappened extends ArrayAdapter { //< make it string
private Activity context;
private String[] eventType;
private final Integer[] imgid;
public asItHappened(Context context, String[] event, Integer[] icon) {
super(context, R.layout.asithappens\_listview,event); //<-- pass event
this.eventType=event;
this.imgid=icon;
}
//rest of the code
}
```
Upvotes: 0 <issue_comment>username_3: You are missing an Override method
**Add this**
```
@Override
public int getCount() {
return eventType.length;
}
```
Upvotes: 0 <issue_comment>username_4: You have created the adapter but you have not added objects into it. You might want to `add()` (method of adapter) the objects into the adapter so that the count gets updated.
Alternatively you will have to implement the `getCount()` method and maybe the `getItemId()` and `getItem()` method too.
Upvotes: 0 <issue_comment>username_5: override the getcount method and return the size of array
Upvotes: 0 |
2018/03/19 | 489 | 1,649 | <issue_start>username_0: I created a button. The language on it has to be changed whenever required. I wrote the following code to do the task
```
var $button = $( '' )
.attr( 'href', '#' ).prepend(
'', ' ' )
.attr( 'data-i18n', 'text' )
.tooltip( {
title: 'change item'
} );
```
this successfully change the language but it doesn't display icon "+".
```
var $button = $( '' )
.text( 'sample text' )
.append( 'sample text' )
.attr( 'href', '#' ).prepend(
'', ' ' )
.tooltip( {
title: 'change item'
} );
```
The second case worked and displayed it correctly including the change in language. But I can't understand the mistake in the first code sample. can anyone help me out? Thanks in advance<issue_comment>username_1: Your code syntax is invalid. You have an extra `'` after the text variable inside the second attr function
Your code:
```
var $button = $( '' )
.attr( 'href', '#' ).prepend(
'', ' ' )
.attr( 'data-i18n', text' )
.tooltip( {
title: 'change item'
});
```
Valid code:
```
var $button = $( '' )
.attr( 'href', '#' ).prepend(
'', ' ' )
.attr( 'data-i18n', text )
.tooltip( {
title: 'change item'
});
```
Upvotes: 0 <issue_comment>username_2: i guess you use jquery-i18next:
`hello` will get it's content replaced by the translation given by key text. So after translation you will have: whatever the translation is`
having it like you did in the second sample asserts only the inner span gets replaced not the complete content of the anchor tag.
but you also can do something like `...`: <https://github.com/i18next/jquery-i18next#prepend-content> to achieve the same.
Upvotes: 2 [selected_answer] |
2018/03/19 | 428 | 1,339 | <issue_start>username_0: So...
I've been banging my head on the wall over this problem for a few days now, but still couldn't find a solution.
I have two ranges of numbers
A -> B
C -> D
A given number (x) is on the A -> B range.
I need to find it's equivalent in the C -> D range.
eg:
A -> B = (2 -> 4)
C -> D = (-148 -> -50)
x = 2.3
What is the equivalent value on the (-148 -> -50) range?<issue_comment>username_1: Your code syntax is invalid. You have an extra `'` after the text variable inside the second attr function
Your code:
```
var $button = $( '' )
.attr( 'href', '#' ).prepend(
'', ' ' )
.attr( 'data-i18n', text' )
.tooltip( {
title: 'change item'
});
```
Valid code:
```
var $button = $( '' )
.attr( 'href', '#' ).prepend(
'', ' ' )
.attr( 'data-i18n', text )
.tooltip( {
title: 'change item'
});
```
Upvotes: 0 <issue_comment>username_2: i guess you use jquery-i18next:
`hello` will get it's content replaced by the translation given by key text. So after translation you will have: whatever the translation is`
having it like you did in the second sample asserts only the inner span gets replaced not the complete content of the anchor tag.
but you also can do something like `...`: <https://github.com/i18next/jquery-i18next#prepend-content> to achieve the same.
Upvotes: 2 [selected_answer] |
2018/03/19 | 1,764 | 5,842 | <issue_start>username_0: I need to write some custum code using multiple columns within a group of my data.
My custom code is to set a flag if a value is over a threshold, but suppress the flag if it is within a certain time of a previous flag.
Here is some sample code:
```py
df = spark.createDataFrame(
[
("a", 1, 0),
("a", 2, 1),
("a", 3, 1),
("a", 4, 1),
("a", 5, 1),
("a", 6, 0),
("a", 7, 1),
("a", 8, 1),
("b", 1, 0),
("b", 2, 1)
],
["group_col","order_col", "flag_col"]
)
df.show()
+---------+---------+--------+
|group_col|order_col|flag_col|
+---------+---------+--------+
| a| 1| 0|
| a| 2| 1|
| a| 3| 1|
| a| 4| 1|
| a| 5| 1|
| a| 6| 0|
| a| 7| 1|
| a| 8| 1|
| b| 1| 0|
| b| 2| 1|
+---------+---------+--------+
from pyspark.sql.functions import udf, col, asc
from pyspark.sql.window import Window
def _suppress(dates=None, alert_flags=None, window=2):
sup_alert_flag = alert_flag
last_alert_date = None
for i, alert_flag in enumerate(alert_flag):
current_date = dates[i]
if alert_flag == 1:
if not last_alert_date:
sup_alert_flag[i] = 1
last_alert_date = current_date
elif (current_date - last_alert_date) > window:
sup_alert_flag[i] = 1
last_alert_date = current_date
else:
sup_alert_flag[i] = 0
else:
alert_flag = 0
return sup_alert_flag
suppress_udf = udf(_suppress, DoubleType())
df_out = df.withColumn("supressed_flag_col", suppress_udf(dates=col("order_col"), alert_flags=col("flag_col"), window=4).Window.partitionBy(col("group_col")).orderBy(asc("order_col")))
df_out.show()
```
The above fails, but my expected output is the following:
```py
+---------+---------+--------+------------------+
|group_col|order_col|flag_col|supressed_flag_col|
+---------+---------+--------+------------------+
| a| 1| 0| 0|
| a| 2| 1| 1|
| a| 3| 1| 0|
| a| 4| 1| 0|
| a| 5| 1| 0|
| a| 6| 0| 0|
| a| 7| 1| 1|
| a| 8| 1| 0|
| b| 1| 0| 0|
| b| 2| 1| 1|
+---------+---------+--------+------------------+
```<issue_comment>username_1: I think, You don't need custom function for this. you can use rowsBetween option along with window to get the 5 rows range. Please check and let me know if missed something.
```
>>> from pyspark.sql import functions as F
>>> from pyspark.sql import Window
>>> w = Window.partitionBy('group_col').orderBy('order_col').rowsBetween(-5,-1)
>>> df = df.withColumn('supr_flag_col',F.when(F.sum('flag_col').over(w) == 0,1).otherwise(0))
>>> df.orderBy('group_col','order_col').show()
+---------+---------+--------+-------------+
|group_col|order_col|flag_col|supr_flag_col|
+---------+---------+--------+-------------+
| a| 1| 0| 0|
| a| 2| 1| 1|
| a| 3| 1| 0|
| b| 1| 0| 0|
| b| 2| 1| 1|
+---------+---------+--------+-------------+
```
Upvotes: 0 <issue_comment>username_2: Editing answer after more thought.
The general problem seems to be that the result of the current row depends upon result of the previous row. In effect, there is a recurrence relationship. I haven't found a good way to implement a recursive UDF in Spark. There are several challenges that result from the assumed distributed nature of the data in Spark which would make this difficult to achieve. At least in my mind. The following solution should work but may not scale for large data sets.
```
from pyspark.sql import Row
import pyspark.sql.functions as F
import pyspark.sql.types as T
suppress_flag_row = Row("order_col", "flag_col", "res_flag")
def suppress_flag( date_alert_flags, window_size ):
sorted_alerts = sorted( date_alert_flags, key=lambda x: x["order_col"])
res_flags = []
last_alert_date = None
for row in sorted_alerts:
current_date = row["order_col"]
aflag = row["flag_col"]
if aflag == 1 and (not last_alert_date or (current_date - last_alert_date) > window_size):
res = suppress_flag_row(current_date, aflag, True)
last_alert_date = current_date
else:
res = suppress_flag_row(current_date, aflag, False)
res_flags.append(res)
return res_flags
in_fields = [T.StructField("order_col", T.IntegerType(), nullable=True )]
in_fields.append( T.StructField("flag_col", T.IntegerType(), nullable=True) )
out_fields = in_fields
out_fields.append(T.StructField("res_flag", T.BooleanType(), nullable=True) )
out_schema = T.StructType(out_fields)
suppress_udf = F.udf(suppress_flag, T.ArrayType(out_schema) )
window_size = 4
tmp = df.groupBy("group_col").agg( F.collect_list( F.struct( F.col("order_col"), F.col("flag_col") ) ).alias("date_alert_flags"))
tmp2 = tmp.select(F.col("group_col"), suppress_udf(F.col("date_alert_flags"), F.lit(window_size)).alias("suppress_res"))
expand_fields = [F.col("group_col")] + [F.col("res_expand")[f.name].alias(f.name) for f in out_fields]
final_df = tmp2.select(F.col("group_col"), F.explode(F.col("suppress_res")).alias("res_expand")).select( expand_fields )
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 673 | 1,684 | <issue_start>username_0: I have a list of tuples:
```
card_list= [(2, (1, S)), (0, (12, H)), (1, (5, C)]
```
This list contains cards: (cardindex, (value, suit)) where cardindex is a index to store the position of the card but irrelevant for this my particular question.
So in the example there are 3 cards in the list:
* (2, (1, S)) = Ace of Spades with an index of 2.
* (0, (12, H)) = King
of Hearts with an index of 0
* (1, (5, C)) = 5 of Clubs with index 1
Well, my question is: I desire to obtain the item with the max value, this is, i have to get the item: (0, (12, H))
My attempt is:
```
CardWithHighestValue= max(card_list,key=itemgetter(1)[0])
```
But I get the item or the value? And the most important: is it really correct that sentence?
Thanks in advance.<issue_comment>username_1: replace
```
CardWithHighestValue= max(card_list,key=itemgetter(1)[0])
```
with
```
CardWithHighestValue= max(card_list,key=itemgetter(1))
```
**Demo**
```
from operator import itemgetter
card_list= [(2, (1, "S")), (0, (12, "H")), (1, (5, "C"))]
print max(card_list,key=itemgetter(1))
card_list= [(2, (1, "S")), (0, (4, "H")), (1, (5, "C"))]
print max(card_list,key=itemgetter(1))
```
**Output:**
```
(0, (12, 'H'))
(1, (5, 'C'))
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can also use an anonymous function as key:
Demo:
```
print(max(card_list, key=lambda x:x[1]))
```
Output:
```
(0, (12, 'H'))
```
Upvotes: 1 <issue_comment>username_3: Try this:
```
lst=[(1,('a',10)), (2,('b',10)),(10,('a',10)), (3,('a',10))]
```
So
```
print("min: ", min(lst)[0]) # min: 1
```
And
```
print("max: ", max(lst)[0]) # max: 10
```
Upvotes: 0 |
2018/03/19 | 474 | 1,386 | <issue_start>username_0: I have this HTML code and it works perfect:
`[](www.link.com)`
I want to add this code in PHP and replace the link and image urls with this variables: $link, $image\_src1 and $image\_src2.
I tried this code:
`[](.$link.)`
I think I can not manage how to use quotes, because of this, I am getting an error.
Thank you in advance!<issue_comment>username_1: Try this:
```
$link = 'http://www.google.com';
$image_src1 = "https://image.flaticon.com/icons/svg/148/148766.svg";
$image_src2 = "https://image.flaticon.com/icons/svg/149/149147.svg";
echo '[]('.$link.')';
```
But you really need to look in your code logic, for mouseover/out. You can achieve same logic using CSS `:hover` property in simple and elegant way.
Upvotes: 1 [selected_answer]<issue_comment>username_2: Thank you @Muhammad I managed it to work with CSS and :hover
This is my code in case someone needs it:
```
echo '';
echo '<img class="image" src="'.$image\_src.'';
echo '<img class="image hover" src="'.$image\_src2.'';
echo '</div>';
```
And the CSS:
```
.effect img.image{
display: block;
width: 100%;
max-width: 100%;
height: auto;
}
.effect:hover img.image{
display:none;
}
.effect img.hover{
display:none;
}
.effect:hover img.hover{
display:block;
}
```
Upvotes: 1 |
2018/03/19 | 589 | 1,846 | <issue_start>username_0: I need to validate the dates with different formats like
`Thursday March 15, 2018, 05-21-1995, 04.03.1934` and I may get Invalid Dates like `N/A, #### etc.,`. I am using the Following Query to validate the date in Stored procedure, here I insert the date into the date column and set Error Flag If there is an Invalid date.
```
INSERT INTO table_name(date_column,date_error)
SELECT
CASE WHEN TRY_PARSE(date_column AS datetime USING 'en-US') is NULL THEN date_column
ELSE TRY_PARSE(date_column AS datetime USING 'en-US')
END as date_column,
CASE WHEN TRY_PARSE(date_column AS datetime USING 'en-US') is NULL THEN 1
ELSE 0
END as date_error
FROM @temp_table;
```
I'm getting the Error as `Conversion failed when converting date and/or time from character string` for date value `####`.<issue_comment>username_1: Try this:
```
$link = 'http://www.google.com';
$image_src1 = "https://image.flaticon.com/icons/svg/148/148766.svg";
$image_src2 = "https://image.flaticon.com/icons/svg/149/149147.svg";
echo '[]('.$link.')';
```
But you really need to look in your code logic, for mouseover/out. You can achieve same logic using CSS `:hover` property in simple and elegant way.
Upvotes: 1 [selected_answer]<issue_comment>username_2: Thank you @Muhammad I managed it to work with CSS and :hover
This is my code in case someone needs it:
```
echo '';
echo '<img class="image" src="'.$image\_src.'';
echo '<img class="image hover" src="'.$image\_src2.'';
echo '</div>';
```
And the CSS:
```
.effect img.image{
display: block;
width: 100%;
max-width: 100%;
height: auto;
}
.effect:hover img.image{
display:none;
}
.effect img.hover{
display:none;
}
.effect:hover img.hover{
display:block;
}
```
Upvotes: 1 |
2018/03/19 | 394 | 1,661 | <issue_start>username_0: I am using MPAndroidChart library to make charts for an android application. I would like to make 3-4 charts and want to swipe them. Is it possible to have swipe functionality using MPAndroidChart library and how can I implement such swipe function?<issue_comment>username_1: Use a [ViewPager](https://developer.android.com/training/animation/screen-slide.html) and attach a FragmentStatePagerAdapter
```
public class SomePagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public MISPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new LineChartFragment();
case 1:
return new BarChartFragment();
case 2:
return new PieChartFragment();
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}}
```
Each Fragment will have its own dataset using which the charts will be drawn.
Upvotes: 0 <issue_comment>username_2: I think by understanding your problem I may suggest two possible ways to do so.
1] Use horizontal recycler view and each row will have a chart to show and to do so create a list with custom model class.
2] Use ViewPager with Fragment:
To create a view pager pass your expected list of graphs and on every getItem create a new Fragment instance and attach it to viewpager.
Pass custom model class as a input values to render your chart through bundle using parcable or serializable interface.
Each fragment will have a chart to show.
Upvotes: 1 |
2018/03/19 | 460 | 1,814 | <issue_start>username_0: I'm trying to create a file inside a Django project on Amazon ElasticBeanstalk WebServer Environment. However it gives me a `Permission Denied` error.
Here is the error.
```
Traceback (most recent call last):
File "/opt/python/current/app/foo/boo.py", line 25, in create_file
input_file = open(input_filename, "w")
IOError: [Errno 13] Permission denied: 'testing.txt'
```
Thanks in advance!<issue_comment>username_1: Use a [ViewPager](https://developer.android.com/training/animation/screen-slide.html) and attach a FragmentStatePagerAdapter
```
public class SomePagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public MISPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new LineChartFragment();
case 1:
return new BarChartFragment();
case 2:
return new PieChartFragment();
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}}
```
Each Fragment will have its own dataset using which the charts will be drawn.
Upvotes: 0 <issue_comment>username_2: I think by understanding your problem I may suggest two possible ways to do so.
1] Use horizontal recycler view and each row will have a chart to show and to do so create a list with custom model class.
2] Use ViewPager with Fragment:
To create a view pager pass your expected list of graphs and on every getItem create a new Fragment instance and attach it to viewpager.
Pass custom model class as a input values to render your chart through bundle using parcable or serializable interface.
Each fragment will have a chart to show.
Upvotes: 1 |
2018/03/19 | 585 | 2,052 | <issue_start>username_0: Given a string:
How can I printout all values enclosed in brackets from a string in one line?
```
String str = "java programming (for)all (beginners) is (very) interesting";
String values= StringUtils.substringBetween(str,"(",")");
System.out.print(values);
```
What I need is: for beginners very
But i'm only getting one value: for<issue_comment>username_1: By reading the documentation [here](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#substringsBetween(java.lang.String,%20java.lang.String,%20java.lang.String)), i would say you are using the wrong function.
```
String[] values= StringUtils.substringsBetween(str,"(",")");
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Reading up on `substringBetween` [it says it](http://libcommons-lang-java.sourcearchive.com/documentation/2.0/classorg_1_1apache_1_1commons_1_1lang_1_1StringUtils_f47b956d27f446d016888970cd3ce187.html)
>
> Gets the String that is nested in between two instances of the same String.
>
>
>
I read that as it only does it once. I.e. once it finds the first string between the brackets, it's 'done' and returns it, without continuing. Notice how it's return:
```
String values ....
```
is a `String`, not a string array `String[]`.
There would be two ways to solve the problem. First, you could do `substringBetween` on the next bit of string, and repeat until you ran out. Or you could do it a different way completely. Given that the `substringBetween` does not give you any positional information (i.e. it's found the substring at character 12 etc) it wouldn't be very easy to repeat the operation, so I'd suggest you use a different method (maybe start with `String.split("(")` ?)
Or as Till says, use substringsBetween which returns an array of all strings. Does feel like it's cheating a little if this is a homework assignment though! Worth giving it a go with a for loop yourself or something to try write your own `substringsBetween` function.
Upvotes: 0 |
2018/03/19 | 350 | 996 | <issue_start>username_0: How do I print a map of maps?
I have written
```
map foreach (x => println (x._1 + "-->" + {x._2 foreach {y=> println( y._1 +" ->"+ y._2)}}))
```
It works.
But it looks like a hack.
Is there a better way to write it in Scala.<issue_comment>username_1: You can just use `println`. It *will print all the nested `Maps`*
```
println(map)
```
Upvotes: 1 <issue_comment>username_2: Depending on what you need to do, you may benefit from actually rendering the full string, then do a single print. See:
```
scala> val mapmap = Map(1 -> Map("a" -> "z"), 2 -> Map("b" -> "y", "c" -> "x"))
mapmap: scala.collection.immutable.Map[Int,scala.collection.immutable.Map[String,String]] = Map(1 -> Map(a -> z), 2 -> Map(b -> y, c -> x))
scala> mapmap.foldLeft(""){case (x,accX)=> x.foldLeft(""){case (y,accY) => y + accY} + accX}
res0: String = (1,Map(a -> z))(2,Map(b -> y, c -> x))
```
Now res0 is a fully materialized string output, with no side-effects.
Upvotes: -1 |
2018/03/19 | 1,461 | 3,934 | <issue_start>username_0: I have the following data structure:
```
var = [['x_A_B', 1], ['x_A_C', 1], ['x_B_A', 1], ['x_B_D', 1], ['x_C_A', 1], ['x_C_D', 1], ['x_D_B', 1], ['x_D_C', 1]]
```
I would like to extract these values as
```
var2 = [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'D'), ('C', 'A'), ('C', 'D'), ('D', 'B'), ('D', 'C')]
```
Currently I use the following line
```
var2 = [(item[0].split("_")[1], item[0].split("_")[2]) for item in var]
```
but it's tedious to write, and also calculates the same `split` two times.
Is there a way of writing this in a compact way, maybe with keywords `with ... as`, something like this?
```
# not working
var2 = [(u, v) with item[0].split("_") as _, u, v for item in var]
```
EDIT: I was looking for a more general solution, where I can use arbitrary indices of the split string with arbitrary length of substrings, I just used an improper example. See the solution I accepted.<issue_comment>username_1: Why even use `split`? You know the exact indices of the letters you want.
```
>>> var = [['x_A_B', 1], ['x_A_C', 1], ['x_B_A', 1], ['x_B_D', 1], ['x_C_A', 1], ['x_C_D', 1], ['x_D_B', 1], ['x_D_C', 1]]
>>> [(x[0][2], x[0][4]) for x in var]
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'D'), ('C', 'A'), ('C', 'D'), ('D', 'B'), ('D', 'C')]
```
>
> I am interested in a more general case, suppose there can be 'x\_word1\_word2' variable names.
>
>
>
Well in that case internet\_user gave you the solution in the comments.
```
>>> var = [['x_A_B', 1], ['x_word1_word2']]
>>> [tuple(x[0].rsplit('_', 2)[1:]) for x in var]
[('A', 'B'), ('word1', 'word2')]
```
(I used `rsplit` constrained to two splits for a very minor efficiency improvement.)
Upvotes: 2 <issue_comment>username_2: The general case would be:
```
[tuple(item[0].split('_')[1:3]) for item in var]
```
And the most general case would be:
```
indices = {1,2}
[tuple([x for i, x in enumerate(item[0].split('_')) if i in indices]) for item in var]
```
But if you have two indices that are one next to another this would be too much.
Upvotes: 2 <issue_comment>username_3: You can use:
```
[tuple(x[0].split('_')[1:]) for x in var]
out: [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'D'), ('C', 'A'), ('C', 'D'), ('D', 'B'), ('D', 'C')]
```
Upvotes: 0 <issue_comment>username_4: The other answers already talk about your specific case. In the more general case, if you're observing that the same value appears multiple times in a comprehension...
```
var2 = [(item[0].split("_")[1], item[0].split("_")[2]) for item in var]
^ ^
```
and you'd like to avoid this repetition. Is that about right?
One way is to use a nested loop, but that's really a code golfing trick...
```
[(parts[1], parts[2] for item in var for parts in [item[0].split("_")]]
# or
[(a, b) for item in var for (_, a, b) in [item[0].split("_")]]
```
but yeah, that wouldn't pass code review...
How about writing a function instead?
```
def extract_parts(item):
parts = item[0].split("_")
return parts[1], parts[2]
[extract_parts(item) for item in var]
# or:
map(extract_parts, var)
```
Upvotes: 1 <issue_comment>username_5: To answer your question with a similar approach to your example, and including your [comment](https://stackoverflow.com/questions/49362449/compact-way-using-generators-with-as-in-python/49362594#comment85725268_49362594):
>
> Yes that works in this case, @internet\_user also suggested this. But
> what if the indices I need are not consecutive, i.e. I need 0 and 2?
>
>
>
The `with...as...` syntax is for context managers, which has a totally different use. However, a work-around is to use for-loop unpacking.
```
var = [['x_A_B', 1], ['x_A_C', 1], ['x_B_A', 1], ['x_B_D', 1], ['x_C_A', 1], ['x_C_D', 1], ['x_D_B', 1], ['x_D_C', 1]]
var2 = [(u, v) for item in var for _, u, v in (item[0].split("_"), )]
print(var2)
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 1,401 | 3,619 | <issue_start>username_0: I am new to CSS grid, I have a nested [grid layout page](https://codepen.io/saravananr/pen/OvbaVK). I could not get a scroll bar for grid child **`div.fieldsContainer`**.
```css
html,body,
.wrapper{
height: 100%;
width: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
.wrapper{
display: grid;
grid-template-rows: 50px 1fr 50px;
}
.header{
border: 1px solid #ddd;
background: lightyellow;
}
.footer{
background: lightpink;
}
.content{
display: grid;
grid-template-columns: 250px 1fr 300px;
grid-gap: 10px;
overflow: hidden;
}
.fieldTypes{
display: grid;
grid-template-rows: 40px 1fr;
}
.fieldTypes .search{
border: 1px solid red;
}
.fieldTypes .fieldsContainer{
display: grid;
grid-template-columns: repeat(3, minmax(70px,1fr));
grid-auto-rows: 50px;
grid-gap: 10px;
}
.card{
padding: 10px;
background: #ddd;
}
```
```html
Header
search
1
2
3
4
5
6
7
8
9
10
11
12
10
11
12
10
11
12
innder content
graphs
Footer
```<issue_comment>username_1: One solution would be to set `overflow-y:auto` on the parent ( `.fieldTypes` ) and `overflow-y:scroll` on `.fieldsContainer`
There is no ' story ' behind this. Just that you have to set a default overflow for the parent to accept it, and then specify overflow-y:scroll( as you want vertical scroll ) on the child.
```css
html,body,
.wrapper{
height: 100%;
width: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
.wrapper{
display: grid;
grid-template-rows: 50px 1fr 50px;
}
.header{
border: 1px solid #ddd;
background: lightyellow;
}
.footer{
background: lightpink;
}
.content{
display: grid;
grid-template-columns: 250px 1fr 300px;
grid-gap: 10px;
overflow: hidden;
}
.fieldTypes{
display: grid;
grid-template-rows: 40px 1fr;
overflow-y:auto;/*added*/
}
.fieldTypes .search{
border: 1px solid red;
}
.fieldTypes .fieldsContainer{
display: grid;
grid-template-columns: repeat(3, minmax(70px,1fr));
grid-auto-rows: 50px;
grid-gap: 10px;
overflow-y:scroll;/*added*/
}
.card{
padding: 10px;
background: #ddd;
}
```
```html
Header
search
1
2
3
4
5
6
7
8
9
10
11
12
10
11
12
10
11
12
innder content
graphs
Footer
```
Upvotes: 6 [selected_answer]<issue_comment>username_2: Here's a more reduced case (to cut through the irrelevant parts)
```css
html, body, .A {
height: 100%; /* matters */
width: 100%;
margin: 0;
padding: 0;
}
.A {
max-height: 300px; /* matters */
display: grid; /* matters */
overflow: hidden; /* matters */
}
.B {
display: grid; /* matters */
overflow-y: auto; /* matters */
}
.D {
overflow-y: scroll; /* matters */
}
.C {
padding: 10px;
background-color: #07f;
}
.E {
padding: 10px;
background-color: #eee;
}
```
```html
search
1
2
3
4
5
6
7
8
9
10
11
12
10
11
12
10
11
12
```
Upvotes: 4 <issue_comment>username_3: Set the parent's height to `100vh`. Then `overflow-y: scroll` will work on the children.
See this example (based on the reduced case answer).
```css
html, body, .A {
margin: 0;
padding: 0;
}
.A {
height: 100vh; /* matters */
display: grid; /* matters */
}
.B {
padding: 10px;
background-color: #07f;
}
.C {
overflow-y: scroll; /* matters */
}
.D {
padding: 10px;
background-color: #eee;
}
```
```html
search
1
2
3
4
5
6
7
8
9
10
11
12
10
11
12
10
11
12
```
Upvotes: 1 |
2018/03/19 | 248 | 1,063 | <issue_start>username_0: Using Multi language(Arabic,English) in Application.
If we set Arabic language as language in the app.For Numbers,Text view showing Arabic number.I want English numbers not Arabic number even if we selected English language.**how to show number in English even if language is in Arabic?**<issue_comment>username_1: By default numbers are displayed in English only, unless you format the string, but it is not a good practice to use digits in English while using language that supports RTL specification. Please refer this: <https://developer.android.com/training/basics/supporting-devices/languages.html#FormatNumbers>
It seems that you are changing language from device setting, please try changing language within the app, changing language from device setting will display numbers in that language.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Ok
Just Try to put Your string and Numbers In formatted String and use this
something like this
```
Hello, %1$s! You have %2$d new messages.
```
and then
```
```
Upvotes: 2 |
2018/03/19 | 1,006 | 3,335 | <issue_start>username_0: I'm trying to implement the macro-function `OR` in Lisp
My attempt:
```
(defmacro or2 (test &rest args)
`(if ,test ,test (if (list ,@args) (or2 ,@args) nil)) )
```
However, if I test with something like this:
```
(or2 (print 1) 2 )
1
1
1
```
Whereas with the default `OR`:
```
(or (print 1) 2)
1
1
```
I understand that this is because of my two `,test` at the beginning of my `if` clause, but I don't see how i could avoid it. How could I avoid applying twice the test effects ?<issue_comment>username_1: How would you solve the problem of side-effects if you had to code it by hand?
```
(or2 (print 1) 2)
```
Intermediate variable
---------------------
Most probably, you would do this:
```
(let ((value (print 1)))
(if value value 2))
```
You need to define a local variable which holds the value of the first expression, so that later you can reference the variable instead of re-evaluating the same expression more than once.
But what if you already have a variable named `value` in the lexical context where you expand the code? What if, instead of `2`, you were referencing that other `value`? This problem is named *variable capture*.
Gensym
------
In Common Lisp, you introduce a fresh symbol, that is guaranteed to not be already bound to anything, using [`GENSYM`](http://www.lispworks.com/reference/HyperSpec/Body/f_gensym.htm).
```
(let ((symbol (gensym)))
`(let ((,symbol ,test))
(if ,symbol ,symbol ...)))
```
Recursive expansion
-------------------
```
(list ,@args)
```
The above is the same as writing directly `,args`.
But you are confusing macroexpansion and execution times. If you inject `args` directly in the code, it will be evaluated (most likely, this is going to fail as a bad function call). What you want instead is to test if `args` is non-null during macroexpansion.
Besides, you should probably first test if your list of expression contains more than one element, in order to simplify the generated code.
Roughly speaking, you have to take into account the following cases:
* `(or2)` is `nil`
* `(or2 exp)` is the same as `exp`
* `(or2 exp &rest args)` is the same as the following, where `var` is a fresh symbol:
```
`(let ((,var ,exp))
(if ,var ,var (or2 ,@args)))
```
Upvotes: 2 <issue_comment>username_2: Please make use of `macroexpand-1`:
```scm
(macroexpand-1 '(or2 (print 1) 2))
; ==> (if (print 1) (print 1) (if (list 2) (or2 2) nil)) ;
; ==> t
```
With macros you wish the order of evaluation to be expected and you wish expressions to only be evaluated once. Thus the expansion should have been something like this:
```scm
(let ((tmp (print 1)))
(if tmp
tmp
(or2 2)))
```
And `tmp` should be a symbol generated by `gensym`. Also when `args` is `nil` you should expand `or2` to only `test`:
```scm
(defmacro or2 (test &rest args)
(if (endp args)
test
(let ((tmp (gensym "tmp")))
`(let ((,tmp ,test))
(if ,tmp
,tmp
(or2 ,@args))))))
```
you can [make use of macros](http://www.gigamonkeys.com/book/macros-defining-your-own.html) to simplify this:
```scm
(defmacro or2 (test &rest args)
(if (endp args)
test
(once-only (test)
`(if ,test
,test
(or2 ,@args)))))
```
Upvotes: 1 |
2018/03/19 | 602 | 2,292 | <issue_start>username_0: I have enabled a diagnostic storage account for my virtual machine. Now I want to change the diagnostic storage account. How do I do it in portal / PowerShell?
I can see that we have a cmdlet - "Set-AzureRmVMBootDiagnostics", however, this is not updating the diagnostic storage account to a new one.
In specific:
My current diagnostic storage is "ibmngeus2" and I would like to change to "sqlbackupacct".<issue_comment>username_1: I got the settings under the "Boot Diagnostic" option under the Virtual machine pane.
Upvotes: 0 <issue_comment>username_2: In the Azure portal, you should be able to click on the boot diagnostics section of the virtual machine, and then click the settings, and then click the storage account section to change the storage account. Keep in mind that the new storage account you want to use must be in the same subscription and location or it will not show up as one you can choose.
[](https://i.stack.imgur.com/gOI0n.png)
Upvotes: 3 [selected_answer]<issue_comment>username_3: In PowerShell (with the [now-deprecated AzureRM module](https://learn.microsoft.com/en-za/powershell/azure/azurerm/overview?view=azurermps-6.13.0)), you can do this:
```
Get-AzureRmVM | Set-AzureRmVMBootDiagnostics -Enable -ResourceGroupName -StorageAccountName | Update-AzureRmVM
```
This will get the VM objects, change the setting and apply the change.
Example, to update **all VMs**' diag storage account to `bucket` in RG `mygroup`:
```
Get-AzureRmVM | Set-AzureRmVMBootDiagnostics -Enable -ResourceGroupName mygroup -StorageAccountName bucket | Update-AzureRmVM
```
(You probably want to filter more...)
For the new [Az module](https://learn.microsoft.com/en-us/powershell/azure/overview), the commands would change to: (same warnings as above will apply)
```
Get-AzVM | Set-AzVMBootDiagnostic -Enable -ResourceGroupName -StorageAccountName | Update-AzVM
Get-AzVM | Set-AzVMBootDiagnostic -Enable -ResourceGroupName mygroup -StorageAccountName bucket | Update-AzVM
```
(There is a [deprecation warning for the plural version of the command](https://github.com/Azure/azure-powershell/issues/8599) - this uses the new name, but the warning still shows)
Upvotes: 0 |
2018/03/19 | 7,193 | 30,635 | <issue_start>username_0: After upgrading Spring boot from 1.5 to 2.0 we keep getting this exception:
```
[PersistenceUnit: default] Unable to build Hibernate SessionFactory
```
Stack trace:
```
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:155)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234)
at com.nevron.backend.BackendApplication.main(BackendApplication.java:14)
Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:125)
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.(TomcatWebServer.java:86)
at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:417)
at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:176)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:179)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:152)
... 8 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcConfig': Unsatisfied dependency expressed through field 'tenantFilter'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'tenantFilter': Unsatisfied dependency expressed through field 'projectService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'projectService': Unsatisfied dependency expressed through field 'settingService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'settingService': Unsatisfied dependency expressed through field 'settingDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'settingDao': Cannot create inner bean '(inner bean)#7127180a' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7127180a': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/nevron/backend/config/HibernateConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:205)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:226)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:214)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addServletContextInitializerBeans(ServletContextInitializerBeans.java:91)
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.(ServletContextInitializerBeans.java:79)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getServletContextInitializerBeans(ServletWebServerApplicationContext.java:250)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.selfInitialize(ServletWebServerApplicationContext.java:237)
at org.springframework.boot.web.embedded.tomcat.TomcatStarter.onStartup(TomcatStarter.java:54)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5204)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'tenantFilter': Unsatisfied dependency expressed through field 'projectService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'projectService': Unsatisfied dependency expressed through field 'settingService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'settingService': Unsatisfied dependency expressed through field 'settingDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'settingDao': Cannot create inner bean '(inner bean)#7127180a' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7127180a': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/nevron/backend/config/HibernateConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 33 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'projectService': Unsatisfied dependency expressed through field 'settingService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'settingService': Unsatisfied dependency expressed through field 'settingDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'settingDao': Cannot create inner bean '(inner bean)#7127180a' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7127180a': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/nevron/backend/config/HibernateConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 46 common frames omitted
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'settingService': Unsatisfied dependency expressed through field 'settingDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'settingDao': Cannot create inner bean '(inner bean)#7127180a' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7127180a': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/nevron/backend/config/HibernateConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 59 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'settingDao': Cannot create inner bean '(inner bean)#7127180a' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7127180a': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/nevron/backend/config/HibernateConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:327)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:131)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1613)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1357)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
... 72 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#7127180a': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/nevron/backend/config/HibernateConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:378)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:110)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:622)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:440)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:312)
... 85 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/nevron/backend/config/HibernateConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:367)
... 93 common frames omitted
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:970)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:895)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:388)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706)
... 100 common frames omitted
Caused by: org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.UnionSubclassEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:112)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:128)
at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:300)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:460)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
... 107 common frames omitted
Caused by: java.lang.NullPointerException: null
at org.hibernate.persister.entity.AbstractPropertyMapping.getSuperCollection(AbstractPropertyMapping.java:285)
at org.hibernate.persister.entity.AbstractPropertyMapping.addPropertyPath(AbstractPropertyMapping.java:198)
at org.hibernate.persister.entity.AbstractPropertyMapping.initPropertyPaths(AbstractPropertyMapping.java:395)
at org.hibernate.persister.entity.AbstractEntityPersister.initOrdinaryPropertyPaths(AbstractEntityPersister.java:2300)
at org.hibernate.persister.entity.AbstractEntityPersister.initPropertyPaths(AbstractEntityPersister.java:2347)
at org.hibernate.persister.entity.AbstractEntityPersister.postConstruct(AbstractEntityPersister.java:3906)
at org.hibernate.persister.entity.UnionSubclassEntityPersister.(UnionSubclassEntityPersister.java:213)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 112 common frames omitted
```
We are using a multi tenant system. Tenants are separated by schemas in the database.
Our entity manager factory looks like this:
```
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, MultiTenantConnectionProvider multiTenantConnectionProviderImpl, CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl) {
Map properties = new HashMap<>(jpaProperties.getHibernateProperties(dataSource));
properties.put(Environment.MULTI\_TENANT, MultiTenancyStrategy.SCHEMA);
properties.put(Environment.MULTI\_TENANT\_CONNECTION\_PROVIDER, multiTenantConnectionProviderImpl);
properties.put(Environment.MULTI\_TENANT\_IDENTIFIER\_RESOLVER, currentTenantIdentifierResolverImpl);
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("com.nevron.backend");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaPropertyMap(properties);
return em;
}
```
In version 2.0 this line is also problematic:
```
Map properties = new HashMap<> jpaProperties.getHibernateProperties(dataSource));
```
Because the function 'getHibernateProperties' expects 'HibernateSettings'.
How to solve this problem?
Is there any other way to implement multi tenant in Spring Boot 2.0?<issue_comment>username_1: Yes the method signature for getHibernateProperties has changed from version 1.x to 2.x. Try changing your line
```
Map properties = new HashMap<>(jpaProperties.getHibernateProperties(dataSource));
```
to
```
Map properties = new HashMap<>(jpaProperties.getHibernateProperties(new HibernateSettings()));
```
Upvotes: 2 <issue_comment>username_2: I updated Spring Boot to 2.0.1 (build snapshot) and now is working.
Upvotes: 3 [selected_answer]<issue_comment>username_3: Change your code to be something like this:
```
Map hibernateProps = new LinkedHashMap<>();
hibernateProps.putAll(this.jpaProperties.getProperties());
hibernateProps.put(Environment.MULTI\_TENANT, MultiTenancyStrategy.DATABASE);
hibernateProps.put(Environment.MULTI\_TENANT\_CONNECTION\_PROVIDER, multiTenantConnectionProvider);
hibernateProps.put(Environment.MULTI\_TENANT\_IDENTIFIER\_RESOLVER, currentTenantIdentifierResolver);
```
The code snippet abobe is from a multi-tenant web application example (with complete source code) built using Spring Boot 2. [Take a look](https://username_3.blogspot.com/2018/04/building-saas-style-multi-tenant-web.html).
Upvotes: 1 <issue_comment>username_4: I know I'm late to the party, but my answer may help someone who is trying to switch schemas in Multi-tenant Env and upgraded to latest SpringBoot version.
We need to pass HibernateProperties to the method to get the properties as the signature for getHibernateProperties has changed from version 1.x to 2.x. (Pointed out by username_1)
```
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
MultiTenantConnectionProvider multiTenantConnectionProviderImpl,
CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl,
HibernateProperties hibernateProperties) {
Map properties = hibernateProperties.determineHibernateProperties(
jpaProperties.getProperties(), new HibernateSettings());
properties.put(Environment.MULTI\_TENANT, MultiTenancyStrategy.SCHEMA);
properties.put(Environment.MULTI\_TENANT\_CONNECTION\_PROVIDER, multiTenantConnectionProviderImpl);
properties.put(Environment.MULTI\_TENANT\_IDENTIFIER\_RESOLVER, currentTenantIdentifierResolverImpl);
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("com.nevron.backend");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaPropertyMap(properties);
return em;
}
```
Upvotes: 1 |
2018/03/19 | 571 | 2,253 | <issue_start>username_0: I have this formrequest that contains rules and a withValidator as a second layer of validation.
Note: I am aware that having it unique on the rules would supress the need for this example, but I'll need to do further validations here.
```
public function rules(Request $request) {
return [
"name" => "required|max:191",
"begin_date" => "required|after_or_equal:today|date_format:d-m-Y",
"end_date" => "required|after:begin_date|date_format:d-m-Y",
];
}
public function withValidator($factory) {
$result = User::where('name', $this->name)->get();
if (!$result->isEmpty()) {
$factory->errors()->add('User', 'Something wrong with this guy');
}
return $factory;
}
```
I am positive that it enters the `if` as I've placed a dd previously it to check if it's going inside. However, it proceeds to this method on the Controller and I don't want it to.
```
public function justATest(UserRequest $request) {
dd("HI");
}
```<issue_comment>username_1: I'm an idiot and didn't read the full doc.
It needs to specify with an after function,like this:
```
public function withValidator($factory) {
$result = User::where('name', $this->name)->get();
$factory->after(function ($factory) use ($result) {
if (!$result->isEmpty()) {
$factory->errors()->add('User', 'Something wrong with this guy');
}
});
return $factory;
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: I was facing this problem too.
I changed my withValidator to this:
```
public function withValidator($validator)
{
if (!$validator->fails()) {
$validator->after(function ($validator) {
if (Cache::has($this->mobile)) {
if (Cache::get($this->mobile) != $this->code) {
$validator->errors()->add('code', 'code is incorrect!');
} else {
$this->user = User::where('mobile', $this->mobile)->first();
}
} else {
$validator->errors()->add('code', 'code not found!');
}
});
}
```
Upvotes: 0 |
2018/03/19 | 1,239 | 4,989 | <issue_start>username_0: I have a main component with a child chart component. On connecting to a websocket, the main component updates the state of the child chart component. This however does not redraw. When I click on the chart however, the labels appear, and when I click again, the values appear with the labels.
Main.js:
```
import IO from 'socket.io-client';
import React from "react";
import { Switch, Route } from 'react-router-dom';
import { Chart } from "./Chart";
let ftse100Tickers = require('./ftse_100_tickers.json');
let randomInt = Math.floor(Math.random() * ftse100Tickers.tickers.length);
/**
* Main application component which contains
*/
export class Main extends React.Component {
componentWillMount() {
this.socket = IO(location.protocol + "//" + document.domain + ":" + location.port);
this.socket.on("connect", (() => this.connect()));
this.socket.on("disconnect", (() => this.disconnect()));
this.socket.on("initial data", ((data) => this.createInitialChart(data)))
}
connect(){
this.setState({status: 'connected'});
this.socket.emit("get initial data", this.state.ticker);
}
disconnect(){
this.setState({status: 'disconnected'})
}
createInitialChart(data){
let tempErrorChart= this.state.errorChart;
for (let row of data){
tempErrorChart.labels.push(row.time_stamp);
tempErrorChart.datasets[0].data.push(row.error);
}
this.setState({errorChart: tempErrorChart});
}
constructor(props){
super(props);
this.state = {
errorChart: {
labels: [],
datasets: [
{
label: 'Error',
data: [],
},
]
},
status: 'disconnected',
ticker : ftse100Tickers.tickers[randomInt],
twitter : ftse100Tickers.twitter[randomInt]
}
}
render() {
return (
)
}
}
```
The chart component is as so:
Chart.js
```
import { Line } from "react-chartjs-2"
import React from "react";
/*
* General charting component used for rendering charts
*/
export class Chart extends React.Component {
render() {
return (
)
}
}
```<issue_comment>username_1: You might need componentWillReceiveProps(nextProps, nextState).
You can compare the old state here with the new state and update the state accordingly.
Please set the initialState like so:
```
constructor(props){
super(props);
this.state = {errorChart: {...}}; //your initial values here.
}
```
then,
```
componentWillReceiveProps(nextProps, nextState){
if(this.state.errorChart !== nextState.errorChart){
let tempErrorChart = {...this.state.errorChart};
for (let row of data){
tempErrorChart.labels.push(row.time_stamp);
tempErrorChart.datasets[0].data.push(row.error);
}
this.setState({errorChart: tempErrorChart});
}
}
```
Upvotes: 0 <issue_comment>username_2: I see one problem and that is you are not changing object references in `this.state.errorChart` upon errorChart update before you call `setState`. Even though you push to its properties new items, the object and even the inner array references do not change, and if the Line component does some props checking on whether it should rerender itself or not, it figures by receiving still the same references that nothing has changed and there is no need to rerender.
Now this was just my assumption, but either way it is a good practice to **always create new objects while creating new state** once those objects are about to be modified. This allows for fast object (state) references comparisons in `shouldComponentUpdate` methods or while using `PureComponent`which in turn makes it easier and more performant to determine whether to rerender the component or not. On the other hand, if you would use the same references still, you would have to implement deep comparison of the old and the new state, which is definitely more expensive and very fragile in the long run.
Example on how to correctly update the state follows:
```
createInitialChart(data) {
const errorChart = this.state.errorChart
const newErrorChart = {
...errorChart
}
newErrorChart.labels = [...errorChart.labels, data.map(row => row.time_stamp)]
newErrorChart.datasets[0].data = [
...errorChart.datasets[0].data,
data.map(row => row.error)
]
this.setState({ errorChart: newErrorChart })
}
```
**Edit:**
By looking at the component's `shouldComponentUpdate` implementation - [ChartComponent](https://github.com/jerairrest/react-chartjs-2/blob/master/src/index.js), It can be clearly seen, that there are multiple options on how to make the **Line** rerender, eg. by giving `redraw={true}` prop to the **Line** component. The procedure above is generally still the safest way to ensure rerender though.
Upvotes: 3 |
2018/03/19 | 653 | 2,702 | <issue_start>username_0: I have the following piece of codeοΌ
```
// using Windows.Storage;
internal static class AppData {
private static ApplicationDataContainer container;
public static bool FirstTime { get; } = !GetContainer("UserInfo").Values.ContainsKey("complete");
static AppData() {
container = ApplicationData.Current.LocalSettings;
}
private static ApplicationDataContainer GetContainer(string name) {
return container.CreateContainer(name,ApplicationDataCreateDisposition.Always);
}
}
```
>
> NullReferenceException: Object reference not set to an instance of an object.
>
>
>
I don't know why it's wrong. Make some changes to the code
```
// using Windows.Storage;
internal static class AppData {
private static ApplicationDataContainer container;
public static bool FirstTime => !GetContainer("UserInfo").Values.ContainsKey("complete");
static AppData() {
container = ApplicationData.Current.LocalSettings;
}
private static ApplicationDataContainer GetContainer(string name) {
return container.CreateContainer(name,ApplicationDataCreateDisposition.Always);
}
}
```
>
> OK, No error.
>
>
>
Why?<issue_comment>username_1: I'll have to look up [the reference](https://stackoverflow.com/a/8285210/5311735) but the issue is that
```
public static bool FirstTime { get; } = ....;
```
is an initializer. And as an initializer it is executed just before the constructor.
When you change it to a function (or readonly lambda property), it is a normal member and it gets executed after the constructor.
Upvotes: 4 [selected_answer]<issue_comment>username_2: There is a big difference in the two syntaxes:
```
public static bool Property { get; set; } = true;
```
This is a property initialization syntax and is evaluated before any constructor runs. The property can have a setter as well here.
```
public static bool Property => true;
```
This is an expression property, get-only and the right hand side is evaluated only when it is called. This also means that it is evaluated each time it is accessed, so it is not a good design choice to use a complex method call on the right-hand side for example.
Also if you want to have the expression syntax while ensuring the right-hand side will be evaluated only when actually needed and only once, you can combine this syntax with a private field:
```
private static bool? _property;
public static bool Property => _property ?? ( _property = CalculateProperty() );
```
This will first check if the private backing field is `null` and if yes, initialize it, while the assignment itself will then return the assigned value as well.
Upvotes: 2 |
2018/03/19 | 1,316 | 4,907 | <issue_start>username_0: I've been going through the angularfire2 documentation to retrieve a downloadURl from storage. I'm hoping I'm missing something simple here.
The documentation states:
```
@Component({
selector: 'app-root',
template: `![]()`
})
export class AppComponent {
profileUrl: Observable;
constructor(private storage: AngularFireStorage) {
const ref = this.storage.ref('users/davideast.jpg');
this.profileUrl = ref.getDownloadURL();
}
}
```
However, once I've uploaded an image I want to return the download url as a string to upload to firestore. I need the download URL for an external service.
**My function**
```
uploadImage(base64data) {
const filePath = (`myURL/photo.jpg`);
const storageRef = firebase.storage().ref();
var metadata = {
contentType: 'image',
cacheControl: "public, max-age=31536000",
};
const ref = this.storage.ref(filePath);
const task = ref.putString(base64data, 'data_url', metadata).then(() => {
var downloadURL = ref.getDownloadURL();
})
}
```
This uploads the image perfectly fine. However, I would then like to write the download URL to firestore. When console logging my 'downloadURL' variable, I get the following:
>
> PromiseObservableΒ {\_isScalar: false, promise: y, scheduler: undefined}
>
>
>
The download is inside the promise observable. How do I just get the download URL string as my variable? Once I have that I can sort the firestore updates out.<issue_comment>username_1: **This answer is not relevant from Firebase 5.0 release, they removed downloadURL() from upload task.** Please refer to [doc](https://github.com/angular/angularfire2/blob/master/docs/storage/storage.md#example-usage).
The `.downloadURL()` observable emits the download URL string once the upload is completed. Then you need to subscribe to get the value.
```
uploadImage(base64data) {
const filePath = (`myURL/photo.jpg`);
//const storageRef = firebase.storage().ref();
var metadata = {
contentType: 'image',
cacheControl: "public, max-age=31536000",
};
const ref = this.storage.ref(filePath);
const task = ref.putString(base64data, 'data_url', metadata);
const downloadURL = task.downloadURL();
downloadURL.subscribe(url=>{
if(url){
console.log(url);
//wirte the url to firestore
}
})
}
```
Hope this helps. check this blog for more [detail](https://blog.angular.io/file-uploads-come-to-angularfire-6842352b3b47)
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
//observable to store download url
downloadURL: Observable;
task.snapshotChanges().pipe(
finalize(() => {
this.downloadURL = fileRef.getDownloadURL();
this.downloadURL.subscribe(url=>{this.imageUrl = url})
})
)
```
refer :<https://github.com/ReactiveX/rxjs/blob/master/doc/observable.md>
Upvotes: 3 <issue_comment>username_3: `.downloadURL()` doesn't works longer anymore, you need to use `.getDownloadURL()` combined with `finalize()` like so:
**.html** file
```
```
**.ts** file
```
import {
AngularFireStorage,
AngularFireStorageReference,
AngularFireUploadTask
} from '@angular/fire/storage';
import { Component } from '@angular/core';
import { finalize } from 'rxjs/operators';
@Component({
selector: 'app-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.scss']
})
export class UploadComponent {
constructor(private angularFireStorage: AngularFireStorage) {}
public uploadFile(event: any): void {
for (let i = 0; i < event.target.files.length; i++) {
const file = event.target.files[i];
const fileRef: AngularFireStorageReference = this.angularFireStorage.ref(
file.name
);
const task: AngularFireUploadTask = this.angularFireStorage.upload(
file.name,
file
);
task
.snapshotChanges()
.pipe(
finalize(() => {
fileRef.getDownloadURL().subscribe(downloadURL => {
console.log(downloadURL);
});
})
)
.subscribe();
}
}
}
```
Also, note the **@angular/fire**, it's because all **AngularFire2** package is moving into **@angular/fire** and this is the recommended way to use from now onwards.
Upvotes: 2 <issue_comment>username_4: Nesting subscriptions is an antipattern so instead of subscribing in `finalize` you should use `last` + `switchMap` or `concat` + `defer`.
**last + switchMap**
```js
task.snapshotChanges().pipe(
last(),
switchMap(() => fileRef.getDownloadURL())
).subscribe(url => console.log('download url:', url))
```
**concat + defer**
```js
concat(
task.snapshotChanges().pipe(ignoreElements()),
defer(() => fileRef.getDownloadURL())
).subscribe(url => console.log('download url:', url))
```
Upvotes: 3 |
2018/03/19 | 410 | 1,670 | <issue_start>username_0: I have a .NET application on a Windows machine and a Cassandra database on a Linux (CentOS) server. The Windows machine **might be with a couple of seconds in the past** sometimes and when that thing happens, the deletes or updates queries does not take effect.
Does Cassandra require all servers to have the same time? Does the Cassandra driver send my query with timestamp? (I just write simple delete or update query, with not timestamp or TTL).
Update: I use the [Datastax C# driver](https://github.com/datastax/csharp-driver)<issue_comment>username_1: Cassandra operates on the "last write wins" principle. The system time is therefore critically important in determining which writes succeed. Google for "cassandra time synchronization" to find [results like this](https://blog.rapid7.com/2014/03/14/synchronizing-clocks-in-a-cassandra-cluster-pt-1-the-problem/) and [this](https://blog.rapid7.com/2014/03/17/synchronizing-clocks-in-a-cassandra-cluster-pt-2-solutions/) which explain why time synchronization is important and suggests a method to solve the problem utilizing an internal NTP pool. The articles specifically refer to AWS architecture, but the principals apply to any cassandra installation.
Upvotes: 3 <issue_comment>username_2: The client timestamps are used to order mutation operations relative to each other.
The [DataStax C# driver uses a generator to create them](https://docs.datastax.com/en/developer/csharp-driver/latest/features/query-timestamps/), it's important for all the hosts running the client drivers (origin of the execution request) to have clocks in sync with each other.
Upvotes: 3 [selected_answer] |
2018/03/19 | 612 | 2,159 | <issue_start>username_0: I currently trying to get myself familiar with react and the state of a component.
I am trying to create a component, use the constructor to initialise the state, do a get request to the server to get an array of object and finally I am trying to update the state of the component accordingly. But I end up with the following error and I can't understand the problem:
>
> Objects are not valid as a React child (found: object with keys {title, content}).
>
>
>
My code looks like this:
```
import React, { Component } from 'react';
import axios from "axios";
class Display extends Component {
constructor(){
super();
this.state = { posts: []}
}
componentDidMount(){
this.fetchData();
}
fetchData(){
const ROOT_URL = "http://localhost:5000";
axios.get(`${ROOT_URL}/api/post`)
.then(response => response.data.map(post => (
{
title: post.title,
content: post.content
}))
)
.then(
posts => {
this.setState({
posts
})
}
)
}
render(){
const { posts } = this.state;
return (
List of Posts:
{this.state.posts}
)
}
}
export default Display;
```
Does anyone know what am I doing wrong?
Thanks<issue_comment>username_1: this.state.posts is an object like
```
{
title: post.title,
content: post.content
}
```
and hence you can't render it direct like
```
List of Posts:
{this.state.posts}
```
You might as well render it like
```
List of Posts:
{this.state.posts.map((post) => {
return
{post.title}
{post.content}
})
```
above is assuming that `content` is also not an `object` or `array`. Check [How to render an array of objects](https://stackoverflow.com/questions/41374572/how-to-render-an-array-of-objects-in-react/41374730#41374730) for more details
Upvotes: 1 <issue_comment>username_2: You would need to iterate over the `posts` array and return the html you want to display
Something like this
```
List of Posts:
{this.state.posts.map(post=>(
{post.title}
{post.content}
))}
```
Upvotes: 0 |
2018/03/19 | 492 | 2,060 | <issue_start>username_0: There is no error But I am unable to configuration httponly status in browser.
Can you check my code please.
```
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddMvc();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
app.UseStaticFiles();
app.UseCookiePolicy(new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.Always,
Secure =CookieSecurePolicy.Always,
MinimumSameSitePolicy=SameSiteMode.None
});
}
```<issue_comment>username_1: According to the [documentation](https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x) you can configure `HttpOnly` via `IApplicationBuilder.UseCookiePolicy()`:
```
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
/*..*/
app.UseStaticFiles();
app.UseSession();
app.UseCookiePolicy(new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.Always
});
}
```
Upvotes: 2 <issue_comment>username_2: In ASP.NET Core 2.X you can use the following code:
```
public void ConfigureServices(IServiceCollection services)
{
// This can be removed after https://github.com/aspnet/IISIntegration/issues/371
services.AddAuthentication(
options =>
{
//Blah Blah Blah
}).AddCookie(opts =>
{
opts.Cookie.HttpOnly = false;
});
}
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
}
```
Note that this changed from ASP.NET Core 1.X
Upvotes: 2 |
2018/03/19 | 1,144 | 3,070 | <issue_start>username_0: ```
var foo = { "a": [1,2,3] }
var bar = { "b": [7,8,9] }
```
output should look like this
```
[ {a: 1, b: 7}, {a: 2, b: 8}, {a:3, b: 9}]
```
How can I do this using ramda or javascript functional programming ?
I have done this using for loop i = 0, is it possible using functional ramda programming<issue_comment>username_1: If both arrays are always the same length, you can do this using `map`.
```js
function mergeArrays(arr1, arr2) {
return arr1.map(function(item, index) {
return {
a: arr1[index], //or simply, item
b: arr2[index]
};
});
}
var a = [1, 2, 3];
var b = [7, 8, 9];
var joined = mergeArrays(a, b);
document.getElementById('result').innerHTML = JSON.stringify(joined, null, 2);
```
```html
```
```
```
Upvotes: 2 <issue_comment>username_2: i am having an array
>
> const peopleObject = { "123": { id: 123, name: "dave", age: 23 },
>
> "456": { id: 456, name: "chris", age: 23 }, "789": { id: 789, name:
> "bob", age: 23 }, "101": { id: 101, name: "tom", age: 23 }, "102":
> { id: 102, name: "tim", age: 23 } }
>
>
>
for this particular i have created a code that convrts array to object i hope this is usefull for you
```
const arrayToObject = (array) =>
array.reduce((obj, item) => {
obj[item.id] = item
return obj
}, {})
const peopleObject = arrayToObject(peopleArray)
console.log(peopleObject[idToSelect])
```
Upvotes: 0 <issue_comment>username_3: Your expected output doesn't have a valid format. You should store the data in array. Like ,
```
var output = [];
var a = [1,2,3], b = [7,8,9];
for(var i=0; i< a.length; i++){
var temp = {};
temp['a'] = a[i];
temp['b'] = b[i];
output.push(temp);
}
```
You cannot store the result in an object the way you want. Objects are key-value pairs. But what you expect is only the values without keys which is not possible!
Upvotes: 0 <issue_comment>username_4: Assuming you want `[{a:1,b:7},{a:2,b:8},{a:3,b:9}]` it can be done pretty easily with map using the index to get the value in b:
```
var result = a.map((v, i) =>({ a: v, b: b[i] }));
```
Upvotes: 1 <issue_comment>username_5: You can achieve this using [`R.transpose`](http://ramdajs.com/docs/#transpose) to convert an array of `[[1,2,3], [7,8,9]]` to `[[1, 7], [2, 8], [3, 9]]` and then map over it with [`R.zipObj`](http://ramdajs.com/docs/#zipObj).
```js
const fn = R.compose(
R.map(R.zipObj(["a", "b"])),
R.transpose
)
const a = [1, 2, 3], b = [7, 8, 9]
const result = fn([a, b])
console.log(result)
```
If you would prefer to pass `a` and `b` as two arguments to `fn` rather than an array then you can swap `R.transpose` in the example above with `R.unapply(R.transpose)`.
Upvotes: 2 <issue_comment>username_6: create function form ramda's `addIndex` and `map`
```
const data = { keys: ['a', 'b', 'c'], values: ['11', '22', '33'] }
const mapIndexed = R.addIndex(R.map)
const result = mapIndexed((item, i) => {
return { [item]: data.values[i] }
}, data.keys)
```
You will get an array of objects
Upvotes: 0 |
2018/03/19 | 780 | 2,503 | <issue_start>username_0: I have table:
```
Id Value
1 79868
2 79868
3 79868
4 97889
5 97889
```
Now, I want to make next select with bool variable that check if table contains difrent values at table column `Value`. Something like this:
```
select
v= (select case when exists(...)
then 1
else 0
end)
```
Table contais Values: 79868, 97889 so `v` should return 1 in other case 0.
How to write select iniside select case??<issue_comment>username_1: You can compare the min and max values:
```
select (case when (select min(value) from t) = (select max(value) from t)
then 1 else 0
end) as all_same
```
With an index on `(value)`, this should be quite fast.
The above solution assumes that there are no `null` values or that `NULL` values should be ignored.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You might try this:
```
SELECT CASE COUNT(*)
WHEN 1 THEN 1
ELSE 0
END AS all_equal
FROM (SELECT DISTINCT Value FROM my_table);
```
Upvotes: 2 <issue_comment>username_3: So, you just need one `case` expression with two Boolean variable
```
declare @bit1 bit = 1, @bit0 bit = 0
select
(case when min(value) = max(value) then @bit1 else @bit0 end) as v
from table t
where value is not null
```
Upvotes: 0 <issue_comment>username_4: If I get your question correct, you want to check if value column contains more than 1 distinct values. You can achieve this using,
```
select (case when count(value) > 1 then 1 else 0 end) as out
from (select value from table group by value) temp
```
Upvotes: 1 <issue_comment>username_2: May this is better:
```
SELECT CASE COUNT(DISTINCT value) WHEN 1 THEN 1
ELSE 0
END AS all_equal
FROM my_table;
```
Upvotes: 0 <issue_comment>username_5: This is a the same as another answers
But is has some test data
```
declare @T table(pk int identity primary key, val int not null);
insert into @T (val) values (79868), (79868), (79868);
select case when count(distinct(val)) = 1 then 0 else 1 end as dd
from @t t;
select case when min(val) = max(val) then 0 else 1 end as dd
from @t t;
insert into @T (val) values (97889), (97889);
select case when count(distinct(val)) = 1 then 0 else 1 end as dd
from @t t;
select case when min(val) = max(val) then 0 else 1 end as dd
from @t t;
```
I like the min max answer from Gordon best
Upvotes: 0 |
2018/03/19 | 777 | 2,837 | <issue_start>username_0: I have written a test that mocks the sumbitChoice() function as this function is responsible for an API call. The function is called on clicking the button, '#buttonOption1'.
Currently, the test's assertion fails i.e. 'Expected mock function to have been called.'
**App.test.js**
```
import React from 'react';
import App from './App';
import { mount, shallow } from 'enzyme';
import { waitForState } from 'enzyme-async-helpers';
describe('App', () => {
it('should call the submitChoice method on click' , () => {
//arrange
const mockSubmitChoice = jest.fn();
const app = mount();
//act
app.find('#buttonOption1').simulate('click');
//assert
expect(mockSubmitChoice).toBeCalled();
})
})
```
**App.js**
```
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = { imageURLs: [] }
}
componentDidMount() {
fetch('/comparison')
.then(res => res.json())
.then(images => this.setState({
imageURLs: [...this.state.imageURLs, images]
}))
// .bind(this);
console.log(this.state)
}
submitChoice(data) {
fetch('/comparison', {
method: 'POST',
body: JSON.stringify([...this.state.imageURLs, data]),
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
render() {
return (


Select Option 1
);
}
}
export default App;
```<issue_comment>username_1: Try to bind your `this.submitChoice()` function in the constructor.
```
this.submitChoice = this.submitChoice.bind(this)
```
Upvotes: 0 <issue_comment>username_2: You are not binding your function to onClick event, you are calling it and since it return nothing you are basically binding undefined to onclick.
this:
```
onClick={this.submitChoice(this.state.imageURLs[0])}
```
is same as this:
```
onClick-{undefined}
```
because
```
console.log(this.submitChoice(this.state.imageURLs[0])) // output will be undefined
```
so just change your code like this:
```
onClick={this.submitChoice}
```
and find another way to pass data, since you are just passing static dammy data it should not be much issue anyway.
Upvotes: 0 <issue_comment>username_3: I went for a different test method in the end. This passes:
```
it('should call the submitChoice method on click', () => {
//arrange
const spy = jest.spyOn(App.prototype, 'submitChoice');
const app = shallow();
//act
const button = app.find('#buttonOption1')
button.simulate('click');
//assert
expect(spy).toBeCalled();
})
```
Upvotes: 1 |
2018/03/19 | 2,416 | 9,218 | <issue_start>username_0: I'm new in angular.
I create new project in-memory-web-api, all worked but i must add method in player.ts who upperCase me player object in app.component.ts
the player is a object and i must generate upperCase method in player.ts who upperCase me player object in app.component.ts
How i can do this?
Now i have upperCase method in app.component.ts and working but how i can create method upperCase in player.ts ?
My project:
app.component.ts:
```
import { Component, OnInit } from '@angular/core';
import { PlayerService } from './player.service';
import { PlayerNationality } from './player';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private playerService: PlayerService) {}
players: PlayerNationality[];
formPlayer: PlayerNationality;
showForm: boolean;
newForm: boolean;
ngOnInit(): void {
this.getPlayers();
}
getPlayers(): void {
this.playerService.getPlayer().subscribe(players => this.players = players);
}
addOrUpdatePlayer(player: PlayerNationality) {
if(this.newForm) {
this.playerService.addPlayer(player).subscribe(add => this.players.push(add));
}
else {
this.playerService.updatePlayer(player).subscribe(() => {});
}
this.newForm = false;
this.hidePlayerForm();
}
deletePlayer(player: PlayerNationality) {
this.playerService.deletePlayer(player).subscribe(() => this.deletePlayerFromList(player));
}
deletePlayerFromList(player: PlayerNationality) {
const index = this.players.indexOf(player, 0)
if(index > -1) {
this.players.splice(index, 1);
}
}
upperCase(player: PlayerNationality) {
player.name = player.name.toUpperCase();
player.last = player.last.toUpperCase();
player.nationality = player.nationality.toUpperCase();
console.log(player);
}
playerChange(player) {
player.name = player.last;
player.last = player.nationality;
}
showPlayerForm(player: PlayerNationality) {
if(!player) {
player = new PlayerNationality()
this.showForm = true;
this.newForm = true;
}
this.showForm = true;
this.formPlayer = player;
}
hidePlayerForm() {
this.showForm = false;
}
}
```
player.service.ts:
```
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { PlayerNationality } from './player';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { PlayerNationalityData } from './player-data';
@Injectable()
export class PlayerService {
constructor(private http: Http) {}
private url = 'app/players';
private headers = new Headers({'Content-Type': 'application/json'})
private options = new RequestOptions({ headers: this.headers });
getPlayer(): Observable {
return this.http.get(this.url).map(response => response.json());
}
addPlayer(player: PlayerNationality): Observable {
return this.http.post(this.url, player, this.options).map(response => response.json());
}
updatePlayer(player: PlayerNationality): Observable {
const updateUrl = `${this.url}/${player.id}`
return this.http.put(updateUrl, player, this.options).map(response => response.json());
}
deletePlayer(player: PlayerNationality): Observable {
const deleteUrl = `${this.url}/${player.id}`
return this.http.delete(deleteUrl).map(response => response.json());
}
}
```
player.ts:
```
import { PlayerService } from './player.service';
export class PlayerNationality {
id: number;
name: String;
last: String;
nationality: String;
}
```
player-data.ts:
```
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class PlayerNationalityData implements InMemoryDbService {
createDb() {
const players = [
{id: 1, name: 'Joseph', last: 'Dart', nationality: 'Scotland'},
{id: 2, name: 'Joseph', last: 'Dart', nationality: 'Scotland'},
{id: 3, name: 'Joseph', last: 'Dart', nationality: 'Scotland'}
];
return {players};
}
}
```<issue_comment>username_1: Since `PlayerNationality` is a class itself, it can have some methods.
Also, why do you `import { PlayerService } from './player.service';` in `player.ts`. Seems unnecessary to me.
```
export class PlayerNationality {
// if your constructor has some inputs with `public`, `protected` or `private`,
// typescript will create those field for you in your class.
constructor(
public id: number,
public name: string,
public last: string,
public nationality: string) {
this.upperCase(); // call upperCase to make everything upper case
}
upperCase() {
this.name = this.name.toUpperCase();
this.last = this.last.toUpperCase();
this.nationality = this.nationality.toUpperCase();
}
}
```
in `player-data.ts`
```
export class PlayerNationalityData implements InMemoryDbService {
createDb() {
const players: PlayerNationality[] = [
new PlayerNationality(1, 'Joseph', 'Dart', 'Scotland'),
new PlayerNationality(2, 'Joseph', 'Dart', 'Scotland'),
new PlayerNationality(3, 'Joseph', 'Dart', 'Scotland')
];
}
}
```
Upvotes: 0 <issue_comment>username_2: You need to make the response json from the server a type of `PlayerNationality` and not just an object.
I am a fan of having a constructor for my transfer objects that take a partial of that object and then set the appropriate properties. Example:
```js
export class PlayerNationality {
id: number;
name: String;
last: String;
nationality: String;
constructor(player: Partial) {
Object.entries(player).forEach(([key, value]) => {
if(!(this[key] instanceof Function)) {
this[key] = value;
}
});
}
public upperCase(){
this.name = this.name.toUpperCase();
this.last = this.last.toUpperCase();
this.nationality = this.nationality.toUpperCase();
}
}
```
```js
@Injectable()
export class PlayerService {
getPlayer(): Observable {
return this.http.get(this.url).map(response => response.json().map((p) => new PlayerNationality(p)));
}
addPlayer(player: PlayerNationality): Observable {
return this.http.post(this.url, player, this.options).map(response => new PlayerNationality(response.json()));
}
updatePlayer(player: PlayerNationality): Observable {
const updateUrl = `${this.url}/${player.id}`
return this.http.put(updateUrl, player, this.options).map(response => new PlayerNationality(response.json()));
}
deletePlayer(player: PlayerNationality): Observable {
const deleteUrl = `${this.url}/${player.id}`
return this.http.delete(deleteUrl).map(response => new PlayerNationality(response.json()));
}
}
```
Upvotes: 0 <issue_comment>username_3: I can't quite understand your question. But you are doing it wrong,,,
But if you want to have upperCase method in player.ts
```
//import { PlayerService } from './player.service'; //remove this line.. you don't need this import of a service class since this is a model class
export class PlayerNationality {
public id: number;
public name: String;
public last: String;
public nationality: String;
//note this method will change the case to uppercase of "name", "last","nationality"
toUpperCase(){
this.name=this.name.toUpperCase();
this.last=this.last.toUpperCase();
this.nationality=this.nationality.toUpperCase();
}
}
```
Now you can call this method from anywhere if you have the *PlayerNationality* object
PlayerService.ts
```
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { PlayerNationality } from './player';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { PlayerNationalityData } from './player-data';
@Injectable()
export class PlayerService {
constructor(private http: Http) {}
private url = 'app/players';
private headers = new Headers({'Content-Type': 'application/json'})
private options = new RequestOptions({ headers: this.headers });
getPlayer(): Observable {
return this.http.get(this.url).map(response => response.json());
}
addPlayer(player: PlayerNationality): Observable {
return this.http.post(this.url, player, this.options).map(response => response.json());
}
updatePlayer(player: PlayerNationality): Observable {
const updateUrl = `${this.url}/${player.id}`
//suppose you want to have playerNationality to uppercase here...
player.toUpperCase(); //add line
return this.http.put(updateUrl, player, this.options).map(response => response.json());
}
deletePlayer(player: PlayerNationality): Observable {
const deleteUrl = `${this.url}/${player.id}`
return this.http.delete(deleteUrl).map(response => response.json());
}
}
```
Upvotes: 1 |
2018/03/19 | 1,571 | 6,264 | <issue_start>username_0: I have a worksheet with names and addresses of people. I want to make a Userform that finds a person in Column 1 and then output the data from the following cells in the same row as a list. So the output would look like this:
>
> John
>
>
> Time Squares 12
>
>
> New York
>
>
> 0123123123
>
>
>
I manage to find the cell and output the information, but I can't find a way to find and add the info in the following cells in the same row.
```
Dim FindString As String
Dim Rng As Range
FindString = txtSearch
If Trim(FindString) <> "" Then
With Sheets("servicepartner").Range("A:A")
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
MailFormat.Text = Rng.Value & vbNewLine
Else
MsgBox "Nothing found"
End If
End With
End If
```
Anyone have a suggestion on how to approach this issue? Thanks!<issue_comment>username_1: Since `PlayerNationality` is a class itself, it can have some methods.
Also, why do you `import { PlayerService } from './player.service';` in `player.ts`. Seems unnecessary to me.
```
export class PlayerNationality {
// if your constructor has some inputs with `public`, `protected` or `private`,
// typescript will create those field for you in your class.
constructor(
public id: number,
public name: string,
public last: string,
public nationality: string) {
this.upperCase(); // call upperCase to make everything upper case
}
upperCase() {
this.name = this.name.toUpperCase();
this.last = this.last.toUpperCase();
this.nationality = this.nationality.toUpperCase();
}
}
```
in `player-data.ts`
```
export class PlayerNationalityData implements InMemoryDbService {
createDb() {
const players: PlayerNationality[] = [
new PlayerNationality(1, 'Joseph', 'Dart', 'Scotland'),
new PlayerNationality(2, 'Joseph', 'Dart', 'Scotland'),
new PlayerNationality(3, 'Joseph', 'Dart', 'Scotland')
];
}
}
```
Upvotes: 0 <issue_comment>username_2: You need to make the response json from the server a type of `PlayerNationality` and not just an object.
I am a fan of having a constructor for my transfer objects that take a partial of that object and then set the appropriate properties. Example:
```js
export class PlayerNationality {
id: number;
name: String;
last: String;
nationality: String;
constructor(player: Partial) {
Object.entries(player).forEach(([key, value]) => {
if(!(this[key] instanceof Function)) {
this[key] = value;
}
});
}
public upperCase(){
this.name = this.name.toUpperCase();
this.last = this.last.toUpperCase();
this.nationality = this.nationality.toUpperCase();
}
}
```
```js
@Injectable()
export class PlayerService {
getPlayer(): Observable {
return this.http.get(this.url).map(response => response.json().map((p) => new PlayerNationality(p)));
}
addPlayer(player: PlayerNationality): Observable {
return this.http.post(this.url, player, this.options).map(response => new PlayerNationality(response.json()));
}
updatePlayer(player: PlayerNationality): Observable {
const updateUrl = `${this.url}/${player.id}`
return this.http.put(updateUrl, player, this.options).map(response => new PlayerNationality(response.json()));
}
deletePlayer(player: PlayerNationality): Observable {
const deleteUrl = `${this.url}/${player.id}`
return this.http.delete(deleteUrl).map(response => new PlayerNationality(response.json()));
}
}
```
Upvotes: 0 <issue_comment>username_3: I can't quite understand your question. But you are doing it wrong,,,
But if you want to have upperCase method in player.ts
```
//import { PlayerService } from './player.service'; //remove this line.. you don't need this import of a service class since this is a model class
export class PlayerNationality {
public id: number;
public name: String;
public last: String;
public nationality: String;
//note this method will change the case to uppercase of "name", "last","nationality"
toUpperCase(){
this.name=this.name.toUpperCase();
this.last=this.last.toUpperCase();
this.nationality=this.nationality.toUpperCase();
}
}
```
Now you can call this method from anywhere if you have the *PlayerNationality* object
PlayerService.ts
```
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { PlayerNationality } from './player';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { PlayerNationalityData } from './player-data';
@Injectable()
export class PlayerService {
constructor(private http: Http) {}
private url = 'app/players';
private headers = new Headers({'Content-Type': 'application/json'})
private options = new RequestOptions({ headers: this.headers });
getPlayer(): Observable {
return this.http.get(this.url).map(response => response.json());
}
addPlayer(player: PlayerNationality): Observable {
return this.http.post(this.url, player, this.options).map(response => response.json());
}
updatePlayer(player: PlayerNationality): Observable {
const updateUrl = `${this.url}/${player.id}`
//suppose you want to have playerNationality to uppercase here...
player.toUpperCase(); //add line
return this.http.put(updateUrl, player, this.options).map(response => response.json());
}
deletePlayer(player: PlayerNationality): Observable {
const deleteUrl = `${this.url}/${player.id}`
return this.http.delete(deleteUrl).map(response => response.json());
}
}
```
Upvotes: 1 |
2018/03/19 | 655 | 2,057 | <issue_start>username_0: I'm trying to perform a VLOOKUP in VBA, using a table in a different workbook.
I've tried:
```
width = Application.VLookup(code, Workbooks("T:\Data\Dimensions.xlsx").Sheets("Main").Range("A61:G1500"), 7, False)
```
where `code` is a variable I've already set, but it just returns "Subscript out of range".
I'm sure you can see what I'm trying to do, but I'm guessing I've got the syntax wrong in the vlookup.
Thanks.<issue_comment>username_1: Make sure the target workbook is opened. Try this:
```
Set src = Workbooks.Open("T:\Data\Dimensions.xlsx")
width = Application.VLookup(code, src.Sheets("Main").Range("A61:G1500"), 7, False)
```
Upvotes: 1 <issue_comment>username_2: You have to open that workbook or use cell to get value from closed one
```
range("A1").formula = "=vlookup(" & code & ",'T:\Data\[Dimensions.xlsx]Main'!A61:G1500,7,0)"
range("A1").calculate
width = range("A1").value
```
Upvotes: -1 <issue_comment>username_3: The code below is a little long, but it will work you through step-by-step, defining and setting all your objects (see comments in the code itself).
You also need to handle a scenario where `Vlookup` will not be able to find `code` in your specified `Range`,
***Code***
```
Option Explicit
Sub VlookupClosedWorkbook()
Dim Width, code
Dim WorkbookName As String
Dim WB As Workbook
Dim Sht As Worksheet
Dim Rng As Range
WorkbookName = "Dimensions.xlsx"
' set the workbook object
On Error Resume Next
Set WB = Workbooks(WorkbookName) ' first try to see if the workbook already open
On Error GoTo 0
If WB Is Nothing Then ' if workbook = Nothing (workbook is closed)
Set WB = Workbooks.Open("T:\Data\" & WorkbookName)
End If
' set the worksheet object
Set Sht = WB.Sheets("Main")
' set the Range object
Set Rng = Sht.Range("A61:G1500")
' verify that Vlookup found code in the Range
If Not IsError(Application.VLookup(code, Rng, 7, False)) Then
Width = Application.VLookup(code, Rng, 7, False)
Else
MsgBox "Vlookyp Error finding " & code
End If
End Sub
```
Upvotes: 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.