date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/19 | 448 | 1,201 | <issue_start>username_0: I've a property named as messageDict sometimes it will get nil value due to that app is crashing. can someone suggest me how to properly handle it.
```
var messageDict : [String : NSArray]?
if let messageDict = messageDict {
let messageArray = messageDict[outBoxId]! as! [MCOIMAPMessage] // crash indicates here
}
```
If the data is availabe i will store below data. sometimes it will be nil
```
Message-ID: <EMAIL>=<EMAIL>
References: [<EMAIL>,<EMAIL>=<EMAIL>]
In-Reply-To: [<EMAIL>=<EMAIL>]
```<issue_comment>username_1: Don't force unwrap it, try to check if there is something first
```
if let messageDict = messageDict, let messageArray = messageDict[outBoxId] as? [MCOIMAPMessage] {
}
```
Upvotes: 3 <issue_comment>username_2: Unwrap with guard/if will be safe.
```
var messageDict : [String : NSArray]?
guard let message = messageDict else {
return
}
guard let messageArray = message[outBoxId] as? [MCOIMAPMessage] else {
return
}
```
Upvotes: 1 |
2018/03/19 | 815 | 2,535 | <issue_start>username_0: **First iteration:-**
```
class ConcurrentHashMapBehaviour
{
public static void main(String[] args)
{
ConcurrentHashMap map = new ConcurrentHashMap();
map.put("ONE", 1);
map.put("TWO", 2);
map.put("THREE", 3);
map.put("FOUR", 4);
Iterator it = map.keySet().iterator();
while (it.hasNext()){
String key = (String) it.next();
System.out.println(key+" : "+map.get(key));
map.put("SEVEN", 7);
}
}
}
```
**Output is :**
```
ONE : 1
FOUR : 4
TWO : 2
THREE : 3
SEVEN : 7
```
**Second Iteration after changing the key**
```
class ConcurrentHashMapBehaviour
{
public static void main(String[] args)
{
ConcurrentHashMap map = new
ConcurrentHashMap();
map.put("ONE", 1);
map.put("TWO", 2);
map.put("THREE", 3);
map.put("FOUR", 4);
Iterator it = map.keySet().iterator();
while (it.hasNext()){
String key = (String) it.next();
System.out.println(key+" : "+map.get(key));
map.put("FIVE", 5);
}
}
}
```
**Output is:**
```
ONE : 1
FOUR : 4
TWO : 2
THREE : 3
```
So my question is why first iteration include the SEVEN as output but not FIVE in second iteration?<issue_comment>username_1: Javadoc (with my emphasis):
>
> Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table ***at some point at or since the creation of the iterator/enumeration***.
>
>
>
In other words, there are NO guarantees on the view available to the iterator. It may or may not be aware of changes to the map after the `Iterator` is created. The only guarantee is
>
> They do not throw ConcurrentModificationException.
>
>
>
Upvotes: 4 [selected_answer]<issue_comment>username_2: When you type
```
Iterator it = map.keySet().iterator();
while (it.hasNext())
{
String key = it.next();
System.out.println(key + " : " + map.get(key));
map.put("FIVE", 5);
}
```
You might put `("FIVE", 5)` to the map each time you print a value, but that doesn't add it to the running iterator. The iterator does not update. In fact, changing an iterating list or map without an iterator (for example with a for each-loop) would result in a `ConcurrentModificationException`.
---
When you do a second loop after your first and create a new iterator. It will also print out the new value:
```
Iterator it2 = map.keySet().iterator();
while (it2.hasNext())
{
String key = it2.next();
System.out.println(key + " : " + map.get(key));
}
```
Output:
```
FIVE : 5
ONE : 1
FOUR : 4
TWO : 2
THREE : 3
```
Upvotes: 0 |
2018/03/19 | 333 | 1,223 | <issue_start>username_0: I want to implement click event on click of submit button but sometimes it is firing before form submission and sometimes it does not work and form is submitted before click event.
How I can trigger this click event every time.
Here is code for this click event
```
jQuery(document).ready(function(){
jQuery("#addbtn").click(function(){
});
});
```<issue_comment>username_1: You can trigger an event on HTML element programmatically using [`.trigger()`](http://api.jquery.com/trigger/) method. Below, when the is submitted, the click event is triggered on the submit button.
```js
$("form").on("submit", function(event) {
event.preventDefault();
$(event.target).find("button[type='submit']").trigger("click");
});
$("button").on("click", function(event) {
console.log("Button clicked");
});
```
```html
Submit
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: you can use the trigger method to fire an event from another event
```
("button").on("click",()=>{
alert("button clicked")
if($("form").trigger("submit")){
alert("form submited")
}
})
Submit
```
here is the code pen so you can test
<https://codepen.io/anon/pen/WzoJJy>
Upvotes: 1 |
2018/03/19 | 580 | 2,146 | <issue_start>username_0: My Question is when an null ability occur in one to one relation even my child class Primary Key same like parent class Primary Key So when Insert @PrimaryKeyJoinColumn on one to one relation in Insertion I have seen below Link Issue [not-null property references a null or transient value in one to one relation](https://stackoverflow.com/questions/49273260/org-hibernate-propertyvalueexception-not-null-property-references-a-null-or-tra)
and when i Remove this tag n+1 issue resolved ...so how can i resolved it Please Help
```
private SiteSecurity siteSecurity;
private SiteDetails details;
private SiteAvr avr;
private SiteRectifier rectifier;
@OneToOne( fetch = FetchType.LAZY, mappedBy = "site")
@PrimaryKeyJoinColumn
```
in Parent Class Fields regarding one to one relations
```
@GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "site"))
@Id
@GeneratedValue(generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public Site getSite() {
return site;
}
public void setSite(Site site) {
this.site = site;
}
```
this is child class so how can i resolved both issue not null and n+1<issue_comment>username_1: Simply set `optional=true` in your `OneToOne` relationship like:
```
@OneToOne(fetch = FetchType.LAZY, optional=true)
@PrimaryKeyJoinColumn
public Site getSite() {
return site;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: To avoid the n+1 Problem ensure the one to one relationship in sync with the other table if Site Table has a row so another one to one relation table has a row against them and this annotation @PrimaryKeyJoinColumn is on them...
In My case, this strategy will work to avoid the n+1 problem
Please Got through this Like is also Briefly elaborate the One to One Relation [Post](https://stackoverflow.com/questions/17987638/hibernate-one-to-one-lazy-loading-optional-false?noredirect=1&lq=1)
Upvotes: 0 |
2018/03/19 | 598 | 1,982 | <issue_start>username_0: This is the text I get from database:
```
Lorem ipsum dolor sit amet
```
How can I also enclose words before and after into spans with PHP? I need to control every span differently with CSS.
```
Lorem ipsum dolor sit amet
```<issue_comment>username_1: You can achieve this without the need of regular expressions with a simple string replacement. What you can do is first remove all the by using `str_replace`:
```
$new_string = str_replace('', '', $string\_from\_db);
$new\_string = str\_replace('', '', $new_string);
```
Which can be also used as follows:
```
$new_string = str_replace(array('', ''), '', $string_from_db);
```
And then put the again on the whole string:
```
$new_string = '' . $new\_string . '';
```
Which will result into the following:
```
Lorem ipsum dolor sit amet
```
**Since you did not specify that you need a different class for each span I think that having the text enclosed in a single span would work the same for you**
Upvotes: 0 <issue_comment>username_2: You can use explode function in php.
```
$str = "Lorem ipsum dolor sit amet";
$sp = explode("",$str);
$sp1 = explode("",$str);
preg_match_all('/.\*?<\/span>/is', $str, $matches);
echo "".$sp[0]." ".$matches[0][0]." ".$sp1[1]."";
```
Result:
```
Lorem ipsum dolor sit amet
```
Upvotes: 0 <issue_comment>username_3: ```
php
//your code to get text from db
$text_from_db = 'Lorem ipsum <spandolor sit amet';
$text_parts = preg_split( '##', $text_from_db );
$text_output = '';
foreach($text_parts as $key => $text_part){
$text_output .= "$text\_part";
}
```
I think you would need separate classes to treat each span differently.
Upvotes: 3 [selected_answer]<issue_comment>username_4: Use preg\_replace to replace all text before the span, and all text after the span with data in tags:
```
$data = "Lorem ipsum dolor sit amet";
$newdata = preg_replace('#^(.*?)(.\*)(.*?)$#', '$1$2$3', $data);
```
Upvotes: 1 |
2018/03/19 | 709 | 2,476 | <issue_start>username_0: After hours of research, I could not find any example on multi-label predictions with object detection API. Basically I would like to predict more than one label per instance in an image. As the image shown below:
[](https://i.stack.imgur.com/4wbwa.jpg)
I would like to predict clothing categories, but also the attributes such as color and pattern.
From my understanding, I need to attach more classification head per each attribute to the 2nd stage ROI feature map, and sums each attribute's loss? However, I have trouble implement this in the object detection code. Can somebody give me some tips on which functions should I start to modify? Thank you.<issue_comment>username_1: You can achieve this without the need of regular expressions with a simple string replacement. What you can do is first remove all the by using `str_replace`:
```
$new_string = str_replace('', '', $string\_from\_db);
$new\_string = str\_replace('', '', $new_string);
```
Which can be also used as follows:
```
$new_string = str_replace(array('', ''), '', $string_from_db);
```
And then put the again on the whole string:
```
$new_string = '' . $new\_string . '';
```
Which will result into the following:
```
Lorem ipsum dolor sit amet
```
**Since you did not specify that you need a different class for each span I think that having the text enclosed in a single span would work the same for you**
Upvotes: 0 <issue_comment>username_2: You can use explode function in php.
```
$str = "Lorem ipsum dolor sit amet";
$sp = explode("",$str);
$sp1 = explode("",$str);
preg_match_all('/.\*?<\/span>/is', $str, $matches);
echo "".$sp[0]." ".$matches[0][0]." ".$sp1[1]."";
```
Result:
```
Lorem ipsum dolor sit amet
```
Upvotes: 0 <issue_comment>username_3: ```
php
//your code to get text from db
$text_from_db = 'Lorem ipsum <spandolor sit amet';
$text_parts = preg_split( '##', $text_from_db );
$text_output = '';
foreach($text_parts as $key => $text_part){
$text_output .= "$text\_part";
}
```
I think you would need separate classes to treat each span differently.
Upvotes: 3 [selected_answer]<issue_comment>username_4: Use preg\_replace to replace all text before the span, and all text after the span with data in tags:
```
$data = "Lorem ipsum dolor sit amet";
$newdata = preg_replace('#^(.*?)(.\*)(.*?)$#', '$1$2$3', $data);
```
Upvotes: 1 |
2018/03/19 | 686 | 2,390 | <issue_start>username_0: I'm trying to make an app that plays audio with the MediaBrowserService but also use the new Architecture Components to structure the whole app. I have use MediaBrowserService before for another app(<https://github.com/willhwongwork/PodCast>) but in that app I did not use the OnGetRoot() and OnGetChildren() methods to load the data I just load data using loader or asynctask from network(and there's no architecture in that app).
So now if I want to use LiveData and ViewModel how should I structure the code? Should I use them in the MediaBrowserService and through the OnGetRoot() and OnGetChildren() methods provide the data to the UI?<issue_comment>username_1: You can achieve this without the need of regular expressions with a simple string replacement. What you can do is first remove all the by using `str_replace`:
```
$new_string = str_replace('', '', $string\_from\_db);
$new\_string = str\_replace('', '', $new_string);
```
Which can be also used as follows:
```
$new_string = str_replace(array('', ''), '', $string_from_db);
```
And then put the again on the whole string:
```
$new_string = '' . $new\_string . '';
```
Which will result into the following:
```
Lorem ipsum dolor sit amet
```
**Since you did not specify that you need a different class for each span I think that having the text enclosed in a single span would work the same for you**
Upvotes: 0 <issue_comment>username_2: You can use explode function in php.
```
$str = "Lorem ipsum dolor sit amet";
$sp = explode("",$str);
$sp1 = explode("",$str);
preg_match_all('/.\*?<\/span>/is', $str, $matches);
echo "".$sp[0]." ".$matches[0][0]." ".$sp1[1]."";
```
Result:
```
Lorem ipsum dolor sit amet
```
Upvotes: 0 <issue_comment>username_3: ```
php
//your code to get text from db
$text_from_db = 'Lorem ipsum <spandolor sit amet';
$text_parts = preg_split( '##', $text_from_db );
$text_output = '';
foreach($text_parts as $key => $text_part){
$text_output .= "$text\_part";
}
```
I think you would need separate classes to treat each span differently.
Upvotes: 3 [selected_answer]<issue_comment>username_4: Use preg\_replace to replace all text before the span, and all text after the span with data in tags:
```
$data = "Lorem ipsum dolor sit amet";
$newdata = preg_replace('#^(.*?)(.\*)(.*?)$#', '$1$2$3', $data);
```
Upvotes: 1 |
2018/03/19 | 757 | 2,046 | <issue_start>username_0: I have an array -
```
[[Rice, 125.0, 5000.0, Sat Dec 30 01:23:24 GMT-06:36 1899], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ]]
```
I am needing to remove the empty arrays from the end of the array how can I do this?<issue_comment>username_1: A slightly more elegant way would be to filter via Boolean
```
inputArr.filter(function(a) {
return a.filter(Boolean).length > 0;
});
```
Upvotes: 2 <issue_comment>username_2: What you can do is `join` the inner array with respect to `""` so that if there are any values in that array then it will not result to `""`. Thus, you can compare this condition and create a new array in `res` variable:
```js
var inputArray = [['Rice', 125.0, 5000.0, 'Sat Dec 30 01:23:24 GMT-06:36 1899'], [ , , ], [ , , ], [ , , ], [ , , ]];
var res = inputArray.filter(
innerArray => innerArray.join("") !== ""
);
console.log(res);
```
Upvotes: 0 <issue_comment>username_3: You could check for existent items and adjust the length of the array for removing sparse arrays from the end.
```js
var array = [['some data', 42], [0, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ]],
i = array.length;
while (i--) {
if (array[i].some(function () { return true; })) {
break;
}
array.length = i;
}
console.log(array);
```
Upvotes: 0 <issue_comment>username_4: Here is solution !
Enjoy !
```js
var test = [['Rice', 125.0, 5000.0, 'Sat Dec 30 01:23:24 GMT-06:36 1899'], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ]];
console.log(test.length)
for (var x = test.length-1; x > 0; x--) {
// console.log(test[x][0] )
if ( test[x][0] === undefined ) {
test.splice( x, 1 )
}
}
console.log(test)
// METHOD Use it test = clearEmpty(test)
function clearEmpty ( arrayForClear ) {
for (var x = arrayForClear.length-1; x > 0; x--) {
if ( arrayForClear[x][0] === undefined ) {
arrayForClear( x, 1 )
}
}
return arrayForClear;
}
```
Upvotes: 0 |
2018/03/19 | 812 | 2,484 | <issue_start>username_0: My examples are made with easy available data:
```
data(Salaries, package="car")
library(tidyverse)
```
When running:
```
ggplot(Salaries, aes(x=yrs.since.phd, y=salary, color=rank))+
geom_point() +
geom_smooth(method="lm", size=0.5)+
facet_grid(~sex)
```
I got this graph which creates an lm line for every rank:
[](https://i.stack.imgur.com/k82iu.png)
But when I use
```
ggplot(Salaries, aes(x=yrs.since.phd, y=salary, color=rank))+
geom_point() +
geom_smooth(method="lm", colour="black", size=0.5)+
facet_grid(~sex)
```
The graph shows now an unique lm line for all data:
[](https://i.stack.imgur.com/4lHqB.png)
Any idea of what's happening? Why setting colour="black" changes the whole appearence of the lm line in the graphic?<issue_comment>username_1: This happens because by specifying `color` in `geom_smooth`, you are overriding the aesthetics set in the top line of your code. If you want the lines for all groups to be black, you can use the `group`-aesthetic in `geom_smooth` the following way:
```
ggplot(Salaries, aes(x=yrs.since.phd, y=salary, color=rank))+
geom_point() +
geom_smooth(aes(group=rank), method="lm", color = "black", size=0.5)+
facet_grid(~sex)
```
[](https://i.stack.imgur.com/HZI1y.png)
Upvotes: 4 [selected_answer]<issue_comment>username_2: The aesthetics are re-used in every layer: from `help(aes)`
*Aesthetics supplied to ggplot() are used as defaults for every layer.
You can override them, or supply different aesthetics for each layer*
When you define *colour* as the levels of rank, ggplot does just that. At the moment you **override the colour setting** (levels of rank) in the call to `geom_smooth`, ggplot drops the levels for plotting the line.
you could work around this by using `fill` and `shape=21` and using `color` for the line like this:
```
ggplot(Salaries, aes(x=yrs.since.phd, y=salary, fill=rank))+
geom_point(shape=21) +
geom_smooth(method="lm",
color="black",
size=0.5)+
facet_grid(~sex)
```
adding `se=FALSE` to the call to `geom_smooth` will drop the coloured standard error intervals.
yielding this plot:
[](https://i.stack.imgur.com/KjrjE.png)
Upvotes: 3 |
2018/03/19 | 548 | 1,293 | <issue_start>username_0: I am trying to assign float value in php to variable I tried following,
```
$_web_lat=18.501059;
$_web_long=73.862686;
echo $_web_lat .'='. $_web_long;
[Parse error: syntax error, unexpected '.501059' (T_DNUMBER)]
```
OR
```
$_web_lat=floatval('18.501059');
$_web_long=floatval('73.862686');
echo $_web_lat .'='. $_web_long;
```
Both shows 0 as output?
Anyone guide me on this?<issue_comment>username_1: Try to write floating values like
```
php
$_web_lat=floatval('18.501059f');
$_web_long=floatval('73.862686f');
$float_value_of_var1 = floatval($_web_lat);
$float_value_of_var2 = floatval($_web_long);
echo $float_value_of_var1; // 18.501059
echo $float_value_of_var2; // 73.862686
?
```
Upvotes: 0 <issue_comment>username_2: Your code seems to have a hidden character ?
Try copy and use this:
```
php
$_web_lat=18.501059;
$_web_long=73.862686;
echo $_web_lat .'='. $_web_long;
?
```
Upvotes: 5 [selected_answer]<issue_comment>username_3: the sintax error is caused by automatic string conversion do the string operator `.` (dot concat)
if you want avoid this you could use or cast float value ast string
```
$_web_lat=18.501059;
$_web_long=73.862686;
echo (string) $_web_lat .'='. (string>$_web_long;
```
Upvotes: 0 |
2018/03/19 | 1,111 | 3,957 | <issue_start>username_0: I want to send private messages to a User with a Discord Bot.
The user is not in the same server as the bot.
If I can use author.sendMessage, how can I initialize(find) author variable?
Can I find the user with User id?
Thank you for reading.<issue_comment>username_1: Your [Client](https://discord.js.org/#/docs/main/stable/class/Client) object have a [`users`](https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=users) property which has all the cached users that share a server with the bot.
So you can use `.users.get('id')` to get a user by their id.
Also, you should consider using `.send('Hi')` instead since `sendMessage` is deprecated.
Upvotes: 0 <issue_comment>username_2: First of all, `sendMessage` is deprecated and will be removed in further updates. To send a message, you would use `send`. To find a user by their user ID and DM them, you can just do `Client.users.get("User ID here").send("Message to Send")`. I hope this answer was useful to you.
Upvotes: 0 <issue_comment>username_3: >
> And The user is not in the same server with bot.
>
>
>
And
>
> I make a mistake, I want to send Privatemessage to User who isn't in same server with bot I added.. [[source]](https://stackoverflow.com/questions/49358108/in-discord-js-can-i-send-directmessage-to-user-with-discordbot/49403030#comment85717838_49358538)
>
>
>
That is **not** possible to do.
Bots need to have at least 1 common server with a user to be able to send a direct message.
If the user is on the same server as the bot, only then you can send a DM, using any of the other methods on this post.
`client.users.get("someID").send("someMessage");`
Upvotes: 5 [selected_answer]<issue_comment>username_4: I found it out you should try this. It should work! Take out the spaces when using!
```
client.on('message', msg => {
if (msg.content === `"Your message!"`) {
msg.channel.type === (`"dm"`) + msg.author.sendMessage(`"Your other message"`)
}
}
```
Upvotes: -1 <issue_comment>username_5: For anyone interested in how to do this with Discord.js v12, here's how:
```
client.users.cache.get('').send('');
```
Hope this helps someone!
Upvotes: 4 <issue_comment>username_6: use:`mesage.author.send("your message!")`
Upvotes: -1 <issue_comment>username_7: These answers are good, but you cannot guarantee that a user is cached with `client.users.cache.get`, especially with intents updates which limits the amount of data Discord sends to you.
**A full proof solution is this (assuming environment is async):**
```js
const user = await client.users.fetch("").catch(() => null);
if (!user) return message.channel.send("User not found:(");
await user.send("message").catch(() => {
message.channel.send("User has DMs closed or has no mutual servers with the bot:(");
});
```
Not only this answer does the job, but it will attempt to fetch the user from the cache first if they exist, and if they do not, the library will attempt to fetch the user from the Discord API which completely shuts down cache from sabotaging everything. I have also added some `.catch` statements to prevent unhandled rejections and give much better responses!
**Similar with sending a DM to a message author (assuming the message object is named as 'message'):**
```js
await message.author.send("message").catch(() => {
message.channel.send("User has DMs closed or has no mutual servers with the bot:(");
});
```
**Please do not rely on cache as much nowadays (except when fetching guilds and channels since they are always cached by the library), and as other answers have already stated, the bot must have at least one mutual server with the user and the user must have their DMs open and have the bot unblocked.**
Upvotes: 2 <issue_comment>username_8: In the new versions of discord.js is only working way this:
```
bot.users.fetch('User ID').then(dm => {
dm.send('Message to send')
})
```
Upvotes: 0 |
2018/03/19 | 327 | 916 | <issue_start>username_0: I have a string 3pm and i want to convert it to HH using moment.js ?
How can I possibly do that.
I need it because the actual date was 10-03-2018 3pm-4pm ; I split this to only get 3pm and now I need this 3pm in 'HH' that is 15.<issue_comment>username_1: Why is using moment a requirement? If you've already split the string just do it yourself, something like:
```
'3pm'.replace(
/(\d+)([ap]m)?/,
(match, digits, ampm) => +digits + (ampm === "pm" ? 12 : 0)
);
```
Upvotes: 0 <issue_comment>username_2: Here you go with moment :
```js
var time24 = moment("3PM", ["hA"]).format("HH:mm");
console.log(time24);
```
Upvotes: 1 <issue_comment>username_3: As per the document
```
H HH 0..23 Hours (24 hour time)
h hh 1..12 Hours (12 hour time used with a A.)
```
Eg :
* moment().format('HH'): time in 24 hrs format
* ment().format('hh'): time in 12 hrs format
Upvotes: 0 |
2018/03/19 | 492 | 1,802 | <issue_start>username_0: I've trouble with the following code. It's showing error while implementing the following code section. It's a code on JavaFX MediaPlayer project.
```
mediaPlayer.currentTimeProperty().addListener(new ChangeListener() {
@Override
public void changed(ObservableValue extends Duration observable, Duration oldValue, Duration newValue) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
```
It shows the following error.
```
C:\Users\User\Documents\NetBeansProjects\Rmedia\src\rmedia\FXMLDocumentController.java:75: error: no suitable method found for addListener(>)
mediaPlayer.currentTimeProperty().addListener(new ChangeListener() {
method Observable.addListener(InvalidationListener) is not applicable
(argument mismatch; > cannot be converted to InvalidationListener)
method ObservableValue.addListener(ChangeListener super javafx.util.Duration) is not applicable
(argument mismatch; > cannot be converted to ChangeListener super javafx.util.Duration)
```
1 error
What should I do to fix this? Thanks in advance.<issue_comment>username_1: Why is using moment a requirement? If you've already split the string just do it yourself, something like:
```
'3pm'.replace(
/(\d+)([ap]m)?/,
(match, digits, ampm) => +digits + (ampm === "pm" ? 12 : 0)
);
```
Upvotes: 0 <issue_comment>username_2: Here you go with moment :
```js
var time24 = moment("3PM", ["hA"]).format("HH:mm");
console.log(time24);
```
Upvotes: 1 <issue_comment>username_3: As per the document
```
H HH 0..23 Hours (24 hour time)
h hh 1..12 Hours (12 hour time used with a A.)
```
Eg :
* moment().format('HH'): time in 24 hrs format
* ment().format('hh'): time in 12 hrs format
Upvotes: 0 |
2018/03/19 | 541 | 2,355 | <issue_start>username_0: When i render the power bi visuals, I notice that there is a grey border on the right and left side of the image. Is there a way to get rid of that?
[](https://i.stack.imgur.com/mwhpV.png)
It's awkward that the grey border is not effecting the top or bottom of the iframe.
Thanks,
Derek<issue_comment>username_1: Try something like this. (extracted from the powerbi-javascript sample). Pass the #reportContainer div as input to powerbi.embed and you should not see the inset borders
```html
#reportContainer {
width: 100%;
height: 750px;
background-color: white;
padding: 0px;
clear: both;
}
.desktop-view iframe, .mobile-view iframe {
border: none;
}
Sample PowerBI Embedded Report
------------------------------
```
[](https://i.stack.imgur.com/jvUnZ.png)
For **Reports**, you can do the following to make the background transparent (and also FitToWidth).
```
var embedConfig = {
type: type,
id: id,
embedUrl: embedUrl,
viewMode: getViewModeFromModel(viewMode),
tokenType: models.TokenType.Aad,
accessToken: token,
pageView: 'fitToWidth', // applies to Dashboard only; for Report, see below
pageName: pageName,
// See https://microsoft.github.io/PowerBI-JavaScript/interfaces/_node_modules_powerbi_models_dist_models_d_.isettings.html
settings: {
filterPaneEnabled: true,
navContentPaneEnabled: true,
background: models.BackgroundType.Transparent,
// START Report specific settings
layoutType: models.LayoutType.Custom,
customLayout: {
displayOption: models.DisplayOption.FitToWidth
}
// END Report specific settings
}
}
```
Upvotes: 3 <issue_comment>username_2: Just add this css code to remove border of generated iframe by powerbi. It worked perfectly for me
```
iframe { border: none; }
```
Upvotes: 3 |
2018/03/19 | 751 | 2,541 | <issue_start>username_0: One of the textbox contains a comma separated set of values as displayed below,
```
1234,1234,1234,1234,1234,1234,1234,1234,1234,1234,1234,1234,1234,1234,1234
```
Existing output:
```
1234,1234,1234,1234,1234,1234,1234,1234,1234,1234,123
4,1234,1234,1234,1234
```
Expected output:
```
1234,1234,1234,1234,1234,1234,1234,1234,1234,1234,
1234,1234,1234,1234,1234
```
Line should only break after coma value rather than breaking the value `1234`
I am looking for an expression to achieve that.
Changing textbox size is not in scope.<issue_comment>username_1: Try something like this. (extracted from the powerbi-javascript sample). Pass the #reportContainer div as input to powerbi.embed and you should not see the inset borders
```html
#reportContainer {
width: 100%;
height: 750px;
background-color: white;
padding: 0px;
clear: both;
}
.desktop-view iframe, .mobile-view iframe {
border: none;
}
Sample PowerBI Embedded Report
------------------------------
```
[](https://i.stack.imgur.com/jvUnZ.png)
For **Reports**, you can do the following to make the background transparent (and also FitToWidth).
```
var embedConfig = {
type: type,
id: id,
embedUrl: embedUrl,
viewMode: getViewModeFromModel(viewMode),
tokenType: models.TokenType.Aad,
accessToken: token,
pageView: 'fitToWidth', // applies to Dashboard only; for Report, see below
pageName: pageName,
// See https://microsoft.github.io/PowerBI-JavaScript/interfaces/_node_modules_powerbi_models_dist_models_d_.isettings.html
settings: {
filterPaneEnabled: true,
navContentPaneEnabled: true,
background: models.BackgroundType.Transparent,
// START Report specific settings
layoutType: models.LayoutType.Custom,
customLayout: {
displayOption: models.DisplayOption.FitToWidth
}
// END Report specific settings
}
}
```
Upvotes: 3 <issue_comment>username_2: Just add this css code to remove border of generated iframe by powerbi. It worked perfectly for me
```
iframe { border: none; }
```
Upvotes: 3 |
2018/03/19 | 1,752 | 6,923 | <issue_start>username_0: In my program, i have a "reset" button that i want to make appear when the user opens the app for the first time each day. So When the view loads, i create a variable to hold what day it is (i.e: 19), and then set that day as a user default. I then use an if statement to determine whether the user default is equal to the actual day it is. I'm not able to get the hiding and unhiding of the "reset" button completely figured out.
Here is the code i have so far. Im new to swift, so any advice or feedback on my approach would be greatly appreciated! Thanks
```
class UserInfoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let date = Date()
let calendar = Calendar.current
let dateToday = calendar.component(.day, from: date)
let dateToCompare = calendar.component(.day , from: date)
UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")
let userDefaultDate = UserDefaults.standard.value(forKey: self.userDefaultDate) as? Int
if userDefaultDate != dateToCompare {
resetLabel.isHidden = false
UserDefaults.standard.set(dateToCompare, forKey: "userDefaultDate")
}
if userDefaultDate == dateToCompare {
resetLabel.isHidden = true
}
}
```<issue_comment>username_1: Let me modify your code:
```
class UserInfoViewController: UIViewController {
let userDefaultDate = "userDefaultDate"
override func viewDidLoad() {
super.viewDidLoad()
let date = Date()
let calendar = Calendar.current
let dateToCompare = calendar.component(.day , from: date)
let userDefaultDate = UserDefaults.standard.integer(forKey: "userDefaultDate")
if userDefaultDate != dateToCompare {
resetLabel.isHidden = false
UserDefaults.standard.set(dateToCompare, forKey: self.userDefaultDate)
} else {
resetLabel.isHidden = true
}
}
```
What you are wrong is that you set the value the user default before you check. So your comparison is always equal. This line I mean: `UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")`
Upvotes: 0 <issue_comment>username_2: Your code cannot work.
The logic is supposed to be:
* Get the day from `UserDefaults`,
* Compare it to the current day.
* If the values are not equal save the new day to `UserDefaults`
---
```
class UserInfoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let dateToday = Calendar.current.component(.day, from: Date())
let dateToCompare = UserDefaults.standard.integer(forKey: "userDefaultDate")
if dateToCompare != dateToCompare {
UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")
resetLabel.isHidden = false
} else {
resetLabel.isHidden = true
}
}
}
```
Note:
**Never use `value(forKey:` with `UserDefaults`**.
There are many convenience methods and for objects use `object(forKey:`
**Edit**
It's more reliable to save the `Date` object and compare using `isDateInToday` of `Calendar`
```
class UserInfoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let dateToday = Date()
let calendar = Calendar.current
let dateToCompare = UserDefaults.standard.object(forKey: "userDefaultDate") as? Date ?? Date.distantPast
if calendar.isDateInToday(dateToCompare) {
resetLabel.isHidden = true
} else {
UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")
resetLabel.isHidden = false
}
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: try this, hope will help you.
```
override func viewDidLoad() {
super.viewDidLoad()
let date = Date()
let calendar = Calendar.current
let dateToday = calendar.component(.day, from: date)
let dateToCompare = Int(calendar.component(.day , from: date))
UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")
let userDefaultDate = UserDefaults.standard.value(forKey: "userDefaultDate") as? Int
if userDefaultDate != dateToCompare {
UserDefaults.standard.set(dateToCompare, forKey: "userDefaultDate")
resetLabel.isHidden = true
} else {
resetLabel.isHidden = true
}
}
```
in this code if userDefaultDate != dateToCompare, dateToCompare save in UserDefaults and hide you resetLabel, else if userDefaultDate = dateToCompare, its simply hide you resetLabel
but if you need show resetLabel if userDefaultDate != dateToCompare you will change this one:
```
UserDefaults.standard.set(dateToCompare, forKey: "userDefaultDate")
resetLabel.isHidden = false
```
Upvotes: 0 <issue_comment>username_4: You will not be able to achieve your requirement as dateToday & dateToCompare will always be equal. Also you might want to use a button instead of a label(resetLabel) if you want a button action.
Try this code:
```
override func viewDidLoad() {
super.viewDidLoad()
let presentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/mm/yyyy"
let dateString = dateFormatter.string(from: presentDate)
guard let userDefaultDate = UserDefaults.standard.object(forKey: "userDefaultDate") as? String else {
UserDefaults.standard.set(dateString, forKey: "userDefaultDate") //this line would be executed when you are setting the date for the first time, i.e on your first app launch.
resetLabel.isHidden = true
return
}
if userDefaultDate != dateString {
resetLabel.isHidden = false
UserDefaults.standard.set(dateString, forKey: "userDefaultDate")
} else {
resetLabel.isHidden = true
}
}
```
Here I'm converting the date into a string in the format dd/mm/yyyy and saving it in the UserDefaults
Upvotes: 0 <issue_comment>username_5: Using [Calendar API](https://developer.apple.com/documentation/foundation/nscalendar/1417149-isdateintoday) implementation:
```
Calendar.current.isDateInToday(dateToCompare)
```
Another Simple approach Using Swift [Compare API](https://developer.apple.com/documentation/foundation/calendar/2293166-compare):
```
func twoDatesAreSame(date1: Date, date2: Date) -> Bool {
let dateCompared = Calendar.current.compare(date1, to: date2, toGranularity: .day)
switch dateCompared {
case .orderedAscending:
//date1 is earlier than date2, when compared at the specified level of precision
return false
case .orderedDescending:
//date1 is later than date2, when compared at the specified level of precision
return false
case .orderedSame:
//date1 is equal to date2, when compared at the specified level of precision
return true
}
}
```
Upvotes: 0 |
2018/03/19 | 1,350 | 4,093 | <issue_start>username_0: Why does this code print 10 = -246 instead of 10 = 10? Does the pointer size matter?
```
#include
int main() {
int i = 10;
int j = -1;
char \*p, \*q;
p = (char\*) &i
q = (char\*) &j
\*q = \*p;
printf("%d = %d\n", i, j);
return 0;
}
```<issue_comment>username_1: First of all, the result here depends on CPU endianess. You appear to have a little endian CPU.
Assuming `int` is 32 bit 2's complement, `-1` is stored in 4 bytes as `0xFFFFFFFF`. A `char` access only affects one byte. Since you have little endian, it will be the least significant byte in your case. This byte will get overwritten with the value 10, 0x0A. You end up with `0xFFFFFF0A` which is the 2's complement representation of -246.
---
Please note that the `char` type has implementation-defined signedness and should therefore always be avoided when doing bit/byte manipulations. Use `uint8_t` instead.
Also note that accessing one data type through a pointer of a different type is risky and poorly-defined, in all other cases than when using character types specifically (uint8\_t is a character type), because they are an exception to the "strict aliasing rule".
Upvotes: 1 <issue_comment>username_2: Assume the CPU is 32bit.
First question: why print `10 = -246`
```
i = 10; (0x0000 000A)
j = -1; (0xFFFF FFFF) Two's Complement
```
\*q pointer to the lowest 8bit of integer j, after `*q = 10;`, j becomes `0xFFFF FF0A` which is the Two's Complement of `-246`
refer [How Computers Represent Negative Binary Numbers?](https://www.programminglogic.com/how-computers-represent-negative-binary-numbers/)
Second question: does the pointer size matter?
Yes, covert int pointer to char pointer will lose the 24bit data in this case.
Upvotes: 0 <issue_comment>username_3: Here p & q is a char pointer.
p = (char\*) &i So p will point to the first byte of the integer var i which is of 4 bytes. So on dereferncing p you will get 10(00001010).
q = (char\*) &j As j = -1, it is the largest negative no. It means j var will have all 1's in 32 bits(11111111 11111111 11111111 11111111)
\*q = \*p; In this line you are copying the lowest first byte(00001010) from i's location to j's location first byte because both pointers are of char \*. So now after copying, value in j's location will be:
11111111 11111111 11111111 00001010 which is equivalent to -246. Calculate the 2's complement of 11111111 11111111 11111111 00001010. It will give you -246.
Upvotes: 0 <issue_comment>username_4: >
> Does the pointer size matter?
>
>
>
No, the **size** of the pointer doesn't matter. What matter is the **type** of pointer, i.e. the type it points to.
The number of bytes copied when assigning through a pointer depends on the pointer type. If the pointer type is a char pointer, it will copy `sizeof(char)` bytes. If the pointer type is an int pointer, it will copy `sizeof(int)` bytes.
>
> Why does this code print 10 = -246 instead of 10 = 10?
>
>
>
It's system dependent. Since you get this result, you are probably on a little endian system which means that data in memory is stored with LSB first (i.e. a pointer to a variable points to LSB of that variable).
So what happens in your code is that LSB of variable `i` is copied to LSB of variable `j`. Since `sizeof(int)` is more than 1, you'll not end in a situation where `i` and `j` are equal. Simply because you didn't copy all bytes of `i` into `j`.
Assuming a 32 bit `int` it may look like:
[](https://i.stack.imgur.com/xOeE9.png)
Upvotes: 1 <issue_comment>username_5: You have to do a casting like this to have the value of i in j:
`* (int*)p = * (int*)q`
It will convert the type of your pointer and you are going to “transfer” the value of i in j.
Or in addition you can do it without casting using a for loop loke this:
`
```
for(int k=0; k
```
`
With this loop you are going to write every single bit of i in every byte of k one byte at time. This because int have a 4 byte structure and char have a 1 byte structure.
Upvotes: 0 |
2018/03/19 | 1,512 | 4,983 | <issue_start>username_0: When I navigate to a page using this event:
```
this.events.subscribe('liveTrackingEvent', (time, unit) => {
console.log("event triggered");
this.searchForm.controls['unitID'].setValue(this.unitSelected.unit.name);
this.GetLiveData();
});
```
everything gets called, also the function GetLiveData(). (I didn't post this function's code because it's irelevant)
However when I look at the page, not 1 element is updating. So this line:
```
this.searchForm.controls['unitID'].setValue(this.unitSelected.unit.name);
```
doesn't update the searchform control, however when I call this line of code from the page itself without the event getting triggered on another page, it works smoothly and updates the searchform control.
(It's like I'm on a separate thread for some reason), I'm putting this between brackets because it's just a thought.
So my question is: How do I force this page to update itself also when the event is triggered?
Thanks in advance and if you guys need more code just ask, but this is the most relevant code because everything is working just not when it gets called inside the event.<issue_comment>username_1: First of all, the result here depends on CPU endianess. You appear to have a little endian CPU.
Assuming `int` is 32 bit 2's complement, `-1` is stored in 4 bytes as `0xFFFFFFFF`. A `char` access only affects one byte. Since you have little endian, it will be the least significant byte in your case. This byte will get overwritten with the value 10, 0x0A. You end up with `0xFFFFFF0A` which is the 2's complement representation of -246.
---
Please note that the `char` type has implementation-defined signedness and should therefore always be avoided when doing bit/byte manipulations. Use `uint8_t` instead.
Also note that accessing one data type through a pointer of a different type is risky and poorly-defined, in all other cases than when using character types specifically (uint8\_t is a character type), because they are an exception to the "strict aliasing rule".
Upvotes: 1 <issue_comment>username_2: Assume the CPU is 32bit.
First question: why print `10 = -246`
```
i = 10; (0x0000 000A)
j = -1; (0xFFFF FFFF) Two's Complement
```
\*q pointer to the lowest 8bit of integer j, after `*q = 10;`, j becomes `0xFFFF FF0A` which is the Two's Complement of `-246`
refer [How Computers Represent Negative Binary Numbers?](https://www.programminglogic.com/how-computers-represent-negative-binary-numbers/)
Second question: does the pointer size matter?
Yes, covert int pointer to char pointer will lose the 24bit data in this case.
Upvotes: 0 <issue_comment>username_3: Here p & q is a char pointer.
p = (char\*) &i So p will point to the first byte of the integer var i which is of 4 bytes. So on dereferncing p you will get 10(00001010).
q = (char\*) &j As j = -1, it is the largest negative no. It means j var will have all 1's in 32 bits(11111111 11111111 11111111 11111111)
\*q = \*p; In this line you are copying the lowest first byte(00001010) from i's location to j's location first byte because both pointers are of char \*. So now after copying, value in j's location will be:
11111111 11111111 11111111 00001010 which is equivalent to -246. Calculate the 2's complement of 11111111 11111111 11111111 00001010. It will give you -246.
Upvotes: 0 <issue_comment>username_4: >
> Does the pointer size matter?
>
>
>
No, the **size** of the pointer doesn't matter. What matter is the **type** of pointer, i.e. the type it points to.
The number of bytes copied when assigning through a pointer depends on the pointer type. If the pointer type is a char pointer, it will copy `sizeof(char)` bytes. If the pointer type is an int pointer, it will copy `sizeof(int)` bytes.
>
> Why does this code print 10 = -246 instead of 10 = 10?
>
>
>
It's system dependent. Since you get this result, you are probably on a little endian system which means that data in memory is stored with LSB first (i.e. a pointer to a variable points to LSB of that variable).
So what happens in your code is that LSB of variable `i` is copied to LSB of variable `j`. Since `sizeof(int)` is more than 1, you'll not end in a situation where `i` and `j` are equal. Simply because you didn't copy all bytes of `i` into `j`.
Assuming a 32 bit `int` it may look like:
[](https://i.stack.imgur.com/xOeE9.png)
Upvotes: 1 <issue_comment>username_5: You have to do a casting like this to have the value of i in j:
`* (int*)p = * (int*)q`
It will convert the type of your pointer and you are going to “transfer” the value of i in j.
Or in addition you can do it without casting using a for loop loke this:
`
```
for(int k=0; k
```
`
With this loop you are going to write every single bit of i in every byte of k one byte at time. This because int have a 4 byte structure and char have a 1 byte structure.
Upvotes: 0 |
2018/03/19 | 498 | 1,768 | <issue_start>username_0: Is it possible to sum two values from subqueries?
I need select three values: total\_view, total\_comments and rating.
Both subqueries is very complicated, so i don't wish duplicate it.
My query example:
```
SELECT p.id,
(
FIRST subquery
) AS total_view,
(
SECOND subquery
) AS total_comments,
(
total_view * total_comments
) AS rating
FROM products p
WHERE p.status = "1"
ORDER BY rating DESC
```<issue_comment>username_1: You can't use alias but you can use the same code eg:
```
SELECT p.id,
(
FIRST subquery
) AS total_view,
(
SECOND subquery
) AS total_comments,
(
(
FIRST subquery
) * (
SECOND subquery
)
) AS rating
FROM products p
WHERE p.status = "1"
ORDER BY rating DESC
```
Upvotes: 1 <issue_comment>username_2: Simply use a Derived Table to be able to reuse the aliases:
```
SELECT p.id,
total_view,
total_comments,
total_view * total_comments AS rating
FROM
(
SELECT p.id,
(
FIRST subquery
) AS total_view,
(
SECOND subquery
) AS total_comments
FROM products p
WHERE p.status = "1"
) as dt
ORDER BY rating DESC
```
Upvotes: 0 <issue_comment>username_3: I would suggest using a subquery:
```
SELECT p.*, (total_view * total_comments) as rating
FROM (SELECT p.id,
(FIRST subquery) AS total_view,
(SECOND subquery) AS total_comments,
FROM products p
WHERE p.status = '1' -- if status is a number, then remove quotes
) p
ORDER BY rating DESC;
```
MySQL materializes the subquery. But because the `ORDER BY` is on a computed column, it needs to sort the data anyway, so the materialization is not extra overhead.
Upvotes: 4 [selected_answer] |
2018/03/19 | 5,281 | 22,011 | <issue_start>username_0: I wants to display my location in android device in google may using marker. I have written the following code. But there has no marker in the map. I also implement the LocationListener. But no marker. I am thankful to you if you send some code or give some suggestion.
I am also checking the isProviderAvailable and provider. They are not coming properly. isProviderAvailable returns false. Is I have to change some facility on my device? or any other problem. Please share your thought. I am waiting.
```
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private LocationManager mLocationManager = null;
private String provider = null;
private Marker mCurrentPosition = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Toast.makeText(this, "locateCurrentPosition Test", Toast.LENGTH_SHORT).show();
if (isProviderAvailable() && (provider != null)) {
locateCurrentPosition();
}
else
{
Toast.makeText(this, "Not satisfied:"+isProviderAvailable(), Toast.LENGTH_SHORT).show();
}
}
private void locateCurrentPosition() {
Toast.makeText(this, "locateCurrentPosition", Toast.LENGTH_SHORT).show();
int status = getPackageManager().checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
getPackageName());
if (status == PackageManager.PERMISSION_GRANTED) {
Location location = mLocationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
// mLocationManager.addGpsStatusListener(this);
long minTime = 5000;// ms
float minDist = 5.0f;// meter
mLocationManager.requestLocationUpdates(provider, minTime, minDist,
this);
}
}
private boolean isProviderAvailable() {
mLocationManager = (LocationManager) getSystemService(
Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = mLocationManager.getBestProvider(criteria, true);
if (mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
return true;
}
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
return true;
}
if (provider != null) {
return true;
}
return false;
}
private void updateWithNewLocation(Location location) {
if (location != null && provider != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
addBoundaryToCurrentPosition(lat, lng);
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(10f).build();
if (mMap != null)
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
}
private void addBoundaryToCurrentPosition(double lat, double lang) {
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(new LatLng(lat, lang));
mMarkerOptions.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker));
mMarkerOptions.anchor(0.5f, 0.5f);
CircleOptions mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(10000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
mMap.addCircle(mOptions);
if (mCurrentPosition != null)
mCurrentPosition.remove();
mCurrentPosition = mMap.addMarker(mMarkerOptions);
}
@Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}
}
}
```
Mainfest.xml
```
```
build.gradle
```
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "26.0.2"
defaultConfig {
applicationId "com.live.bbw.locationtest"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.google.android.gms:play-services-maps:11.0.4'
testCompile 'junit:junit:4.12'
}
```<issue_comment>username_1: get latlng and put it in the code that i wrote bellow and put it on your OnMapReadyCallback
```
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
```
if you have any other questions im there
Upvotes: 0 <issue_comment>username_2: if you need to fetch current location lat and log value and also show marker.
fetch current location lat and long value and show marker on that used below code ...
```
public class MapLocationActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Map Location Activity");
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
@Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
@Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapLocationActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
```
}
if you want only fetch current location lat and long value and some interval time used below class i make for separate ...
```
public class LocationFetcher implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
// LogCat tag
private static final String TAG = LocationFetcher.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mBestReading;
private static final long ONE_MIN = 1000 * 60;
private static final long TWO_MIN = ONE_MIN * 2;
private static final long FIVE_MIN = ONE_MIN * 5;
private static final long POLLING_FREQ = 1000 * 30;
private static final long FASTEST_UPDATE_FREQ = 1000 * 5;
private static final float MIN_ACCURACY = 25.0f;
private static final float MIN_LAST_READ_ACCURACY = 500.0f;
private double mLattitude;
private double mLongitue;
private double mAltitude;
private Activity mContext;
private UpdatedLocation updatedLocation;
private Location mLocation;
public void setListener(UpdatedLocation updatedLocation) {
if(mGoogleApiClient == null) {
init();
}
this.updatedLocation = updatedLocation;
updateLocation();
}
public void removeListener(){
this.updatedLocation = null;
mGoogleApiClient = null;
/*if(mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}*/
}
public LocationFetcher(Activity context) {
// First we need to check availability of play services
this.mContext = context;
```
// init();
// Show location button click listener
}
```
private void init(){
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(POLLING_FREQ);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
PendingResult result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION\_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
status.startResolutionForResult(mContext, 101);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS\_CHANGE\_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
private boolean servicesAvailable() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
//TODO ALERT
Toast.makeText(mContext,
"context device is not supported.", Toast.LENGTH\_LONG)
.show();
return false;
}
}
/\*\*
\* Google api callback methods
\*/
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
@Override
public void onConnected(Bundle arg0) {
if (servicesAvailable()) {
// Get best last location measurement meeting criteria
mBestReading = bestLastKnownLocation(MIN\_LAST\_READ\_ACCURACY, FIVE\_MIN);
if (null == mBestReading
|| mBestReading.getAccuracy() > MIN\_LAST\_READ\_ACCURACY
|| mBestReading.getTime() < System.currentTimeMillis() - TWO\_MIN) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS\_FINE\_LOCATION) == PackageManager.PERMISSION\_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS\_COARSE\_LOCATION) == PackageManager.PERMISSION\_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(location != null) {
mLocation = location;
mLattitude = location.getLatitude();
mLongitue = location.getLongitude();
```
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
```
}
return;
}
}
}
}
private Location bestLastKnownLocation(float minAccuracy, long minTime) {
if(mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MIN_VALUE;
// Get the best most recent location currently available
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
if (mCurrentLocation != null) {
float accuracy = mCurrentLocation.getAccuracy();
long time = mCurrentLocation.getTime();
if (accuracy < bestAccuracy) {
bestResult = mCurrentLocation;
bestAccuracy = accuracy;
bestTime = time;
}
}
if (bestAccuracy > minAccuracy || bestTime < minTime) {
return null;
} else {
mLocation = bestResult;
mLattitude = bestResult.getLatitude();
mLongitue = bestResult.getLongitude();
mAltitude = bestResult.getAltitude();
```
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
```
return bestResult;
}
}
return null;
}
return null;
}
@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(android.location.Location location) {
mLocation = location;
mLattitude = location.getLatitude();
mLongitue = location.getLongitude();
```
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
```
if(updatedLocation != null)
updatedLocation.updateUI(location);
CustomLogHandler.printDebuglog("Location","========>>" + location);
}
public Location getLocation(){
return mLocation;
}
public double getLatitude(){
return mLattitude;
}
public double getLongitude(){
return mLongitue;
}
public double getAltitude(){
return mAltitude;
}
public void updateLocation(){
bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
}
public interface UpdatedLocation {
public void updateUI(Location location);
}
```
}
Upvotes: 1 <issue_comment>username_3: You can retrieve `onLocationChanged` Listener and Add maker init
```
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
```
Implement your `onLocationChanged` like this
```
@Override
public void onLocationChanged(Location location) {
if (location != null) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
Marker marker = mMap.addMarker(new MarkerOptions().position(latLng));
marker.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
} else {
Toast.makeText(getContext(), "Location not found", Toast.LENGTH_SHORT).show();
}
}
```
Upvotes: 0 |
2018/03/19 | 3,968 | 16,774 | <issue_start>username_0: Something a coworker of mine found:
Using Java 8, the `javadoc` for this class doesn't generate correct html:
```
public class JavadocBounds {
/**
* A method with a parameter of type {@link Callback}.
\*/
public void method(Callback callback) {}
static class Callback {}
static class ResultCode {}
}
```
This works fine (without the generic's bound):
```
/**
* A method with a parameter of type {@link Callback}<{@link ResultCode}>.
*/
```
Are we getting the syntax wrong?
Is this fixed in later Java versions?
Is this relevant enough to post a bug? If so, where?<issue_comment>username_1: get latlng and put it in the code that i wrote bellow and put it on your OnMapReadyCallback
```
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
```
if you have any other questions im there
Upvotes: 0 <issue_comment>username_2: if you need to fetch current location lat and log value and also show marker.
fetch current location lat and long value and show marker on that used below code ...
```
public class MapLocationActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Map Location Activity");
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
@Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
@Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapLocationActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
```
}
if you want only fetch current location lat and long value and some interval time used below class i make for separate ...
```
public class LocationFetcher implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
// LogCat tag
private static final String TAG = LocationFetcher.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mBestReading;
private static final long ONE_MIN = 1000 * 60;
private static final long TWO_MIN = ONE_MIN * 2;
private static final long FIVE_MIN = ONE_MIN * 5;
private static final long POLLING_FREQ = 1000 * 30;
private static final long FASTEST_UPDATE_FREQ = 1000 * 5;
private static final float MIN_ACCURACY = 25.0f;
private static final float MIN_LAST_READ_ACCURACY = 500.0f;
private double mLattitude;
private double mLongitue;
private double mAltitude;
private Activity mContext;
private UpdatedLocation updatedLocation;
private Location mLocation;
public void setListener(UpdatedLocation updatedLocation) {
if(mGoogleApiClient == null) {
init();
}
this.updatedLocation = updatedLocation;
updateLocation();
}
public void removeListener(){
this.updatedLocation = null;
mGoogleApiClient = null;
/*if(mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}*/
}
public LocationFetcher(Activity context) {
// First we need to check availability of play services
this.mContext = context;
```
// init();
// Show location button click listener
}
```
private void init(){
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(POLLING_FREQ);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
PendingResult result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION\_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
status.startResolutionForResult(mContext, 101);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS\_CHANGE\_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
private boolean servicesAvailable() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
//TODO ALERT
Toast.makeText(mContext,
"context device is not supported.", Toast.LENGTH\_LONG)
.show();
return false;
}
}
/\*\*
\* Google api callback methods
\*/
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
@Override
public void onConnected(Bundle arg0) {
if (servicesAvailable()) {
// Get best last location measurement meeting criteria
mBestReading = bestLastKnownLocation(MIN\_LAST\_READ\_ACCURACY, FIVE\_MIN);
if (null == mBestReading
|| mBestReading.getAccuracy() > MIN\_LAST\_READ\_ACCURACY
|| mBestReading.getTime() < System.currentTimeMillis() - TWO\_MIN) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS\_FINE\_LOCATION) == PackageManager.PERMISSION\_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS\_COARSE\_LOCATION) == PackageManager.PERMISSION\_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(location != null) {
mLocation = location;
mLattitude = location.getLatitude();
mLongitue = location.getLongitude();
```
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
```
}
return;
}
}
}
}
private Location bestLastKnownLocation(float minAccuracy, long minTime) {
if(mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MIN_VALUE;
// Get the best most recent location currently available
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
if (mCurrentLocation != null) {
float accuracy = mCurrentLocation.getAccuracy();
long time = mCurrentLocation.getTime();
if (accuracy < bestAccuracy) {
bestResult = mCurrentLocation;
bestAccuracy = accuracy;
bestTime = time;
}
}
if (bestAccuracy > minAccuracy || bestTime < minTime) {
return null;
} else {
mLocation = bestResult;
mLattitude = bestResult.getLatitude();
mLongitue = bestResult.getLongitude();
mAltitude = bestResult.getAltitude();
```
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
```
return bestResult;
}
}
return null;
}
return null;
}
@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(android.location.Location location) {
mLocation = location;
mLattitude = location.getLatitude();
mLongitue = location.getLongitude();
```
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
```
if(updatedLocation != null)
updatedLocation.updateUI(location);
CustomLogHandler.printDebuglog("Location","========>>" + location);
}
public Location getLocation(){
return mLocation;
}
public double getLatitude(){
return mLattitude;
}
public double getLongitude(){
return mLongitue;
}
public double getAltitude(){
return mAltitude;
}
public void updateLocation(){
bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
}
public interface UpdatedLocation {
public void updateUI(Location location);
}
```
}
Upvotes: 1 <issue_comment>username_3: You can retrieve `onLocationChanged` Listener and Add maker init
```
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
```
Implement your `onLocationChanged` like this
```
@Override
public void onLocationChanged(Location location) {
if (location != null) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
Marker marker = mMap.addMarker(new MarkerOptions().position(latLng));
marker.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
} else {
Toast.makeText(getContext(), "Location not found", Toast.LENGTH_SHORT).show();
}
}
```
Upvotes: 0 |
2018/03/19 | 642 | 2,173 | <issue_start>username_0: I got this array of string
```
String s1[] = {"H","E","L","L","O"};
```
and a method to convert it into int
```
public static int[] String2Int(String[] k){
int[] arrayBuffer = new int[k.length];
for (int i=0; i < k.length; i++)
{
//arrayBuffer[i] = Integer.parseInt(k[i]);
arrayBuffer[i] = Integer.parseInt(k[i]);
}
return arrayBuffer;
```
I want the decimal values of the characters but no luck on getting it.
Google is only helping with if the string were a number.<issue_comment>username_1: You shouldn't convert it to integer. It should be
```
arrayBuffer[i] =k[i].charAt(0);
```
That way you get the ASCII value of char and gets assigned to int.
Edit :
You can also use `arrayBuffer[i] = Character.codePointAt(input, 0);` as pointed in comments.
Upvotes: 3 [selected_answer]<issue_comment>username_2: ### Try this:
```
class MainClass
{
public static void main(String[] args)
{
System.out.println(Arrays.toString(String2Int("HELLO")));
}
public static int[] String2Int(String k)
{
int[] arrayBuffer = new int[k.length()];
for (int i = 0; i < arrayBuffer.length; i++)
{
//arrayBuffer[i] = Integer.parseInt(k[i]);
arrayBuffer[i] = k.charAt(i);
}
return arrayBuffer;
}
}
```
### Output:
```
[72, 69, 76, 76, 79]
```
### Explanation
`char` and `int` is almost the same in Java. You don't need to parse it, you just implicitly cast it by asigning it to the `int[]`. Also you shouldn't take a `String[]` as an argument, that makes no sense. A String is already almost a `char[]`. So either take a `String`, or a `char[]`. In my example I've used a `String` because that is more convenient to call.
Upvotes: 1 <issue_comment>username_3: Using the Java 8 Stream API:
```
public static int[] convert(String[] strings)
{
Objects.requireNonNull(strings);
return Arrays.stream(strings)
.mapToInt(str -> Character.getNumericValue(str.charAt(0)))
.toArray();
}
```
I assume you dont need to check that the input strings contain exactly one character.
Upvotes: 0 |
2018/03/19 | 622 | 2,251 | <issue_start>username_0: I have installed and configured Team Foundation Server 2015 Update 3 in one of our server a few weeks ago.
All was going well until the pc unexpectedly was shut down due to electrical problem. After turning on again we now get:
>
> Error 500 internal server error.
>
>
>
Tried to access the web server and got the HTTP Error
>
> 403.14 - Forbidden.
>
>
>
TFS administration console seems fine. I'm not sure where to look next. Help would be greatly appreciated.<issue_comment>username_1: First, please check your **Event View** on your TFS server machine to see if there are more detail info or error message for trouble shooting.
For `Error 500 internal server error.` There's no much value for now.
For `403.14-Forbidden` error, this may related to IIS server. Suggest you try to restart the TFS applicaton on IIS. And also [clean all cache of TFS server](https://blogs.msdn.microsoft.com/willy-peter_schaub/2010/09/15/if-you-have-problems-with-tfs-or-visual-studio-flush-the-user-cache-or-not/), located at`%LOCALAPPDATA%\Microsoft\Team Foundation\7.0\Cache`
To narrow down the issue, you could also use Visual Studio to connect TFS server. If this works, suggest you to clear IE cache and try again.
Besides, since the PC unexpectedly shut down, please also check if the related TFS service started properly, if not manually start them.
Upvotes: 2 [selected_answer]<issue_comment>username_2: In case someone else runs across this issue, we had the same problem and it turned out to be the system time on our TFS SQL Server had gotten out of sync. It was off by a number of hours. When I reset the time to be correct, I was able to connect to the TFS instance again without issue.
Upvotes: 0 <issue_comment>username_3: I got this error when I was migrating from TFS 2013 to AzureDevops Server 2020 using XAML Build. The error on Event Viewer from Application Tier Server was "*Exception Message: The protocol binding '*:443:*.domain.com.br' is not valid for 'https'. This might be because the port number is out of range. (type UriFormatException)*". I adjusted on IIS the https bindings to accept requests from IP Server.
[enter image description here](https://i.stack.imgur.com/WTLX7.png)
Upvotes: 0 |
2018/03/19 | 857 | 3,515 | <issue_start>username_0: Hello guys I just joined this forum and I must say using it has been tremendously helpful...thanks a lot. However I would like to know what's the difference between:
```
export const Hello = (props)=>{ returnHello {props.name}
==================
; }
```
AND
```
export default ({ name }) => Hello {name}!
=============
;
```
For some reason the first option keeps giving me error in my code. BTW the component's name for both is 'Hello'.<issue_comment>username_1: The only functional difference between your 2 exports is between `export const Hello = ...` and `export default ...`
When using `export default`, your are basically saying : Give this value when the file is imported. So you would use in another file
```
import Hello from './Hello'
```
When using `export const Hello = ...` you're exporting `Hello` as a property of the exported object. You would then use
```
import { Hello } from './Hello'
```
or
```
import HelloFile from './Hello'
...
const Hello = HelloFile.Hello;
```
For the other differences, you can check for username_2's answer, and if you want to document yourself further, you can checkout for [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) and [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), but basically your 2 pieces of code are doing the exact same thing
Upvotes: 1 <issue_comment>username_2: There are a couple of things to unpack here.
1. `export` vs `export default`
-------------------------------
When you export something as a named const like your first example it allows you to `import` it like this:
```
import { Hello } from './yourFile'
```
If you export something as the default you can import it like this:
```
import Hello from './yourFile'
```
In the first example, `Hello` must match the name of the `const` you are exporting and in the second, `Hello` is the name you give to the imported default, so could be anything you want (although convention is that you keep it the same for clarify).
2. `(props)` vs `({name})`
--------------------------
What you're doing here is defining what will be passed in as the parameters to your component.
The first example is using the whole props object, so you need to do `props.name` in your component and the second is using object destructuring to unpack the property `name` from your input parameter (which is still the props).
The advantage of the second is that it's a bit more explicit when you come back to the component, what properties you are expecting to use and it allows you to be more concise in your component. The downside is that it can be a bit more verbose if you need to unpack a lot of properties.
3. `=> { return xyz }` vs `=>`
------------------------------
This is just a syntactic difference, they do the same thing in your example but the second is slimmer.
The first is basically defining a method body with the curly braces which can allow you to perform other actions before returning the component HTML, you could for example assign some variable in there.
The second is more concise but it's a shorthand for returning the contents and the curly braces and personally I think nicer if you don't need to do anything else inside the method body.
A third way is to write `=> (Hello {name}!
=============
)` which is the same as the second example just with parenthesis!
Upvotes: 2 |
2018/03/19 | 830 | 2,626 | <issue_start>username_0: I'm trying to follow a react tutorial, My webpack.config.js file is as follows:
```
var webpack = require("webpack");
var pth = require("path");
module.exports = {
entry: "./src/index.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
devServer: {
inline: true,
contentBase: './dist',
port: 3000
},
module: {
rules: [
{ test: /\.js$/, exclude: /(node_modules)/, use: 'babel-loader' },
{ test: /\.json$/, exclude: /(node_modules)/, use: 'json-loader' }
]
}
}
```
While my Code files are as follows: I have made components here in lib.js and rendering is being done in index.js which ultimately is called in a HTML div in index.html
lib.js
```
import React from 'react'
import text from './titles.json'
export const hello = (
{text.hello}
==============
)
export const goodbye = (
{text.goodbye}
================
)
```
index.js
```
import React from 'react'
import {render} from 'react-dom'
import {hello, goodbye} from './lib'
const design = {
backgroundColor: 'red',
color: 'white',
fontFamily:'verdana'
}
render(
{hello}
{goodbye}
,
document.getElementById('react-container')
)
```
When I run `webpack -w` command, I experience the following error
```
ERROR in ./src/titles.json
Module parse failed: Unexpected token m in JSON at position 0
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token m in JSON at position 0
at Object.parse (native)
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:447:3)
@ ./src/lib.js 12:14-38
@ ./src/index.js
ERROR in chunk main [entry]
bundle.js
Cannot read property 'replace' of undefined
```
My JSON file is as follows:
titles.json
```
{
"hello": "Bonjour!",
"goodbye": "<NAME>"
}
```
My Module verions are as follows:
webpack 4.1.1
json-loader 0.5.7
I have installed webpack and json-loader globally using npm install
TIA<issue_comment>username_1: I was importing the titles.json the wrong way in lib.js
We can do it as follows:
In lib.js
```
var greetings = require('./titles.json')
```
And it will be utilized as follows:
```
{greetings.hello}
```
Upvotes: 0 <issue_comment>username_2: I notice you are using webpack 4. According to [json-loader README](https://github.com/webpack-contrib/json-loader):
>
> username_2ce webpack >= v2.0.0, importing of JSON files will work by default
>
>
>
So if you are using `webpack >= v2.0.0` and `json-loader` together, the file will be transformed twice which caused the issue. The solution is simply delete the `json-loader` rule.
Upvotes: 5 [selected_answer] |
2018/03/19 | 1,701 | 6,401 | <issue_start>username_0: I recently heard about the new C# Feature in 7.2, so that we now can return a reference of value type (for example `int`) or even a readonly reference of a value type. So as far as I know a value type is stored in the stack. And when the method is left, they are removed from stack. So what happens with the int when the method `GetX` exits?
```
private ref int GetX()
{
// myInt is living on the stack now right?
int myInt = 5;
return ref myInt;
}
private void CallGetX()
{
ref int returnedReference = ref GetX();
// where does the target of 'returnedReference' live now?
// Is it somehow moved to the heap, because the stack of 'GetX' was removed right?
}
```
I'm getting the error
>
> Error CS8168: Cannot return local 'myInt' by reference because it is not a ref local (11, 24)
>
>
>
So why does it not work? Does it not work just because the variable can not be moved to the heap? Is this the problem? can we only return value types by reference if they do not live in the stack? I know that this are two question in one.
First: Where do value type-variables returned by ref live? Stack or heap? (I guess on the heap but why)?
Second: Why can a value type created on the stack not be returned by reference?
So this is able to be compiled:
```
private int _myInt;
private ref int GetX()
{
// myInt is living on the stack now right?
_myInt = 5;
return ref _myInt;
}
private void CallGetX()
{
ref int returnedReference = ref GetX();
// where does the target of 'returnedReference' live now?
// Is it somehow moved to the heap? becase the stack of 'GetX' was removed right?
}
```
If I understand your comments right it is because now the \_myInt lives not inside the method `GetX` and there fore is not created in the stack right?<issue_comment>username_1: I feel like you understand yourself already why it does not work. You cannot return *local variable* by reference from method (unless it's ref local), because in most cases lifetime of local variable is the method, so its reference outside of method does not have any meaning (outside of method this variable is dead and location where it were before might contain anything). As documentation states:
>
> The return value must have a lifetime that extends beyond the
> execution of the method. In other words, it cannot be a local variable
> in the method that returns it
>
>
>
In practice some local variables might live longer than execution of method they are declared in. For example, variables captured by closure:
```
int myLocal = 5;
SomeMethodWhichAcceptsDelegate(() => DoStuff(myLocal));
return ref myLocal;
```
However, this introduces additional complications without any benefits, so this is also forbidden, even though lifetime of `myLocal` might be much longer than containing method.
It's better to not think about it in terms of stack and heap. For example you might think that you cannot return reference to something allocated on stack from the method via `ref return`. That's not true, for example:
```
private void Test() {
int myLocal = 4;
GetX(ref myLocal);
}
private ref int GetX(ref int i) {
return ref i;
}
```
Here `myLocal` is clearly on stack, and we pass it by reference to `GetX` and then return this (stack allocated) variable with `return ref`.
So just think about it in terms of variable lifetimes and not stack\heap.
In your second example, lifetime of `_myInt` field is clearly longer than execution of `GetX`, so there is no problem to return it by reference.
Note also that whether you return value type or reference type with `return ref` doesn't make any difference in context of this question.
Upvotes: 3 [selected_answer]<issue_comment>username_2: >
> So as far as I know a value type is stored in the stack.
>
>
>
and thus is the basis of your confusion; this is a simplification that is *grossly inaccurate*. Structs *can* live on the stack, but they can also live:
* as field on objects on the heap
* as fields on *other* structs that are (etc etc) a field on an object on the heap
* boxed on the heap (directly, or via either of the above)
* in unmanaged memory
You're right, though: if you passed a `ref return` *out* of a method, to a local *inside* a method, you will have violated stack integrity. That's precisely why that scenario *isn't allowed*:
```
ref int RefLocal()
{
int i = 42;
return ref i;
// Error CS8168 Cannot return local 'i' by reference because it is not a ref local
}
```
There *are* some scenarios when the compiler can prove that even though it was stored as a local, the lifetime was was scoped to this method; it helps that you can't reassign a `ref` local (to be honest, this check is a key reason for this restriction); this allows:
```
ref int RefParamViaLoval(ref int arg)
{
ref int local = ref arg;
return ref local;
}
```
Since `ref int arg` has lifetime that isn't scoped to the method, our `ref int local` can inherit this lifetime in the assignment.
---
So what *can* we usefully return?
It could be a reference to *the interior of an array*:
```
ref int RefArray(int[] values)
{
return ref values[42];
}
```
It could be a field (not property) on an object:
```
ref int ObjFieldRef(MyClass obj)
{
return ref obj.SomeField;
}
```
It could be a field (not property) on a struct *passed in by reference*:
```
ref int StructFieldRef(ref MyStruct obj)
{
return ref obj.SomeField;
}
```
It could be something obtained from an onward call *as long as the call doesn't involve any ref locals known to point to locals* (which would make it impossible to prove validity):
```
ref int OnwardCallRef()
{
ref MyStruct obj = ref GetMyStructRef();
return ref obj.SomeField;
}
```
Here again note that the lifetime of the local inherits the lifetime of any parameters passed into the onward call; if the onward call involved a `ref`-local *with constrained lifetime*, then the *result* would inherit that constrained lifetime, and you would not be able to return it.
And that onward call could be, for example, calling out to structs held in unmanaged memory:
```
ref int UnmanagedRef(int offset)
{
return ref Unsafe.AsRef(ptr + offset);
}
```
So: lots of very valid and useful scenarios that don't involve references to the current stack-frame.
Upvotes: 2 |
2018/03/19 | 1,729 | 6,553 | <issue_start>username_0: im kinda new to the site, as a user atleast, been finding my answers in here for a long time :)
My problem is this, i work at a rather big hospital, where we run a mysql db containing all our employees, and now i need to make a query that can show my all employees who's employment ended during 2017. The thing is, since its a big hospital where ALOT of departments alot of the employees change jobs internally between the different departments, and everytime they do a new row in the table is created with their new employment details.
in every row for every employment, it contains their employer ID, the start date and end date, and some other info. the end date, can be either a date ofc, it can be NULL or 0000-00-00, the last 2 indicates that their imployment has no end date.
So its easy enough to do a simple search containing all users with and end date containing 2017
```
(SELECT * FROM table WHERE enddate LIKE '%2017%')
```
and it gives me all the users who has an end date in 2017, problem is ofc, that it does not account for users who might just have switched department, and has ended its employment in one department to start in another.
So what im trying to do is get all users with a 2017 enddate and then all people that has no enddate or and enddate after 2017 and then remove them from the list of people with an 2017 enddate.
i tried the following:
```
SELECT *
FROM users
WHERE enddate LIKE '%2017%' AND employid NOT IN
(
SELECT * FROM users WHERE enddate LIKE '%0000%'
);
```
i know it doesnt really over all i wanted, but at first i was really just trying to get the NOT IN to work in some way, and then after that work my way on to include the rest, but i cant even get that to work.
I tried searching for some uses of NOT IN, but it seemed to always be some very simple uses of them and always on 2 different tables.
I hope i explained it correct, as stated im still kinda new to mysql and sql in general :)<issue_comment>username_1: I feel like you understand yourself already why it does not work. You cannot return *local variable* by reference from method (unless it's ref local), because in most cases lifetime of local variable is the method, so its reference outside of method does not have any meaning (outside of method this variable is dead and location where it were before might contain anything). As documentation states:
>
> The return value must have a lifetime that extends beyond the
> execution of the method. In other words, it cannot be a local variable
> in the method that returns it
>
>
>
In practice some local variables might live longer than execution of method they are declared in. For example, variables captured by closure:
```
int myLocal = 5;
SomeMethodWhichAcceptsDelegate(() => DoStuff(myLocal));
return ref myLocal;
```
However, this introduces additional complications without any benefits, so this is also forbidden, even though lifetime of `myLocal` might be much longer than containing method.
It's better to not think about it in terms of stack and heap. For example you might think that you cannot return reference to something allocated on stack from the method via `ref return`. That's not true, for example:
```
private void Test() {
int myLocal = 4;
GetX(ref myLocal);
}
private ref int GetX(ref int i) {
return ref i;
}
```
Here `myLocal` is clearly on stack, and we pass it by reference to `GetX` and then return this (stack allocated) variable with `return ref`.
So just think about it in terms of variable lifetimes and not stack\heap.
In your second example, lifetime of `_myInt` field is clearly longer than execution of `GetX`, so there is no problem to return it by reference.
Note also that whether you return value type or reference type with `return ref` doesn't make any difference in context of this question.
Upvotes: 3 [selected_answer]<issue_comment>username_2: >
> So as far as I know a value type is stored in the stack.
>
>
>
and thus is the basis of your confusion; this is a simplification that is *grossly inaccurate*. Structs *can* live on the stack, but they can also live:
* as field on objects on the heap
* as fields on *other* structs that are (etc etc) a field on an object on the heap
* boxed on the heap (directly, or via either of the above)
* in unmanaged memory
You're right, though: if you passed a `ref return` *out* of a method, to a local *inside* a method, you will have violated stack integrity. That's precisely why that scenario *isn't allowed*:
```
ref int RefLocal()
{
int i = 42;
return ref i;
// Error CS8168 Cannot return local 'i' by reference because it is not a ref local
}
```
There *are* some scenarios when the compiler can prove that even though it was stored as a local, the lifetime was was scoped to this method; it helps that you can't reassign a `ref` local (to be honest, this check is a key reason for this restriction); this allows:
```
ref int RefParamViaLoval(ref int arg)
{
ref int local = ref arg;
return ref local;
}
```
Since `ref int arg` has lifetime that isn't scoped to the method, our `ref int local` can inherit this lifetime in the assignment.
---
So what *can* we usefully return?
It could be a reference to *the interior of an array*:
```
ref int RefArray(int[] values)
{
return ref values[42];
}
```
It could be a field (not property) on an object:
```
ref int ObjFieldRef(MyClass obj)
{
return ref obj.SomeField;
}
```
It could be a field (not property) on a struct *passed in by reference*:
```
ref int StructFieldRef(ref MyStruct obj)
{
return ref obj.SomeField;
}
```
It could be something obtained from an onward call *as long as the call doesn't involve any ref locals known to point to locals* (which would make it impossible to prove validity):
```
ref int OnwardCallRef()
{
ref MyStruct obj = ref GetMyStructRef();
return ref obj.SomeField;
}
```
Here again note that the lifetime of the local inherits the lifetime of any parameters passed into the onward call; if the onward call involved a `ref`-local *with constrained lifetime*, then the *result* would inherit that constrained lifetime, and you would not be able to return it.
And that onward call could be, for example, calling out to structs held in unmanaged memory:
```
ref int UnmanagedRef(int offset)
{
return ref Unsafe.AsRef(ptr + offset);
}
```
So: lots of very valid and useful scenarios that don't involve references to the current stack-frame.
Upvotes: 2 |
2018/03/19 | 1,703 | 4,831 | <issue_start>username_0: I want to get the value of the json response. I wrote an Ajax function as below:
```
$.ajax({
url: '/v1/shopify-Ajax/ajax.php',
method: 'post',
data: {datalog: dataLog, variant: $('#prod').val()}
})
.success(function(response){
//window.location.href = "/v1/thank-you.php";
})
```
I get the response from the server side script as below:
```
{"order":
{"id":303657910281,
"email":"<EMAIL>",
"closed_at":null,
"created_at":"2018-03-19T01:04:58-07:00",
"updated_at":"2018-03-19T01:04:58-07:00",
"number":811,
"note":null,
"token":"9709d7c295ac1dbbaf29c2d09a9d5a9d",
"gateway":"",
"test":false,
"total_price":"82.49",
"subtotal_price":"82.49",
"total_weight":null,
"total_tax":"0.00",
"taxes_included":false,
"currency":"USD",
"financial_status":"paid",
"confirmed":true,
"total_discounts":"0.00",
"total_line_items_price":"82.49","cart_token":null,"buyer_accepts_marketing":false,"name":"#1811","referring_site":null,"landing_site":null,"cancelled_at":null,"cancel_reason":null,"total_price_usd":"82.49","checkout_token":null,"reference":null,"user_id":null,"location_id":null,"source_identifier":null,"source_url":null,"processed_at":"2018-03-19T01:04:58-07:00","device_id":null,"phone":null,"customer_locale":null,"app_id":2306584,"browser_ip":null,"landing_site_ref":null,"order_number":1811,"discount_codes":[],"note_attributes":[],"payment_gateway_names":[""],"processing_method":"","checkout_id":null,"source_name":"2306584","fulfillment_status":null,"tax_lines":[],"tags":"","contact_email":"<EMAIL>","order_status_url":"https:\/\/checkout.shopify.com\/19258983\/orders\/9709d7c295ac1dbbaf29c2d09a9d5a9d\/authenticate?key=0XXX","line_items":[{"id":610330640393,"variant_id":2323256639497,"title":"XX","quantity":1,"price":"82.49","sku":"","variant_title":"3 XX","vendor":"X1","fulfillment_service":"manual","product_id":235965415433,"requires_shipping":false,"taxable":false,"gift_card":false,"pre_tax_price":"82.49","name":"XXXX","variant_inventory_management":null,"properties":[],"product_exists":true,"fulfillable_quantity":1,"grams":0,"total_discount":"0.00","fulfillment_status":null,"tax_lines":[]}],"shipping_lines":[],"billing_address":{"first_name":"","address1":"","phone":null,"city":"","zip":"","province":"","country":null,"last_name":"","address2":null,"company":null,"latitude":null,"longitude":null,"name":"","country_code":null,"province_code":null},"shipping_address":{"first_name":"test","address1":"6116 Beverly Dr","phone":null,"city":"Adair","zip":"50002","province":"Iowa","country":"United States","last_name":"tes","address2":null,"company":null,"latitude":null,"longitude":null,"name":"test tes","country_code":"US","province_code":"IA"},"fulfillments":[],"refunds":[],"customer":{"id":324158947337,"email":"<EMAIL>","accepts_marketing":false,"created_at":"2018-03-19T01:04:58-07:00","updated_at":"2018-03-19T01:04:58-07:00","first_name":"test","last_name":"tes","orders_count":1,"state":"disabled","total_spent":"0.00","last_order_id":303657910281,"note":null,"verified_email":true,"multipass_identifier":null,"tax_exempt":false,"phone":null,"tags":"","last_order_name":"#1811","default_address":{"id":371809157129,"customer_id":324158947337,"first_name":"test","last_name":"tes","company":null,"address1":"6116 Beverly Dr","address2":null,"city":"Adair","province":"Iowa","country":"United States","zip":"50002","phone":null,"name":"test tes","province_code":"IA","country_code":"US","country_name":"United States","default":true}}}}
```
My question is, how to access the order id directly (no loop) and check if the order id is not null or blank.
!<issue_comment>username_1: If `response` is a string, you might need to parse it, otherwise you can read the value directly.
If `console.log` shows an object you can expand (in developer tools console) just use
```
var id = response.order.id;
```
If that doesn't work, or you're sure it's a string use
```
var responseObj = JSON.parse(response);
var id = responseObj.order.id;
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: You need to ensure that `response` is parsed into an object before doing `response.order.id`
Mention
```
dataType : "json"
```
i.e.
```
$.ajax({
url: '/v1/shopify-Ajax/ajax.php',
dataType : "json",
method: 'post',
data: {datalog: dataLog, variant: $('#prod').val()}
})
.success( function(response){ console.log( response.order.id ) })
//window.location.href = "/v1/thank-you.php";
})
```
Upvotes: 2 <issue_comment>username_3: In your AJAX success you need to decode the JSON.
```
var data = $.parseJSON(response);
alert(data.order.id); //you will get order id
```
Upvotes: 0 |
2018/03/19 | 453 | 1,674 | <issue_start>username_0: It should work but it doesn't.
I have referred others but couldn't find the reason.
```
OracleCommand cmd = con.CreateCommand();
var query = $@"UPDATE Customer SET ContactName = :ct WHERE CustomerID = :id";
cmd.CommandText = query;
cmd.Parameters.Clear();
cmd.Parameters.Add(new OracleParameter(":id", OracleDbType.Varchar2, "bbb1", System.Data.ParameterDirection.Input));
cmd.Parameters.Add(new OracleParameter(":ct", OracleDbType.Varchar2, "Joon", System.Data.ParameterDirection.Input));
var rst = cmd.ExecuteNonQuery();
```
Thanks in advance.
Joon<issue_comment>username_1: I found why it didn't update table.
To make it work I added parameters in the order of the query parameter and found it works. But I still do not understand why the order of adding parameters is so important to make it work.But the thing clear is that it is working when I make it like this:
```
OracleCommand cmd = con.CreateCommand();
var query = $@"UPDATE Customer SET ContactName = :ct WHERE CustomerID = :id";
cmd.CommandText = query;
cmd.Parameters.Clear();
cmd.Parameters.Add(new OracleParameter(":ct", OracleDbType.Varchar2, "Joon", System.Data.ParameterDirection.Input));
cmd.Parameters.Add(new OracleParameter(":id", OracleDbType.Varchar2, "bbb1", System.Data.ParameterDirection.Input));
var rst = cmd.ExecuteNonQuery();
```
Thanks everybody who paid attention on it.
Joon
Upvotes: 4 [selected_answer]<issue_comment>username_2: In order to avoid the order declaration, you can use BindByName:
```cs
OracleCommand cmd = con.CreateCommand();
cmd.BindByName = true; // Just add this
...
```
Upvotes: 0 |
2018/03/19 | 541 | 1,688 | <issue_start>username_0: Heei, I have a problem when view my html result with blade laravel. Look at this pictures
**Code**
[](https://i.stack.imgur.com/atsoj.png)
**HTML**
```
@foreach($acara as $value)

@endforeach
```
CSS
```
* {
box-sizing: border-box;
margin: 0;
padding: 0;
list-style-type: none;
text-decoration: none;
}
a {
color: inherit;
}
/*and some other css which is not appropriate with this case*/
body {
font-size: 16px;
overflow-x: hidden;
}
main {
padding: 20px 0;
}
.container {
width: 90%;
margin: 0 auto;
overflow: hidden;
}
```
**Result**
[](https://i.stack.imgur.com/xv5yd.png)
Please look. Why the `a` tag not wrapping the `figure`? and the `a`tag looks like repeat on every element inside `figure`?<issue_comment>username_1: According to these ([1](https://stackoverflow.com/questions/41959446/href-inside-href), [2](https://stackoverflow.com/questions/9882916/are-you-allowed-to-nest-a-link-inside-of-a-link)) answers. Nesting an is bad practice. You can force to make it work by wrapping the nested href's inside an tag
Upvotes: 2 [selected_answer]<issue_comment>username_2: You have child links inside parent link, instead of this you can just move a link tag from your wrapper to the image (or any another element inside `figure`).
```
[](#)
{{ $value->tanggal\_event }}
{{ $value->nama\_event }}
[{{ $value->lokasi\_event }}](#)
[{{ $value->kategori\_event }}](#)
```
Upvotes: 0 |
2018/03/19 | 1,549 | 3,928 | <issue_start>username_0: ```
#include
int main()
{
int a, b, c, temp;
scanf("%d %d %d", &a, &b, &c);
if (a > b)
{
temp = a;
a = b;
b = temp;
}
else if (b > c)
{
temp = b;
b = c;
c = temp;
}
else if (c > a)
{
temp = c;
c = a;
a = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
```
If I put 8,6,3, the output comes 6,8,3. It doesn't change the last number. I am trying to arrange three 3 numbers in ascending manner using if statement, but this doesn't work for the third number. What can be done about it?<issue_comment>username_1: It easiest if you first find the smallest, then make sure the remaining two are correct :
```
int main()
{
int a, b, c, temp;
int ret = scanf("%d %d %d", &a, &b, &c);
if (ret != 3) {
printf("scanf() error\n");
exit(1);
}
// get smallest into a
if ((b < a) && (b < c)) {
temp = a;
a = b;
b = temp;
} else if ((c < a) && (c < b)) {
temp = a;
a = c;
c = temp;
}
// a is smallest, check b and c
if (c < b) {
temp = b;
b = c;
c = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
```
Upvotes: 1 <issue_comment>username_2: I think you have misunderstood the concept of if else if structure, In your case it is not working for third number because the execution will reach to else if part only when the if condition is false.
```
#include
int main()
{
int a,b,c,temp;
scanf("%d %d %d",&a,&b,&c);
if(a>b) //evaluates to true.
{
temp=a;
a=b;
b=temp;
}
else if(b>c) // not able to execute.
{
temp=b;
b=c;
c=temp;
}
else if(c>a) // not able to execute
{
temp=c;
c=a;
a=temp;
}
printf("%d %d %d",a,b,c);
return 0;
}
a = 8
b = 6
c = 3
checking a>b evaluates to true hence swapped
now:
a = 6 // your output
b = 8
c = 3
```
you may need to go over the concept of if else structure once again
Upvotes: 0 <issue_comment>username_3: ```
#include
int main()
{
int a,b,c,temp,min;
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
temp=a;
a=b;
b=temp;
}
if(ca && b
```
you are comparing using `else if`, if any one condition satisfies it won't execute the other `else` condition.
Upvotes: -1 <issue_comment>username_4: ```
#include
int main()
{
int a ,b,c;
printf("Enter the number : \n");
scanf("%d %d %d",&a,&b,&c);
if((a>b)&&(a>c))
{
if(b>c)
printf("%d %d %d",a,b,c);
else
printf("%d %d %d",a ,c,b);
}
else if((b>c)&&(b>a))
{
if(c>a)
printf("%d %d %d",b,c,a);
else
printf("%d %d %d",b,a,c);
}
else if((c>a)&&(c>b))
{
if(a>b)
printf("%d %d %d",c,a,b);
else
printf("%d %d %d",c,b,a);
}
return 0;
}
```
Upvotes: 0 <issue_comment>username_5: You need to use `if` instead of `else if` as you want to compare a with b, b with c and a with c (the three and not only one of them). Moreover, as you are moving the numbers you have to take into account where they are moved for the last comparison. And your third condition was wrong. So this should be what you are trying to do:
```
#include
int main(){
int a, b, c, temp;
scanf("%d %d %d", &a, &b, &c);
if (a > b){
temp = a;
a = b;
b = temp;
}
if (b > c){
temp = b;
b = c;
c = temp;
if (a > b){
temp = a;
a = b;
b = temp;
}
}
else if (a > c){
temp = c;
c = a;
a = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
```
Upvotes: 1 <issue_comment>username_6: The easiest way is to use an array instead of three individual variables. Then use `qsort` for getting the input sorted.
Like:
```
#include
#include
// Compare function for qsort
int cmp(const void \*p1, const void \*p2)
{
if (\*(int\*)p1 < \*(int\*)p2) return -1;
if (\*(int\*)p2 < \*(int\*)p1) return 1;
return 0;
}
int main()
{
int arr[3];
if (scanf("%d %d %d", &arr[0], &arr[1], &arr[2]) != 3) exit(1);
// Sort the input
qsort(arr, sizeof(arr)/sizeof(int), sizeof(int), cmp);
printf("%d %d %d\n", arr[0], arr[1], arr[2]);
return 0;
}
```
Upvotes: 0 |
2018/03/19 | 648 | 2,448 | <issue_start>username_0: Is it possible to sync users from cloud Azure Active Directory to on premise AD? On premise is a bit wrong here because it is actually a virtual network in Azure with a Windows Server virtual machine AD. I started with Azure AD and therefore all users are there but I would like to sync them to this virtual machine AD in a virtual network in Azure. I tried Azure AD Connect but this works to sync form on premise to Azure AD. How can I do it the other way around?<issue_comment>username_1: >
> Is it possible to sync users from cloud Azure Active Directory to on
> premise AD?
>
>
>
For now, it is not possible.
Here the [feedback](https://feedback.azure.com/forums/169401-azure-active-directory/suggestions/6455327-sync-azure-active-directory-down-to-on-premises-ad) about it, maybe you can vote up it, that feedback will be monitored and reviewed by the Microsoft engineering teams.
As a workaround, we can use powershell to export Azure AD users' information to local file, then use that file to create users in on premise AD.
Here a similar [case](https://superuser.com/questions/1050567/can-we-sync-azure-ad-users-to-our-on-premise-ad) about you, please refer to it.
Hope this helps.
Upvotes: 2 <issue_comment>username_2: I have written a custom algorithm to do the process and it works for me so far so well.
I would state the approach that I have followed. This process will get executed after user logs in through `Single Sign On`.
Step-by-step process to be followed once the user is validated with AD.
* Fetch User Manager Chain for the user with Indian Region Filter
through Graph API
https://graph.microsoft.com/v1.0/users/${usermail}?$expand=manager($levels=max;
* Convert User Chain Nested Objects to Array of Users
* Loop user array in reverse
* For every traversal, check if the user present (match with Object ID)
If User Present in Database,
```
a. Compare user data with OIDC :id:
b. On Variance, call update() to keep data in sync with AD information
```
User not Present in DB,
```
a. Call insert() to insert the user data to the database
```
***Note:**
I am calling this process every time a user logs in and it is able to insert any new users or update the data in the database if it doesn't match with AAD. This would be an efficient approach if the management chain is around 10. I couldn't find a way to do this thing anywhere else so came up with this process.*
Upvotes: 0 |
2018/03/19 | 2,620 | 8,153 | <issue_start>username_0: I'm able to capture signals from a RTL-SDR by using the following:
```
from rtlsdr import *
i = 0
signals = []
sdr = RtlSdr()
sdr.sample_rate = 2.8e6
sdr.center_freq = 434.42e6
sdr.gain = 25
while True:
samples = sdr.read_samples(1024*1024)
decibel = 10*log10(var(samples))
if decibel >= -10:
signals.append(samples)
i += 1
if i == 2:
break
```
If I plot the signals using Matplotlib and Seaborn, they look something like this:
[](https://i.stack.imgur.com/52dMy.png)
Now, what I would need is to get the coordinates of all peaks above a certain power level, e.g., -20.
I found a rather promising listing of the various [Python options](https://github.com/MonsieurV/py-findpeaks#peakutilspeakindexes). However, all those examples use a simple Numpy array which the different algorithms can easily work with.
This was the best attempt (because my guess is that I get a complex signal from the RTL-SDR and have to "transform" it to an array with real values?):
```
import numpy as np
import peakutils.peak
real_sig = np.real(signals[0])
indexes = peakutils.peak.indexes(real_sig, thres=-20.0/max(real_sig), min_dist=1)
print("Peaks are: %s" % (indexes))
```
With these few lines added to the script above I do get some output, but, first, there are way too many values for the just five peaks above power level -20. And, second, the values don't make much sense in the given context.
[](https://i.stack.imgur.com/wzOlI.png)
So, what do I need to change to get meaningful results like "Peak 1 is at 433.22 MHz"?
Ideally, I should get coordinates like `Peak 1: X = 433.22, Y = -18.0`, but I guess I can figure that out myself once I know how to get the correct X-values.<issue_comment>username_1: You are missing several steps.
You first need to: Pick a segment of complex IQ data from the RTL-SDR of length N (you may need to convert the raw IQ samples from unsigned 8-bit to signed floating point), window it (von Hann or Hamming, etc.), convert it to the frequency domain via an FFT of length N, convert the FFT result to log magnitude, and label the FFT log magnitude result bins (e.g. array elements) by frequency, which will be roughly
```
frequency(i) = sdr.center_freq + i * sdr.sample_rate / N
```
for bins 0 to N/2
```
frequency(i) = sdr.center_freq - (N - i) * sdr.sample_rate / N
```
for bins N/2 to N-1
Then you can search along that log magnitude array for peaks, and apply the frequency label to the peaks found.
Added: You can't get frequency domain information (as in frequency peaks) directly from an RTL-SDR. The peaks you want are not there. An RTL-SDR outputs raw complex/IQ time domain samples, not frequency domain data. So first you need to look up, study, and understand the difference between the two. Then you might understand why an FFT (or DFT, or Goertzels, or wavelets, etc.) is needed to do the conversion.
Upvotes: 1 <issue_comment>username_2: I have now tried the following code (inspired by the answer from username_1 and by what I found on Google):
```
from numpy.fft import fft, fftshift
window = np.hamming(sdr.sample_rate/1e6+1)
plt.figure()
A = fft(window, 2048) / 25.5 # what do these values mean?
mag = np.abs(fftshift(A))
freq = np.linspace(sdr.center_freq/1e6-(sdr.sample_rate/1e6)/2, sdr.center_freq/1e6+(sdr.sample_rate/1e6)/2, len(A))
response = 20 * np.log10(mag)
#response = np.clip(response, -100, 100)
plt.plot(freq, response)
plt.title("Frequency response of Hamming window")
plt.ylabel("Magnitude [dB]")
plt.xlabel("Normalized frequency [cycles per sample]")
plt.axis("tight")
plt.show()
```
Source: <https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.hamming.html>
This results in the following (absolutely useless) signal plot:
[](https://i.stack.imgur.com/BfEPq.png)
I need a plot like the PSD in my original posting, in which I can then detect the peaks.
Can someone, please, explain to my why I'm supposed to do all this Hamming/FFT stuff?
All I want is a representation of my signal (as received by the RTL-SDR) that the peakutils.peak.indexes() method accepts and returns the correct peaks from.
Upvotes: 0 <issue_comment>username_3: Something similar to:
get your `signals` array of y value relative power.
```
sort([x for x in signals > -20])
sort[:i]
```
for the i fist peaks.
For frequency range:
```
frequency_peaks = [ frequencyspectrum[a] for a in signals[:i]]
```
But really you should be using Fourrier transform and binning (@username_1's answer):
[](https://i.stack.imgur.com/URhwk.png)
`numpy.fft` will do the trick:
<https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.fft.html>
Also see:
<https://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem>
for background theory.
Upvotes: 1 <issue_comment>username_2: I believe I'm starting to understand what all of you were trying to tell me ...
The goal is still to reproduce a chart like the following (which was created using Matplotlib's plt.psd() method):
[](https://i.stack.imgur.com/2raB5.png)
Now, I have been able to come up with three different code segments, each of which got me pretty close, but none is perfect yet:
```
# Scipy version 1
from scipy.signal import welch
sample_freq, power = welch(signal[0], sdr.sample_rate, window="hamming")
plt.figure(figsize=(9.84, 3.94))
plt.semilogy(sample_freq, power)
plt.xlabel("Frequency (MHz)")
plt.ylabel("Relative power (dB)")
plt.show()
```
The above one produces the following plot:
[](https://i.stack.imgur.com/dbXOJ.png)
While the figure doesn't look too bad, I have absolutely no idea why a part of the center peak is missing and where that strange line that connects both ends of the figure comes from. Also, I couldn't figure out how to display the proper values for power level and frequencies.
My next attempt:
```
# Scipy version 2
from scipy.fftpack import fft, fftfreq
window = np.hamming(len(signal[0]))
sig_fft = fft(signal[0])
power = 20*np.log10(np.abs(sig_fft)*window)
sample_freq = fftfreq(signal[0].size, sdr.sample_rate/signal[0].size)
plt.figure(figsize=(9.84, 3.94))
plt.plot(sample_freq, power)
plt.xlabel("Frequency (MHz)")
plt.ylabel("Relative power (dB)")
plt.show()
```
This gets me the following result:
[](https://i.stack.imgur.com/WbLq7.png)
Clearly, I'm on the right track again but I have no idea how to apply the Hamming window in that version of the code (obviously, I did it the wrong way). And like in the previous attempt I couldn't figure out how to display the correct frequencies in the x-axis.
My last attempt uses Numpy instead of Scipy:
```
# Numpy version
window = np.hamming(len(signal[0]))
sig_fft = np.fft.fft(signal[0])
sample_freq = np.fft.fftfreq(signal[0].size, sdr.sample_rate/signal[0].size)
power = 20*np.log10(np.abs(sig_fft))
plt.figure(figsize=(9.84, 3.94))
plt.plot(sample_freq, power)
plt.xlabel("Frequency (MHz)")
plt.ylabel("Relative power (dB)")
plt.show()
```
And the result is:
[](https://i.stack.imgur.com/MsswW.png)
I'd say this one probably comes closest to what I want (the Scipy version 2 would look the same without the wrongly applied hamming window), if it weren't for all that noise. Again, no idea how to apply the Hamming window to get rid of the noise.
**My questions are:**
* How do I apply the Hamming window in the second and third code segment?
* How do I get the proper frequencies (values from 434.42-1.4 to 434.42+1.4) on the x-axis?
* Why is the signal displayed on a significantly higher power level in all three plots than it is in the original plot (created by plt.psd())?
Upvotes: 0 |
2018/03/19 | 453 | 1,755 | <issue_start>username_0: Recently I'm programing an app with nativescript, and now I have a problem that I don't know how to save the user's login state. For example, if user login at the first time, he will not need to login in the future. So how could I achieve this?<issue_comment>username_1: Use **application-settings** module to store your session key or something, if no value is there consider it's first time login.
Docs: <https://docs.nativescript.org/cookbook/application-settings>
Upvotes: 0 <issue_comment>username_2: You can use the [`application-settings`](https://docs.nativescript.org/api-reference/modules/_application_settings_) module to store different type of values (e.g. `number`, `string`, `boolean`) and use the module to check if the user has already logged in.
Upvotes: 0 <issue_comment>username_3: I do use `application-settings` on my apps, the same module that the other answers suggest.
You can get code samples for [Angular](https://docs.nativescript.org/angular/code-samples/application-settings) and [vanilla](https://docs.nativescript.org/cookbook/application-settings) JS.
Also, in one of my apps, I've created a `config.ts` class that handles my app's settings:
```
import {
getBoolean,
setBoolean,
getNumber,
setNumber,
getString,
setString,
hasKey,
remove,
clear
} from "application-settings";
export class Config {
clear() {
clear()
}
get token(): string {
return getString('token')
}
set token(token: string) {
setString('token', token)
}
get userId(): string {
return getString('userId')
}
set userId(userId: string) {
setString('userId', userId)
}
}
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 764 | 2,941 | <issue_start>username_0: I need guys your help.
I can't understand what to use either list or set. List is more efficient. dictionary also need index. but my problem is text should be string so variable must equal to text as string. I can't D=['a','b','c'].
text gives me error because it can't compare them all except individual and i must create such as abc or word example as \_success and confirm its in the list to be true.
This is my code so far but i have problem which is now it accepts numbers and letters and symbols. Symbols such as !@#$% should be returning False.
Having it as own function works but i need it in the if statement.
return text.isalnum() doesn't work in the if statement. Thats my problem symbols should be false.
```
def check(text):
if text== '':
return False
if text.isalpha() == text.isdigit():
return True
else:
return text.isalnum()
def main():
text = str(raw_input("Enter text: "))
print(check(text))
main()
```
output problem.
Enter text: \_
False
\_ is suppose to be one of the symbols True. Example \_success123 is True
!@#$% is suppose to be false but its showing as True as output Another example is !@#A123. This output is False.
The code up there does accept the underscore and letter and number
output:
\_success123
but problem is also accepts !@#$ as True.
return text.isalnum() Does deny the symbols but its not working in the if statement.<issue_comment>username_1: Use **application-settings** module to store your session key or something, if no value is there consider it's first time login.
Docs: <https://docs.nativescript.org/cookbook/application-settings>
Upvotes: 0 <issue_comment>username_2: You can use the [`application-settings`](https://docs.nativescript.org/api-reference/modules/_application_settings_) module to store different type of values (e.g. `number`, `string`, `boolean`) and use the module to check if the user has already logged in.
Upvotes: 0 <issue_comment>username_3: I do use `application-settings` on my apps, the same module that the other answers suggest.
You can get code samples for [Angular](https://docs.nativescript.org/angular/code-samples/application-settings) and [vanilla](https://docs.nativescript.org/cookbook/application-settings) JS.
Also, in one of my apps, I've created a `config.ts` class that handles my app's settings:
```
import {
getBoolean,
setBoolean,
getNumber,
setNumber,
getString,
setString,
hasKey,
remove,
clear
} from "application-settings";
export class Config {
clear() {
clear()
}
get token(): string {
return getString('token')
}
set token(token: string) {
setString('token', token)
}
get userId(): string {
return getString('userId')
}
set userId(userId: string) {
setString('userId', userId)
}
}
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 494 | 1,855 | <issue_start>username_0: Hi I'm a beginner in Asp.net actually I'm trying to prevent the user from inserting letter in the phone number text box, I am trying this code but it doesn't work.
```
private void TxtBox5_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!Char.IsDigit(ch) && ch !=8)
{
e.Handled = true;
}
}
```<issue_comment>username_1: Use **application-settings** module to store your session key or something, if no value is there consider it's first time login.
Docs: <https://docs.nativescript.org/cookbook/application-settings>
Upvotes: 0 <issue_comment>username_2: You can use the [`application-settings`](https://docs.nativescript.org/api-reference/modules/_application_settings_) module to store different type of values (e.g. `number`, `string`, `boolean`) and use the module to check if the user has already logged in.
Upvotes: 0 <issue_comment>username_3: I do use `application-settings` on my apps, the same module that the other answers suggest.
You can get code samples for [Angular](https://docs.nativescript.org/angular/code-samples/application-settings) and [vanilla](https://docs.nativescript.org/cookbook/application-settings) JS.
Also, in one of my apps, I've created a `config.ts` class that handles my app's settings:
```
import {
getBoolean,
setBoolean,
getNumber,
setNumber,
getString,
setString,
hasKey,
remove,
clear
} from "application-settings";
export class Config {
clear() {
clear()
}
get token(): string {
return getString('token')
}
set token(token: string) {
setString('token', token)
}
get userId(): string {
return getString('userId')
}
set userId(userId: string) {
setString('userId', userId)
}
}
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 633 | 2,513 | <issue_start>username_0: I have been working on this issue for some time now
This is the code I am testing
```
public Observable prepare() {
return Observable.create(subscriber -> {
// Some work is being done here but this part is never reached
subscriber.onCompleted();
}).subscribeOn(scheduler);
}
```
The scheduler is the looper's scheduler (the class inherits from HandlerThread)
The test I am writing is as follows:
```
@Test
public void prepare() throws Exception {
TestSubscriber testSubscriber = new TestSubscriber<>();
subject.start();
Observable obs = subject.prepare();
obs.subscribe(testSubscriber);
testSubscriber.awaitTerminalEvent(15, TimeUnit.SECONDS);
//assertions go here
subject.quit();
}
```
The problem is the code in the Observable.create is never reached and the testSubscriber's timeout is always hit.
I've checked that the looper runs and that the scheduler exists. It works well when I run the app. I am using RobolectricTestRunner.
Any ideas why the code is never reached?<issue_comment>username_1: Use **application-settings** module to store your session key or something, if no value is there consider it's first time login.
Docs: <https://docs.nativescript.org/cookbook/application-settings>
Upvotes: 0 <issue_comment>username_2: You can use the [`application-settings`](https://docs.nativescript.org/api-reference/modules/_application_settings_) module to store different type of values (e.g. `number`, `string`, `boolean`) and use the module to check if the user has already logged in.
Upvotes: 0 <issue_comment>username_3: I do use `application-settings` on my apps, the same module that the other answers suggest.
You can get code samples for [Angular](https://docs.nativescript.org/angular/code-samples/application-settings) and [vanilla](https://docs.nativescript.org/cookbook/application-settings) JS.
Also, in one of my apps, I've created a `config.ts` class that handles my app's settings:
```
import {
getBoolean,
setBoolean,
getNumber,
setNumber,
getString,
setString,
hasKey,
remove,
clear
} from "application-settings";
export class Config {
clear() {
clear()
}
get token(): string {
return getString('token')
}
set token(token: string) {
setString('token', token)
}
get userId(): string {
return getString('userId')
}
set userId(userId: string) {
setString('userId', userId)
}
}
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 415 | 1,468 | <issue_start>username_0: I am trying to add both an ID and class to input fields plus the addition of a number after each ID and class element so that they all have unique ID's and Class's. I need this to be added to the input fields on window load. After many attempts I am having trouble doing this with various counter suggestions.
I have now removed the non working code(s) to show where I am starting and hopefully someone can give me that extra bit of JavaScript to do this :), what I have so far is
```
Name:
Phone:
A button
```<issue_comment>username_1: ```
var elements = document.getElementsByTagName('input');
var index = 1;
for(var e of elements){
e.setAttribute("id", "fieldid"+index);
index++;
}
```
And you can do the same for the class attribute. Of course if you don't want every input element on the page to get new ids you have to use a more specific selector.
Upvotes: 0 <issue_comment>username_2: Here is an example of how you can use the incremental values for your `id` and `class` name for the `input` elements:
```js
function myFunc() {
var inputElem = document.getElementsByTagName("input");
for(var i=0; i < inputElem.length; i++){
inputElem[i].setAttribute("id", "field"+i);
inputElem[i].value = "<NAME> "+i;
inputElem[i].classList.add("mystyle" + i);
}
}
window.onload = myFunc();
```
```html
Name1:
Phone1:
Name2:
Phone2:
Name3:
Phone3:
A button
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 1,192 | 4,950 | <issue_start>username_0: I want to migrate my asp.net (UI ASPX pages WebForms) application to ASP.NET Core 2. By some search I found out aspx is not supported in .net core. If this is true(anyone has exact documentation for this?) how should anyone proceed to convert from pure asp.net aspx project to asp.net core 2.0?
I used portable analyzer tool but it is confusing to just give every .dll file and get report which is more confusing.
Please give valid Microsoft document if possible.<issue_comment>username_1: It all depends on what you mean by "migrate". As mentioned in the comments to your question, ASP.NET Core does not support web forms so there isn't any way to just automatically convert an a Web Forms website to an ASP.NET Core website.
That said, it is possible to make the migration. I have been working to do just that for a very large web forms based website that I want to convert to ASP.NET Core. If you are serious about making the journey, then here is some info that will probably help you.
The general architecture of ASP.NET Core is based on MVC so it's much more similar to ASP.NET MVC than ASP.NET Web Forms. So you will end up rewriting pretty much all of your UI code using some derivative of a MVC pattern. Instead of master pages you will be using layouts. Instead of server controls you will be using tag helpers. Instead of user controls you will be using partials and view components. Instead of code behinds you will be using controllers and view models. Etc.
It's worth noting that there is still an http context object, request object and response object and they are extremely similar to the analogous objects in web forms. So that helps with the conversion.
Also to make the conversion process easier, you can build an ASP.NET Core web application that targets the full framework. This means that you will have access to most everything you are use to in the full framework except anything in the System.Web namespace. Targeting the Full framework does mean that your new website will only run on windows. But if you can live with that (at least for now) it will make the conversion process easier for you.
If, in your old website, you broke out a bunch of the functionality into class libraries, that will make your life easier. You should be able to bring those class libraries over to the new website unchanged and reference them from the ASP.NET Core website and they will most likely work fine provided they don't reference System.Web. Any code that does reference System.Web will need to be modified to use the new analogous objects or UI approaches.
**So in the end, you may be able to bring over your data models, data access code, business objects, and business logic without too much hassle.** But you will have to do a total rewrite of your UI related code. That's the journey I'm on and it's not as hard as you might think, at least not once you get up to speed with ASP.NET Core in the first place. Go get `em!
Upvotes: 4 [selected_answer]<issue_comment>username_2: You can transfer all your business logic, models and even some controller methods (You just need to adjust those ActionResult to IActionResult). If you're using Ninject (for ASP.NET Framework IOS), you just need to register them to your Startup.cs. Basically, what I'm trying to say, you need to create a new application under .NET Core. It would be changes in the actual project solution, but your actual business flow won't be different. I hope this helps you.
Upvotes: -1 <issue_comment>username_3: I found [an article](https://tomasherceg.com/blog/post/migrating-asp-net-web-forms-apps-to-net-core-using-dotvvm) claiming that it's possible somehow.
As you know it's not easy to migrate entire project from WebForm to .Net Core instantly. So what if I be able to have my web form pages working on production and at the same time start to convert pages one by one gradually? I mean there are the combination of two approaches at the same project.
It's the idea that an open source named [DotVVM](https://github.com/riganti/dotvvm) proposes. You have your ASP.Net web form pages and merely install DotVVM through Nuget. DotVVM supports both approaches. DotVVM contains similar controls like GridView, Repeater, FileUpload and more, you need to know about DotVVM syntax though.
>
> DotVVM can run side-by-side with other ASP.NET frameworks (Web Forms, MVC, Razor Pages)
>
>
>
it's claimed that:
>
> If the business layer is separated properly, rewrite on one page takes about 1 hour in average.
>
>
>
After a few months (if your project is large), when all the ASPX pages are rewritten in DotVVM, you will be able to create a new ASP.NET Core project, move all DotVVM pages and viewmodels into it and use them with .NET Core. The syntax of DotVVM is the same on both platforms.
[Here](https://github.com/riganti/dotvvm-samples-webforms-migration) you can see five steps needed for the migration.
Upvotes: 2 |
2018/03/19 | 528 | 1,937 | <issue_start>username_0: I have this JSON object:
```
{"home_device_name":"light","light_status":[{"id_light":"1","status":"1"},{"id_light":"2","status":"0"}]}
```
I read it as a JSON object but I can't access "light\_status", I want to convert it to an array to be able to read it.<issue_comment>username_1: First add below model into your project
```
class LightStatus {
var idLight: String? = null
var status: String? = null
}
```
Now You can use following code for getting light array
```
fun getLightArray() :ArrayList{
val jsonString = "{\"home\_device\_name\":\"light\",\"light\_status\":[{\"id\_light\":\"1\",\"status\":\"1\"},{\"id\_light\":\"2\",\"status\":\"0\"}]}";
val jsonObject=JSONObject(jsonString)
val jsonArray =jsonObject.getJSONArray("light\_status")
val lightArray =ArrayList()
for (i in 0..jsonArray.length()-1){
val lightStatus=LightStatus()
lightStatus.idLight=jsonArray.getJSONObject(i).getString("id\_light")
lightStatus.status=jsonArray.getJSONObject(i).getString("status")
lightArray.add(lightStatus)
}
return lightArray
}
```
Upvotes: 0 <issue_comment>username_2: Use following code :
```
String str = "{\"home_device_name\":\"light\",\"light_status\":[{\"id_light\":\"1\",\"status\":\"1\"},{\"id_light\":\"2\",\"status\":\"0\"}]}";
try {
JSONObject jsonObject = new JSONObject(str);
String home_device_name = jsonObject.getString("home_device_name");
JSONArray jsonArray = jsonObject.getJSONArray("light_status");
for (int i = 0; i < jsonArray.length(); i++) {
String id_light = jsonArray.getJSONObject(i).getString("id_light");
String status = jsonArray.getJSONObject(i).getString("status");
Log.d("Value", "Pos = " + i + " id_light = " + id_light + " status = " + status);
}
} catch (JSONException e) {
e.printStackTrace();
}
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 460 | 1,691 | <issue_start>username_0: C:\apache-jmeter-4.0\bin>jmeter.bat
The JMETER\_HOME environment variable is not defined correctly
This environment variable is needed to run this program
JMETER\_HOME is set correctly in environment variable.
ApacheJMeter.jar is working fine.
Similar issue found in below link but this also not helping me.
[JMETER\_HOME environment variable is not defined](https://stackoverflow.com/questions/48882280/jmeter-home-environment-variable-is-not-defined)<issue_comment>username_1: You don't need to set `JMETER_HOME` variable manually, `jmeter.bat` script should detect it automatically.
Just in case you want to override it for any reason make sure you do this carefully and the variable points to your JMeter installation like:
```
set JMETER_HOME=C:\apache-jmeter-4.0 pushd %JMETER_HOME% && jmeter.bat
```
It might also be the case that Windows doesn't have necessary permissions assuming JMeter lives in root of system drive, try [running command prompt as Administrator](https://www.howtogeek.com/194041/how-to-open-the-command-prompt-as-administrator-in-windows-8.1/)
More information:
* [Running JMeter](http://jmeter.apache.org/usermanual/get-started.html#running)
* [How to Get Started With JMeter: Part 1 - Installation & Test Plans](https://www.blazemeter.com/blog/how-get-started-jmeter-part-1-installation-test-plans)
Upvotes: 0 <issue_comment>username_2: You don't need to set JMETER\_HOME path explicitly under user variables, just add/change under system variables under path variable as your bin path. If you already have earlier version of JMeter just append with latest version. Path looks like : C:\XXX\apache-jmeter-4.0\bin
Upvotes: -1 |
2018/03/19 | 437 | 1,518 | <issue_start>username_0: I am trying to create a flag for date from datetime column. but getting an error after applying the below function.
```
def f(r):
if r['balance_dt'] <= '2016-11-30':
return 0
else:
return 1
df_obctohdfc['balance_dt_flag'] = df_obctohdfc.apply(f,axis=1)
```<issue_comment>username_1: You don't need to set `JMETER_HOME` variable manually, `jmeter.bat` script should detect it automatically.
Just in case you want to override it for any reason make sure you do this carefully and the variable points to your JMeter installation like:
```
set JMETER_HOME=C:\apache-jmeter-4.0 pushd %JMETER_HOME% && jmeter.bat
```
It might also be the case that Windows doesn't have necessary permissions assuming JMeter lives in root of system drive, try [running command prompt as Administrator](https://www.howtogeek.com/194041/how-to-open-the-command-prompt-as-administrator-in-windows-8.1/)
More information:
* [Running JMeter](http://jmeter.apache.org/usermanual/get-started.html#running)
* [How to Get Started With JMeter: Part 1 - Installation & Test Plans](https://www.blazemeter.com/blog/how-get-started-jmeter-part-1-installation-test-plans)
Upvotes: 0 <issue_comment>username_2: You don't need to set JMETER\_HOME path explicitly under user variables, just add/change under system variables under path variable as your bin path. If you already have earlier version of JMeter just append with latest version. Path looks like : C:\XXX\apache-jmeter-4.0\bin
Upvotes: -1 |
2018/03/19 | 1,367 | 4,885 | <issue_start>username_0: I'm trying to create a wrapper component around the react-router-dom `NavLink` component.
I would like my custom component to accept all of NavLinks props, and proxy them down to `NavLink`.
However when I do this, I'm getting:
>
> Warning: React does not recognize the `staticContext` prop on a DOM
> element. If you intentionally want it to appear in the DOM as a custom
> attribute, spell it as lowercase `staticcontext` instead. If you
> accidentally passed it from a parent component, remove it from the DOM
> element.
>
>
>
A working demo of the issue can be found here:
* <https://codesandbox.io/s/w0n49rw7kw><issue_comment>username_1: There is a way to overcome that is using:
```
const { to, staticContext, ...rest } = this.props;
```
So your `...rest` will never contain `staticContext`
Upvotes: 8 [selected_answer]<issue_comment>username_2: This is a common problem with a simple solution as documented in the [React documentation](https://reactjs.org/warnings/unknown-prop.html "React Docs"):
>
> The unknown-prop warning will fire if you attempt to render a DOM
> element with a prop that is not recognized by React as a legal DOM
> attribute/property. You should ensure that your DOM elements do not
> have spurious props floating around.
>
>
> The spread operator can be used to pull variables off props, and put
> the remaining props into a variable.
>
>
>
```
function MyDiv(props) {
const { layout, ...rest } = props
if (layout === 'horizontal') {
return
} else {
return
}
}
```
>
> You can also assign the props to a new object and delete the keys that
> you’re using from the new object. Be sure not to delete the props from
> the original this.props object, since that object should be considered
> immutable.
>
>
>
```
function MyDiv(props) {
const divProps = Object.assign({}, props);
delete divProps.layout;
if (props.layout === 'horizontal') {
return
} else {
return
}
}
```
Upvotes: 5 <issue_comment>username_3: The given answer by the React docs was not quite good enough for my situation, so I found/developed one which isn't perfect, but is at least not so much of a hassle.
You can see the Q/A in which it arose here:
[What is Reacts function for checking if a property applies?](https://stackoverflow.com/questions/50977515/what-is-reacts-function-for-checking-if-a-property-applies/50978965#50978965)
The gist is, use a function to pick the bad props out for you.
```
const SPECIAL_PROPS = [
"key",
"children",
"dangerouslySetInnerHTML",
];
const defaultTester = document.createElement("div")
function filterBadProps(props: any, tester: HTMLElement = defaultTester) {
if(process.env.NODE_ENV !== 'development') { return props; }
// filter out any keys which don't exist in reacts special props, or the tester.
const out: any = {};
Object.keys(props).filter((propName) =>
(propName in tester) || (propName.toLowerCase() in tester) || SPECIAL_PROPS.includes(propName)
).forEach((key) => out[key] = props[key]);
return out;
}
```
Personally, I felt that the warning was completely useless in the first place, so I added a line which skips the check entirely when not in development mode (and warnings are suppressed). If you feel that the warnings have merit, just remove the line:
`if(process.env.NODE_ENV !== 'development') { return props; }`
You can use it like this:
```
public render() {
const tooManyProps = this.props;
const justTheRightPropsForDiv = filterBadProps(tooManyProps);
const justTheRightPropsForSpan = filterBadProps(tooManyProps, document.createElement("span"));
return (
)
}
```
Upvotes: 2 <issue_comment>username_4: If someone has this issue with react-admin, check if you don't have a Link as a child of Admin. Like this:
```
}>
something <-- causing issue
```
Just move it to another component. For instance, inside the Layout.
Upvotes: 0 <issue_comment>username_5: This happens because you probably used `{...props}` somewhere in your component.
Example from [React](https://reactjs.org/warnings/unknown-prop.html):
```
function MyDiv(props) {
const { layout, ...rest } = props
if (layout === 'horizontal') {
return
} else {
return
}
}
```
We grab `layout` separately so that it won't be contained in `{...rest}`.
Upvotes: 4 <issue_comment>username_6: I got the same issue when passing data in child component with camelCase property.
>
> Warning: React does not recognize the `moreInfo` prop on a DOM element.
> If you intentionally want it to appear in the DOM as a custom attribute,
> spell it as lowercase `moreinfo` instead. If you accidentally passed it
> from a parent component, remove it from the DOM element.
>
>
>
```
```
To fix that error, I used all lowercase letters for property.
```
```
Upvotes: 0 |
2018/03/19 | 513 | 1,712 | <issue_start>username_0: Is there a simple way to get the class name without the namespace **without** using Reflection?
This is my class and when I call `get_class()` I get `CRMPiccoBundle\Services\RFC\Webhook\SiteCancelled`
```
namespace CRMPiccoBundle\Services\RFC\Webhook;
class SiteCancelled extends Base implements Interface
{
public function process() {
// echo get_class()
}
}
```<issue_comment>username_1: So many ways to do it using string manipulation…
If you're certain your class name contains a namespace:
```
$c = 'CRMPiccoBundle\Services\RFC\Webhook';
echo ltrim(strrchr($c, '\\'), '\\');
echo substr($c, strrpos($c, '\\') + 1);
```
If you're uncertain whether the class may or may not contain a namespace:
```
echo ltrim(substr($c, strrpos($c, '\\')), '\\');
preg_match('/[^\\\\]+$/', $c, $m)
echo $m[0];
```
And probably many other variations on that theme…
Upvotes: 1 <issue_comment>username_2: Or simply exploding the return from `class_name` and getting the last element:
```
$class_parts = explode('\\', get_class());
echo end($class_parts);
```
Or simply removing the namespace from the output of `get_class`:
```
echo str_replace(__NAMESPACE__ . '\\', '', get_class());
```
Either works with or without namespace.
And so on.
Upvotes: 5 [selected_answer]<issue_comment>username_3: Use the `class_basename()` function to get your class name without the namespace
```
php
echo class_basename(__CLASS__);
</code
```
Upvotes: 3 <issue_comment>username_4: This is the fastest method I've came up with and seems to be working for all cases:
```
function toUqcn(string $fqcn) {
return substr($fqcn, (strrpos($fqcn, '\\') ?: -1) + 1);
}
```
Upvotes: -1 |
2018/03/19 | 551 | 1,882 | <issue_start>username_0: I have a error with my login script. The connection is successful but it does not display a success message when the login is successful. Still displays my dbconn file message.
**Any ideas on how to make this work?**
dbconn code
```
php
$user = 'root';
$password = '<PASSWORD>';
$db = 'peerwise';
$host = 'localhost';
$port = 8889;
$link = mysqli_init();
$dbconn = mysqli_real_connect($link, $host, $user, $password, $db, $port);
if (!$dbconn){
echo "Not connected to database";
}else{
echo "Successfully connected";
}
?
```
login code
```
php
include_once("includes/dbconn.php");
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$sql = "SELECT * FROM Users WHERE username = '$username' AND password = '$<PASSWORD>'";
$query = mysqli_query($dbconn, $sql) or die(mysqli_error());
$data = mysqli_fetch_array($query);
if ($data['username'] == $username && $data['password'] == $password) {
echo "success";
} else {
echo "errr";
}
?
```<issue_comment>username_1: Your using the wrong connection object. Rather than variable **$dbconn** use **$link** instead in your query calls, so no mysql error will halt execution of your script, from **or die(mysqli\_error());**
Replace with this:
```
$query = mysqli_query($link, $sql) or die(mysqli_error());
```
Upvotes: 1 <issue_comment>username_2: ```
Login
Username or Password is incorrect
Create a account
```
Upvotes: 0 <issue_comment>username_3: Use `mysqli_connect` for connection:
```
php
$user = 'root';
$password = '<PASSWORD>';
$db = 'test';
$host = 'localhost';
$port = 3306;
$dbconn = mysqli_connect($host, $user, $password, $db,$port);
if (!$dbconn){
echo "Not connected to database";
}else{
echo "Successfully connected";
}
?
```
Upvotes: 0 |
2018/03/19 | 3,046 | 8,797 | <issue_start>username_0: Given a `data_frame` which represent some kind of hierarchy I want to transform this data into a nested JSON with a specific structure.
Given this `data_frame`
```
df <- data_frame(
"parent" = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C", "C", "C"),
"child1" = c("a", "a", "b", "b", "c", "d", "d", "e", "e", "f", "f", "f", "f", "g", "g"),
"child2" = c("aa", "ab", "ba", "bb", "ca", "da", "db", "ea", "eb", "fa", "fb", "fc", "fd", "ga", "gb"),
"value" = sample(seq(1,100,1), 15)
)
```
I want to result in the following JSON structure:
```
[
{
"name": "A",
"children": [
{
"name": "a",
"children": [
{"name": "aa", "value": 89},
{"name": "ab", "value": 20}
]
},
{
"name": "b",
"children": [
{"name": "ba", "value": 25},
{"name": "bb", "value": 15}
]
},
{
"name": "c",
"children": [
{"name": "ca","value": 95}
]
}
]
},
{
"name": "B",
"children": [
{
"name": "d",
"children": [
{"name": "da", "value": 54},
{"name": "db", "value": 62}
]
},
{
"name": "e",
"children": [
{"name": "ea", "value": 100},
{"name": "eb", "value": 56}
]
}
]
},
{
"name": "C",
"children": [
{
"name": "f",
"children": [
{"name": "fa", "value": 69},
{"name": "fb", "value": 98},
{"name": "fc", "value": 83},
{"name": "fd", "value": 63}
]
},
{
"name": "g",
"children": [
{"name": "ga", "value": 91},
{"name": "gb", "value": 77}
]
}
]
}
]
```
At the moment I use nested loops to construct a nested list as follows:
```
lll <- list()
i <- 1
for (a in unique(df$parent)) {
lll[[i]] <- list(
"name" = a,
"children" = list()
)
ii <- 1
for (b in unique(df$child1[df$parent == a])) {
lll[[i]]$children[[ii]] <- list(
"name" = b,
"children" = list()
)
iii <- 1
for(c in unique(df$child2[df$parent == a & df$child1 == b])) {
lll[[i]]$children[[ii]]$children[[iii]] <- list(
"name" = c,
"value" = df$value[df$parent == a & df$child1 == b & df$child2 == c ]
)
iii <- iii + 1
}
ii <- ii + 1
}
i <- i + 1
}
```
Using `jsonlite::toJSON(lll, pretty = TRUE, auto_unbox = TRUE)` one can transform this list to the nested JSON.
I wonder if there is a more elegant way. I tried to solve this using `purrr`, but I did not succeed.<issue_comment>username_1: You can achieve this by using a combination of `dplyr::group_by()` and `tidyr::nest()`:
```r
library(dplyr)
library(tidyr)
df %>%
rename(name = child2) %>%
group_by(parent, child1) %>%
nest(.key = "children") %>%
rename(name = child1) %>%
group_by(parent) %>%
nest(.key = "children") %>%
rename(name = parent) %>%
jsonlite::toJSON(pretty = TRUE, auto_unbox = TRUE)
#> [
#> {
#> "name": "A",
#> "children": [
#> {
#> "name": "a",
#> "children": [
#> {
#> "name": "aa",
#> "value": 64
#> },
#> {
#> "name": "ab",
#> "value": 29
#> }
#> ]
#> },
#> {
#> "name": "b",
#> "children": [
#> {
#> "name": "ba",
#> "value": 73
#> },
#> {
#> "name": "bb",
#> "value": 45
#> }
#> ]
#> },
#> {
#> "name": "c",
#> "children": [
#> {
#> "name": "ca",
#> "value": 95
#> }
#> ]
#> }
#> ]
#> },
#> {
#> "name": "B",
#> "children": [
#> {
#> "name": "d",
#> "children": [
#> {
#> "name": "da",
#> "value": 26
#> },
#> ...
```
In order to reproduce your column names, the code got clunkier through the calls to `dplyr::rename`. Without them, the structure of the operation becomes more apparent:
```r
df %>%
group_by(parent, child1) %>%
nest() %>%
group_by(parent) %>%
nest() %>%
jsonlite::toJSON(pretty = TRUE, auto_unbox = TRUE)
```
Upvotes: 2 <issue_comment>username_2: I don't know if this is a more elegant solution, but it is functional and probably a tad more efficient.
There isn't really anything wrong with for-loops, except for issues with side-effects when you updated variables, but using lists to map from keys to values will at best give you a quadratic running time for updating. I have solved it using a red-black search tree from my [`matchbox` package](https://github.com/mailund/matchbox). I also use `bind` syntax from my [`pmatch` package.](https://github.com/mailund/pmatch)
```
## Pattern matching + bind[...] syntax
#devtools::install_github("mailund/pmatch")
library(pmatch)
## linked list and rbt-map data structures
#devtools::install_github("mailund/matchbox")
library(matchbox)
```
First, I translate the data-frame into red-black maps of red-black maps. The data-frame structure is hardwired here, but it wouldn't be much of a problem to generalise the code.
```
## Building a hierarchy of maps from the data frame
# returns the value for a key in a red-black tree unless the
# key is not in the tree, in which case it returns a new
# empty tree
match_or_empty <- function(tree, key) {
if (rbt_map_member(tree, key))
rbt_map_get(tree, key)
else
empty_red_black_map()
}
get_row_nodes <- function(df, row, nodes) {
bind[parent, child1, child2, value] <- df[row,]
parent_node <- match_or_empty(nodes, parent)
child1_node <- match_or_empty(parent_node, child1)
list(parent_node, child1_node)
}
build_hierarchy_row <- function(df, row, nodes) {
bind[parent, child1, child2, value] <- df[row,]
bind[parent_node, child_node] <- get_row_nodes(df, row, nodes)
child_node <- rbt_map_insert(child_node, child2, value)
parent_node <- rbt_map_insert(parent_node, child1, child_node)
rbt_map_insert(nodes, parent, parent_node)
}
build_hierarchy <- function(df) {
nodes <- empty_red_black_map()
for (i in seq_along(df$parent)) {
nodes <- build_hierarchy_row(df, i, nodes)
}
nodes
}
```
Next, I translate this structure into json strings.
```
## Translating the hierarchy of rbt-maps into son
library(magrittr)
library(glue)
# this should probably be in matchbox but it isn't yet.
rbt_map_to_llist <- function(tree, f, acc = NIL) {
if (is_red_black_map_empty(tree)) acc
else {
left_result <- rbt_map_to_llist(tree$left, f, acc)
right_result <- rbt_map_to_llist(tree$right, f, left_result)
CONS(list(key=tree$key, val=tree$val), right_result)
}
}
llist_to_json <- function(lst) {
paste0("[", paste0(lst, collapse = ", "), "]")
}
to_json <- function(node) {
bind[key, val] <- node
if (inherits(val, "rbt_map")) {
children <- val %>% rbt_map_to_llist %>% llmap(to_json) %>% llist_to_json
glue::glue('{{ "name": "{key}", "children" = {children} }}')
} else {
glue::glue('{{ "name": "{key}", "value": {val} }')
}
}
```
Now, we can combine the two steps with a bit of pipe-based point-free programming:
```
df_to_json <- . %>%
build_hierarchy %>%
rbt_map_to_llist %>%
llmap(to_json) %>%
llist_to_json %>%
cat
```
Testing it:
```
library(tibble)
df <- tibble(
parent = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C", "C", "C"),
child1 = c("a", "a", "b", "b", "c", "d", "d", "e", "e", "f", "f", "f", "f", "g", "g"),
child2 = c("aa", "ab", "ba", "bb", "ca", "da", "db", "ea", "eb", "fa", "fb", "fc", "fd", "ga", "gb"),
value = sample(seq(1,100,1), 15)
)
> df_to_json(df)
[{ "name": "B", "children" = [{ "name": "d", "children" = [{ "name": "da", "value": 12 }, { "name": "db", "value": 88 }] }, { "name": "e", "children" = [{ "name": "ea", "value": 17 }, { "name": "eb", "value": 94 }] }] }, { "name": "C", "children" = [{ "name": "f", "children" = [{ "name": "fb", "value": 46 }, { "name": "fc", "value": 1 }, { "name": "fd", "value": 100 }, { "name": "fa", "value": 86 }] }, { "name": "g", "children" = [{ "name": "ga", "value": 97 }, { "name": "gb", "value": 19 }] }] }, { "name": "A", "children" = [{ "name": "b", "children" = [{ "name": "ba", "value": 54 }, { "name": "bb", "value": 64 }] }, { "name": "c", "children" = [{ "name": "ca", "value": 22 }] }, { "name": "a", "children" = [{ "name": "aa", "value": 63 }, { "name": "ab", "value": 76 }] }] }]
```
Upvotes: 0 |
2018/03/19 | 697 | 2,555 | <issue_start>username_0: I am new to Django and don't understand what really is causing this:
I have a Model Company which has an OneToOneField, creator.
```
# models.py
class Company(models.Model):
class Meta:
verbose_name = 'Company'
verbose_name_plural = 'Companies'
creator = models.OneToOneField(User, related_name="company", on_delete=models.CASCADE, unique=False, null=True)
name = models.CharField(max_length=50)
```
I have a TemplateView class to handle get and post requests for creating a Company model:
```
# views.py
class create_company(TemplateView):
def get(self, request):
form = CompanyCreateForm()
title = "Some form"
return render(request, "form.html", {"form": form, "title": title})
def post(self, request):
form = CompanyCreateForm(request.POST)
if form.is_valid():
comp = form.save(commit=False)
comp.creator = request.user
comp.save()
return redirect('index')
```
The form is showing correctly also storing when I submit, the problem I am facing is with base.html where I show {% user.company %}; the form template extends it like:
```
{% extends "account/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
{% csrf\_token %}
{{form|crispy}}
Save
{% endblock %}
```
and in base.html I access
```
{% if user.is_authenticated %}
{% user.company %}
{% endif %}
```
But user.company is not showing even it is set; it shows only when I redirect to index but not when I render the form.
Can someone help me understand what causes this?<issue_comment>username_1: ```
{% if request.user.is_authenticated %}
{% request.user.company %}
{% endif %}
```
you are not sending any context to the `base.html`, thus only `user` wont work.
Upvotes: 1 <issue_comment>username_2: This was the error when I simulated your code.
```
Error during template rendering
In template /home/user/django/drf_tutorial/snippets/templates/base.html, error at line 2
Invalid block tag on line 2: 'user.company', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
1 {% if user.is_authenticated %}
2 {% user.company %}
3 {% endif %}
4 {% block content %}{% endblock %}
```
It gives hint that the code to show company should be variable `{{ }}` instead of tag `{% %}`. So the base.html template should be as below.
```
{% if user.is_authenticated %}
{{ user.company }}
{% endif %}
{% block content %}{% endblock %}
```
Upvotes: 0 |
2018/03/19 | 460 | 1,649 | <issue_start>username_0: Unable to invoke the class, although i defined it. I tried with many methods.
**Error:**
```
error: cannot find symbol
StopWord d= new StopWord();//test for StopWord
^
symbol: class StopWord
```
**Code:**
This is my main file
```
public static void main(String[]args)throws Exception {
StopWord dis= new StopWord();
System.out.println("whencesoever is in Hahtable :" +
dis.isStopWord("whencesoever"));
}
```
And my file that contains Class StopWord is
```
public class StopWord {
public static boolean isStopWord(String s) {
//statements
}
}
```
Regards!!!<issue_comment>username_1: Did you import the `StopWord` class ?
Side note:
if `isStopWord` is static, you should call it like this:
```
StopWord.isStopWord("whencesoever"));
```
if you want to call `dis.isStopWord("whencesoever"))` do not mark it `static`, ie
```
public boolean isStopWord(String s)
```
Upvotes: 1 <issue_comment>username_2: This may help
```
public Class Test{
public static void main(String[] args) throws Exception
{
java.lang.StringIndexOutOfBoundsException sb;
StopWord dis= new StopWord();
System.out.println("whencesoever is in Hahtable :" +
dis.isStopWord("whencesoever"));
}
}
```
There is no return statement.
```
public class StopWord{
public static boolean isStopWord(String s){
return true;
}
}
```
### static is not required.
```
public class StopWord{
public boolean isStopWord(String s){
return true;
}
}
```
Upvotes: -1 |
2018/03/19 | 813 | 2,870 | <issue_start>username_0: Visual Studio Code highlights string literals with prefixes `r` and `R` differently:
```
Match = re.search(r"\d{2} \d{4} \d{2}:\d{2}:\d{2})", Output)
Match = re.search(R"\d{2} \d(4} \d{2}:\d{2}:\d{2})", Output)
```
[](https://i.stack.imgur.com/hFPlM.png)
Is there a difference in meaning between these two notations? Are different conventions used for `r` and `R`? What about other prefixes like `"b"`, `"u"`, or `"f"`?<issue_comment>username_1: There's no difference in meaning between these notations. [Reference](https://docs.python.org/3/reference/lexical_analysis.html):
>
> Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters
>
>
>
The same goes for other prefixes.
---
Now regarding VSCode behaviour:
* the first coloring (with yellow `{2}`) happens when the editor assumes you're writing a regular expression,
* the second one (with blue `{2}`) happens when the editor thinks you're writing a format string, something like `"{0}, {1}!".format("Hello", "world")`.
This becomes more obvious when we add some more syntax:
[](https://i.stack.imgur.com/44nKJ.png)
~~Now, looks like VSCode should treat `R"literal"` the same as `r"literal"`, but instead it colors it the same as `"literal"`, which is probably a tiny bug that nobody spotted because everyone writes lowercase `r`.~~
Correction from [comment](https://stackoverflow.com/questions/49358590/is-there-a-difference-between-r-and-r-string-prefixes-in-python/49358682?noredirect=1#comment96150908_49358682): It's not a bug, it's a feature! [VSCode's highlighter](https://github.com/MagicStack/MagicPython#strings) makes clever use of the fact that `r` and `R` prefixes are equivalent, and allows you, the developer, to have correct coloring by adopting a convention of using `r` for regex raw strings and `R` for non-regex raw strings.
>
> Raw strings are often interpreted as regular expressions. This is a bit of a problem, because depending on the application this may actually not be the most common case. (...) MagicPython follows a convention that **a lower-case r prefix means a regexp string, but an upper-case R prefix means just a raw string with no special regexp semantics.**
>
>
>
Upvotes: 7 [selected_answer]<issue_comment>username_2: In general, Python is case sensitive. Per the [string literal](https://docs.python.org/3/reference/lexical_analysis.html#grammar-token-stringliteral) syntax specification, however, string prefixes can be either case (or order). So the difference is visual, although tradition is mostly to use lower case, and upper case letters can be harder to distinguish.
Upvotes: 2 |
2018/03/19 | 808 | 2,848 | <issue_start>username_0: I have a Table named "LANGUAGE" - with words in SPANISH and ENGLISH.
Like:
```
ID - SPA - ENG
1 - Hoy - Hello
2 - Nombre - Name
3 - Jugar - Play
```
I Got the Spanish words:
```
SQL= "SELECT SPA FROM LANGUAGES"
SET LANGDB = conn.Execute(SQL)
```
And I want to identify ID 2 word (Nombre) to print on screen
It's possible? Or I need to create a DB for each word?
like:
```
SQL= "SELECT SPA FROM LANGUAGES WHERE ID = 2"
SET LANGDB = conn.Execute(SQL)
```
Tks!<issue_comment>username_1: There's no difference in meaning between these notations. [Reference](https://docs.python.org/3/reference/lexical_analysis.html):
>
> Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters
>
>
>
The same goes for other prefixes.
---
Now regarding VSCode behaviour:
* the first coloring (with yellow `{2}`) happens when the editor assumes you're writing a regular expression,
* the second one (with blue `{2}`) happens when the editor thinks you're writing a format string, something like `"{0}, {1}!".format("Hello", "world")`.
This becomes more obvious when we add some more syntax:
[](https://i.stack.imgur.com/44nKJ.png)
~~Now, looks like VSCode should treat `R"literal"` the same as `r"literal"`, but instead it colors it the same as `"literal"`, which is probably a tiny bug that nobody spotted because everyone writes lowercase `r`.~~
Correction from [comment](https://stackoverflow.com/questions/49358590/is-there-a-difference-between-r-and-r-string-prefixes-in-python/49358682?noredirect=1#comment96150908_49358682): It's not a bug, it's a feature! [VSCode's highlighter](https://github.com/MagicStack/MagicPython#strings) makes clever use of the fact that `r` and `R` prefixes are equivalent, and allows you, the developer, to have correct coloring by adopting a convention of using `r` for regex raw strings and `R` for non-regex raw strings.
>
> Raw strings are often interpreted as regular expressions. This is a bit of a problem, because depending on the application this may actually not be the most common case. (...) MagicPython follows a convention that **a lower-case r prefix means a regexp string, but an upper-case R prefix means just a raw string with no special regexp semantics.**
>
>
>
Upvotes: 7 [selected_answer]<issue_comment>username_2: In general, Python is case sensitive. Per the [string literal](https://docs.python.org/3/reference/lexical_analysis.html#grammar-token-stringliteral) syntax specification, however, string prefixes can be either case (or order). So the difference is visual, although tradition is mostly to use lower case, and upper case letters can be harder to distinguish.
Upvotes: 2 |
2018/03/19 | 606 | 2,154 | <issue_start>username_0: I've just started to learn React and I would like to create simple page with form. Form should contain inputs `keywords` and `city`, select list `date` and submit buttom.
It's structure of my project
[](https://i.stack.imgur.com/y3Q5f.png)
**index.html**
```
Application
```
**index.js**
```
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import './bootstrap.min.css';
import './SearchForm.js';
```
**SearchForm.js**
```
const formContainer = document.querySelector('.form-container')
class SeacrhForm extends React.Component {
constructor(props) {
super(props)
this.state = {
keywords: '',
city: '',
date: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
render() {
return (
Say Hi!
=======
)
}
}
ReactDOM.render(, formContainer)
```
And I got errors on my page in browser
[](https://i.stack.imgur.com/T73ov.png)
What did I do wrong?<issue_comment>username_1: Add
* `import React from 'react'`
* `import ReactDOM from 'react-dom'`
to `SearchForm.js`
Modern JS works well with ES modules, that means that you need to import dependencies into every file(module), otherwise such libraries will not be available.
Upvotes: 1 <issue_comment>username_2: Okay You need to add the following imports to you searchform.js file
```
import React from 'react';
import ReactDOM from 'react-dom';
```
and remove this line:
```
const formContainer = document.querySelector('.form-container')
```
And don't change the index.html file ever, instead create a new component like you have created searchform.js and render it in app.js and then react will automatically render that component inside
```
```
you may not need to manually do it.
check out the following link, It may help you to understand reactJs better.
<https://reactjs.org/docs/hello-world.html>
Upvotes: 3 [selected_answer] |
2018/03/19 | 1,359 | 4,607 | <issue_start>username_0: My son is doing times tables practice on this page, a timed test in which he gets 10 seconds for each sum.
<https://www.timestables.com/speed-test/> - this is not my site or code, I have no direct control over the source code.
I want to give him a little more time per sum but I cannot find a way to modify the relevant code and make it work with 20 seconds instead of 10.
It looks to me like the relevant variable is maxTime (milliseconds) in this function, but nothing I do using the Chrome Developer Tools will modify this in a live running page to give 20 seconds instead of 10.
```
function startSom(){
vraagnr = vraagnr + 1;
if(vraagnr <= totaalSommen)
{
bezig = true;
$('#pbar_innerdiv').stop();
$('#pbar_innerdiv').css("width","100%");
$('#pbar_innerdiv').css("backgroundColor","#33BF00");
$('#pbar_innerdiv').css("borderColor","#33BF00");
if(mobiel){
$("#antwVak").html("");
}
else{
$("#antwoordI").val("");
$("#antwoordI").focus();
}
$('#pbar_innerdiv').stop();
start = new Date();
maxTime = 10000;
timeoutVal = Math.floor(maxTime/100);
var somT = sommen[vraagnr-1].split(",");
$('#somVak').html(somT[1]+"×"+somT[0]+"=");
$('#voortgangVak').html("Question "+vraagnr+" / "+totaalSommen+"
"+ punten + " points");
animateUpdate();
started = false;
}
else
{
showEindScherm();
}
}
```
Can anyone suggest what to do please?<issue_comment>username_1: There is a possibility to change files persistently in chrome devtools: [Overrides](https://developers.google.com/web/updates/2018/01/devtools#overrides).
If the script is in a seperate file you can change the maxTime directly there or if it is in a file, which needs to be reloaded you can edit any other .js and add an eventlistener there to change the startSom method on page load.
Upvotes: 0 <issue_comment>username_2: You can copy the entire method, pase it into chrome devtools and change
```
function startSom() {
```
to
```
window.startSom = function() {
```
And obviously change your time from 10000 to 20000. This changes the amount of time it allows you to answer, but not the moving progress bar which will still only take 10 seconds.
Upvotes: 3 [selected_answer]<issue_comment>username_3: Please paste this:
```
window.startSom = function(){
vraagnr = vraagnr + 1;
if(vraagnr <= totaalSommen)
{
bezig = true;
$('#pbar_innerdiv').stop();
$('#pbar_innerdiv').css("width","100%");
$('#pbar_innerdiv').css("backgroundColor","#33BF00");
$('#pbar_innerdiv').css("borderColor","#33BF00");
if(mobiel){
$("#antwVak").html("");
}
else{
$("#antwoordI").val("");
$("#antwoordI").focus();
}
$('#pbar_innerdiv').stop();
start = new Date();
maxTime = 20000;
timeoutVal = Math.floor(maxTime/100);
var somT = sommen[vraagnr-1].split(",");
$('#somVak').html(somT[1]+"×"+somT[0]+"=");
$('#voortgangVak').html("Question "+vraagnr+" / "+totaalSommen+"
"+ punten + " points");
animateUpdate();
started = false;
}
else
{
showEindScherm();
}
}
```
Here:
[](https://i.stack.imgur.com/vwBZT.jpg)
And if you want to make the progress bar following the new max Time, also paste this:
```
window.animateUpdate = function() {
if(bezig)
{
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
if(!started){
$('#pbar_innerdiv').css("width", (100) + "%");
$('#pbar_innerdiv').animate({width: 0 + "%"},20000);
started = true;
}
perc = Math.round((timeDiff/maxTime)*100);
console.log(perc);
if(perc == 33)
{
$('#pbar_innerdiv').css("backgroundColor", "#FF9500");
$('#pbar_innerdiv').css("borderColor", "#FF9500");
}
if(perc== 66)
{
$('#pbar_innerdiv').css("backgroundColor", "#FF0000");
$('#pbar_innerdiv').css("borderColor", "#FF0000");
}
if (perc <= 100) {
//updateProgress(perc);
setTimeout(animateUpdate, timeoutVal);
}
else
{
bezig = false;
showTeLaat();
//alert("tijd is om");
}
}
}
```
Upvotes: 1 |
2018/03/19 | 531 | 1,898 | <issue_start>username_0: **I want to create a list with Horizontal listview but vertical text. Just like this.**
[](https://i.stack.imgur.com/Dq8Gr.png)
**I have wrote the code,as following**
```
ListView {
id: listView;
orientation: ListView.Horizontal
delegate: listDelegate;
ScrollBar.horizontal: bar
model: ListModel {
id: phoneModel;
ListElement{
name: "wewqeq";
}
ListElement{
name: "rrr";
}
ListElement{
name: "Engine auto stop";
}
ListElement{
name: "wewq";
}
ListElement{
name: "weweqwe";
}
}
}
```
**My code showed the result that**
1. list item has Horizontal view, but the text is the same! How can i change the text orientation of ListElement?
2. The bar is at the bottom side, how can i make it to top side?
**My result like this**
[](https://i.stack.imgur.com/Y3ujz.png)<issue_comment>username_1: You can use a vertical `ListView` and rotate it:
```
ListView {
id: listView
height: //...
width: //...
transformOrigin: Item.TopLeft
rotation: -90
y: listView.width
orientation: ListView.Vertical
ScrollBar.vertical: ScrollBar{}
}
```
The vertical `ScrollBar` will become horizontal on the top side.
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
ListView {
id: listView
delegate: listDelegate
rotation:-90
model: ListModel {
id: phoneModel;
ListElement{
name: "wewqeq";
}
ListElement{
name: "rrr";
}
ListElement{
name: "Engine auto stop";
}
ListElement{
name: "wewq";
}
ListElement{
name: "weweqwe";
}
}
}
```
Upvotes: 0 |
2018/03/19 | 1,299 | 5,202 | <issue_start>username_0: I want generate C# classes from wsdl url in ASP.NET Core 2.1.
WSDL url is:<https://airarabia.isaaviations.com/webservices/services/AAResWebServices?wsdl>
I used "Microsoft WCF Web Service Reference Provider" tool to generate C# class and got following error:
>
> Error: No code was generated.
> If you were trying to generate a client, this could be because the metadata documents did not contain any valid contracts or services
> or because all contracts/services were discovered to exist in /reference assemblies. Verify that you passed all the metadata documents to the tool.
> Done.
>
>
>
Any solution will be appreciate.<issue_comment>username_1: Download your WSDL files to local. Then, run the following command:
```
wsdl.exe /verbose /namespace:Air /out:D:\t\ar /protocol:SOAP /language:CS C:\path\to\wsdl\AAResWebServices_1.wsdl
```
Change namespace to a namespace of your choice.
WSDL.exe is part of your Windows SDK:
```
C:\Program Files (x86)\Microsoft SDKs\Windows
```
Mine was in `C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin`
This generated the classes without any issues. I tested this solution.
Upvotes: 3 <issue_comment>username_2: **Short answer**
Open a development command prompt and run to generate the proxy classes:
```
svcutil http://airarabia.isaaviations.com/webservices/services/AAResWebServices?wsdl
```
Notice that I used `http` instead of `https`. The server's certificate causes problems with `svcutil`. Copy the classes into your project folder.
Add `System.ServiceModel.Primitives` from NuGet to the project's dependencies. Since ASP.NET Core doesn't use `web.config` files, you may have to create the bindings yourself when creating the proxy class, eg :
```
var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
var address = new EndpointAddress("http://airarabia.isaaviations.com/webservices/services/AAResWebServices");
var client = new AAResWebServicesClient((Binding)binding, address);
```
In the bindings, `BasicHttpsBinding` is used since no airline will accept unencrypted connections. Sabre requires TLS 1.2 or greater.
**Explanation**
Airlines and GDSs aren't great at following web interoperability standards. They are big enough that if there are any changes, it's the travel agent that has to accomodate them. Once they specify *their* standard, they don't care to change it either.
The OTA standard and Sabre's implementation for example were created in 2003 using ebXML, an alternative proposal to SOAP that didn't become a standard. Then they used ebXML over SOAP using mechanisms that didn't become part of the later SOAP standards. When the WS-\* standards were created to fix the mess and ensure interoperability, they didn't even bother.
The WSDL you provided is similar to Sabre's. It uses *some* of OTA's operations like OTA\_PING and adds custom ones. Fortunately, it doesn't include any tool-breakers like anonymous inner types.
You *could* use wsdl.exe to create an ASMX proxy, using the pre-2008 .NET stack. This hasn't been ported to .NET Core as far as I know though. *Maybe* it's part of the Windows Compatibility pack. After all, it *is* non-compliant and deprecated 10 years ago. ASMX hasn't had any significant upgrades in ages either. I *have* run into concurrency issues with deserializers in the past, when using ASXM services eg with Amadeus.
And then, there are those that won't even respect their own XSDs, eg Farelogix. They may return out-of-range values for enumerations and say "well, the XSD is for information purposes only". The `wsdl` file is clearly marked `not for production use`
There's no generic solution unfortunately. Here are some options:
* `wsdl.exe` and ASMX are out of the question if you want to use .NET Core. You'll have to switch to the Full framework if you have to use them.
* Create WCF *individual* proxies for each service. The size of the files is a lot smaller and you avoid clashes between types like Airport that are used by multiple services with slight variations or even incompatibilities.
* Use Fiddler or another tool to capture the requests and responses. Use these as templates to create plain HTTP GET requests. It's a dirty solution but *could* prove quicker and ever more reliable if you can't trust the provider's WSDL and XSDs
**WARNING**
Making the call doesn't mean that you can communicate with the provider. One of the main problems with ebXML over SOAP is that the body is OK but the *headers*, including those used for authentication are all wrong. This means that one has to create the authentication element
Another issue is that authentication fields are often misused eg using authentication headers we'd consider *session* tokens. GDSs still use mainframes and those session tokens often map to actual terminal sessions.
This means that one has to create authentication headers manually instead of relying on WCF to generate them. It also means that transactions are stateful - one has to keep track of which session was used for that reservation in order to book it, make sure all previous transactions are complete before starting a new one etc.
Upvotes: 5 [selected_answer] |
2018/03/19 | 383 | 1,446 | <issue_start>username_0: I have come across many questions and answers related to this kind of questions, but not for exactly this question.
Well, according to the official [MYSQL documentation](https://dev.mysql.com/doc/refman/5.7/en/update.html) it says
>
> If you set a column to the value it currently has, MySQL notices this
> and does not update it.
>
>
>
But practically, when I update a same value to a MYSQL column, the query successfully executing and displaying "*Your query has been successfully executed "*.
So How do I exactly know that the query hasn't updated, when I update a column with the same value?
Also Is it possible to get an error message to the client (browser), when I try to update a same value, from the browser via a *submit form* to the MYSQL server via a backend language like PHP?<issue_comment>username_1: When updating a Mysql table with identical values nothing's really affected so rowCount will return 0.
Just create your PDO object with
```
php
$p = new PDO($dsn, $user, $password, array(PDO::MYSQL_ATTR_FOUND_ROWS = true));
?>
```
and `rowCount()` will tell you how many rows your update-query actually found/matched.
Check this [link](http://php.net/manual/en/ref.pdo-mysql.php) also.
Upvotes: 2 <issue_comment>username_2: you may use like to avoid updating same value
UPDATE users
SET first\_name = 'Michael'
WHERE id = 123
AND first\_name IS DISTINCT FROM 'Michael';
Upvotes: -1 |
2018/03/19 | 1,452 | 4,330 | <issue_start>username_0: ```
| Name | Email |
| --- | --- |
var Classmates = ["Chris", "Jan", "Thomas", "Julia", "Tess", "Remco", "Kris", "Mark", "Rick", "Sara"];
var Emails = ["<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>"];
for (var i = 0; i < 11; i++) {
document.write("| " + i + " |");
document.write(" " + Classmates[i], Emails[i] + " |
");
}
```
I want this array to be shown in a simple html table so it shows the email next to the classmates name.<issue_comment>username_1: Give the table an id. in my case i use 'table\_1'.
and also include jquery library.
```
for (var i = 0; i < 11; i++) {
$('#table_1').append('|');
$('#table\_1').append(" " + i + " |");
$('#table\_1').append(" " + Classmates[i], Emails[i] + " |");
$('#table\_1').append('
');
}
```
Upvotes: -1 <issue_comment>username_2: There are few improvements that needs to be done
1. For **table**, you need to write the table tag as well
2. For iteration, you can simply use the length of either of the array (improves code by removing hard coding)
3. For showing classmate and email as comma separated, you need to put comma in quotes
4. Start of array is at index 0, hence, to get the number correct increment it by 1 in the document.write statement
```js
var Classmates = ["Chris", "Jan", "Thomas", "Julia", "Tess", "Remco", "Kris", "Mark", "Rick", "Sara"];
var Emails = ["<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>"];
document.write("
");
for (var i = 0; i < Classmates.length; i++) {
document.write("| " + (i+1) + " |");
document.write(" " + Classmates[i] +", " + Emails[i] + " |
");
}
document.write("
");
```
Upvotes: 0 <issue_comment>username_3: Iterate each array and create a dome node using `document.createNode`.Use `appendChild` to append tr & td to the table
```js
var Classmates = ["Chris", "Jan", "Thomas", "Julia", "Tess", "Remco", "Kris", "Mark", "Rick", "Sara"];
var Emails = ["<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>"];
for (var i = 0; i < Classmates.length; i++) {
let _tr = document.createElement('tr');
let _tdClassmates = document.createElement('td');
let _tdEmail = document.createElement('td');
_tdClassmates.innerHTML = Classmates[i];
_tdEmail.innerHTML = Emails[i];
_tr.appendChild(_tdClassmates);
_tr.appendChild(_tdEmail);
document.getElementById('studentTable').appendChild(_tr);
}
```
```html
```
Upvotes: 0 <issue_comment>username_4: create a string variable and append the html to it and do document.write for that variable.
```
var output = "";
for (var i = 0; i < 11; i++) {
output += "| " + i + " |";
output += " " + Classmates[i] + "," + Emails[i] + " |
";
}
document.write(output);
```
Upvotes: 2 [selected_answer]<issue_comment>username_5: You could define all variable at top and crearte new elements and build a new table. Later append the table to the body.
```js
var classmates = ["Chris", "Jan", "Thomas", "Julia", "Tess", "Remco", "Kris", "Mark", "Rick", "Sara"],
emails = ["<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>"],
table = document.createElement('table'),
tr = document.createElement('tr'),
td, th,
i;
th = document.createElement('th');
th.appendChild(document.createTextNode('Name'));
tr.appendChild(th);
th = document.createElement('th');
th.appendChild(document.createTextNode('e-Mail'));
tr.appendChild(th);
table.appendChild(tr);
for (i = 0; i < 10; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode(classmates[i]));
tr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(emails[i]));
tr.appendChild(td);
table.appendChild(tr);
}
document.body.appendChild(table);
```
Upvotes: 0 |
2018/03/19 | 670 | 2,305 | <issue_start>username_0: When trying to save a script as an R file, I am not able to. The save as window opens, but the 'save as type' bar below the 'file name' bar is blocked/greyed-out. I am, however, able to save the script as an unreadable file. When I open it again to continue working on it, it cannot run. I then have to copy paste it to a new script to continue working on it and running the commands. I cannot seem to find many questions on the internet relating to this problem except this one: <https://support.rstudio.com/hc/en-us/community/posts/219163988-Can-not-save-new-R-script-save-as-bar-grayed-out>.
I have tried `save()` which does not work. I have also uninstalled R and installed the latest version of R, this does not help either. Would anyone know how to fix this problem so that I can save it as an R file?
**EDITED:**
I am using RStudio version 3.4.4. on the Windows 10 Home edition.
Processor: Intel(R) Core(TM) i5-7300HQ CPU @ 2.50GHz.
RAM: 8.00 GB.
System type: 64-bit Operating System, x64-based processor.
Many thanks<issue_comment>username_1: friend!
I had the same problem as you. But what resolved was just put ".R" (example: save.R) in the end of the name, even with the grey bar, it generated the script automatically.
Hope it can help.
Upvotes: 2 <issue_comment>username_2: Windows 10 now prevents Rstudio to save a new document.
Give Rstudio permission, restart it and than it worked for me.
Upvotes: 2 <issue_comment>username_3: By saving the R script with .R at the end automatically saves it as an R file!
Upvotes: 1 <issue_comment>username_4: These other answers don't solve it for me. What I noticed is:
1. Working off of a network drive is a nightmare for R Studio.
2. Even if you *do* save it as an `.R` file, R Studio may not be able to open it.
What I did was:
1. Paste my script into a notepad file; save it as `.R`
2. Right click my `.R` file and Open With RStudio.
This minimizing RStudio doing the driving of opening files. And once the file is NAMED (it was named and saved as .R in notepad) RStudio seems to be able to save/overwrite changes to the file. It just cannot save the file the *first* time nor save TXT files it opens as .R files.
So yeah, for the initial script; template it in notepad and never change it's name.
Upvotes: 2 |
2018/03/19 | 480 | 1,710 | <issue_start>username_0: I need to store only say 10 number docs under a particular index. And the 11th item should replace the old item i.e 1st item. So that i will be having only 10 doc at any time.
I am using elacticsearch in golang<issue_comment>username_1: I'm assuming you will have fixed names for documents, like 1, 2,...,10 or whatever. So one approach could be to use Redis to implement a circular list <https://redis.io/commands/rpoplpush#pattern-circular-list> (you can also implement your own algorithm to implement that circular list by code)
So basically you should follow the next steps:
* You load those 10 values ordered in the circular list, let's say 1,2, 3, ... 10
* When you want to store a document in Redis, you extract an element from the list, for our list that element will be `1`
* make a query count on your ElasticSearch index to get the number of the document in the index
* if you get a count < 10 you call insert document query with your data and with the number extracted from the list as the document name. If count = 10 you call update document query on ElasticSearch
The circular will progress in this way:
* The initial state of the list is `[1, 2, ...10]`. You extract `1` and after extracting it, it goes to the end of the list: `[2,3,..., 10,1]`
* Second extraction from the list, current state of the list: `[2, 3, ...10, 1]`. You extract `2` and after extracting it, it goes to the end of the list: `[3,4,..., 1,2]`
* and so on
Upvotes: -1 <issue_comment>username_2: If you want to store only 10 doc then
you should apply algo = (document no%10)+1.
the return value is your elasticsearch \_id field
the algo retyrn only 1 to 10. and always index it.
Upvotes: 1 |
2018/03/19 | 400 | 1,556 | <issue_start>username_0: as a webdeveloper I really love developing on chrome. Now I noticed a bug with position: sticky on Google Chrome Browser. Elements that a positioned sticky wont behave correctly, means: everything seems to be good, until you hover an sticky positioned element, it wont react on interactions etc. (also JavaScript-Functions won't fire on click)
I tested it also on Mozillas Firefox, there it's working as it should.
It's position (of the related element) is sticky but it's behavor is buggy!
Is there any fix for that problem?<issue_comment>username_1: In case anybody is curious, this is probably a bug in chrome:
<https://bugs.chromium.org/p/chromium/issues/detail?id=827224>
That one was fixed as of Chrome 68, (not yet released as of 4/17/2018), however, there is another bug that is still open if the container of the sticky element has padding:
<https://bugs.chromium.org/p/chromium/issues/detail?id=834054>
Upvotes: 2 <issue_comment>username_2: **Now position sticky in flex containers is working in Chrome, and there could be a solution if it does not work in your case:**
Since flex box elements default to stretch, all the elements are the same height, which can't be scrolled against.
Adding `align-self: flex-start` to the sticky element set the height to auto, which allowed scrolling, and fixed it.
Currently this is supported in all major browsers, but Safari is still behind a -webkit- prefix, and other browsers except for Firefox have some issues with position: sticky tables.
Upvotes: 1 [selected_answer] |
2018/03/19 | 1,239 | 4,174 | <issue_start>username_0: I want to write a class that takes a pair of iterators as parameters to the constructor, but I dont know how to raise an error at compile-time when those iterators' `value_type` doesn't match an expected type. This is what I tried using `typeid`:
```
#include
struct foo {
std::vector data;
template
foo(IT begin, IT end){
typedef int static\_assert\_valuetype\_is\_double[
typeid(typename IT::value\_type) == typeid(double) ? 1 : -1
];
std::cout << "constructor called \n";
data = std::vector(begin,end);
}
};
int main()
{
std::vector x(5);
foo f(x.begin(),x.end()); // double: ok
std::vector y(10);
foo g(y.begin(),y.end()); // int: should not compile
}
```
Note that in this case, `int` to `double` would be fine, but thats just an example and in the real code the types have to match exactly. To my surprise in both cases, the constructor works without errors (there is only a warning about the unused typedef). Does the `-1` sized array static assert trick not work when the typedef is declared inside a method? **How do I produce an error when `IT::value_type` is the wrong type?**
PS: would be nice if there was an easy C++98 solution, but if this gets too complicated, I could also accept a C++11 solution.<issue_comment>username_1: In modern C++, you could have used [`std::is_same`](http://en.cppreference.com/w/cpp/types/is_same) and `static_assert`:
```
static_assert(std::is_same_v::value\_type, double>,
"wrong iterator");
```
See also [`std::iterator_traits`](http://en.cppreference.com/w/cpp/iterator/iterator_traits): an iterator `it` is not guaranteed to have a `value_type` typedef, and one should use `std::iterator_traits::value\_type` instead.
In C++ 98, `is_same` is trivial to implement, `static_assert` needs a [negative-size array trick](https://stackoverflow.com/a/14621998/5470596) or the [`BOOST_STATIC_ASSERT`](http://www.boost.org/doc/libs/1_60_0/doc/html/boost_staticassert.html).
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is a C++98 compliant way to implement it.....
First the fun part: Implementing a `is_same` is rather straightforward
```
template struct is\_same\_type { static const bool value; };
template const bool is\_same\_type::value = false;
template struct is\_same\_type { static const bool value; };
template const bool is\_same\_type::value = true;
```
Now the not-so-fun part (C++11 really helps to statically assert without causing coworkers raising some eyebrows):
```
struct foo {
std::vector data;
template
foo(IT begin, IT end) : data(begin,end) {
typedef int static\_assert\_valuetype\_is\_double[
is\_same\_type::value ? 1 : -1
];
std::cout << "constructor called \n";
}
};
int main(){
std::vector x(5,2.3);
foo f(x.begin(),x.end());
for (std::vector::iterator it = f.data.begin(); it != f.data.end();++it) std::cout << \*it << " ";
//std::vector y(10,3);
//foo g(y.begin(),y.end()); // THIS FAILS (AS EXPECTED)
}
```
As pointed out by others, I should actually be using `std::iterator_traits::value\_type` as not every iterator has a `value_type`. However, in my case I rather want to restrict the possible iterators to a small set and disallowing iterators without a `value_type` isnt a problem in my specific case.
Also note that the code in the question assigned to the member, while it is of course better to use the initializer list.
Upvotes: 1 <issue_comment>username_3: For a solution that works in C++98 and later.....
```
#include
template struct TypeChecker
{};
template<> struct TypeChecker
{
typedef double valid\_type;
};
template
void foo(IT begin, IT end)
{
typename TypeChecker::value\_type>::valid\_type type\_checker;
(void)type\_checker;
// whatever
}
```
Instantiations of `foo()` will succeed for any for an iterator for which `value_type` is `double`, and fail to compile otherwise.
The premise is that `TypeChecker` does not have a `valid_type` for any `x` other than `double`, but we attempt to instantiate an instance of that type in `foo()`. The `(void)type_checker` prevents warnings, from some compilers about a variable that is never used, for valid types.
Upvotes: 1 |
2018/03/19 | 1,164 | 4,076 | <issue_start>username_0: I am starting to use promise in NodeJS. The requirement is to use these because of async calls. Here is the first code I wrote for promise.
```
function asyncFunc(data) {
return new Promise(
function(resolve, reject) {
try {
resolve(data);
} catch (err) {
reject("Custom Error");
}
});
}
//Usage:
asyncFunc('Sample String')
.then(result => { console.log(result); })
.catch(error => { console.log(error); });
//Output:
Sample String
null
//If I change the code to:
function asyncFunc(data) {
return new Promise(
function(resolve, reject) {
try {
reject("Custom Error");
} catch (err) {
resolve("Data");
}
});
}
//Output:
//Exception has occurred: string
//I get the above exception at line: reject("Custom Error");
```
So the question is "reject" can only be used from "catch" block? Why can't I raise "reject" event manually? What is the scenario "reject" is used? Can someone provide me a better example where I can use both "resolve" and "reject"?<issue_comment>username_1: In modern C++, you could have used [`std::is_same`](http://en.cppreference.com/w/cpp/types/is_same) and `static_assert`:
```
static_assert(std::is_same_v::value\_type, double>,
"wrong iterator");
```
See also [`std::iterator_traits`](http://en.cppreference.com/w/cpp/iterator/iterator_traits): an iterator `it` is not guaranteed to have a `value_type` typedef, and one should use `std::iterator_traits::value\_type` instead.
In C++ 98, `is_same` is trivial to implement, `static_assert` needs a [negative-size array trick](https://stackoverflow.com/a/14621998/5470596) or the [`BOOST_STATIC_ASSERT`](http://www.boost.org/doc/libs/1_60_0/doc/html/boost_staticassert.html).
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is a C++98 compliant way to implement it.....
First the fun part: Implementing a `is_same` is rather straightforward
```
template struct is\_same\_type { static const bool value; };
template const bool is\_same\_type::value = false;
template struct is\_same\_type { static const bool value; };
template const bool is\_same\_type::value = true;
```
Now the not-so-fun part (C++11 really helps to statically assert without causing coworkers raising some eyebrows):
```
struct foo {
std::vector data;
template
foo(IT begin, IT end) : data(begin,end) {
typedef int static\_assert\_valuetype\_is\_double[
is\_same\_type::value ? 1 : -1
];
std::cout << "constructor called \n";
}
};
int main(){
std::vector x(5,2.3);
foo f(x.begin(),x.end());
for (std::vector::iterator it = f.data.begin(); it != f.data.end();++it) std::cout << \*it << " ";
//std::vector y(10,3);
//foo g(y.begin(),y.end()); // THIS FAILS (AS EXPECTED)
}
```
As pointed out by others, I should actually be using `std::iterator_traits::value\_type` as not every iterator has a `value_type`. However, in my case I rather want to restrict the possible iterators to a small set and disallowing iterators without a `value_type` isnt a problem in my specific case.
Also note that the code in the question assigned to the member, while it is of course better to use the initializer list.
Upvotes: 1 <issue_comment>username_3: For a solution that works in C++98 and later.....
```
#include
template struct TypeChecker
{};
template<> struct TypeChecker
{
typedef double valid\_type;
};
template
void foo(IT begin, IT end)
{
typename TypeChecker::value\_type>::valid\_type type\_checker;
(void)type\_checker;
// whatever
}
```
Instantiations of `foo()` will succeed for any for an iterator for which `value_type` is `double`, and fail to compile otherwise.
The premise is that `TypeChecker` does not have a `valid_type` for any `x` other than `double`, but we attempt to instantiate an instance of that type in `foo()`. The `(void)type_checker` prevents warnings, from some compilers about a variable that is never used, for valid types.
Upvotes: 1 |
2018/03/19 | 736 | 2,899 | <issue_start>username_0: I'm trying to send a GET request with a token authentication, but i get an unauthorized response.
If i send the same request on Postman, it works.
Here's my code :
```
string url = string.Format("{0}batchs", MyUrl);
RestClient client = new RestClient(url);
RestRequest getRequest = new RestRequest(Method.GET);
getRequest.AddHeader("Accept", "application/json");
getRequest.AddHeader("Authorization", "token " + MyToken);
getRequest.AddParameter("name", MyName, ParameterType.QueryString);
IRestResponse getResponse = client.Execute(getRequest);
```
And here's my postman request :
[Postman request](https://i.stack.imgur.com/10J0p.png)
Any ideas on how to correct this ?
Thanks !<issue_comment>username_1: I'm not sure exactly what kind of auth you're using, but I use a firebase token generated at runtime, and this is the only thing I could get to work for me.
```
request.AddHeader("authorization", "Bearer " + _fireBaseService.AuthToken);
```
Upvotes: 4 <issue_comment>username_2: I encountered a similar problem in my implementation. I've explored various solutions, but none of them have been effective so far. Eventually, I discovered that Postman handles HTTP redirection automatically. However, when using RestSharp for implementation, the headers we initially set are not included in the redirected request.
To verify, disable the "Automatically follow redirects" setting in Postman. After turning off this setting, if the issue still persists in Postman, it indicates that the problem lies in the extraction process.
[](https://i.stack.imgur.com/yGohH.png)
So I added a check that resends the API request of receiving a 401 with the below code.
```
... rest of your code
RestResponse response = await client.ExecuteAsync(request);
int numericStatusCode = (int)response.StatusCode;
if (numericStatusCode == 401)
{
var redirectedClient = new RestClient(response.ResponseUri.ToString());
var newResponse = redirectedClient.Execute(request);
Console.WriteLine(newResponse.ResponseStatus);
}
```
Here is my full code:
```
var url = $"{_apiCredentials.DataServer}/test/data/contracts/";
var options = new RestClientOptions(url)
{
MaxTimeout = -1,
Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(
accessToken.Token, // Update the token
"Bearer")
};
var client = new RestClient(options);
var request = new RestRequest("", Method.Get);
RestResponse response = await client.ExecuteAsync(request);
int numericStatusCode = (int)response.StatusCode;
if (numericStatusCode == 401)
{
var redirectedClient = new
RestClient(response.ResponseUri.ToString());
var newResponse = redirectedClient.Execute(request);
Console.WriteLine(newResponse.ResponseStatus);
}
```
Upvotes: 0 |
2018/03/19 | 981 | 3,897 | <issue_start>username_0: If I run the following query in sqldeveloper (or sqlplus):
```
select *
from passwordlog
where exists(
select USERUID
from otherTable
where uid=2
);
```
and the `where exists` evaluates to false, the result is just empty.
The result isn't either null or a boolean, so I test if the length of this result is greater than 1.
But I just started to wonder. What is the result really? Is it an empty string? Or null? And is there a better way to perform this check, than checking on the length of the returned string?
I want to be able to do something like this (assume we have the Oracleconnection, OracleDataAdapter etc.):
```
string query = select *
from passwordlog
where exists(
select USERUID
from otherTable
where uid=2
);
```
And then in a C# method:
```
public void SomeMethod() {
if(query == null) { } ...
or maybe
if(query == false) { } ...
}
```
Thanks<issue_comment>username_1: As you check only whether something "exists" or not (at least, that's what your C# code looks like), if you - instead of `select *` - use `select count(*)`, you might fix it as `COUNT` will return 0 (zero) if there's nothing to be returned, so you'd easily check that in your C# code.
Upvotes: 3 [selected_answer]<issue_comment>username_2: It's an empty result set or record set. So the below query can be simplified to. Thus no rows would be selected since the predicate is `false`. So your check if no.of rows > 1 would always be false as well
```
select *
from passwordlog
where false
```
To check, if you just do below, the record count would be `0`
```
select count(*) from passwordlog where 1 = 0
```
Upvotes: 2 <issue_comment>username_3: alter the code like this and try..
```
select count(*)
from passwordlog
where exists (select useruid
from othertable
where uid=2)
```
Upvotes: 0 <issue_comment>username_4: Usually in an `EXISTS` subquery you would refer to the record in the main query, e.g. find out whether there exists an otherTable entry for the passwordlog's userid:
```
select *
from passwordlog p
where exists (select * from otherTable o where o.uid = p.uid);
```
Your subquery, however, is not correlated to the main query. It is either true or false, no matter what passwordlog record you are looking at. This means you either select all passwordlog records or none at all.
As to your question when the expression evaluates to false (no uid=2 record in otherTable): This is the case you select no records. You are asking whether this is an empty string or null, but keep in mind: you have selected no rows. If you had selected some rows, you could have asked for a specific column in a specific row, e.g.: what is the password in the first row or what is the user ID in the second row? But of course you cannot ask "what is the columns in the zeroth row".
As to merely checking whether a uid=2 record in otherTable exists, that would be
```
select exists (select * from otherTable where uid = 2);
```
in standard SQL returning a boolean. In Oracle however you must always select from a table (the dual table for one row) and there is no boolean datatype. Hence:
```
select
case when exists (select * from otherTable where uid = 2) then 1 else 0 end
from dual;
```
Another option would be counting the records, but you don't want to read all records and keep counting all the while, when you only want to know whether at least one record matches. In Oracle you can use rownum for that:
```
select count(*)
from otherTable
where uid = 2 and rownum = 1;
```
Oracle will stop at the first match and hence return either 0 or 1, depending on whether a uid=2 record in otherTable exists.
Upvotes: 2 |
2018/03/19 | 950 | 3,769 | <issue_start>username_0: The project spring boot 1..5.7 release. I am using Intellij IDEA 2017.2.4 and gradle for dependency management. When i build the project it builds successfully with no error. When I run the application with bootRun gradle task it shows the following error.
```
Exception in thread "main" java.lang.IllegalArgumentException: Cannot instantiate interface org.springframework.boot.SpringApplicationRunListener : org.springframework.boot.context.event.EventPublishingRunListener
at org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:413)
at org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:392)
at org.springframework.boot.SpringApplication.getRunListeners(SpringApplication.java:378)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:291)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
at com.kifiya.lmanagement.LmanagementApplication.main(LmanagementApplication.java:13)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.context.event.EventPublishingRunListener]: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.aop.framework.AopProxyUtils.getSingletonTarget(Ljava/lang/Object;)Ljava/lang/Object;
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:409)
... 6 more
Caused by: java.lang.NoSuchMethodError: org.springframework.aop.framework.AopProxyUtils.getSingletonTarget(Ljava/lang/Object;)Ljava/lang/Object;
at org.springframework.context.event.AbstractApplicationEventMulticaster.addApplicationListener(AbstractApplicationEventMulticaster.java:105)
at org.springframework.boot.context.event.EventPublishingRunListener.(EventPublishingRunListener.java:56)
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.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 7 more
```<issue_comment>username_1: It looks like `spring-aop` doesn't match the rest of your libraries. Try running `gradle dependencies` and check that all Spring dependencies are in the same version. More on inspecting dependencies in [Gradle User Manual](https://docs.gradle.org/current/userguide/userguide_single.html#inspecting_dependencies).
Upvotes: 1 <issue_comment>username_2: It seems like a dependency problem within Spring, as it's mentioned above. The easiest way IMHO is to check your POM file.
Check out here for more info: <https://docs.gradle.org/current/userguide/introduction_dependency_management.html>
Upvotes: 2 <issue_comment>username_3: Old question, but I had the same error after converting a Spring application to Spring Boot. Using the `spring-boot-starter-aop` instead of a direct dependency on a specific version of `spring-aop` resolved it for me, e.g. in `build.gradle`:
```
plugins {
id 'org.springframework.boot' version '1.5.17.RELEASE'
}
apply plugin: 'io.spring.dependency-management'
dependencies {
compile 'org.springframework.boot:spring-boot-starter-aop'
}
```
instead of
```
dependencies {
compile 'org.springframework:spring-aop:4.2.4.RELEASE'
}
```
Upvotes: 1 |
2018/03/19 | 443 | 1,478 | <issue_start>username_0: It is a simple controller. Receive requests from users, do task and response to them. My goal is to make the response as soon as possible and do the task then so the user will not notice the lengthy waiting time.
Here is my code:
```
router.post("/some-task", (req, res, next) => {
res.send("ok!");
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5000); // lengthy task
});
```
When post to this controller, I need to wait 5000ms before getting the response, which is not I want. I have tried promise but don't work either. What is the correct way to do it?<issue_comment>username_1: You can have a callback after `res.end` that will execute as soon as the response was sent.
```
router.get('/', function(req, res, next) {
res.end('123', () => {
setTimeout(() => {console.log('456')}, 5000)
})
});
```
Notice you're browser will receive `123` and after 5 seconds your server will log `456`.
Upvotes: 1 <issue_comment>username_2: Improve version for username_1tar Meged answer:
```
router.post("/some-task", (req, res, next) => {
res.send("ok!");
setTimeout(()=>{
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5000); // lengthy task
}, 0);
});
```
It is not about `res.end`, just `setTimeout` do the thing. But I don't recommend this since it will block the entire app for handling other requests. You may need to think to use `child process` instead.
Upvotes: 4 [selected_answer] |
2018/03/19 | 438 | 1,300 | <issue_start>username_0: I have the following code snippet:
```
bevs <- data.frame(cbind(name = c("Bill", "Llib"), drink = c("coffee", "tea", "cocoa", "water"), cost = seq(1:8)))
bevs$cost <- as.integer(bevs$cost)
library(plyr)
count(bevs, "name")
```
Output Should be:
```
name freq
1 Bill 4
2 Llib 4
```
But the output is :
```
count(bevs, "name")
# A tibble: 1 x 2
`"name"` n
1 name 8
```
Please help.<issue_comment>username_1: You can have a callback after `res.end` that will execute as soon as the response was sent.
```
router.get('/', function(req, res, next) {
res.end('123', () => {
setTimeout(() => {console.log('456')}, 5000)
})
});
```
Notice you're browser will receive `123` and after 5 seconds your server will log `456`.
Upvotes: 1 <issue_comment>username_2: Improve version for username_1tar Meged answer:
```
router.post("/some-task", (req, res, next) => {
res.send("ok!");
setTimeout(()=>{
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5000); // lengthy task
}, 0);
});
```
It is not about `res.end`, just `setTimeout` do the thing. But I don't recommend this since it will block the entire app for handling other requests. You may need to think to use `child process` instead.
Upvotes: 4 [selected_answer] |
2018/03/19 | 313 | 1,033 | <issue_start>username_0: How can I override the **favicon.ico** in the Hybris using an addon?
I tried to overwrite the property `img.favIcon` but it doesn't work<issue_comment>username_1: You can have a callback after `res.end` that will execute as soon as the response was sent.
```
router.get('/', function(req, res, next) {
res.end('123', () => {
setTimeout(() => {console.log('456')}, 5000)
})
});
```
Notice you're browser will receive `123` and after 5 seconds your server will log `456`.
Upvotes: 1 <issue_comment>username_2: Improve version for username_1tar Meged answer:
```
router.post("/some-task", (req, res, next) => {
res.send("ok!");
setTimeout(()=>{
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5000); // lengthy task
}, 0);
});
```
It is not about `res.end`, just `setTimeout` do the thing. But I don't recommend this since it will block the entire app for handling other requests. You may need to think to use `child process` instead.
Upvotes: 4 [selected_answer] |
2018/03/19 | 497 | 1,808 | <issue_start>username_0: I'm trying to create `DatagridComboBoxColumn` from code behind. How can I link it to `ElementStyle` and `EditingElementStyle`?
I'm trying to create this:
```
```
which creates this:
[](https://i.stack.imgur.com/U4fag.png)
from this:
```
private DataGridComboBoxColumn CreateComboValueColumn()
{
DataGridComboBoxColumn column = new DataGridComboBoxColumn();
column.ElementStyle = ???;
column.EditingElementStyle = ???;
return column;
}
```
Which do not display comboBox:
[](https://i.stack.imgur.com/wiuU9.png)
Style which I'm trying to link:
```
<Setter Property="ItemsSource" Value="{Binding ComboItems}"/>
<Setter Property="SelectedValue" Value="{Binding Value}" />
<Setter Property="DisplayMemberPath" Value="Text"/>
<Setter Property="SelectedValuePath" Value="ID" />
<Setter Property="ItemsSource" Value="{Binding ComboItems}"/>
<Setter Property="SelectedValue" Value="{Binding Value}" />
<Setter Property="DisplayMemberPath" Value="Text"/>
<Setter Property="SelectedValuePath" Value="ID" />
```<issue_comment>username_1: Hello try something like this:
```
private DataGridComboBoxColumn CreateComboValueColumn()
{
DataGridComboBoxColumn column = new DataGridComboBoxColumn();
column.ElementStyle = YourWindowName.FindResource("ComboBoxElementStyle") as Style;
column.EditingElementStyle = YourWindowName.FindResource("ComboBoxEditingElementStyle") as Style;
return column;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Try something like`(Style)FindResource("StyleOne")`
Have a look here:
<https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/resources-and-code>
Upvotes: 0 |
2018/03/19 | 358 | 1,392 | <issue_start>username_0: I want to create several VM's from [this](https://azuremarketplace.microsoft.com/en-us/marketplace/apps/microsoft-ads.windows-data-science-vm?tab=Overview) Image automatically.
When I'm getting redirected to the Portals Website I can choose the option "Want to deploy programmatically? Get started-->". Yes, I want to, but in this Windows it seems like my Subscription isn't enabled for this option.
[(Picture)](https://i.stack.imgur.com/6bSws.jpg) So it's just a button to enable my Subscription, isn't it? Otherwise the status was "Enabled" or "Disable" to disable my Subscription. If I click the "Enable"-Button, nothing happens.
Does anyone of you have an idea how to enable my Subscription? Well, perhaps my thinking is wrong?
Thank you in advance!<issue_comment>username_1: Hello try something like this:
```
private DataGridComboBoxColumn CreateComboValueColumn()
{
DataGridComboBoxColumn column = new DataGridComboBoxColumn();
column.ElementStyle = YourWindowName.FindResource("ComboBoxElementStyle") as Style;
column.EditingElementStyle = YourWindowName.FindResource("ComboBoxEditingElementStyle") as Style;
return column;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Try something like`(Style)FindResource("StyleOne")`
Have a look here:
<https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/resources-and-code>
Upvotes: 0 |
2018/03/19 | 1,771 | 5,585 | <issue_start>username_0: Following [my other question on how to parse date-only strings as LocalDateTime](https://stackoverflow.com/questions/49323017/parse-date-only-as-localdatetime-in-java-8/), on attempt to parse string 20120301122133 using pattern yyyyMMdd[HHmmss] I get an error. Strange thing is that parsing 20120301 122133 using pattern yyyyMMdd[ HHmmss] works perfectly.
So this code works fine
```
LocalDateTime.parse(
"19940513 230000",
new DateTimeFormatterBuilder()
.appendPattern("yyyyMMdd[ HHmmss]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter()
)
```
And this one fails
```
LocalDateTime.parse(
"19940513230000",
new DateTimeFormatterBuilder()
.appendPattern("yyyyMMdd[HHmmss]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter()
)
```
How should I parse Strings in format yyyyMMdd[HHmmss], i.e. in format yyyyMMddHHmmss with optional time part using the java 8 time API?
The parse pattern is a configurable option and thus is known only at runtime. So I can't e.g. replace the String pattern with hard-coded DateTimeFormatterBuilder invocations.<issue_comment>username_1: The problem is that the pattern expression "yyyy" does not indicate a fixed four-digit-year but at least 4 digits (or more, so the parser is greedy). But you can do following:
```
LocalDateTime ldt =
LocalDateTime.parse(
"19940513230000",
new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4)
.appendPattern("MMdd[HHmmss]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter());
System.out.println(ldt); // 1994-05-13T23:00
```
Upvotes: 2 <issue_comment>username_2: ```
System.out.println(LocalDateTime.parse(
"19940513230000",
new DateTimeFormatterBuilder()
.appendPattern("[uuuuMMddHHmmss][uuuuMMdd]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter()
));
```
This prints:
>
> 1994-05-13T23:00
>
>
>
If instead I try to parse a string with just the date, `"19940513"`, I get
>
> 1994-05-13T00:00
>
>
>
It works with `yyyy` instead of `uuuu` too. Assuming all your years are in this era (year 1 or later), it doesn’t make any difference which one you use. Generally `uuuu` will accept a negative year too, 0 meaning 1 BCE, -1 meaning 2 BCE and so forth.
Upvotes: 3 [selected_answer]<issue_comment>username_3: This happens because the year hasn't a fixed value, it is normally limited to 19 digits.
If you create the following formatter (minutes and seconds are not required) and use the `toString()` method:
```
new DateTimeFormatterBuilder()
.appendPattern("yyyyMMdd[ HHmmss]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter()
.toString();
```
You could see the following:
>
> "Value(**YearOfEra,4,19,EXCEEDS\_PAD**)Value(MonthOfYear,2)Value(DayOfMonth,2)[' 'Value(HourOfDay,2)Value(MinuteOfHour,2)Value(SecondOfMinute,2)]java.time.format.DateTimeFormatterBuilder$DefaultValueParser@32eff876"
>
>
>
Here you can see that `YearOfEra` has a minimun width of 4 and a maximun of 19.
You can use one of the answers of Meno or Ole.
However if you need to receive the format and the date as parameters, and you want to be able to specify the date format in a simpler way (e.g. `yyyyMMdd[HHmmSS]` instead `[...][...]`), you may preprocess one of the to values (either the format of the date).
You can create 'dinamically' the formatter, so every `yyyy` is interpreted as a 4 digits year only.
A custom format builder could be something like (can be improved):
```
public static DateTimeFormatter createFixed4DigitYearFormatter(String format) {
DateTimeFormatterBuilder formatBuilder = new DateTimeFormatterBuilder();
Arrays.stream(format.split("yyyy", -1))
.flatMap(cur -> Stream.of("yyyy", cur)).skip(1)
.filter(str -> !str.isEmpty())
.forEach(pattern -> {
if ("yyyy".equals(pattern)) formatBuilder
.appendValue(ChronoField.YEAR_OF_ERA, 4);
else formatBuilder.appendPattern(pattern);
});
return formatBuilder.parseDefaulting(ChronoField.HOUR_OF_DAY, 0).toFormatter();
}
```
This formater split the format by the string `"yyyy"`, then every non `"yyyy"` is added as a pattern (with `appendPattern(..)`) and the `"yyyy"` is added as a value of type `YEAR_OF_ERA` with fixed 4 digits (with `appendValue(..)`).
Finally you can use the formatter with multiple formats:
```
System.out.println(LocalDateTime.parse("19940513230000",
createFixed4DigitYearFormatter("yyyyMMdd[HHmmss]"))); // 1994-05-13T23:00
System.out.println(LocalDateTime.parse("19940513",
createFixed4DigitYearFormatter("yyyyMMdd[HHmmss]"))); // 1994-05-13T00:00
System.out.println(LocalDateTime.parse("1994-05-13 23:00:00",
createFixed4DigitYearFormatter("yyyy-MM-dd[ HH:mm:ss]"))); // 1994-05-13T23:00
System.out.println(LocalDateTime.parse("1994-05-13",
createFixed4DigitYearFormatter("yyyy-MM-dd[ HH:mm:ss]"))); // 1994-05-13T00:00
```
Upvotes: 2 |
2018/03/19 | 861 | 2,985 | <issue_start>username_0: Odoo service is started by `systemctl start odoo`. I am usin Centos. When I want to update my changed \*.py code I used to do like this:
```
1. systemctl stop odoo
Then I update my module and database by useing this:
2. ./odoo.py -c openerp-server.conf -u -d
3. stop service by ctrl + c
4. systemctl start odoo
```
But it's realy long and uncomfortable way to update changes.
Is there a shorter way to do the same operations in shorter way?<issue_comment>username_1: Odoo with Service
-----------------
You can make changes like this:
1. Stop the server: `systemctl stop odoo`
2. Start the server: `systemctl start odoo`. Here the `.py` are updated
3. If you also need to update `xml` or some translations you can press the `Update` button on the Odoo interface, on the module description form.
**Note**: There are modules to reload specific xml views. If you are interested in it I can take a look to check if I find one.
Odoo without Service
--------------------
If you are developing on your local computer, you don´t need to use `systemctl`. Just run Odoo directly with `odoo.py` and you can see the changes immediately:
```
./odoo.py -c openerp-server.conf -u -d
```
Autoreload Python Files
-----------------------
There is another option to reload python files when they have changed. Check this [**other answer**](https://stackoverflow.com/a/29247084/4891717):
>
> Normally if you change your python code means, you need to restart the
> server in order to apply the new changes.
>
>
> `--auto-reload` parameter is enabled means, you don't need to restart the server. It enables auto-reloading of python files and xml files
> without having to restart the server. It required
> [pyinotify](https://github.com/seb-m/pyinotify/wiki). It is a Python
> module for monitoring filesystems changes.
>
>
> Just add `--auto-reload` in your configuration file. By default the
> value will be "false". You don't need to pass any extra arguments.
> `--auto-reload` is enough. If everything setup and works properly you will get
>
>
>
> ```
> openerp.service.server: Watching addons folder /opt/odoo/v8.0/addons
> openerp.service.server: AutoReload watcher running in the server log. Don't forget to install pyinotify package.
>
> ```
>
>
But in odoo 10 just add `--dev=reload` paramter
```
--dev=DEV_MODE Enable developer mode. Param: List of options
separated by comma. Options : all,
[pudb|wdb|ipdb|pdb], reload, qweb, werkzeug, xml
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
Failed to stop odoo.service: Access denied. See system logs and 'systemctl status odoo.service' for details.
```
Initially, I got this error. Then tried with su and got this.
```
Failed to stop odoo.service: Unit odoo.service not loaded.
```
My concern is how to identify the perfect file through which I can restart the Odoo services post new module installation.
Upvotes: 0 |
2018/03/19 | 658 | 2,082 | <issue_start>username_0: What is difference in creating a string object within the while loop, assign different values in each iteration and create string object outside the loop and assign value in each iteration?<issue_comment>username_1: The difference between the two code is the scope of the name variable.
name can be used in the body of the while loop only in the first code, while it can be used in the whole main body in the second code.
Upvotes: 1 <issue_comment>username_2: After compilation, as you can see there is no difference. You can view Java bytecode with `javap -c`.
```
C:\Users\y7017\Desktop>javac Test.java
C:\Users\y7017\Desktop>javac Test1.java
C:\Users\y7017\Desktop>javap -c Test
Compiled from "Test.java"
public class Test {
public Test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst\_0
1: istore\_1
2: iload\_1
3: bipush 10
5: if\_icmpge 17
8: ldc #2 // String Tester
10: astore\_2
11: iinc 1, 1
14: goto 2
17: return
}
C:\Users\y7017\Desktop>javap -c Test1
Compiled from "Test1.java"
public class Test1 {
public Test1();
Code:
0: aload\_0
1: invokespecial #1 // Method java/lang/Object."":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst\_0
1: istore\_1
2: iload\_1
3: bipush 10
5: if\_icmpge 17
8: ldc #2 // String Tester
10: astore\_2
11: iinc 1, 1
14: goto 2
17: return
}
```
**Edit: Added example code blocks removed from question.**
### Test.java
```
public class Test {
public static void main(String args[]) {
int iterator = 0;
String name;
while( iterator < 10 ) {
name = "Tester";
iterator++;
}
}
}
```
### Test1.java
```
public class Test1 {
public static void main(String args[]) {
int iterator = 0;
while( iterator < 10 ) {
String name = "Tester";
iterator++;
}
}
}
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 629 | 2,187 | <issue_start>username_0: I am getting this error while sync gradle project.
Unable to resolve dependency for `':app@debugAndroidTest/compileClasspath': Could not resolve com.android.support:design:26.1.0`
can anyone help me?
```
apply plugin: 'com.android.application' android {
compileSdkVersion 26
defaultConfig {
applicationId "com.example.phaniteja.sample1"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
} } dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' }
```<issue_comment>username_1: `Unable to resolve dependency for` `:app@debugAndroidTest/compileClasspath': Could not resolve com.android.support:design:26.1.0` This issue usually happens when the Android Studio is not able to download that dependency.That can be due to many reasons like [this](https://stackoverflow.com/questions/46999594/unable-to-resolve-dependency-for-appdebug-compileclasspath-could-not-resolv/48092108#48092108) Or like in my case where the `Maven2` and `jcenter` repositories are blocked in Company. So what can you do is like check this folder
>
> Android-sdk\extras\android\m2repository\com\android\support\appcompat-v7
>
>
>
and check which all versions are available to you in the SDK, use either one of those versions ,So instead of downloading from repository studio will take that lib from SDK.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Try to add your Google maven repo. it works for me.##
```
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
```
Upvotes: 0 |
2018/03/19 | 494 | 1,794 | <issue_start>username_0: I have downloaded the source code of example cordapp from [here](https://github.com/corda/cordapp-example).
I am getting following error when I give the command :
`gradle deployNodes`.
Please guide me on what can be done.
Note: This is Corda V3.
```
> Task :java-source:deployNodes
Bootstrapping local network in C:\Blockchain\cordapp-example-release-V3\java-source\build\nodes
Node config files found in the root directory - generating node directories
Generating directory for Notary
Generating directory for PartyA
Generating directory for PartyB
Generating directory for PartyC
Nodes found in the following sub-directories: [Notary, PartyA, PartyB, PartyC]
Waiting for all nodes to generate their node-info files...
Distributing all node info-files to all nodes
Gathering notary identities
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':java-source:deployNodes'.
> java.util.concurrent.ExecutionException: java.lang.RuntimeException: Unknown constant pool tag [I@5d453b56 in classfile module-info.class (element size unknown, cannot continue reading class. Please report this on the FastClasspathScanner GitHub page.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 45s
5 actionable tasks: 2 executed, 3 up-to-date
```<issue_comment>username_1: Also faced the same issue on V2 to V3 migration. I had to downgrade Gradle from 4.5.1 to 4.1 in my project to get it working again.
Upvotes: 3 [selected_answer]<issue_comment>username_2: This is fixed in Corda 3.1. Upgrade notes here: <https://docs.corda.net/upgrade-notes.html#v3-0-to-v3-1>.
Upvotes: 0 |
2018/03/19 | 298 | 1,110 | <issue_start>username_0: The Unicode is allowed in identifiers in backticks
```
val `id` = "1"
```
But slash is not allowed
```
val `application/json` = "application/json"
```
In Scala we can have such names.<issue_comment>username_1: Kotlin's identifiers are used as-is, without any mangling, in the names of JVM classes and methods generated from the Kotlin code. The slash has a special meaning in JVM names (it separates packages and class names). Therefore, Kotlin doesn't allow using it in an identifier.
Upvotes: 3 <issue_comment>username_2: This is a JVM limitation. From the specification section [4.2.2](https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.2.2):
>
> Names of methods, fields, local variables, and formal parameters are stored as unqualified names. An unqualified name must contain at least one Unicode code point and must not contain any of the ASCII characters . ; [ / (that is, period or semicolon or left square bracket or forward slash).
>
>
>
In Scala names are mangled to avoid this limitation, in Kotlin they are not.
Upvotes: 5 [selected_answer] |
2018/03/19 | 655 | 2,076 | <issue_start>username_0: I am trying to increment a value of an element here's my array object
```
"options": [
{
"key": "banana",
"votes": 0
},
{
"key": "apple",
"votes": 0
},
{
"key": "mango",
"votes": 0
},
{
"key": "grapes",
"votes": 0
}
]
```
im trying to increment the votes value of the selected
`item` while also matching the `id` of that data
```
db().collection('polls').update(
{ _id: id, "options.key": item },
{$set: { $inc: { "options.$.votes" : 1 } }})
```
But it didn't work... the `db()` here is a function that returns the db.. im not getting any errors.
here is the full data
```
{
"_id": {
"$oid": "5aae26203ab1cc0f15e43dc6"
},
"author": "me",
"title": "fruits you love the most",
"options": [
{
"key": "banana",
"votes": 0
},
{
"key": "apple",
"votes": 0
},
{
"key": "mango",
"votes": 0
},
{
"key": "grapes",
"votes": 0
}
]
}
```<issue_comment>username_1: Remove `$set` and try. It should work then. Also, the `db` should be used without paranthesis like `db` and not `db()`:
```
db.collection('polls').update(
{ _id: id, "options.key": item },
{ $inc: { "options.$.votes" : 1 } }
)
```
If you are running this query directly in your mongodb shell then you need to specify `_id: ObjectId(id)` in your query so your query will be:
```
var id = '5aaf66812b0e3813178a8a14'
db.collection('polls').update(
{ _id: ObjectId(id), "options.key": item },
{ $inc: { "options.$.votes" : 1 } }
)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You are doing thing all correct but only one mistake is **$inc** should not be inside **$set**.
Following will fulfil your requirement.
```
db.collection.update(
{"options.key": "banana" },
{ $inc: { "options.$.votes" : 1 } }
)
```
Upvotes: 0 |
2018/03/19 | 562 | 2,137 | <issue_start>username_0: Is it possible to start an `Activity` using an `Intent` from a class that extends `LinearLayout`?
Here is my code:
```
@Override
public void onClick(View v) {
if (inputConnection == null)
return;
if (v.getId()==R.id.replay) {
//do not work ???
Intent intent= new Intent(this.MyKeyboard,Main2Activity.class);
startActivity(intent);
}
if (v.getId() == R.id.button_delete) {
CharSequence selectedText = inputConnection.getSelectedText(0);
if (TextUtils.isEmpty(selectedText)) {
inputConnection.deleteSurroundingText(1, 0);
} else {
inputConnection.commitText("", 1);
}
} else {
String value = keyValues.get(v.getId());
inputConnection.commitText(value, 1);
}
}
public void setInputConnection(InputConnection ic) {
this.inputConnection = ic;
}
```<issue_comment>username_1: `LinearLayout` extends `ViewGroup`, which extends `View`, so you may access your context using [`getContext()`](https://developer.android.com/reference/android/view/View.html#getContext())
```
Intent intent= new Intent(this.getContext(),Main2Activity.class);
startActivity(intent);
```
Upvotes: 0 <issue_comment>username_2: Your problem seems to be that `this.MyKeyboard`is not a [Context](https://developer.android.com/reference/android/content/Context.html) object, since it is a subclass of LinearLayout. Hopefully, this class extends the View class so you can access your context using [getContext()](https://developer.android.com/reference/android/view/View.html#getContext()). Your code should look like :
```
Intent intent = new Intent(this.getContext(), Main2Activity.class);
startActivity(intent);
```
Edit:
If your context is not an Activity context you need to add the flag [FLAG\_ACTIVITY\_NEW\_TASK](https://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NEW_TASK) using [addFlags()](https://developer.android.com/reference/android/content/Intent.html#addFlags(int)) :
```
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 897 | 3,083 | <issue_start>username_0: I'm trying to make a \*ngFor directive to put data in two columns, instead of just one column as usual. I even followed an example I saw over there, but it didn't work at all. Let's start with the graphic part:
I've got this:
[](https://i.stack.imgur.com/Bg90z.png)
... but I want it to look like this (so I can fit more items than before without making the card bigger):
[](https://i.stack.imgur.com/9Evyq.png)
This is the code I currently have, which does absolutely nothing (it just shows the first image):
```
[{{ level?.label || level }}](javascript:void(0))
[{{ level?.label || level }}](javascript:void(0))
```
This uses the following CSS:
```
.left-style{
float:left;
width:45%;
}
.right-style{
float:right;
width:45%;
}
```
I know it wouldn't be needed in this example, but it was just a try. I'm quite confused why this is not working at all. Inside the created divs, the bootstrap classes (col-md-6) are not being applied at all.
Why is this happening?
**EDIT:**
Let me expand a little how the app looks like so it's easy to find out what's going on. After trying other methods that didn't really work, I guess it's time to give you a wider view of what this looks like in order to find out how to fix this weird thing.
The parent component uses "cards" like the one you see upper in this post. So, the main template looks like this:
[](https://i.stack.imgur.com/0MpmK.png)
The "cards" component has a ng-content which draws inside another component that I provide, as you could see in the parent component's implementation. This is the cards component:
```
import { Component, Input } from '@angular/core';
@Component({
selector: "card",
styleUrls: ["./card.css"],
template: `
{{title}}
`
})
export class Card{
@Input() title: string;
constructor(){
}
}
```
Somehow, just as I stated in the comments of the first proposed answer, the divs aren't compiling the bootstrap classes as they normally would:
[](https://i.stack.imgur.com/geOge.png)
It's becoming really weird at this moment. Can anyone spot what's wrong here?<issue_comment>username_1: The issue is that you have two `class` attributes for each div, so Angular is taking the later class only.
Simply merge the class attribute like:
And both classes will be applied.
You can actually use less html and use `ngClass` as follows
```
[{{ level?.label || level }}](javascript:void(0))
```
Upvotes: 2 <issue_comment>username_2: Easy way:
I am making the `Angular` demo `Tour of Heroes` and i wanted to divide in two columns the dashboard data \*ngFor display;(like this)
[](https://i.stack.imgur.com/f1i0z.png)
this is code it works for me right now:
```
{{hero.name}}
```
Upvotes: 1 |
2018/03/19 | 1,181 | 4,837 | <issue_start>username_0: I have Listview, ArrayAdapter and Layout for ArrayAdapter as ItemView.
Now, I have managed to change the background color of selected/clicked item's layout.
But how can I change the background color to the original when another item is selected?
Code Sample :
```
Listview listview;
int PREVIOUSLY_SELECTED_ID = -1;
if (arrayList != null) {
Collections.sort(arrayList);
arrayAdapter = new ArrayAdapter(getContext(), android.R.layout.simple\_list\_item\_1, arrayList){
@NonNull
@Override public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
// This is the Layout File "listitem\_layout.xml" i am inflating to arrayadapter.
@SuppressLint({"ViewHolder", "InflateParams"}) final View view = layoutInflater.inflate(R.layout.listitem\_layout, null, true);
// This is the RelativeLayout in "listitem\_layout.xml".
final RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.relativelayout\_selected\_item);
// This is onClick event of "relativelayout".
relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
if (PREVIOUSLY\_SELECTED\_ID != position)
{
// Here, i am changing background color of relativelayout when item is clicked.
v.setBackgroundResource(R.color.tomatoLight);
if(PREVIOUSLY\_SELECTED\_ID != -1)
{
// Here, i want to change Previously Selected Item's Background Color to it's original(Which is 'Orange').
listView.getAdapter().getView(position,convertView,parent).setBackgroundResource(R.color.orange);
}
PREVIOUSLY\_SELECTED\_ID = position;
}
else
{
v.setBackgroundResource(R.color.orange);
}
});
return view;
}
};
listView.setAdapter(arrayAdapter);
}
```<issue_comment>username_1: You can just keep track of your last clicked item then notify the adapter so that it'll set the backgrounds accordingly
**Update**
Use an `OnItemClickListener` to catch the click instead of using the view itself
```
Listview listview;
int selectedPosition = -1;
if (arrayList != null) {
Collections.sort(arrayList);
arrayAdapter = new ArrayAdapter(getContext(), android.R.layout.simple\_list\_item\_1, arrayList) {
@NonNull
@Override
public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
@SuppressLint({"ViewHolder", "InflateParams"})
final View view = layoutInflater.inflate(R.layout.listitem\_layout, null, true);
final RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.relativelayout\_selected\_item);
// if the views that is currently being created is the same is the one clicked before notifying the adapter then change it's color
if (selectedPosition == position) {
relativeLayout.setBackgroundResource(R.color.tomatoLight);
} else {
relativeLayout.setBackgroundResource(R.color.orange);
}
return view;
}
};
listView.setAdapter(arrayAdapter);
listView.setOnItemclickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView adapter, View arg1, int position, long id) {
selectedPosition = position;
arrayAdapter.notifyDataSetChanged();
}
});
}
```
Upvotes: 0 <issue_comment>username_2: You can use [getChildAt()](https://developer.android.com/reference/android/view/ViewGroup.html#getChildAt%28int%29) method of Listview to get the view and then change the color.
```
if (SELECTED_ID != -1) {
View view1 = listView.getChildAt(SELECTED_ID -
listView.getFirstVisiblePosition());
// Here, i want to change Previously Selected Item's Background Color to it's original(Which is 'Orange').
view1.setBackgroundResource(R.color.Orange);
}
```
Hope this helps.
Upvotes: 1 <issue_comment>username_3: @username_1 is right in that you have to **override** the default behavior of ArrayAdapter's `getView` method. I believe just using ListView's `getChild` method just returns a view with a difference reference. That's why nothing happens when you try to modify it by calling `setBackgroundColor` (you're setting the background color of a difference list item view.
If you want other items color to change when you click another item, you'll need to remember more than just one value. e.g.: Perhaps you'd want to use another variable in addition to `selectedPosition`, say `previousPosition`, and keep track on the values of these variables when changes occur. These are just two variables which means you can only remember two things at a time. Perhaps use a `List` or an `int[]` array and add or remove values as the user selects and deselects items in the list.
Upvotes: 0 |
2018/03/19 | 800 | 3,264 | <issue_start>username_0: Given an object definition that I'm not allowed to modify:
```
let a = {"a-b" : 5};
```
How can I add JSDoc over it ?
I tried
```
/**
* @type {{"a-b": number}}
*/
```
But WebStorm tells me that this is not valid JSDoc.<issue_comment>username_1: You can just keep track of your last clicked item then notify the adapter so that it'll set the backgrounds accordingly
**Update**
Use an `OnItemClickListener` to catch the click instead of using the view itself
```
Listview listview;
int selectedPosition = -1;
if (arrayList != null) {
Collections.sort(arrayList);
arrayAdapter = new ArrayAdapter(getContext(), android.R.layout.simple\_list\_item\_1, arrayList) {
@NonNull
@Override
public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
@SuppressLint({"ViewHolder", "InflateParams"})
final View view = layoutInflater.inflate(R.layout.listitem\_layout, null, true);
final RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.relativelayout\_selected\_item);
// if the views that is currently being created is the same is the one clicked before notifying the adapter then change it's color
if (selectedPosition == position) {
relativeLayout.setBackgroundResource(R.color.tomatoLight);
} else {
relativeLayout.setBackgroundResource(R.color.orange);
}
return view;
}
};
listView.setAdapter(arrayAdapter);
listView.setOnItemclickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView adapter, View arg1, int position, long id) {
selectedPosition = position;
arrayAdapter.notifyDataSetChanged();
}
});
}
```
Upvotes: 0 <issue_comment>username_2: You can use [getChildAt()](https://developer.android.com/reference/android/view/ViewGroup.html#getChildAt%28int%29) method of Listview to get the view and then change the color.
```
if (SELECTED_ID != -1) {
View view1 = listView.getChildAt(SELECTED_ID -
listView.getFirstVisiblePosition());
// Here, i want to change Previously Selected Item's Background Color to it's original(Which is 'Orange').
view1.setBackgroundResource(R.color.Orange);
}
```
Hope this helps.
Upvotes: 1 <issue_comment>username_3: @username_1 is right in that you have to **override** the default behavior of ArrayAdapter's `getView` method. I believe just using ListView's `getChild` method just returns a view with a difference reference. That's why nothing happens when you try to modify it by calling `setBackgroundColor` (you're setting the background color of a difference list item view.
If you want other items color to change when you click another item, you'll need to remember more than just one value. e.g.: Perhaps you'd want to use another variable in addition to `selectedPosition`, say `previousPosition`, and keep track on the values of these variables when changes occur. These are just two variables which means you can only remember two things at a time. Perhaps use a `List` or an `int[]` array and add or remove values as the user selects and deselects items in the list.
Upvotes: 0 |
2018/03/19 | 1,235 | 5,574 | <issue_start>username_0: How to open Url in Webview activity
Hi,
i want to open link in WebView activity right now my code is scan barcode & open link directly to browser but
i want to change it and open in Webview
how can i do this please help me to fix this issue
thanks
here is code of BarcodeScannerActivity
```
public class BarcodeScannerActivity extends AppCompatActivity {
String scanContent;
String scanFormat;
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode_scanner);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(BarcodeScannerActivity.this);
scanIntegrator.setPrompt("Scan");
scanIntegrator.setBeepEnabled(true);
//enable the following line if you want QR code
//scanIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
scanIntegrator.setCaptureActivity(CaptureActivityAnyOrientation.class);
scanIntegrator.setOrientationLocked(true);
scanIntegrator.setBarcodeImageEnabled(true);
scanIntegrator.initiateScan();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanningResult != null) {
if (scanningResult.getContents() != null) {
scanContent = scanningResult.getContents().toString();
scanFormat = scanningResult.getFormatName().toString();
}
Toast.makeText(this, scanContent + " type:" + scanFormat, Toast.LENGTH_SHORT).show();
textView.setText(scanContent + " type:" + scanFormat);
Intent browseintent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com/index.php?iduser="+ scanContent));
startActivity(browseintent);
} else {
Toast.makeText(this, "Nothing scanned", Toast.LENGTH_SHORT).show();
}
}
}
```
Webview Activity Code
```
public class SecondActivity extends AppCompatActivity {
Button b1;
EditText ed1;
private WebView wv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
b1=(Button)findViewById(R.id.button);
ed1=(EditText)findViewById(R.id.editText);
wv1=(WebView)findViewById(R.id.webView);
wv1.setWebViewClient(new MyBrowser());
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = ed1.getText().toString();
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl(url);
}
});
}
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
```<issue_comment>username_1: Replace the following code
```
Intent browseintent=new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.example.com/index.php?iduser="+ scanContent));
startActivity(browseintent);
```
with below code
```
Intent browseintent=new Intent(this, SecondActivity.class);
browseintent.putExtra("url","http://www.example.com/index.php?iduser="+ scanContent);
startActivity(browseintent);
```
This will open the secondactivity with url in intent extras. You can set it to your edittext or you can use it directly to your webview.
You can receive the url in the second activity using the following code
```
String url = getIntent().getExtras().getString("url");
```
You can use it in your button click as follows
```
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = getIntent().getExtras().getString("url");
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl(url);
}
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You try this, it should open link with webview:
```
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowContentAccess(true);
settings.setDomStorageEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://vk.com/zabroshkiborika");
```
Upvotes: 2 |
2018/03/19 | 914 | 3,542 | <issue_start>username_0: I'm creating authorization app, where I'm using Retrofit 2. When I'm doing call, that goes to onFailure method and gets exception
`"javax.net.ssl.SSLException: Connection closed by peer"`
But the problem is, that yesterday this worked great. Today it gives exception. I find in internet some [SSLException - Connection closed by peer on Android 4.x versions](https://stackoverflow.com/questions/37006416/sslexception-connection-closed-by-peer-on-android-4-x-versions), or this [How to add TLS v 1.0 and TLS v.1.1 with Retrofit](https://stackoverflow.com/questions/33693120/how-to-add-tls-v-1-0-and-tls-v-1-1-with-retrofit), but this not helped me. Any ideas how to fix it. In backend TLS1.2 is enable.
```
public class RegistrationFragment extends BaseFragment {
View mainView;
ApiClient apiClient = ApiClient.getInstance();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate
(R.layout.registration_fragment, container, false);
//Calling the authorization method
registerCall();
}
});
return mainView;
}
//User authorization method
public void registerCall() {
Call call = apiClient.registration(supportopObj);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
//Calling the clientCall method for getting the user clientID and clientSecret
Toast.makeText(getActivity(), "Registration Successful ",
Toast.LENGTH\_SHORT).show();;
} else {
//if the response not successful
Toast.makeText(getActivity(), "Could not register the user maybe already registered ",
Toast.LENGTH\_SHORT).show();
}
}
@Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(getActivity(), "An error occurred", Toast.LENGTH\_SHORT).show();
}
});
}
}
```<issue_comment>username_1: Replace the following code
```
Intent browseintent=new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.example.com/index.php?iduser="+ scanContent));
startActivity(browseintent);
```
with below code
```
Intent browseintent=new Intent(this, SecondActivity.class);
browseintent.putExtra("url","http://www.example.com/index.php?iduser="+ scanContent);
startActivity(browseintent);
```
This will open the secondactivity with url in intent extras. You can set it to your edittext or you can use it directly to your webview.
You can receive the url in the second activity using the following code
```
String url = getIntent().getExtras().getString("url");
```
You can use it in your button click as follows
```
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = getIntent().getExtras().getString("url");
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl(url);
}
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You try this, it should open link with webview:
```
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowContentAccess(true);
settings.setDomStorageEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://vk.com/zabroshkiborika");
```
Upvotes: 2 |
2018/03/19 | 663 | 2,544 | <issue_start>username_0: I have an activity that uses recyclerView and for each item's view there is an Image.[](https://i.stack.imgur.com/oe6cw.png)
I have used Garbage Collector GC() on Destroy as follows
```
recyclerView= null;
adapter=null;
Runtime.getRuntime().gc();
```
But the following thing happens while releasing memory[](https://i.stack.imgur.com/0t71K.png)
---
**And When** I start another activity that loads images from a remote host using Picasso **It says**
```
java.lang.OutOfMemoryError: Failed to allocate a 94784012 byte allocation with 4194304 free bytes and 87MB until OOM
```
**I found an answer** that works for me to overcome that **OutOfMemoryError**
by **Increasing heap size** for application But I still want to release and ensure that memory occupied by an Activity is released instead of going to increase heap size for app.Thanks in advance , please help to do that task.<issue_comment>username_1: The code that you are using in your `onDestroy` method is not needed there. If destroy is called your acitivity will be removed from the stack and is free for gc anyway with all the resources in it that are only referenced by the activity.
`OnDestroy` doesn't always get called that's why your method may not be called at all. You could try and explicitly call for `finish()` in activity then onDestroy will be called and see how the situation will change.But then the activity will be removed from stack.
Also to call for gc manually is supposed to be bad style. On Android the system nearly always knows when it is the best time to do a garbage collection. Most of the times an activity finishes garbage collection is triggered automatically.
I would look into resizing images you get from `Picasso` first as they just could be too big in general for you heap even if there is space.
Look into resizing options [link](https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit)
Upvotes: 3 [selected_answer]<issue_comment>username_2: Seems the problem is related to huge images, try to not keep images in memory, load images only on demand(with some cache strategy)
Try to replace picasso with glide. Glide provides better memory performance <https://medium.com/@multidots/glide-vs-picasso-930eed42b81d>
Try to load all your images with closest context
<https://stackoverflow.com/a/32887693/6193843>
Upvotes: 1 |
2018/03/19 | 597 | 1,878 | <issue_start>username_0: I tried using `dict.fromkeys([1,2,3],set())`. This initializes creates the dictionary but when I add a value to any one of the sets all the sets get updated!
```
>>> d=dict.fromkeys([1,2,3],set())
>>> d
>>> {1: set(), 2: set(), 3: set()}
>>> d[1].add('a')
>>> d
>>> {1: {'a'}, 2: {'a'}, 3: {'a'}}
```
It seems that all the three values of the dictionary are referring to the same set. I want to initialize all the values of the dictionary to empty sets so that I can perform some operations on these sets in a loop based on the keys later.<issue_comment>username_1: Using dictionary comprehension
```
d = {x: set() for x in [1, 2, 3]}
```
Or using [collections.defaultdict](https://docs.python.org/3/library/collections.html#collections.defaultdict)
Upvotes: 4 [selected_answer]<issue_comment>username_2: You can use [**`collections.defaultdict`**](https://docs.python.org/3/library/collections.html#collections.defaultdict)
```
>>> from collections import defaultdict
>>> d = defaultdict(set)
>>> d[1].add('a')
>>> d
defaultdict(, {1: {'a'}})
>>> d[2].add('b')
>>> d
defaultdict(, {1: {'a'}, 2: {'b'}})
```
The way it works, is, when you try to add a value to a key like `dict[key].add(value)`, it checks whether the key is present; if so, then it adds the value to the set. If it is not present the value is added as a `set` since the default is set as a `set` (`defaultdict(set)`).
Upvotes: 2 <issue_comment>username_3: You want a [`defaultdict`](https://docs.python.org/dev/library/collections.html#collections.defaultdict) **so you don't need to initialize the sets** in the first place:
```
>>> from collections import defaultdict
>>> d = defaultdict(set)
# That's it, initialization complete. Use goes like this:
>>> d[1].add('a')
>>> d[2].add('b')
>>> d[3].add('c')
>>> d
defaultdict(, {1: {'a'}, 2: {'b'}, 3: {'c'}})
```
Upvotes: 1 |
2018/03/19 | 280 | 969 | <issue_start>username_0: I have a following SQL query which I want to "build" with the ORM of Yii2:
```
SELECT * FROM table WHERE [some conditions] AND (col1 <> 0 OR col2 <> 0)
```
So I want to exclude all results where col1 and col2 equals 0, but I don't want to do this with the SQL `EXCEPT` command.
The SQL should be correct, but my question is now how to build that with the yii2 ORM.<issue_comment>username_1: Use this code:
```
Model::find()->where(['condition' => 1])
->andWhere(['condition2' => 20])
->andWhere(['not', ['col1' => 0]])
->andWhere(['not', ['col2' => 0]])
->all();
```
Upvotes: -1 <issue_comment>username_2: You need to use condition in one array with key 'OR'
```
Model::find()
->where(['condition' => 1])
->andWhere([
'OR',
['!=', 'col1', 'val1'],
['!=', 'col2', 'val2'],
])
->all();
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 353 | 1,413 | <issue_start>username_0: On a Redhat OS, I have a script that launches a Java program. This script can be started from the command line but is launched (periodically) by crontab as well.
Within this program, I need to know how the program was started. This because the output is written either to STDOUT (if started from the command line) or in a logfile (if launched by crontab).
First I thought I could use `System.console()`.
The problem is that this method returns `null` also if the program was started from the command line but with STDIN and/or STDOUT redirected.
Any idea how to resolve this?
I tried [How can I check if a Java program's input/output streams are connected to a terminal?](https://stackoverflow.com/questions/1403772/how-can-i-check-if-a-java-programs-input-output-streams-are-connected-to-a-term) but that doesn't answer my question.<issue_comment>username_1: Use an environment variable that you set in the cron job before starting the java program. Query the environment variable inside your program.
Upvotes: 0 <issue_comment>username_2: Lots of options:
1. Add a `-Dcron=1` command line option when running from cron, to set a property that can be checked
2. Add a simple argument to the command line when running from cron and check it by looking in the `args[]` array
3. Set an environment variable in the script and check it in the program.
Upvotes: 3 [selected_answer] |
2018/03/19 | 357 | 1,191 | <issue_start>username_0: I have a little bit more complicated row than I can handle.
I am echoing and I got lost in the " ', could someone help me out and tell me how to have this line correctly?
```
echo ' |';
```<issue_comment>username_1: Escape single quotation?
```
echo '...';
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Use the heredoc syntax to create the string and your `"` and `'` can be used freely inside the string.
See manual about heredoc <http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc>
Example of heredoc:
<https://3v4l.org/SJTBO>
Upvotes: 0 <issue_comment>username_3: I don't know about a third quotation mark in code.
But, using "heredoc" syntax is really usefull when you want/need to keep both the single and double quotes unescaped.
Using it, your code should look like this:
```
echo <<

EOD;
```
Think about using `{ }` around your variables to make them more visible.
See documentation about it here: <http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc>
Upvotes: 0 |
2018/03/19 | 495 | 1,633 | <issue_start>username_0: I have been trying for sometime now. I want to read from the properties file and store as a hashmap.
Here is an example.
```
sample.properties
pref1.pref2.abc.suf = 1
pref1.pref2.def.suf = 2
...
...
```
Here is the Config class.
```
@ConfiguraionProperties
@PropertySource(value = "classpath:sample.properties")
public class Config{
@Autowired
private Environment env;
public HashMap getAllProps(){
//TO-DO
}
}
```
I want to be able to return `{"abc":1, "def":2};`
I stumbled upon answers like using `PropertySources`, `AbstractEnvironment` etc., but still can't get my head around using it.
Thanks in advance!<issue_comment>username_1: Escape single quotation?
```
echo '...';
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Use the heredoc syntax to create the string and your `"` and `'` can be used freely inside the string.
See manual about heredoc <http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc>
Example of heredoc:
<https://3v4l.org/SJTBO>
Upvotes: 0 <issue_comment>username_3: I don't know about a third quotation mark in code.
But, using "heredoc" syntax is really usefull when you want/need to keep both the single and double quotes unescaped.
Using it, your code should look like this:
```
echo <<

EOD;
```
Think about using `{ }` around your variables to make them more visible.
See documentation about it here: <http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc>
Upvotes: 0 |
2018/03/19 | 9,913 | 30,628 | <issue_start>username_0: I get the following error when I tried building my application again:
`ERROR in ../../../node_modules/@angular/cdk/a11y/typings/aria-describer/aria-describer.d.ts(8,42): error TS2307: Cannot find module '@angular/core`
This error occurred while I was developing my angular application. I apparently got this whilst I was programming but I didn't notice it because the application simply just kept compiling whenever I made some changes. This error only started to prevented me from building the application this morning. Does anybody know what is going on here?
full error:
```
ERROR in ../../../node_modules/@angular/cdk/a11y/typings/aria-describer/aria-describer.d.ts(8,42): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/a11y/typings/focus-monitor/focus-monitor.d.ts(9,82): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/a11y/typings/focus-monitor/focus-monitor.d.ts(10,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/cdk/a11y/typings/focus-trap/focus-trap.d.ts(8,65): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/a11y/typings/key-manager/list-key-manager.d.ts(8,27): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/a11y/typings/key-manager/list-key-manager.d.ts(9,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/cdk/a11y/typings/live-announcer/live-announcer.d.ts(8,53): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/accordion/typings/accordion-item.d.ts(8,60): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/bidi/typings/dir.d.ts(8,59): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/bidi/typings/directionality.d.ts(8,46): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/collections/typings/collection-viewer.d.ts(8,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/cdk/collections/typings/data-source.d.ts(8,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/cdk/collections/typings/selection.d.ts(8,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/cdk/collections/typings/unique-selection-dispatcher.d.ts(8,37): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/layout/typings/breakpoints-observer.d.ts(8,35): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/layout/typings/breakpoints-observer.d.ts(10,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/cdk/overlay/typings/keyboard/overlay-keyboard-dispatcher.d.ts(8,53): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/overlay/typings/overlay-container.d.ts(8,53): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/overlay/typings/overlay-directives.d.ts(9,126): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/overlay/typings/overlay-module.d.ts(1,26): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/overlay/typings/overlay-ref.d.ts(10,55): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/overlay/typings/overlay-ref.d.ts(11,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/cdk/overlay/typings/overlay-ref.d.ts(12,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/cdk/overlay/typings/overlay.d.ts(8,76): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/overlay/typings/position/connected-position-strategy.d.ts(9,28): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/overlay/typings/position/connected-position-strategy.d.ts(12,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/cdk/overlay/typings/position/overlay-position-builder.d.ts(8,28): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/overlay/typings/scroll/close-scroll-strategy.d.ts(8,24): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/overlay/typings/scroll/reposition-scroll-strategy.d.ts(8,24): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/overlay/typings/scroll/scroll-strategy-options.d.ts(8,24): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/portal/typings/dom-portal-outlet.d.ts(8,99): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/portal/typings/portal-directives.d.ts(8,137): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/portal/typings/portal-injector.d.ts(8,26): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/portal/typings/portal.d.ts(8,100): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/scrolling/typings/scroll-dispatcher.d.ts(8,57): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/scrolling/typings/scroll-dispatcher.d.ts(10,30): error TS2307: Cannot find module 'rxjs/Subscription'.
../../../node_modules/@angular/cdk/scrolling/typings/scroll-dispatcher.d.ts(11,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/cdk/scrolling/typings/scrollable.d.ts(8,55): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/scrolling/typings/scrollable.d.ts(9,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/cdk/scrolling/typings/viewport-ruler.d.ts(8,45): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/scrolling/typings/viewport-ruler.d.ts(10,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/cdk/stepper/typings/step-label.d.ts(8,29): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/stepper/typings/stepper.d.ts(8,107): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/stepper/typings/stepper.d.ts(10,33): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/cdk/stepper/typings/stepper.d.ts(12,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/cdk/table/typings/cell.d.ts(8,41): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/table/typings/row.d.ts(8,112): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/table/typings/table.d.ts(8,139): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/cdk/table/typings/table.d.ts(11,33): error TS2307: Cannot find module 'rxjs/BehaviorSubject'.
../../../node_modules/@angular/cdk/table/typings/table.d.ts(13,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/autocomplete/typings/autocomplete-trigger.d.ts(10,100): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/autocomplete/typings/autocomplete-trigger.d.ts(11,38): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/autocomplete/typings/autocomplete-trigger.d.ts(14,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/autocomplete/typings/autocomplete.d.ts(8,119): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/button-toggle/typings/button-toggle.d.ts(10,91): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/button-toggle/typings/button-toggle.d.ts(11,38): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/button/typings/button.d.ts(10,39): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/checkbox/typings/checkbox-config.d.ts(8,32): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/checkbox/typings/checkbox-required-validator.d.ts(8,26): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/checkbox/typings/checkbox-required-validator.d.ts(9,43): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/checkbox/typings/checkbox.d.ts(9,87): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/checkbox/typings/checkbox.d.ts(10,38): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/chips/typings/chip-input.d.ts(1,42): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/chips/typings/chip-list.d.ts(11,118): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/chips/typings/chip-list.d.ts(12,77): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/chips/typings/chip-list.d.ts(15,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/chips/typings/chip.d.ts(9,53): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/chips/typings/chip.d.ts(11,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/core/typings/common-behaviors/color.d.ts(9,28): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/core/typings/common-behaviors/common-module.d.ts(8,32): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/core/typings/common-behaviors/error-state.d.ts(10,55): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/core/typings/common-behaviors/error-state.d.ts(11,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/core/typings/common-behaviors/initialized.d.ts(9,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/core/typings/datetime/date-adapter.d.ts(8,32): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/core/typings/datetime/date-adapter.d.ts(9,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/core/typings/datetime/date-adapter.d.ts(10,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/core/typings/datetime/date-formats.d.ts(8,32): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/core/typings/error/error-options.d.ts(1,57): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/core/typings/gestures/gesture-config.d.ts(8,32): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/core/typings/gestures/gesture-config.d.ts(9,37): error TS2307: Cannot find module '@angular/platform-browser'.
../../../node_modules/@angular/material/core/typings/label/label-options.d.ts(8,32): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/core/typings/line/line.d.ts(8,39): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/core/typings/option/option.d.ts(1,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/core/typings/option/option.d.ts(2,106): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/core/typings/ripple/ripple-renderer.d.ts(8,36): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/core/typings/ripple/ripple.d.ts(9,71): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/datepicker/typings/calendar-body.d.ts(8,30): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/datepicker/typings/calendar.d.ts(1,124): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/datepicker/typings/datepicker-input.d.ts(1,71): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/datepicker/typings/datepicker-input.d.ts(2,84): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/datepicker/typings/datepicker-intl.d.ts(1,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/datepicker/typings/datepicker-toggle.d.ts(1,90): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/datepicker/typings/datepicker.d.ts(10,101): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/datepicker/typings/datepicker.d.ts(13,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/datepicker/typings/month-view.d.ts(8,67): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/datepicker/typings/multi-year-view.d.ts(8,67): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/datepicker/typings/year-view.d.ts(8,67): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/dialog/typings/dialog-animations.d.ts(8,42): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/dialog/typings/dialog-config.d.ts(8,34): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/dialog/typings/dialog-container.d.ts(8,92): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/dialog/typings/dialog-container.d.ts(9,32): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/dialog/typings/dialog-content-directives.d.ts(8,62): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/dialog/typings/dialog-ref.d.ts(9,26): error TS2307: Cannot find module '@angular/common'.
../../../node_modules/@angular/material/dialog/typings/dialog-ref.d.ts(11,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/dialog/typings/dialog.d.ts(3,26): error TS2307: Cannot find module '@angular/common'.
../../../node_modules/@angular/material/dialog/typings/dialog.d.ts(4,55): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/dialog/typings/dialog.d.ts(5,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/dialog/typings/dialog.d.ts(6,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/expansion/typings/expansion-animations.d.ts(8,42): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/expansion/typings/expansion-panel-content.d.ts(8,29): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/expansion/typings/expansion-panel-header.d.ts(9,58): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/expansion/typings/expansion-panel.d.ts(8,32): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/expansion/typings/expansion-panel.d.ts(9,108): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/expansion/typings/expansion-panel.d.ts(13,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/form-field/typings/form-field-animations.d.ts(8,42): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/form-field/typings/form-field-control.d.ts(8,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/form-field/typings/form-field-control.d.ts(9,27): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/form-field/typings/form-field.d.ts(1,112): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/grid-list/typings/grid-list.d.ts(8,68): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/grid-list/typings/grid-tile.d.ts(8,57): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/icon/typings/icon-registry.d.ts(1,26): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/icon/typings/icon-registry.d.ts(2,28): error TS2307: Cannot find module '@angular/common/http'.
../../../node_modules/@angular/material/icon/typings/icon-registry.d.ts(3,47): error TS2307: Cannot find module '@angular/platform-browser'.
../../../node_modules/@angular/material/icon/typings/icon-registry.d.ts(4,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/icon/typings/icon.d.ts(1,62): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/input/typings/autosize.d.ts(8,71): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/input/typings/input-value-accessor.d.ts(8,32): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/input/typings/input.d.ts(2,59): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/input/typings/input.d.ts(3,55): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/input/typings/input.d.ts(6,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/list/typings/list.d.ts(8,57): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/list/typings/selection-list.d.ts(10,109): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/list/typings/selection-list.d.ts(12,38): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/menu/typings/menu-animations.d.ts(8,42): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/menu/typings/menu-content.d.ts(8,110): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/menu/typings/menu-directive.d.ts(8,32): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/menu/typings/menu-directive.d.ts(10,119): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/menu/typings/menu-directive.d.ts(11,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/menu/typings/menu-item.d.ts(9,39): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/menu/typings/menu-item.d.ts(11,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/menu/typings/menu-panel.d.ts(8,43): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/menu/typings/menu-trigger.d.ts(3,105): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/paginator/typings/paginator-intl.d.ts(8,26): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/paginator/typings/paginator-intl.d.ts(9,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/paginator/typings/paginator.d.ts(1,68): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/progress-bar/typings/progress-bar.d.ts(8,28): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/progress-spinner/typings/progress-spinner.d.ts(8,54): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/radio/typings/radio.d.ts(10,124): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/radio/typings/radio.d.ts(11,38): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/select/typings/select-animations.d.ts(8,42): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/select/typings/select.d.ts(12,168): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/select/typings/select.d.ts(13,77): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/select/typings/select.d.ts(16,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/sidenav/typings/drawer-animations.d.ts(8,42): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/sidenav/typings/drawer.d.ts(8,32): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/sidenav/typings/drawer.d.ts(12,146): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/sidenav/typings/drawer.d.ts(13,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/sidenav/typings/drawer.d.ts(14,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/sidenav/typings/sidenav.d.ts(8,46): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/slide-toggle/typings/slide-toggle.d.ts(10,90): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/slide-toggle/typings/slide-toggle.d.ts(11,38): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/slider/typings/slider.d.ts(10,80): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/slider/typings/slider.d.ts(11,38): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/snack-bar/typings/snack-bar-animations.d.ts(8,42): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/snack-bar/typings/snack-bar-config.d.ts(8,50): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/snack-bar/typings/snack-bar-container.d.ts(8,97): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/snack-bar/typings/snack-bar-container.d.ts(9,32): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/snack-bar/typings/snack-bar-container.d.ts(11,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/snack-bar/typings/snack-bar-container.d.ts(12,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/snack-bar/typings/snack-bar-ref.d.ts(9,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/snack-bar/typings/snack-bar.d.ts(12,26): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/sort/typings/sort-animations.d.ts(8,42): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/sort/typings/sort-header-intl.d.ts(8,26): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/sort/typings/sort-header-intl.d.ts(9,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/sort/typings/sort-header.d.ts(8,35): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/sort/typings/sort.d.ts(8,52): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/sort/typings/sort.d.ts(11,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/stepper/typings/step-header.d.ts(9,71): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/stepper/typings/step-label.d.ts(8,29): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/stepper/typings/stepper-animations.d.ts(8,42): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/stepper/typings/stepper-icon.d.ts(8,29): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/stepper/typings/stepper-intl.d.ts(1,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/stepper/typings/stepper.d.ts(10,89): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/stepper/typings/stepper.d.ts(11,57): error TS2307: Cannot find module '@angular/forms'.
../../../node_modules/@angular/material/table/typings/cell.d.ts(8,28): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/table/typings/table-data-source.d.ts(9,33): error TS2307: Cannot find module 'rxjs/BehaviorSubject'.
../../../node_modules/@angular/material/table/typings/table-data-source.d.ts(12,30): error TS2307: Cannot find module 'rxjs/Subscription'.
../../../node_modules/@angular/material/tabs/typings/ink-bar.d.ts(8,36): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/tabs/typings/tab-body.d.ts(8,105): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/tabs/typings/tab-body.d.ts(9,32): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/tabs/typings/tab-group.d.ts(8,122): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/tabs/typings/tab-header.d.ts(9,122): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/tabs/typings/tab-label-wrapper.d.ts(8,28): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/tabs/typings/tab-label.d.ts(8,47): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/tabs/typings/tab-nav-bar/tab-nav-bar.d.ts(11,95): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/tabs/typings/tab.d.ts(9,92): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/tabs/typings/tab.d.ts(11,25): error TS2307: Cannot find module 'rxjs/Subject'.
../../../node_modules/@angular/material/tabs/typings/tabs-animations.d.ts(8,42): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/toolbar/typings/toolbar.d.ts(8,54): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/tooltip/typings/tooltip-animations.d.ts(8,42): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/tooltip/typings/tooltip.d.ts(8,32): error TS2307: Cannot find module '@angular/animations'.
../../../node_modules/@angular/material/tooltip/typings/tooltip.d.ts(14,100): error TS2307: Cannot find module '@angular/core'.
../../../node_modules/@angular/material/tooltip/typings/tooltip.d.ts(15,28): error TS2307: Cannot find module 'rxjs/Observable'.
../../../node_modules/@angular/material/typings/version.d.ts(8,25): error TS2307: Cannot find module '@angular/core'.
```
I'm clueless at this point. Can someone please help me out?
package.json:
<https://pastebin.com/GzfVg1cs><issue_comment>username_1: This problem apparently was being caused by the CDK and material modules of angular. I don't exactly know how it happend but I fixed it.
I fixed it by following an answer in this github issue: <https://github.com/angular/material2/issues/8306>
**Solution**
To fix this issue you have to run the following commands:
```
npm install --save @angular/material @angular/cdk
rm -rf node_modules
npm install
```
Upvotes: 6 [selected_answer]<issue_comment>username_2: In order to fix this issue you have to update to Angular CLI version, as `@angular cdk 6.0` requires `@angular core 6.0 version`(updated version). Try to use updated version for both CLI and material/CDK
Follow these steps:-
```
npm uninstall -g @angular/cli
npm cache verify
```
if `npm` version is less than 5 then use `npm cache clean`
```
npm install -g @angular/cli@latest
```
then create new `angluar/cli` project after that install `@angular/material` and `@angular/cdk`.
I hope this will solve your problem.
Upvotes: 2 <issue_comment>username_3: I see that some solutions are radical, I would not to try that in the first place. My solution was not radical, and it did the job.
I had the problem too, I did a simple
`npm update`
This was what came out:
```
$> npm update
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
+ [email protected]
+ [email protected]
added 2 packages from 6 contributors and audited 38996 packages in 13.315s
found 0 vulnerabilities
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
+ @types/[email protected]
updated 1 package and audited 38996 packages in 12.972s
found 0 vulnerabilities
```
And it solved the problem.
Upvotes: 3 <issue_comment>username_4: For me problem got resolved when I make sure that `@angular/material`, `@angular/ckd` and `@angular/animations` versions are compatible with `@angular/core` version. Just edit `package.json`.
In my case:
```
"@angular/core": "^7.2.15",
"@angular/animations": "^7.2.15",
"@angular/material": "^7.3.3",
"@angular/cdk": "^7.3.7",
```
Upvotes: 2 <issue_comment>username_5: 1. open cmd as administrator
2. check to see if @angular/cdk is being installed or not
npm ls @angular/core
3. If it's not installed, run the below command
npm install @angular/cdk
4. npm install
5. npm install -g @angular/cli@latest
[](https://i.stack.imgur.com/Jor5B.png)
Upvotes: 0 |
2018/03/19 | 618 | 1,932 | <issue_start>username_0: I have 30 variables with the pattern `aod7039, aod7040, ...., aod7068`.
I want to do the same operation (i.e. calculate the mean over an axis) for all these variables and overwrite the original variables.
Up to now I wrote 30 times the same line, and wondered if there isn't maybe an shorter and easier way to do this?
I am gradeful for every idea!<issue_comment>username_1: This will get you all values of variables that start with `'aod'`
```
values = [v for k,v in globals() if k.startswith('aod')]
```
But having 30 variables smells bad.
Upvotes: 2 <issue_comment>username_2: Firstly, don't use 30 variables, use a list `aod[]`
Secondly, use
```
for i in range(7039, 7069):
aod[i] = yourFunction(aod[i])
```
to override existing list
Upvotes: 3 [selected_answer]<issue_comment>username_3: If I understand your question right, you just want to iterate over those variables?
If so you could keep references on some list/dictionary and then iterate/update this way.
```
List = []
List.append(aod7039)
for item in List:
#do something
```
Upvotes: 1 <issue_comment>username_4: >
> I have 30 variables with the pattern aod7039, aod7040, ...., aod7068
>
>
>
Then you have a design problem - you should have a `list` or `dict` instead. Replace all those variables with either a `list` or `dict` (or `collections.OrderedDict` if you need key access while preserving insertion order) and then it's only a matter of iterating over your container, ie
```
# with a list:
for index, item in enumerate(yourlist):
yourlist[index] = do_something_with(item)
# with a dict or OrderedDict:
for key, item in enumerate(yourdict):
yourdic[key] = do_something_with(item)
```
Upvotes: 1 <issue_comment>username_5: store your 30 variables in a list and use map to tackle it without any loop:
```
varlist=[aod7039, aod7040, ...., aod7068]
result=list(map(yourfunction, varlist))
```
Upvotes: 0 |
2018/03/19 | 2,149 | 6,770 | <issue_start>username_0: I have two branches - `master` and `some`:
```
C2---M3---C4---C5 some
/ /
C1---C3---C6---C7 master
```
Where `C1`, `C2`... - it's commits and `M3` - merge commit `C3`.
I want to do:
```
git checkout some
git reset --soft C1
```
But I want to get around the merge commit `M3`.
How can I to do this?<issue_comment>username_1: So you want changes from the commits `C2`, `C4` and `C5`, but not from the merge `M3`. I'd do that with a new branch:
```
# Create a new branch started at C1
git checkout -b some-new C1
# Cherry-pick commits
git cherry-pick C2 C4 C5
# Delete the old branch and rename the new
git branch -D some
git branch -m some
```
Upvotes: 2 <issue_comment>username_2: First, let's note that commits are (entirely) read-only and (mostly) permanent. Given a commit graph fragment like this one:
```
C2---M3---C4---C5 <-- some
/ /
C1---C3---C6---C7 <-- master
```
the no matter what `reset`-ing we do, these same commits will continue to exist, at least for a while. If we add a saving name (branch or tag name) that also points to commit `C5`, then whatever we do to the name `some`, we will still be able to name commits `C5`, `C4`, `M3`, and `C2`.
Second, remember that each commit stores a complete, independent snapshot. That includes merge commit `M3`. We can turn a merge commit into a set of changes by running `git diff` to compare the contents of the snapshot to the contents of the commit's parent—but for a merge commit, which has *two* parents, we have to pick one of the two parents.
Third, since you mention `git reset --soft`, let's note that, separate and apart from commits, Git gives us a *work-tree* in which we do our actual work (and can view commits), and an *index*—also called the *staging area* or the *cache*—that we use to build up each commit before we make it. If we run:
```
git checkout some
```
Git will fill the index and work-tree from the contents of the commit to which the name `some` currently points, i.e., `C5`, and attach our `HEAD` to the name `some`. Let's attach a second name, `tmp`, at this point, using `git branch tmp`:
```
C2---M3---C4---C5 <-- some (HEAD), tmp
/ /
C1---C3---C6---C7 <-- master
```
Running `git reset --soft` at this point will make the name `some` point to commit `C1` while leaving our index and work-tree unchanged. That is, the index and work-tree contents will continue to match those of `C5`:
```
C2---M3---C4---C5 <-- tmp
/ /
C1---C3---C6---C7 <-- master
.
... <-------------- some (HEAD)
```
If we make a new commit now, by running `git commit`, we get a new commit `C8` whose contents match those of `C5`. This is because the new commit is made from the contents of the index, which match the contents of `C5`. The parent of `C8` will be `C1`, however, giving us:
```
C2---M3---C4---C5 <-- tmp
/ /
C1---C3---C6---C7 <-- master
\
C8 <-------------- some (HEAD)
```
after which `git diff some tmp` will show no difference at all.
You mention in comments that what you want, in the index or perhaps as new commit `C8`, is *content* that would be achieved by cherry-picking `C2`, `C4`, and `C5` atop commit `C1`. You cannot get this with `git reset` alone.
### Build by cherry-picking
The most straightforward way to get this is to set a branch name to point to commit `C1` and, at the same time, set up the index and work-tree to match `C1`:
```
git checkout -b new
```
and then use `git cherry-pick`, optionally with `-n`, as in [phd's answer](https://stackoverflow.com/a/49365499/1256452), which went in as I was typing this in. You could also use `git reset --hard`, rather than `git reset --soft`, to move `some` to point to `C1` while retaining a name for commit `C5` (as in the above diagrams using `tmp`). Then the *name* of the new branch you build, by cherry-picking the three desired commits, would be `some`.
### Build by reverting
Last, you can, if you like, try to construct your new commit by a *subtractive* process. This can be a bit error prone as it depends on what went into merge `M3`,1 but it works like this:
* We know that `C5` is, in effect, `C1`, plus `C2`-as-changeset, plus `C1`-vs-`C3` as changeset-via-merge, plus `C4`-as-changeset, plus `C5`-as-changeset.
* We can compute `C1`-vs-`C3` directly, by `git diff`-ing them.
* Better: we can compute `C1-vs-C3` *indirectly*, by `git diff`ing `C2` vs `M3`. This will handle certain cases of duplication, where `C1`-vs-`C3` has the *same* changes as `C1`-vs-`C2`, so that they were not doubly-included in `C2`-vs-`M3`.
* We can (at least try to) *reverse-apply* any patch we like at any time. That is, having turned a commit into a changeset (by comparing against a parent), instead of copying those changes into some commit that *doesn't* have them, we can *undo* those changes in some commit that *does* have them. The command to do this is `git revert`.
Suppose, then, we check out commit `some` as before so that we have just the initial setup:
```
C2---M3---C4---C5 <-- some (HEAD)
/ /
C1---C3---C6---C7 <-- master
```
Now we run `git revert -m 1` . This tells Git to diff `C2` vs `M3` to see what changed.2 The result is a new commit `C8`:
```
C2---M3---C4---C5---C8 <-- some (HEAD)
/ /
C1---C3---C6---C7 <-- master
```
which very likely has the *content* that you want: `C1` as snapshot plus `C2` as changeset to get `C2` as content, plus `M3` vs `C2` as changeset to get `M3` as content (but then eventually *minus* `M3` vs `C2` as changeset at the end), and so on. Since `C8` *un-does* what `M3` did, `C8` should have the desired content.
At this point you can, if you like, `git reset --soft` , leaving the index and work-tree set up the way you wanted, and then run `git commit` to create commit `C9`:
```
C2---M3---C4---C5---C8
/ /
C1---C3---C6---C7 <-- master
\
C9 <-------------- some (HEAD)
```
With no *name* by which to find them, all the commits along the top row of the graph here become invisible, and after 30 days or so, Git really removes them when it runs its garbage collector.
---
1In particular, if we use `git revert` , we might revert too much. That's why we `git revert -m 1` here.
2This assumes the first parent of `M3` is in fact `C2`. In any normal commit growth process, it will be, but it's worth double-checking.
Upvotes: 2 <issue_comment>username_3: I like the cherry-picking approach, but another way would be:
```
git checkout some
git rebase --interactive --preserve-merges C2
```
...then edit the presented picklist, changing the `pick` to `drop` at the front of the line for the merge commit M3. You'll end up with `C5->C4->C2` as the set of commits on `some` that aren't also in `master`.
Upvotes: 2 [selected_answer] |
2018/03/19 | 1,769 | 5,049 | <issue_start>username_0: I am trying to develop drop down box list in HTML and CSS. I am trying to toggle drop-down box list on clicking on it. When I select some item, it is not coming in drop-down button.
Below is my code.
```js
function toggleItems() {
$('.dropdown-menu').toggleClass('open');
}
function test() {
var element = document.getElementById("flat-example-2");
if ($(element).hasClass('on')) {
element.classList.remove("on");
} else {
element.classList.add("on");
}
}
```
```css
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
min-width: 150px;
max-height: 600px;
overflow-x: visible;
overflow-y: visible;
padding: 0;
margin: 0;
list-style: none;
font-size: 13px;
font-weight: 500;
text-align: left;
background-color: #FFFFFF;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 0;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
-webkit-background-clip: padding-box;
background-clip: padding-box;
color: #464646;
transition: all .3s;
transform: translate(-100%);
}
.dropdown-menu.open {
transform: translate(0%);
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
toggle.btn-default {
background: #dedede;
background: rgba(0, 0, 0, 0.13);
border: 1px solid #2E92FA;
color: #464646;
outline: none;
}
```
```html
Filter by
* Sensors
* Actuators
* Digital inputs
* Outputs
* Converters
```
I am not able to select item from drop down. I want to select any item
from the drop down and that item should be selected in drop-down box
list. Can someone help me to make this work? Any help would be
appreciated. Thank you.<issue_comment>username_1: You don't seem to have an event for when an item is selected from the list.
You'll need to attach a click event, preferably to the `li` element, and set the text of the dropdown there.
e.g.
```
$('.dropdown-menu li').click(function() {
var text = $(this).text(); // get text of the clicked item
$(".dropdown-toggle").text(text); // set text to the button (dropdown)
});
```
Full code:
```js
function toggleItems() {
$('.dropdown-menu').toggleClass('open');
}
$('.dropdown-menu li').click(function() {
var text = $(this).text(); // get text of the clicked item
$(".dropdown-toggle").text(text); // set text text to the button (dropdown)
});
function test() {
var element = document.getElementById("flat-example-2");
if ($(element).hasClass('on')) {
element.classList.remove("on");
} else {
element.classList.add("on");
}
}
```
```css
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
min-width: 150px;
max-height: 600px;
overflow-x: visible;
overflow-y: visible;
padding: 0;
margin: 0;
list-style: none;
font-size: 13px;
font-weight: 500;
text-align: left;
background-color: #FFFFFF;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 0;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
-webkit-background-clip: padding-box;
background-clip: padding-box;
color: #464646;
transition: all .3s;
transform: translate(-100%);
}
.dropdown-menu.open {
transform: translate(0%);
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
toggle.btn-default {
background: #dedede;
background: rgba(0, 0, 0, 0.13);
border: 1px solid #2E92FA;
color: #464646;
outline: none;
}
```
```html
Filter by
* Sensors
* Actuators
* Digital inputs
* Outputs
* Converters
```
Upvotes: 1 <issue_comment>username_2: First remove the irrelevant code like `data-toggle` etc...You will need to attach a click event to the dropdown items to change the button text
Also there is no need of using `div` and `label` inside of li...so better to remove it
```js
$(".btn-toggle").on("click", function() {
$('.dropdown-menu').toggleClass('open');
});
$(".dropdown-menu li").on("click", function() {
$('.btn-toggle').text($(this).text());
$('.dropdown-menu').removeClass('open');
});
```
```css
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
min-width: 150px;
padding: 0;
margin: 0;
list-style: none;
font-size: 13px;
font-weight: 500;
background-color: #FFFFFF;
border: 1px solid rgba(0, 0, 0, 0.15);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
color: #464646;
transition: all .3s;
transform: translate(-100%);
}
.dropdown-menu.open {
transform: translate(0%);
}
.btn-group {
position: relative;
display: inline-block;
vertical-align: top;
}
.dropdown-menu li {
margin: 5px;
cursor: pointer;
}
```
```html
Filter by
* Sensors
* Actuators
* Digital inputs
* Outputs
* Converters
```
Upvotes: 4 [selected_answer] |
2018/03/19 | 761 | 2,701 | <issue_start>username_0: I have a highly nested class, and trying to find a single item buried deep within. The following gives me an error "Can't convert type match to bool', although I don't see why it thinks I'm trying to return a boolean.
```
var match = community.TeamLeagues
.Where(x => x.Seasons
.Where(y => y.Divisions
.Where(z => z.Matches
.Where(a => a.Id == "1234").FirstOrDefault())));
```<issue_comment>username_1: The `Where` method needs to evaluate an expression that returns a `bool`. Your nested `Where`s are not doing that - the only Where that is, is the last one `a => a.Id == "1234"`, all the other expressions are returning an `IEnumerable`.
Upvotes: 1 <issue_comment>username_2: `Where` by itself returns a (deferred) enumerable of items and cannot as such be used as a condition by the outer `Where`. What you probably want to do is to use `Contains()`, `Any()` or `All()` inside the outer `Where`s that will return the result you're looking for.
Something like this might be what you're after:
```
var match = community.TeamLeagues.Where(t =>
t.Seasons.Any(
s => s.Divisions.Any(
d => d.Matches.Any(
m => m.Id == "1234")
)));
```
Upvotes: 2 <issue_comment>username_3: `z.Matches.Where(a => a.Id == "1234").FirstOrDefault()` returns a object of type `Match`(your collection item type of the IEnumerable `Matches`) (or null), no boolean value. I guess you need to check if there are entires in matches that have a Id 1234. Use `Any` to evaluate a condition:
```
var match = community.TeamLeagues.Where(x =>
x.Seasons.Any(y =>
y.Divisions.Any(z =>
z.Matches.Any(a => a.Id == "1234")
)));
```
[`items.Where(x => x.Id == 4).Any()` is the same as `items.Any(x => x.Id == 4)`]
This returns you all TeamLeagues which contain a Season which contain a Division which contain a Match which has a element with the id 1234.
Upvotes: 0 <issue_comment>username_4: To make it simple you can also use the `Matches` table directly and using a ViewModel you can represent your view.
like:
var MyViewModel = (from l in Mathes
where l.Id == "1234"
select new MyViewModel
{
Id = l.Id,
MatchName = l.Name,
}).ToList();
Upvotes: 0 <issue_comment>username_5: Couldn't get it working with linq, but works with query syntax.
```
var leagueMatch = (from teamLeague in community.TeamLeagues
from season in teamLeague.Seasons
from division in season.Divisions
from match in division.Matches.Where(x => x.Id == "1234")
select match).FirstOrDefault();
```
Upvotes: 1 [selected_answer] |
2018/03/19 | 306 | 1,095 | <issue_start>username_0: Is there a timer or interval function in Crystal?
I checked the docs for a timer, interval, and under the Time class, but did not see anything.
Something like `setInterval()` or `setTimeout()` from JavaScript?<issue_comment>username_1: For timeout there's [delay](https://crystal-lang.org/api/0.24.2/toplevel.html#delay%28delay%2C%26block%3A-%3E_%29-class-method). Please be aware that the API for this isn't finalized and might get changed in a future release or even temporarily removed again.
For interval there's currently nothing that guarantees exact timings, but if that's no concern and an approximate interval is enough it's as simple to do as
```
spawn do
loop do
sleep INTERVAL
do_regular_work
end
end
sleep # Or some other workload, when the main fiber quits so will the program and thus all other fibers.
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: <https://github.com/hugoabonizio/schedule.cr>
```
require "schedule"
# Print "Hello!" each 2 seconds
Schedule.every(2.seconds) do
puts "Hello!"
end
sleep
```
Upvotes: 0 |
2018/03/19 | 437 | 1,527 | <issue_start>username_0: In Linux/Unix based systems, whenever we execute a command in the shell and we echo the `$?`, the return value is 0 when its a success and the return value is 1 if the command fails.
So, if I am using the BULK COPY utility called BCP for SQL Server, and if the command fails when there is an error with the source file. For example, if I execute a bcp command like this.
`/opt/bin/bcp in -S -U -P -D`
and it says. "**0 Rows Copied**". It might be due to some errors in the source file. And, after that I do a `echo $?`. The value returned is still 0.
Is there a way we can capture the return value as 1, when encountered an error?
Thanks.<issue_comment>username_1: For timeout there's [delay](https://crystal-lang.org/api/0.24.2/toplevel.html#delay%28delay%2C%26block%3A-%3E_%29-class-method). Please be aware that the API for this isn't finalized and might get changed in a future release or even temporarily removed again.
For interval there's currently nothing that guarantees exact timings, but if that's no concern and an approximate interval is enough it's as simple to do as
```
spawn do
loop do
sleep INTERVAL
do_regular_work
end
end
sleep # Or some other workload, when the main fiber quits so will the program and thus all other fibers.
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: <https://github.com/hugoabonizio/schedule.cr>
```
require "schedule"
# Print "Hello!" each 2 seconds
Schedule.every(2.seconds) do
puts "Hello!"
end
sleep
```
Upvotes: 0 |
2018/03/19 | 591 | 1,965 | <issue_start>username_0: I'm trying to make a web page, in this page I need to dysplay in column 6 images of people with their names and description. But I'm stuck trying to display their name and description. Here is my code:
**component.ts**
```
export class TeamComponent implements OnInit {
public team: any[][];
title = ' Team ';
name: string;
description: string;
constructor() {
this.team = [
[this.firstTeamMember(), this.secondTeamMember()],
[this.thirdTeamMember(), this.fourthTeamMember()],
[this.fifthTeamMember(), this.sixthTeamMember()]
];
}
firstTeamMember(): {
this.name = 'A name';
this.description = 'text';
}
secondTeamMember(): {
this.name = 'Another name';
this.description = 'text';
}
thirdTeamMember(): {
this.name = 'Another name';
this.description = 'text';
}
fourthTeamMember(): {
this.name = 'Another name';
this.description = '...';
}
fifthTeamMember(): {
this.name = 'Another name.';
this.description = 'text';
}
sixthTeamMember(): {
this.name = 'Another name';
this.description = 'text';
}
```
**component.html**
```
{{ title }}
===========
{{j}}
```<issue_comment>username_1: For timeout there's [delay](https://crystal-lang.org/api/0.24.2/toplevel.html#delay%28delay%2C%26block%3A-%3E_%29-class-method). Please be aware that the API for this isn't finalized and might get changed in a future release or even temporarily removed again.
For interval there's currently nothing that guarantees exact timings, but if that's no concern and an approximate interval is enough it's as simple to do as
```
spawn do
loop do
sleep INTERVAL
do_regular_work
end
end
sleep # Or some other workload, when the main fiber quits so will the program and thus all other fibers.
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: <https://github.com/hugoabonizio/schedule.cr>
```
require "schedule"
# Print "Hello!" each 2 seconds
Schedule.every(2.seconds) do
puts "Hello!"
end
sleep
```
Upvotes: 0 |
2018/03/19 | 3,386 | 7,466 | <issue_start>username_0: I am getting into the programming of networks with caffe and since I am used to more comfortable and "lazy" solutions I am a bit overwhelmed by the problems that can occur.
Right now I am getting the error
`Check failed: status == CUDNN_STATUS_SUCCESS (3 vs. 0) CUDNN_STATUS_BAD_PARAM`
This one is quite well known to be produced by bad cuda or cudnn versions.
So i checked those and they are up to date. (Cuda: 8.0.61 Cudnn: 6.0.21)
Since I will only get this error when I add this ReLU layer I suppose it is caused by me confusing a parameter:
```
layer{
name: "relu1"
type: "ReLU"
bottom: "pool1"
top: "relu1"
}
```
And to give you all the information, here is the error message I get:
```
I0319 09:41:09.484148 6909 solver.cpp:44] Initializing solver from parameters:
test_iter: 10
test_interval: 1000
base_lr: 0.001
display: 20
max_iter: 800
lr_policy: "step"
gamma: 0.1
momentum: 0.9
weight_decay: 0.04
stepsize: 200
snapshot: 10000
snapshot_prefix: "models/train"
solver_mode: GPU
net: "train_val.prototxt"
I0319 09:41:09.484392 6909 solver.cpp:87] Creating training net from net file: train_val.prototxt
I0319 09:41:09.485164 6909 net.cpp:294] The NetState phase (0) differed from the phase (1) specified by a rule in layer feed2
I0319 09:41:09.485183 6909 net.cpp:51] Initializing net from parameters:
name: "CaffeNet"
state {
phase: TRAIN
}
layer {
name: "feed"
type: "HDF5Data"
top: "data"
top: "label"
include {
phase: TRAIN
}
hdf5_data_param {
source: "train_h5_list.txt"
batch_size: 50
}
}
layer {
name: "conv1"
type: "Convolution"
bottom: "data"
top: "conv1"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
convolution_param {
num_output: 1
kernel_size: 3
stride: 1
weight_filler {
type: "gaussian"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "pool1"
type: "Pooling"
bottom: "conv1"
top: "pool1"
pooling_param {
pool: MAX
kernel_size: 2
stride: 1
}
}
layer {
name: "relu1"
type: "ReLU"
bottom: "pool1"
top: "relu1"
}
layer {
name: "conv2"
type: "Convolution"
bottom: "relu1"
top: "conv2"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
convolution_param {
num_output: 1
kernel_size: 3
stride: 1
weight_filler {
type: "gaussian"
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "ip2"
type: "InnerProduct"
bottom: "conv2"
top: "ip2"
param {
lr_mult: 1
decay_mult: 1
}
inner_product_param {
num_output: 1
weight_filler {
type: "gaussian"
std: 0.01
}
bias_filler {
type: "constant"
value: 0
}
}
}
layer {
name: "sig1"
type: "Sigmoid"
bottom: "ip2"
top: "sig1"
}
layer {
name: "loss"
type: "EuclideanLoss"
bottom: "sig1"
bottom: "label"
top: "loss"
}
I0319 09:41:09.485752 6909 layer_factory.hpp:77] Creating layer feed
I0319 09:41:09.485780 6909 net.cpp:84] Creating Layer feed
I0319 09:41:09.485792 6909 net.cpp:380] feed -> data
I0319 09:41:09.485819 6909 net.cpp:380] feed -> label
I0319 09:41:09.485836 6909 hdf5_data_layer.cpp:80] Loading list of HDF5 filenames from: train_h5_list.txt
I0319 09:41:09.485860 6909 hdf5_data_layer.cpp:94] Number of HDF5 files: 1
I0319 09:41:09.486469 6909 hdf5.cpp:32] Datatype class: H5T_FLOAT
I0319 09:41:09.500986 6909 net.cpp:122] Setting up feed
I0319 09:41:09.501011 6909 net.cpp:129] Top shape: 50 227 227 3 (7729350)
I0319 09:41:09.501027 6909 net.cpp:129] Top shape: 50 1 (50)
I0319 09:41:09.501039 6909 net.cpp:137] Memory required for data: 30917600
I0319 09:41:09.501051 6909 layer_factory.hpp:77] Creating layer conv1
I0319 09:41:09.501080 6909 net.cpp:84] Creating Layer conv1
I0319 09:41:09.501087 6909 net.cpp:406] conv1 <- data
I0319 09:41:09.501101 6909 net.cpp:380] conv1 -> conv1
I0319 09:41:09.880740 6909 net.cpp:122] Setting up conv1
I0319 09:41:09.880765 6909 net.cpp:129] Top shape: 50 1 225 1 (11250)
I0319 09:41:09.880781 6909 net.cpp:137] Memory required for data: 30962600
I0319 09:41:09.880808 6909 layer_factory.hpp:77] Creating layer pool1
I0319 09:41:09.880836 6909 net.cpp:84] Creating Layer pool1
I0319 09:41:09.880846 6909 net.cpp:406] pool1 <- conv1
I0319 09:41:09.880861 6909 net.cpp:380] pool1 -> pool1
I0319 09:41:09.880888 6909 net.cpp:122] Setting up pool1
I0319 09:41:09.880899 6909 net.cpp:129] Top shape: 50 1 224 0 (0)
I0319 09:41:09.880913 6909 net.cpp:137] Memory required for data: 30962600
I0319 09:41:09.880921 6909 layer_factory.hpp:77] Creating layer relu1
I0319 09:41:09.880934 6909 net.cpp:84] Creating Layer relu1
I0319 09:41:09.880941 6909 net.cpp:406] relu1 <- pool1
I0319 09:41:09.880952 6909 net.cpp:380] relu1 -> relu1
F0319 09:41:09.881192 6909 cudnn.hpp:80] Check failed: status == CUDNN_STATUS_SUCCESS (3 vs. 0) CUDNN_STATUS_BAD_PARAM
```
EDIT: Tried setting the solver mode to CPU, I still get this error.<issue_comment>username_1: I found out one of the problems.
```
I0319 09:41:09.880765 6909 net.cpp:129] Top shape: 50 1 225 1 (11250)
I0319 09:41:09.880781 6909 net.cpp:137] Memory required for data: 30962600
I0319 09:41:09.880808 6909 layer_factory.hpp:77] Creating layer pool1
I0319 09:41:09.880836 6909 net.cpp:84] Creating Layer pool1
I0319 09:41:09.880846 6909 net.cpp:406] pool1 <- conv1
I0319 09:41:09.880861 6909 net.cpp:380] pool1 -> pool1
I0319 09:41:09.880888 6909 net.cpp:122] Setting up pool1
I0319 09:41:09.880899 6909 net.cpp:129] Top shape: 50 1 224 0 (0)
```
As you can see the first Convolutional layer will take an input of size (50 227 227 3), wich is a bit problematic, since he thinks that the second dimension contains the channels.
Its only natural that this convolutional layer will simply butcher the dimensions that way and now no further layer after that will get proper input dimensions.
I managed to solve the problem by simply reshaping the input this way:
```
layer {
name: "reshape"
type: "Reshape"
bottom: "data"
top: "res"
reshape_param {
shape {
dim: 50
dim: 3
dim: 227
dim: 227
}
}
}
```
the first dimension in this is the batch size, so whoever reads this has to remember to set this dim to 1 in the .prototxt file for the classification phase (since that one won't work with batches)
EDIT: I will mark this as an answer since it covers the basic solution to the problem i had and no other solution is in sight. If anyone wants to shine more light on the matter, please do so.
Upvotes: 2 <issue_comment>username_2: The reason why it is throwing this error is because you have no more room to "shrink". From your error message: 50 1 224 0 (0)
This indicates the size of the net has a 0 in one dimension.
To fix this error, you can tweak some of the parameters, including (S)tride, (K)ernel size, and (P)adding. To calculate the dimensions of your next layer (W\_new), you can use the formula:
W\_new = (W\_old - K + 2\*P)/S + 1
So, if we have an input that is 227x227x3 and our first layer has K = 5, S = 2, P = 1, and numOutputs = N, conv1 then has a dimension that is:
(227-5+2\*1)/2 + 1 = 112x112xN.
Note: if you end up with an odd number in the numerator, round up after adding 1.
Edit: The reason why it's showing up with the ReLU layer is likely because the ReLU layer has nothing to pass through, ergo it throws an error.
Upvotes: 2 [selected_answer] |
2018/03/19 | 222 | 772 | <issue_start>username_0: I want to check whether the element i click on page is having a background property and this is the code i tried
```
var img = document.querySelectorAll('*');
img.forEach(function(image){
image.addEventListener("click",function(e){
e.preventDefault();
if(this.style.background){
console.log("yes");
}
});
});
```<issue_comment>username_1: Try this:
```
if(e.target.style.background){
console.log("yes");
}
```
Upvotes: 0 <issue_comment>username_2: See [jsfiddle](https://jsfiddle.net/vkpb4mx3/16/)
```
window.getComputedStyle(this , null).getPropertyValue( "background-image" )
```
will do the trick
BTW, I added also a e.stopPropagation(); to prevent bubbling down the DOM
Upvotes: 2 [selected_answer] |
2018/03/19 | 814 | 2,581 | <issue_start>username_0: I have an enum in one class :
```
class SettingManager : public QObject
{
Q_OBJECT
public:
enum BookDisplayKinds{
BookDisplay1=0,
BookDisplay2=1,
};
Q_ENUMS(BookDisplayKinds)
};
```
I want to declare an property in another class
```
#include
class BookManager : public NetworkManager
{
private:
SettingManager::BookDisplayKinds m\_BookDisplayKind;//Error is here
};
```
but I got below error:
>
> 'SettingManager' does not name a type
>
>
>
I add forward delcalration of SettingManager before BookManager
```
#include
class SettingManager;
class BookManager : public NetworkManager
{
private:
SettingManager::BookDisplayKinds m\_BookDisplayKind;//Error is here
};
```
But now I have below error
>
> 'BookDisplayKinds' in 'class SettingManager' does not name a type
>
>
><issue_comment>username_1: There are several ways to do it. You can `include` the header where 'SettingManager::BookDisplayKinds' is declared. Another approach can be forward declaring the `SettingManager::BookDisplayKinds` enum in the same class.
Upvotes: 0 <issue_comment>username_2: You can switch to strong enum available since C++11. I recommend you to put it out of the class.
```
// SettingManager.h header
enum class BookDisplayKinds{
BookDisplay1=0,
BookDisplay2=1,
};
class SettingManager : public QObject
{
Q_OBJECT
public:
};
```
Now it is possible to do a forward declaration like this:
```
// BookManager.h header
enum class BookDisplayKinds; // forward declaration
class BookManager : public NetworkManager
{
private:
BookDisplayKinds m_BookDisplayKind;/
};
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: There's something wrong that you're not showing us, such as a similar-named header earlier in your include path, for example. I tried your code (but completed it with the missing headers):
### `49359142.h`
```
#include
class SettingManager : public QObject
{
Q\_OBJECT
public:
enum BookDisplayKinds{
BookDisplay1=0,
BookDisplay2=1,
};
Q\_ENUMS(BookDisplayKinds)
};
```
### `49359142.cpp`
```
#include "49359142.h"
class BookManager
{
private:
SettingManager::BookDisplayKinds m_BookDisplayKind;//Error is here
};
```
---
### Result
```none
nice make 49359142.o
g++-8 -std=c++2a -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -I/usr/include/x86_64-linux-gnu/qt5/QtCore -I/usr/include/x86_64-linux-gnu/qt5 -c -o 49359142.o 49359142.cpp
Compilation finished at Mon Mar 19 09:31:59
```
Upvotes: 0 |
2018/03/19 | 665 | 2,152 | <issue_start>username_0: I am trying to load csv files in pandas dataframe. However, Python is taking very large amount of memory while loading the files. For example, the size of csv file is 289 MB but the memory usage goes to around 1700 MB while I am trying to load the file. And at that point, the system shows memory error. I have also tried chunk size but the problem persists. Can anyone please show me a way forward?<issue_comment>username_1: There are several ways to do it. You can `include` the header where 'SettingManager::BookDisplayKinds' is declared. Another approach can be forward declaring the `SettingManager::BookDisplayKinds` enum in the same class.
Upvotes: 0 <issue_comment>username_2: You can switch to strong enum available since C++11. I recommend you to put it out of the class.
```
// SettingManager.h header
enum class BookDisplayKinds{
BookDisplay1=0,
BookDisplay2=1,
};
class SettingManager : public QObject
{
Q_OBJECT
public:
};
```
Now it is possible to do a forward declaration like this:
```
// BookManager.h header
enum class BookDisplayKinds; // forward declaration
class BookManager : public NetworkManager
{
private:
BookDisplayKinds m_BookDisplayKind;/
};
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: There's something wrong that you're not showing us, such as a similar-named header earlier in your include path, for example. I tried your code (but completed it with the missing headers):
### `49359142.h`
```
#include
class SettingManager : public QObject
{
Q\_OBJECT
public:
enum BookDisplayKinds{
BookDisplay1=0,
BookDisplay2=1,
};
Q\_ENUMS(BookDisplayKinds)
};
```
### `49359142.cpp`
```
#include "49359142.h"
class BookManager
{
private:
SettingManager::BookDisplayKinds m_BookDisplayKind;//Error is here
};
```
---
### Result
```none
nice make 49359142.o
g++-8 -std=c++2a -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -I/usr/include/x86_64-linux-gnu/qt5/QtCore -I/usr/include/x86_64-linux-gnu/qt5 -c -o 49359142.o 49359142.cpp
Compilation finished at Mon Mar 19 09:31:59
```
Upvotes: 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.