qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
177,082 |
When I say
>
> My friends and I went snowboarding.
>
>
>
somebody said to me there is a grammar mistake in my sentence but I could not figure out what it is. What is the grammar mistake in the sentence? Should it be
>
> I and my friends went snowboarding.
>
>
>
|
2018/08/23
|
[
"https://ell.stackexchange.com/questions/177082",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/11631/"
] |
It is possible your friend had your sentence confused with a similar grammar error that you did NOT make.
It is incorrect to say "John gave apples to Ann and I"
Same reason:
You can say "John gave apples to Ann"
but you cannot say "John gave apples to I"
|
Your friends expected to see 'me' instead of 'I' . For example: 'Me and my friends went snowboarding.'
|
177,082 |
When I say
>
> My friends and I went snowboarding.
>
>
>
somebody said to me there is a grammar mistake in my sentence but I could not figure out what it is. What is the grammar mistake in the sentence? Should it be
>
> I and my friends went snowboarding.
>
>
>
|
2018/08/23
|
[
"https://ell.stackexchange.com/questions/177082",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/11631/"
] |
>
> My friends and I went snowboarding
>
>
>
There's nothing wrong with the sentence; it's perfect.
How come somebody says that your sentence is not correct? Maybe he likes to use object pronouns when they are cojoined with other nouns/subject pronouns as many people tend to do so in informal speaking and writing. In this case, the sentence will be:
>
> My friends and me went snowboarding.
>
>
>
Or maybe he likes to begin the sentence with "I" as follows:
>
> I and my friends went snowboardig.
>
>
>
This sentence is also OK grammatically, but your sentence is more polite and common.
Another reason may be that he prefers the following sentence as presented by J.R:
I went snowboarding with my friends.
This sentence like yours also sounds easy on the ear.
|
Your friends expected to see 'me' instead of 'I' . For example: 'Me and my friends went snowboarding.'
|
177,082 |
When I say
>
> My friends and I went snowboarding.
>
>
>
somebody said to me there is a grammar mistake in my sentence but I could not figure out what it is. What is the grammar mistake in the sentence? Should it be
>
> I and my friends went snowboarding.
>
>
>
|
2018/08/23
|
[
"https://ell.stackexchange.com/questions/177082",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/11631/"
] |
Your friends expected to see 'me' instead of 'I' . For example: 'Me and my friends went snowboarding.'
|
"me and my friends" is a fixed construction, which works well as subject in this sentence, allowing the object form "me". "I and my friends" is not.
One could argue that "my friends and me" is a totally acceptable construction too, but in this sentence, "me" would be followed by the verb, which makes it sound much too close to "me went skiing..", which is by most considered grammatically very wrong.
|
177,082 |
When I say
>
> My friends and I went snowboarding.
>
>
>
somebody said to me there is a grammar mistake in my sentence but I could not figure out what it is. What is the grammar mistake in the sentence? Should it be
>
> I and my friends went snowboarding.
>
>
>
|
2018/08/23
|
[
"https://ell.stackexchange.com/questions/177082",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/11631/"
] |
Your sentence is entirely correct. I'm not sure why they thought it was incorrect, but I'll explain why you're correct, and then guess what *their* mistake may have been.
When we use two subjects together, we should be able to use either one by itself.
>
> My friends went snowboarding.
>
>
> I went snowboarding.
>
>
>
Both of these work fine, so there is no mistake there.
Further, it is traditional to place "I" as the last person in a list of subjects (probably to be humble). "I and my friends", while not grammatically wrong, is generally considered to be incorrect.
Next, we use the verb "go" for (almost) any activity that is made with [verb]-ing. "Go shopping", "go swimming", "go skiing", etc. You used "go" (or here the past tense, "went"), so that's correct.
The only thing that could possibly make your sentence wrong is if it was for the wrong time. For example:
>
> I went snowboarding next week.
>
>
>
This is wrong (assuming you don't have a time machine), but I really don't think you made that mistake.
So why did they say it was wrong? Well, there are two possibilities I can think of. First, they may have been thinking that you should use the verb "do" or "play" instead of "go". That's wrong. "Go" is the correct word.
Second, they may have been making a common mistake (even among native speakers). Many people say "My friends and me went snowboarding." This is not correct, because it doesn't pass the test I mentioned in the beginning.
>
> My friends went snowboarding.
>
>
>
This is correct, but...
>
> Me went snowboarding.
>
>
>
...is not correct. Therefore, it should be I, not me.
Hope that helps!
|
"me and my friends" is a fixed construction, which works well as subject in this sentence, allowing the object form "me". "I and my friends" is not.
One could argue that "my friends and me" is a totally acceptable construction too, but in this sentence, "me" would be followed by the verb, which makes it sound much too close to "me went skiing..", which is by most considered grammatically very wrong.
|
177,082 |
When I say
>
> My friends and I went snowboarding.
>
>
>
somebody said to me there is a grammar mistake in my sentence but I could not figure out what it is. What is the grammar mistake in the sentence? Should it be
>
> I and my friends went snowboarding.
>
>
>
|
2018/08/23
|
[
"https://ell.stackexchange.com/questions/177082",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/11631/"
] |
>
> My friends and I went snowboarding
>
>
>
There's nothing wrong with the sentence; it's perfect.
How come somebody says that your sentence is not correct? Maybe he likes to use object pronouns when they are cojoined with other nouns/subject pronouns as many people tend to do so in informal speaking and writing. In this case, the sentence will be:
>
> My friends and me went snowboarding.
>
>
>
Or maybe he likes to begin the sentence with "I" as follows:
>
> I and my friends went snowboardig.
>
>
>
This sentence is also OK grammatically, but your sentence is more polite and common.
Another reason may be that he prefers the following sentence as presented by J.R:
I went snowboarding with my friends.
This sentence like yours also sounds easy on the ear.
|
Generally speaking..
>
> My friends and I went snowboarding
>
>
>
..would be considered good "proper" English and is grammatically correct.
However, in general conversation people will say..
>
> Me and my friends went snowboarding
>
>
>
..which is *perfectly acceptable* in all but the most polite of circumstances - by which I mean - meeting the queen etc. ( "The Queen"?? :) )
If someone picks you up on using the second form then they are probably either..
* Joking
* President of the Correct English Society (fictitious)
* In need of a stick removing from their a\*\*
**But**
>
> I and my friends went snowboarding
>
>
>
..is not correct, and just sounds "wrong" to a native speaker. It should either be **me and my friends** *or* **my friends and I** (see above).
|
177,082 |
When I say
>
> My friends and I went snowboarding.
>
>
>
somebody said to me there is a grammar mistake in my sentence but I could not figure out what it is. What is the grammar mistake in the sentence? Should it be
>
> I and my friends went snowboarding.
>
>
>
|
2018/08/23
|
[
"https://ell.stackexchange.com/questions/177082",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/11631/"
] |
It is possible your friend had your sentence confused with a similar grammar error that you did NOT make.
It is incorrect to say "John gave apples to Ann and I"
Same reason:
You can say "John gave apples to Ann"
but you cannot say "John gave apples to I"
|
Generally speaking..
>
> My friends and I went snowboarding
>
>
>
..would be considered good "proper" English and is grammatically correct.
However, in general conversation people will say..
>
> Me and my friends went snowboarding
>
>
>
..which is *perfectly acceptable* in all but the most polite of circumstances - by which I mean - meeting the queen etc. ( "The Queen"?? :) )
If someone picks you up on using the second form then they are probably either..
* Joking
* President of the Correct English Society (fictitious)
* In need of a stick removing from their a\*\*
**But**
>
> I and my friends went snowboarding
>
>
>
..is not correct, and just sounds "wrong" to a native speaker. It should either be **me and my friends** *or* **my friends and I** (see above).
|
3,674,944 |
In Exercise 2.24 of Enderton's *Elements of Set Theory*, we are asked to show that $$\bigcup{\{\mathcal{P}}X \ \mid X \in A\} \subseteq \mathcal{P} \bigcup A.$$
Fascinated by this exhilerating problem, I started off my proof by taking an arbitrary element $x$ of $\bigcup{\{\mathcal{P}}X \ \mid X \in A\}$ and showing that by definition of the arbitrary union, there exists a set $b \in \mathcal{P} X$ such that $x \in b$. I then proceeded to show that because $b \in \mathcal{P} X$ implied $b \subseteq X$, that $x \in X$, and that because $X \in A$, that $x \in \bigcup A$.
But as one can probably guess, this is not enough. I must show that $x \subseteq \bigcup A$. Yet, usually, it is not the case that if $a \in B$ and $B \subseteq C$ that $a \subseteq C$. And so I am left sad, confused, and a bit upset, because I can't seem to figure out how to come to that conclusion.
To add to my confusion, looking up a solutions manual online, I find a proof that assumes just that, claiming that "it follows that $x \in X$, but $X \subseteq \bigcup A$, so $x \subseteq \bigcup A$". This solution is probably right, and there's probably some trick involved, but I have no idea what the heck that trick is and I would greatly appreciate any help I can get.
As a poor little senior in high school trying to self-study random maths in quarantine, please help a fellow out!
|
2020/05/14
|
[
"https://math.stackexchange.com/questions/3674944",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/773147/"
] |
Let’s see if I can explain the source of your confusion.
By definition, if $Z$ is a set, then
$$\bigcup Z = \{b\mid \exists W\in Z(b\in W)\}.$$
You are correct on that.
Here what we have is
$$\bigcup \{\mathcal{P}X\mid X\in A\}.$$
The set $Z$ from the definition is
$$Z=\{\mathcal{P}X\mid X\in A\}.$$
That means that the sets $W$ in the description of $\bigcup Z$ will be the sets $\mathcal{P}X$ with $X\in A$.
So by definition, the union you want consists of all elements $b$ for which there exists an element $W$ of $\{\mathcal{P}X\mid X\in A\}$ with $b\in W$. But that means that $W$ must be of the form $\mathcal{P}X$ with $X\in A$. In other words, you are looking for all elements $b$ such that there exists $X\in A$ with $b\in\mathcal{P}X$. Or in yet other words, there exists $X\in A$ with $b\subseteq X$.
Instead, you seem to be looking at elements of $$\bigcup\left(\bigcup\{\mathcal{P}X\mid X\in A\}\right).$$
That is, you went one level too deep.
The confusion seems to arise because here they are describing the set in the unary union by its elements rather than by its name.
|
You are applying the definition of union incorrectly. $$ x\in \bigcup\{\mathcal PX:X\in A\} $$ means that $x\in \mathcal P X$ for some $X\in A,$ not that $x\in b$ for some $b\in \mathcal P X$ for some $X\in A.$
|
3,674,944 |
In Exercise 2.24 of Enderton's *Elements of Set Theory*, we are asked to show that $$\bigcup{\{\mathcal{P}}X \ \mid X \in A\} \subseteq \mathcal{P} \bigcup A.$$
Fascinated by this exhilerating problem, I started off my proof by taking an arbitrary element $x$ of $\bigcup{\{\mathcal{P}}X \ \mid X \in A\}$ and showing that by definition of the arbitrary union, there exists a set $b \in \mathcal{P} X$ such that $x \in b$. I then proceeded to show that because $b \in \mathcal{P} X$ implied $b \subseteq X$, that $x \in X$, and that because $X \in A$, that $x \in \bigcup A$.
But as one can probably guess, this is not enough. I must show that $x \subseteq \bigcup A$. Yet, usually, it is not the case that if $a \in B$ and $B \subseteq C$ that $a \subseteq C$. And so I am left sad, confused, and a bit upset, because I can't seem to figure out how to come to that conclusion.
To add to my confusion, looking up a solutions manual online, I find a proof that assumes just that, claiming that "it follows that $x \in X$, but $X \subseteq \bigcup A$, so $x \subseteq \bigcup A$". This solution is probably right, and there's probably some trick involved, but I have no idea what the heck that trick is and I would greatly appreciate any help I can get.
As a poor little senior in high school trying to self-study random maths in quarantine, please help a fellow out!
|
2020/05/14
|
[
"https://math.stackexchange.com/questions/3674944",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/773147/"
] |
You are applying the definition of union incorrectly. $$ x\in \bigcup\{\mathcal PX:X\in A\} $$ means that $x\in \mathcal P X$ for some $X\in A,$ not that $x\in b$ for some $b\in \mathcal P X$ for some $X\in A.$
|
Thanks to the wonderful comments of @Arturo Magidin and @spaceisdarkgreen, I have figured out both the problem with my original proof, along with the solution to this exercise.
My original answer to the problem was based on a misunderstanding of the notation $\bigcup \{ \mathcal{P} X \mid x \in A\}$. I had assumed that a member of this union would be a member of $\mathcal{P} X$ for some $X \in A$. This is incorrect. Instead, I seemed to be looking at the elements of the union of that union.
To show my thanks, I would like to upload the completed proof. I'll also answer the second part of the original question which asks under which conditions equality holds.
*Proof:* Let us take an arbitrary element $x \in \bigcup \{ \mathcal{P} X \mid x \in A\}$. Then $\left( \exists b \in \{\mathcal{P} X \mid X \in A\}\right) x \in b$. In other words, $\exists b = \mathcal{P} X$ for some $X \in A$ with $x \in \mathcal{P} X$. This implies that $x \subseteq X \subseteq \bigcup A$, which by definition of the power set, implies that $x \in \mathcal{P} \bigcup A$.
Note: $X \subseteq \bigcup A$ because for every element of $X$, there is an element in $A$, mainly $X$ that holds it.
To examine under which conditions equality holds, let us take another arbitrary element $x \in \mathcal{P} \bigcup A$. By definition of the power set, $x \subseteq \bigcup A$. As such, for $x \in \bigcup \{ \mathcal{P} X \mid x \in A\}$ to hold, $x$ must be a subset of $X$ for some $X \in A$, meaning that $\bigcup A$ must be a subset of $X$ for some $X \in A$ for equality to hold.
|
3,674,944 |
In Exercise 2.24 of Enderton's *Elements of Set Theory*, we are asked to show that $$\bigcup{\{\mathcal{P}}X \ \mid X \in A\} \subseteq \mathcal{P} \bigcup A.$$
Fascinated by this exhilerating problem, I started off my proof by taking an arbitrary element $x$ of $\bigcup{\{\mathcal{P}}X \ \mid X \in A\}$ and showing that by definition of the arbitrary union, there exists a set $b \in \mathcal{P} X$ such that $x \in b$. I then proceeded to show that because $b \in \mathcal{P} X$ implied $b \subseteq X$, that $x \in X$, and that because $X \in A$, that $x \in \bigcup A$.
But as one can probably guess, this is not enough. I must show that $x \subseteq \bigcup A$. Yet, usually, it is not the case that if $a \in B$ and $B \subseteq C$ that $a \subseteq C$. And so I am left sad, confused, and a bit upset, because I can't seem to figure out how to come to that conclusion.
To add to my confusion, looking up a solutions manual online, I find a proof that assumes just that, claiming that "it follows that $x \in X$, but $X \subseteq \bigcup A$, so $x \subseteq \bigcup A$". This solution is probably right, and there's probably some trick involved, but I have no idea what the heck that trick is and I would greatly appreciate any help I can get.
As a poor little senior in high school trying to self-study random maths in quarantine, please help a fellow out!
|
2020/05/14
|
[
"https://math.stackexchange.com/questions/3674944",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/773147/"
] |
Let’s see if I can explain the source of your confusion.
By definition, if $Z$ is a set, then
$$\bigcup Z = \{b\mid \exists W\in Z(b\in W)\}.$$
You are correct on that.
Here what we have is
$$\bigcup \{\mathcal{P}X\mid X\in A\}.$$
The set $Z$ from the definition is
$$Z=\{\mathcal{P}X\mid X\in A\}.$$
That means that the sets $W$ in the description of $\bigcup Z$ will be the sets $\mathcal{P}X$ with $X\in A$.
So by definition, the union you want consists of all elements $b$ for which there exists an element $W$ of $\{\mathcal{P}X\mid X\in A\}$ with $b\in W$. But that means that $W$ must be of the form $\mathcal{P}X$ with $X\in A$. In other words, you are looking for all elements $b$ such that there exists $X\in A$ with $b\in\mathcal{P}X$. Or in yet other words, there exists $X\in A$ with $b\subseteq X$.
Instead, you seem to be looking at elements of $$\bigcup\left(\bigcup\{\mathcal{P}X\mid X\in A\}\right).$$
That is, you went one level too deep.
The confusion seems to arise because here they are describing the set in the unary union by its elements rather than by its name.
|
Thanks to the wonderful comments of @Arturo Magidin and @spaceisdarkgreen, I have figured out both the problem with my original proof, along with the solution to this exercise.
My original answer to the problem was based on a misunderstanding of the notation $\bigcup \{ \mathcal{P} X \mid x \in A\}$. I had assumed that a member of this union would be a member of $\mathcal{P} X$ for some $X \in A$. This is incorrect. Instead, I seemed to be looking at the elements of the union of that union.
To show my thanks, I would like to upload the completed proof. I'll also answer the second part of the original question which asks under which conditions equality holds.
*Proof:* Let us take an arbitrary element $x \in \bigcup \{ \mathcal{P} X \mid x \in A\}$. Then $\left( \exists b \in \{\mathcal{P} X \mid X \in A\}\right) x \in b$. In other words, $\exists b = \mathcal{P} X$ for some $X \in A$ with $x \in \mathcal{P} X$. This implies that $x \subseteq X \subseteq \bigcup A$, which by definition of the power set, implies that $x \in \mathcal{P} \bigcup A$.
Note: $X \subseteq \bigcup A$ because for every element of $X$, there is an element in $A$, mainly $X$ that holds it.
To examine under which conditions equality holds, let us take another arbitrary element $x \in \mathcal{P} \bigcup A$. By definition of the power set, $x \subseteq \bigcup A$. As such, for $x \in \bigcup \{ \mathcal{P} X \mid x \in A\}$ to hold, $x$ must be a subset of $X$ for some $X \in A$, meaning that $\bigcup A$ must be a subset of $X$ for some $X \in A$ for equality to hold.
|
25,205,228 |
I am curious about Django database model pk.
Is there any difference this
```
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=50)
```
between this?
```
class Category(models.Model):
category_name = models.CharField(max_length=50)
```
Are the same things `AutoField with primary_key` and `default pk`?
|
2014/08/08
|
[
"https://Stackoverflow.com/questions/25205228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2117469/"
] |
Yes, the difference is, the column name in the database for the primary key is `category_id` and in the second case is `id`.
One way you can make the second example emulate the first one is:
```
class Category(models.Model):
category_name = models.CharField(max_length=50)
@property
def category_id(self):
return self.id
```
From the [documentation](https://docs.djangoproject.com/en/dev/ref/models/fields/#autofield),
>
> AutoField
>
>
> An IntegerField that automatically increments according to available IDs. You usually won’t need to use this directly; a primary key field will automatically be added to your model if you don’t specify otherwise
>
>
>
|
The difference is **field name**.
For example, I definded **the model "Category"** with **the field "category\_id"**:
```py
# "myapp/models.py"
from django.db import models
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=50)
```
Then, run this command below:
```
python manage.py makemigrations && python manage.py migrate
```
Now, I opened **"db.sqlite3"** then the field name is **"category\_id"**:
[](https://i.stack.imgur.com/g2kgo.png)
Next, I definded **the model "Category"** without **the field "category\_id"**:
```py
# "myapp/models.py"
from django.db import models
class Category(models.Model):
category_name = models.CharField(max_length=50)
```
Then, run this command below:
```
python manage.py makemigrations && python manage.py migrate
```
Now, I opened **"db.sqlite3"** then the field name is **"id"**:
[](https://i.stack.imgur.com/A2DYF.png)
|
4,481,318 |
>
> **Possible Duplicate:**
>
> [How do I get this CSS text-decoration override to work?](https://stackoverflow.com/questions/1823341/how-do-i-get-this-css-text-decoration-override-to-work)
>
>
>
Take a look at this simple example:
```html
<a href="#"> A <span>red</span> anchor </a>
```
```css
a {
color:blue;
font-family:Times New Roman;
text-decoration:underline;
}
span {
color:red;
font-family:Arial;
text-decoration:none;
}
```
***Live demo:*** <http://jsfiddle.net/5t9sV/>
As you can see in the demo on JSfiddle, the SPAN element overrides the `color` and `font-family` property values of its ancestor ANCHOR element. However, the `text-decoration` property does not get overridden for some reason.
I assume that some CSS properties can be overridden by ancestor elements, and some other CSS properties cannot.
Is that so?
And if yes, how can I know which ones can and cannot be overridden?
|
2010/12/19
|
[
"https://Stackoverflow.com/questions/4481318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/425275/"
] |
From the [`text-decoration` spec](http://www.w3.org/TR/CSS21/text.html#lining-striking-props):
>
> The 'text-decoration' property on descendant elements cannot have any effect on the decoration of the ancestor.
>
>
>
[The answer in the linked question](https://stackoverflow.com/questions/1823341/how-do-i-get-this-css-text-decoration-issue-to-work/1823388#1823388) further quotes (I can't find this text in the spec anymore however):
>
> Text decorations on inline boxes are drawn across the entire element, going across any descendant elements without paying any attention to their presence.
>
>
>
And another quote, CSS3 seems to introduce [`text-decoration-skip`](http://www.w3.org/TR/2010/WD-css3-text-20101005/#text-decoration-skip0), intended to address this by applying the property on the descendant (in your case, `<span>`):
>
> This property specifies what parts of the element's content any text decoration affecting the element must skip over. It controls all text decoration lines drawn by the element and also any text decoration lines drawn by its ancestors.
>
>
>
|
As suggested by Pekka, here is my answer:
The text decoration DOES get changed when you set the text-decoration value. The problem is that since the Parent Element (the anchor) surrounds the span, it looks as though the span is getting underlined.
This is made obvious if you set the text-decoration of the span to true, because it make the underline blue for JUST the span.
|
27,625,665 |
I understand that -i flag takes a file (which may contain list of URLs) and I know that -o followed by a name can be specified to rename a item being downloaded using wget.
example:
`wget -i list_of_urls.txt`
`wget -o my_custom_name.mp3 http://example.com/some_file.mp3`
I have a file that looks like this:
file name: list\_of\_urls.txt
>
> <http://example.com/some_file.mp3>
> <http://example.com/another_file.mp3>
> <http://example.com/yet_another_file.mp3>
>
>
>
I want to use wget to download these files with the -i flag but also save each file as 1.mp3, 2.mp3 and so on.
Can this be done?
|
2014/12/23
|
[
"https://Stackoverflow.com/questions/27625665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3393361/"
] |
You can overload the division operator, but:
* It must always be a binary operator - you've only provider one operand
* It must always be static
* At least one of the operand types must be the type you're declaring it in
So for example:
```
using System;
class Program
{
public static string operator/ (Program lhs, int rhs)
{
return "I'm divided!";
}
static void Main(string[] args)
{
Console.WriteLine(new Program() / 10);
}
}
```
|
The `/` operator is a "binary" operator, meaning that it takes two arguments: `a / b`. The way you've written this, it's trying to overload it as a "unary" operator, such as `a++`.
Something like this ought to work, assuming your class is called "MyObject".
```
public static string[] operator/ (MyObject mine, object obj) {
...
}
```
Usage:
```
object something = "hi";
string[] result = new MyObject(1) / something;
```
|
34,882,114 |
i'm confused with this problem
when im working **locally** it's all fine
with this :
`foreach (glob("public/FolderA/B/") as $filename) {`
but when i put
`foreach (glob("http://www.exemple.com/public/FolderA/B/") as $filename) {`
doesn't work any solution ???
**History** : in the past i'm working with glob() and communicate with **local server** and the scripte do this jobs perfect now donne is **transfer**t to other server and problem i get is how to put glob() working **with external URL not locally** or some function has same functionality
|
2016/01/19
|
[
"https://Stackoverflow.com/questions/34882114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3542413/"
] |
**glob()** per definition finds pathnames matching a pattern.
This means that the function will not work on remote files as the diretory / files to be examined must be accessible via the server's filesystem.
What you probably would need is accessing a remote filesystem thru an **FTP** server.
This is how it could look like:
```
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
get contents of the current directory
$contents = ftp_nlist($conn_id, "."); // "." means the current directory
var_dump($contents);
```
Alternatively, if the previously local server still can be accessed, you could have a script on this server scan the directory as before and echo the file list (e.g. in XML or JSON format). This script could the be sent a request by the (now) remote script, giving the file list this way.
Update: FTP Access, full script
-------------------------------
```
<?php
$ftp_server = 'ftp.example.org';
$ftp_port = 21;
$ftp_timeout = 90;
$ftp_user = 'my_username';
$ftp_password = 'my_password';
// set up a connection or die
$conn_id = ftp_connect($ftp_server, $ftp_port, $ftp_timeout);
if ($conn_id===false) {
echo 'Failed to connect to the server<br />';
exit(1);
}
// Log in or die
$logged_in = ftp_login($conn_id, $ftp_user, $ftp_password);
if ($logged_in!==true) {
echo 'Failed to log-in<br />';
exit(1);
}
// Change directory if necessary
echo "Current directory: " . ftp_pwd($conn_id) . '<br />';
// Set to passive mode if required
ftp_pasv ($conn_id, true);
// Change directory if necessary
if (ftp_chdir($conn_id, 'subdir1/subdir2')) {
echo "Current directory is now: " . ftp_pwd($conn_id) . '<br />';
} else {
echo 'Could not change directory<br />';
exit(1);
}
// Get list of files in this directory
$files = ftp_nlist($conn_id, ".");
if ($files===false) {
echo 'Failed to get listing<br />';
exit(1);
}
foreach($files as $n=>$file) {
echo "$n: $file<br />";
$local_dir = '/my_local_dir/';
foreach($files as $n => $file) {
// These we don't want to download
if (($file=='.') || ($file=='..') || ($file[0]=='.')) continue;
// These we do want to download
echo "$n: $file<br />";
if (ftp_get($conn_id, $local_dir.$file, $file, FTP_BINARY)) {
echo "Successfully written to $local_dir$file<br />";
} else {
echo "Could not get $local_dir.$file<br />";
}
}
// Do whatever has to been done with $file
}
?>
```
|
If your PHP script is running under Windows, you can use
```
glob("\\\\remoteServer\\public\\FolderA\\B\\*.*")
```
because as hherger said "directory / files to be examined must be accessible via the server's file system." and Windows allows access to other PCs using a UNC path. Because Windows uses backslashes instead of forward slashes, and in PHP a backslash is an escape character, each backslash has to be preceded by a backslash. In Windows Explorer (aka File Explorer), the above UNC path would be
```
\\remoteServer\public\FolderA\B\*.*
```
|
575,710 |
I'm trying to [monkey patch](http://en.wikipedia.org/wiki/Monkey_patch) a Perl class: I want to change the behavior of an existing method.
[This node on perlmonks](http://www.perlmonks.org/?node_id=694332) shows how to *add* a function to an existing class. I found that this pattern can also be used to provide a new implementation for an existing function.
However, I'd like to know how to call the original function.
I'm looking for something like this:
```
use ExistingClass;
# TODO: Somehow rename existingFunction() to oldExistingFunction().
sub ExistingClass::existingFunction {
my $self = shift;
# New behavior goes here.
$self->oldExistingFunction(@_); # Call old behavior.
# More new behavior here.
}
```
|
2009/02/22
|
[
"https://Stackoverflow.com/questions/575710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Typeglob assignment
-------------------
```
*ExistingClass::oldExistingFunction = *ExistingClass::existingFunction;
```
Quick and dirty. This aliases all `existingFunction` symbols to `oldExistingFunction`. This includes the sub you're interested in, but also any scalars, arrays, hashes, handles that might happen to have the same name.
* Advantages: no thinking, it just works. "quick"
* Disadvantages: "dirty"
Coderef assignment
------------------
```
*ExistingClass::oldExistingFunction = \&ExistingClass::existingFunction;
# or something using *ExistingClass::symbol{CODE}
```
That one only aliases the sub. It's still done in the package stash, so the `oldExistingFunction` symbol is globally visible, which might or might not be what you want. Probably not.
* Advantages: that aliasing doesn't 'leak' to other variable types.
* Disadvantages: more thinking, more typing. A lot more thinking if going for the \*...{CODE} syntax (I personnally don't use it every day)
Lexical coderef
---------------
```
my $oldFunction = \&ExistingClass::existingFunction;
```
Using `my` keeps a reference to the old function that is only visible to the currrent block/file. There is no way for external code to get hold of it without your help anymore. Mind the calling convention:
```
$self->$oldFunction(@args);
$oldFunction->($self, @args);
```
* Advantages: no visibility issues anymore
* Disadvantages: harder to get right
Moose
-----
See [jrockway's answer](https://stackoverflow.com/questions/575710/monkey-patching-in-perl-how-to-access-original-method/576425#576425). It's got to be The Right Way, since there's no mucking around with globs and/or references anymore, but I don't know it enough to explain it.
|
For [Moose](http://metacpan.org/module/Moose) classes, you can just [do what jrockway says](https://stackoverflow.com/a/576425/40468); for non-Moose classes, do this:
```
use Class::MOP ();
use ExistingClass;
Class::MOP::Class->initialize('ExistingClass')->add_around_method_modifier(
existingFunction => sub {
my $orig = shift;
# new behaviour goes here
# call old behaviour
my $result = $orig->(@_);
# more new behaviour goes here
}
);
```
|
575,710 |
I'm trying to [monkey patch](http://en.wikipedia.org/wiki/Monkey_patch) a Perl class: I want to change the behavior of an existing method.
[This node on perlmonks](http://www.perlmonks.org/?node_id=694332) shows how to *add* a function to an existing class. I found that this pattern can also be used to provide a new implementation for an existing function.
However, I'd like to know how to call the original function.
I'm looking for something like this:
```
use ExistingClass;
# TODO: Somehow rename existingFunction() to oldExistingFunction().
sub ExistingClass::existingFunction {
my $self = shift;
# New behavior goes here.
$self->oldExistingFunction(@_); # Call old behavior.
# More new behavior here.
}
```
|
2009/02/22
|
[
"https://Stackoverflow.com/questions/575710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Just copy it to a lexical variable and call it.
```
my $existing_function_ref = \&ExistingClass::existingFunction;
*ExistingClass::existingFunction = sub {
my $self = shift;
$self->go_and_do_some_stuff();
my @returns = $existing_function_ref->( $self, @_ );
$self->do_some_stuff_with_returns( @returns );
return wantarray ? @returns : shift @returns;
};
```
If you would feel better about it with OO-syntax, you could create a `UNIVERSAL::apply` method (or at any base class you chose).
```
sub UNIVERSAL::apply {
my ( $self, $block ) = splice( @_, 0, 2 );
unshift @_, $self;
goto &$block;
}
```
That way you can call it like this:
```
my @returns = $self->apply( $existing_function_ref, @_ );
```
|
For [Moose](http://metacpan.org/module/Moose) classes, you can just [do what jrockway says](https://stackoverflow.com/a/576425/40468); for non-Moose classes, do this:
```
use Class::MOP ();
use ExistingClass;
Class::MOP::Class->initialize('ExistingClass')->add_around_method_modifier(
existingFunction => sub {
my $orig = shift;
# new behaviour goes here
# call old behaviour
my $result = $orig->(@_);
# more new behaviour goes here
}
);
```
|
575,710 |
I'm trying to [monkey patch](http://en.wikipedia.org/wiki/Monkey_patch) a Perl class: I want to change the behavior of an existing method.
[This node on perlmonks](http://www.perlmonks.org/?node_id=694332) shows how to *add* a function to an existing class. I found that this pattern can also be used to provide a new implementation for an existing function.
However, I'd like to know how to call the original function.
I'm looking for something like this:
```
use ExistingClass;
# TODO: Somehow rename existingFunction() to oldExistingFunction().
sub ExistingClass::existingFunction {
my $self = shift;
# New behavior goes here.
$self->oldExistingFunction(@_); # Call old behavior.
# More new behavior here.
}
```
|
2009/02/22
|
[
"https://Stackoverflow.com/questions/575710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
[Memoize](http://search.cpan.org/perldoc/Memoize) is a good example of this.
|
As an alterative, what's wrong with:
```
package NewClass;
use base qw/ExistingClass/;
sub existingFunction {
# ....
}
sub oldExistingFunction {
my $self = shift;
return $self->SUPER::existingFunction(@_);
}
```
|
575,710 |
I'm trying to [monkey patch](http://en.wikipedia.org/wiki/Monkey_patch) a Perl class: I want to change the behavior of an existing method.
[This node on perlmonks](http://www.perlmonks.org/?node_id=694332) shows how to *add* a function to an existing class. I found that this pattern can also be used to provide a new implementation for an existing function.
However, I'd like to know how to call the original function.
I'm looking for something like this:
```
use ExistingClass;
# TODO: Somehow rename existingFunction() to oldExistingFunction().
sub ExistingClass::existingFunction {
my $self = shift;
# New behavior goes here.
$self->oldExistingFunction(@_); # Call old behavior.
# More new behavior here.
}
```
|
2009/02/22
|
[
"https://Stackoverflow.com/questions/575710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You should use [Moose](http://search.cpan.org/perldoc?Moose) or [Class::Method::Modifiers](http://search.cpan.org/perldoc?Class::Method::Modifiers).
In that case, you can just say:
```
around 'some_method' => sub {
my ($orig, $self, @args) = @_;
# ... before original ...
$self->$orig(@_);
# ... after original ...
};
```
|
[Memoize](http://search.cpan.org/perldoc/Memoize) is a good example of this.
|
575,710 |
I'm trying to [monkey patch](http://en.wikipedia.org/wiki/Monkey_patch) a Perl class: I want to change the behavior of an existing method.
[This node on perlmonks](http://www.perlmonks.org/?node_id=694332) shows how to *add* a function to an existing class. I found that this pattern can also be used to provide a new implementation for an existing function.
However, I'd like to know how to call the original function.
I'm looking for something like this:
```
use ExistingClass;
# TODO: Somehow rename existingFunction() to oldExistingFunction().
sub ExistingClass::existingFunction {
my $self = shift;
# New behavior goes here.
$self->oldExistingFunction(@_); # Call old behavior.
# More new behavior here.
}
```
|
2009/02/22
|
[
"https://Stackoverflow.com/questions/575710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Typeglob assignment
-------------------
```
*ExistingClass::oldExistingFunction = *ExistingClass::existingFunction;
```
Quick and dirty. This aliases all `existingFunction` symbols to `oldExistingFunction`. This includes the sub you're interested in, but also any scalars, arrays, hashes, handles that might happen to have the same name.
* Advantages: no thinking, it just works. "quick"
* Disadvantages: "dirty"
Coderef assignment
------------------
```
*ExistingClass::oldExistingFunction = \&ExistingClass::existingFunction;
# or something using *ExistingClass::symbol{CODE}
```
That one only aliases the sub. It's still done in the package stash, so the `oldExistingFunction` symbol is globally visible, which might or might not be what you want. Probably not.
* Advantages: that aliasing doesn't 'leak' to other variable types.
* Disadvantages: more thinking, more typing. A lot more thinking if going for the \*...{CODE} syntax (I personnally don't use it every day)
Lexical coderef
---------------
```
my $oldFunction = \&ExistingClass::existingFunction;
```
Using `my` keeps a reference to the old function that is only visible to the currrent block/file. There is no way for external code to get hold of it without your help anymore. Mind the calling convention:
```
$self->$oldFunction(@args);
$oldFunction->($self, @args);
```
* Advantages: no visibility issues anymore
* Disadvantages: harder to get right
Moose
-----
See [jrockway's answer](https://stackoverflow.com/questions/575710/monkey-patching-in-perl-how-to-access-original-method/576425#576425). It's got to be The Right Way, since there's no mucking around with globs and/or references anymore, but I don't know it enough to explain it.
|
[Memoize](http://search.cpan.org/perldoc/Memoize) is a good example of this.
|
575,710 |
I'm trying to [monkey patch](http://en.wikipedia.org/wiki/Monkey_patch) a Perl class: I want to change the behavior of an existing method.
[This node on perlmonks](http://www.perlmonks.org/?node_id=694332) shows how to *add* a function to an existing class. I found that this pattern can also be used to provide a new implementation for an existing function.
However, I'd like to know how to call the original function.
I'm looking for something like this:
```
use ExistingClass;
# TODO: Somehow rename existingFunction() to oldExistingFunction().
sub ExistingClass::existingFunction {
my $self = shift;
# New behavior goes here.
$self->oldExistingFunction(@_); # Call old behavior.
# More new behavior here.
}
```
|
2009/02/22
|
[
"https://Stackoverflow.com/questions/575710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Besides the other answers, look at modules such as:
* [Sub::Override](http://search.cpan.org/dist/Sub-Override)
* [Hook::LexWrap](http://search.cpan.org/dist/Hook-LexWrap)
I also talk about this in the "Dynamic Languages" chapter in [Mastering Perl](http://oreilly.com/catalog/9780596527242/).
|
For [Moose](http://metacpan.org/module/Moose) classes, you can just [do what jrockway says](https://stackoverflow.com/a/576425/40468); for non-Moose classes, do this:
```
use Class::MOP ();
use ExistingClass;
Class::MOP::Class->initialize('ExistingClass')->add_around_method_modifier(
existingFunction => sub {
my $orig = shift;
# new behaviour goes here
# call old behaviour
my $result = $orig->(@_);
# more new behaviour goes here
}
);
```
|
575,710 |
I'm trying to [monkey patch](http://en.wikipedia.org/wiki/Monkey_patch) a Perl class: I want to change the behavior of an existing method.
[This node on perlmonks](http://www.perlmonks.org/?node_id=694332) shows how to *add* a function to an existing class. I found that this pattern can also be used to provide a new implementation for an existing function.
However, I'd like to know how to call the original function.
I'm looking for something like this:
```
use ExistingClass;
# TODO: Somehow rename existingFunction() to oldExistingFunction().
sub ExistingClass::existingFunction {
my $self = shift;
# New behavior goes here.
$self->oldExistingFunction(@_); # Call old behavior.
# More new behavior here.
}
```
|
2009/02/22
|
[
"https://Stackoverflow.com/questions/575710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You should use [Moose](http://search.cpan.org/perldoc?Moose) or [Class::Method::Modifiers](http://search.cpan.org/perldoc?Class::Method::Modifiers).
In that case, you can just say:
```
around 'some_method' => sub {
my ($orig, $self, @args) = @_;
# ... before original ...
$self->$orig(@_);
# ... after original ...
};
```
|
As an alterative, what's wrong with:
```
package NewClass;
use base qw/ExistingClass/;
sub existingFunction {
# ....
}
sub oldExistingFunction {
my $self = shift;
return $self->SUPER::existingFunction(@_);
}
```
|
575,710 |
I'm trying to [monkey patch](http://en.wikipedia.org/wiki/Monkey_patch) a Perl class: I want to change the behavior of an existing method.
[This node on perlmonks](http://www.perlmonks.org/?node_id=694332) shows how to *add* a function to an existing class. I found that this pattern can also be used to provide a new implementation for an existing function.
However, I'd like to know how to call the original function.
I'm looking for something like this:
```
use ExistingClass;
# TODO: Somehow rename existingFunction() to oldExistingFunction().
sub ExistingClass::existingFunction {
my $self = shift;
# New behavior goes here.
$self->oldExistingFunction(@_); # Call old behavior.
# More new behavior here.
}
```
|
2009/02/22
|
[
"https://Stackoverflow.com/questions/575710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Besides the other answers, look at modules such as:
* [Sub::Override](http://search.cpan.org/dist/Sub-Override)
* [Hook::LexWrap](http://search.cpan.org/dist/Hook-LexWrap)
I also talk about this in the "Dynamic Languages" chapter in [Mastering Perl](http://oreilly.com/catalog/9780596527242/).
|
As an alterative, what's wrong with:
```
package NewClass;
use base qw/ExistingClass/;
sub existingFunction {
# ....
}
sub oldExistingFunction {
my $self = shift;
return $self->SUPER::existingFunction(@_);
}
```
|
575,710 |
I'm trying to [monkey patch](http://en.wikipedia.org/wiki/Monkey_patch) a Perl class: I want to change the behavior of an existing method.
[This node on perlmonks](http://www.perlmonks.org/?node_id=694332) shows how to *add* a function to an existing class. I found that this pattern can also be used to provide a new implementation for an existing function.
However, I'd like to know how to call the original function.
I'm looking for something like this:
```
use ExistingClass;
# TODO: Somehow rename existingFunction() to oldExistingFunction().
sub ExistingClass::existingFunction {
my $self = shift;
# New behavior goes here.
$self->oldExistingFunction(@_); # Call old behavior.
# More new behavior here.
}
```
|
2009/02/22
|
[
"https://Stackoverflow.com/questions/575710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Typeglob assignment
-------------------
```
*ExistingClass::oldExistingFunction = *ExistingClass::existingFunction;
```
Quick and dirty. This aliases all `existingFunction` symbols to `oldExistingFunction`. This includes the sub you're interested in, but also any scalars, arrays, hashes, handles that might happen to have the same name.
* Advantages: no thinking, it just works. "quick"
* Disadvantages: "dirty"
Coderef assignment
------------------
```
*ExistingClass::oldExistingFunction = \&ExistingClass::existingFunction;
# or something using *ExistingClass::symbol{CODE}
```
That one only aliases the sub. It's still done in the package stash, so the `oldExistingFunction` symbol is globally visible, which might or might not be what you want. Probably not.
* Advantages: that aliasing doesn't 'leak' to other variable types.
* Disadvantages: more thinking, more typing. A lot more thinking if going for the \*...{CODE} syntax (I personnally don't use it every day)
Lexical coderef
---------------
```
my $oldFunction = \&ExistingClass::existingFunction;
```
Using `my` keeps a reference to the old function that is only visible to the currrent block/file. There is no way for external code to get hold of it without your help anymore. Mind the calling convention:
```
$self->$oldFunction(@args);
$oldFunction->($self, @args);
```
* Advantages: no visibility issues anymore
* Disadvantages: harder to get right
Moose
-----
See [jrockway's answer](https://stackoverflow.com/questions/575710/monkey-patching-in-perl-how-to-access-original-method/576425#576425). It's got to be The Right Way, since there's no mucking around with globs and/or references anymore, but I don't know it enough to explain it.
|
As an alterative, what's wrong with:
```
package NewClass;
use base qw/ExistingClass/;
sub existingFunction {
# ....
}
sub oldExistingFunction {
my $self = shift;
return $self->SUPER::existingFunction(@_);
}
```
|
575,710 |
I'm trying to [monkey patch](http://en.wikipedia.org/wiki/Monkey_patch) a Perl class: I want to change the behavior of an existing method.
[This node on perlmonks](http://www.perlmonks.org/?node_id=694332) shows how to *add* a function to an existing class. I found that this pattern can also be used to provide a new implementation for an existing function.
However, I'd like to know how to call the original function.
I'm looking for something like this:
```
use ExistingClass;
# TODO: Somehow rename existingFunction() to oldExistingFunction().
sub ExistingClass::existingFunction {
my $self = shift;
# New behavior goes here.
$self->oldExistingFunction(@_); # Call old behavior.
# More new behavior here.
}
```
|
2009/02/22
|
[
"https://Stackoverflow.com/questions/575710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Typeglob assignment
-------------------
```
*ExistingClass::oldExistingFunction = *ExistingClass::existingFunction;
```
Quick and dirty. This aliases all `existingFunction` symbols to `oldExistingFunction`. This includes the sub you're interested in, but also any scalars, arrays, hashes, handles that might happen to have the same name.
* Advantages: no thinking, it just works. "quick"
* Disadvantages: "dirty"
Coderef assignment
------------------
```
*ExistingClass::oldExistingFunction = \&ExistingClass::existingFunction;
# or something using *ExistingClass::symbol{CODE}
```
That one only aliases the sub. It's still done in the package stash, so the `oldExistingFunction` symbol is globally visible, which might or might not be what you want. Probably not.
* Advantages: that aliasing doesn't 'leak' to other variable types.
* Disadvantages: more thinking, more typing. A lot more thinking if going for the \*...{CODE} syntax (I personnally don't use it every day)
Lexical coderef
---------------
```
my $oldFunction = \&ExistingClass::existingFunction;
```
Using `my` keeps a reference to the old function that is only visible to the currrent block/file. There is no way for external code to get hold of it without your help anymore. Mind the calling convention:
```
$self->$oldFunction(@args);
$oldFunction->($self, @args);
```
* Advantages: no visibility issues anymore
* Disadvantages: harder to get right
Moose
-----
See [jrockway's answer](https://stackoverflow.com/questions/575710/monkey-patching-in-perl-how-to-access-original-method/576425#576425). It's got to be The Right Way, since there's no mucking around with globs and/or references anymore, but I don't know it enough to explain it.
|
You should use [Moose](http://search.cpan.org/perldoc?Moose) or [Class::Method::Modifiers](http://search.cpan.org/perldoc?Class::Method::Modifiers).
In that case, you can just say:
```
around 'some_method' => sub {
my ($orig, $self, @args) = @_;
# ... before original ...
$self->$orig(@_);
# ... after original ...
};
```
|
63,509,183 |
Is there a way to stream your webcam to your android app using Webrtc?
|
2020/08/20
|
[
"https://Stackoverflow.com/questions/63509183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11141427/"
] |
### Update (Qt 6.2+)
As of Qt 6.2, [qt\_add\_qml\_module](https://doc-snapshots.qt.io/qt6-6.2/qt-add-qml-module.html) is a single command for building qml modules that should take care of virtually everything, replacing amongst others the old `qt6_qml_type_registration` command.
### Old answer (Qt 6.0/6.1)
Now that Qt 6.0 is out this is supported, albeit poorly documented. What you need now is:
```
set_target_properties(foo PROPERTIES
QT_QML_MODULE_VERSION 1.0
QT_QML_MODULE_URI Foo
)
qt6_qml_type_registration(foo)
```
you can then do in qml:
```
import Foo
```
and you'll have access to types that have `QML_ELEMENT` and friends. Notes:
* Two files are created in the build output folder, `<project>_qmltyperegistrations.cpp` and `<project>.qmltypes`, if your imports are failing you can look at those to see which types are missing. I found that I needed to do full recompiles sometimes after adding/removing registered types.
* Qt examples have been migrated to cmake, so take a look at e.g. `Examples/Qt-6.0.0/quick/tableview/gameoflife` to see it in action
* There are now `pro2cmake.py` and `run_pro2cmake.py` files in the Qt sources at `Qt/6.0.0/Src/qtbase/util/cmake`. They are mentioned on this [Readme](https://github.com/qt/qtbase/tree/dev/cmake) page, you can find them [here](https://github.com/qt/qtbase/tree/dev/util/cmake), haven't tried it myself.
|
Edit (Qt 6.x)
-------------
This answer was originally posted for Qt 5.15. Now that Qt 6 is available, and if you are using Qt 6, refer to the [answer from @Adversus](https://stackoverflow.com/a/65530243/4223664).
Original answer (Qt 5.x)
------------------------
From what I can see, `CONFIG += qmltypes`, which is required to use `QML_ELEMENT`, is not yet supported in CMake by looking at the [documentation](https://cmake.org/cmake/help/latest/manual/cmake-qt.7.html), even for the master branch.
And the efforts to provide a python .pro to cmake converter are for Qt6, not merged, and not functional as far as I can tell, by testing them from [util on the `wip/cmake` branch](https://code.qt.io/cgit/qt/qtbase.git/tree/util/cmake?h=wip/cmake) (the CMakeLists.txt didn't have relevant information).
You can see that the actual [conversion script](https://code.qt.io/cgit/qt/qtbase.git/tree/util/cmake/pro2cmake.py?h=wip/cmake) does test for `qmltypes` presence in CONFIG, but it doesn't seem to map to anything usable for CMake.
### Solution
Instead of using `QML_ELEMENT` and `CONFIG += qmltypes`, which is brand new from Qt 5.15 (latest when writing this), and not supported at this time with CMake, use the good old [`qmlRegisterType`](https://doc.qt.io/qt-5/qqmlengine.html#qmlRegisterType) from C++:
```
#include "YouCustomCppClass.h"
int main(int argc, char** argv) {
// Let you import it with "import ModuleName 1.0" on the QML side
qmlRegisterType<YouCustomCppClass>("ModuleName", 1, 0, "YourQmlComponent");
//Create your QML view or engine
}
```
This won't require anything specific on the project file side, as long as your code/plugin executes `qmlRegisterType` statement.
You can refer to Qt's documentation, same page as yours, but for Qt 5.14 instead of latest, which describes exactly that: [Writting QML extensions for C++ | Qt 5.14](https://doc.qt.io/qt-5.14/qtqml-tutorials-extending-qml-example.html)
|
1,090,447 |
>
> For $z\in\mathbb{C}$, calculate the minimum value of
>
>
> $$
> f(z) = \left|z^2+z+1\right|+\left|z^2-z+1\right|
> $$
>
>
>
**My Attempt:**
Let $z= x+iy$. Then
$$
\begin{align}
z^2+z+1 &= (x+iy)^2+(x+iy)+1\\
&= (x^2-y^2+x+1)+i(2xy+y)
\end{align}
$$
and
$$
\begin{align}
z^2-z+1 &= (x+iy)^2-(x+iy)+1\\
&= (x^2-y^2-x+1)+i(2xy-y)
\end{align}
$$
Define $f:\mathbb{R}^2\rightarrow\mathbb{R}$ by
$$
f(x,y) = \sqrt{\big(x^2-y^2+x+1\big)^2+(2xy+y)^2}+\sqrt{\big(x^2-y^2-x+1\big)^2+(y-2xy)^2}
$$
Using the Triangle Inequality, we know that
$$
f(x,y) \geq 2\sqrt{\left(x^2-y^2+1\right)^2+y^2}
$$
How can the problem be solved from this point?
|
2015/01/04
|
[
"https://math.stackexchange.com/questions/1090447",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] |
We can write $f$ in the form
$$f(z)=2|z|\>\left(\left|J(z)-{1\over2}\right|+\left|J(z)+{1\over2}\right|\right)\ ,$$
where $J$ denotes the so-called *Joukowski function*:
$$J(z):={1\over2}\left(z+{1\over z}\right)\ .$$
It is well known that $J$ maps circles $|z|=r$ onto ellipses centered at $0$ with foci $\pm1$ and semiaxes $$a={1\over2}\left(r+{1\over r}\right),\quad b={1\over2}\left|r-{1\over r}\right|\ .$$ Looking at such an ellipse we see that the points minimizing $f$ are the points $J(\pm i r)$ on the imaginary axis. It follows that
$$g(r):=\min\_{|z|=r} f(z)=f(ir)=2\sqrt{(r^2-1)^2+r^2}\ .$$
Now we have to minimize the right side over $r\geq0$. This leads to the equation
$4r^3-2r=0$ with the solutions $r\_1=0$, $r\_2={1\over\sqrt{2}}$. Since $g(0)=2$ and $g\bigl({1\over\sqrt{2}}\bigr)=\sqrt{3}$ we conclude that the global minimum of $f$ on the complex plane is $\sqrt{3}$, and this minimum is taken at the points $\pm{i\over\sqrt{2}}$.
|
Your analysis starts the right way. Substituting $z=x+iy$, you get as you write:
$$f(x,y)=\sqrt{(x^2-y^2+x+1)^2+(2xy+y)^2}+\sqrt{(x^2-y^2-x+1)^2+(y-2xy)^2}$$
The above now is a real multivariable function, so standard calculus techniques apply. In particular, the critical points are determined by looking first at the system:
$$\frac{df}{dx}=0$$
$$\frac{df}{dy}=0$$
This system has the solutions:
$$(x,y)=(0,0)$$
and
$$(x,y)=\left(0,\pm \frac{\sqrt{2}}{2}\right)$$
The null solution is rejected because it is not a global extremum and you are left with the second solution which after switching back to complex variables corresponds to:
$$\left(x=0,y=\pm\frac{i}{\sqrt{2}}\right)$$
as Cristian points out.
Here's the corresponding graph in two variables:

|
10,522,343 |
I need to write following query in Linq to SQL but not sure what is the best way of doing, given it has two derived tables. Any suggestions.
```
SELECT A.ID
FROM
(
SELECT *
FROM Orders
WHERE ProductID = 5
) A
JOIN
(
SELECT CustomerID, MAX(Price) Price
FROM Orders
WHERE ProductID = 5
GROUP BY CustomerID
) B
ON A.CustomerID = B.CustomerID and A.Price = B.Price
```
|
2012/05/09
|
[
"https://Stackoverflow.com/questions/10522343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459876/"
] |
```
var b = (
from o in db.Orders
where o.ProductID == 5
group o by o.CustomerID into og
select new {
CustomerID = og.Key
Price = Max(og.Price)
}
);
var a = (
from o in db.Orders
join p in b on new {a.CustomerID, a.Price} equals
new {b.CustomerID, b.Price}
where o.ProductID == 5
select a.ID
);
var r = a.ToString();
```
These two links are invaluable when forming things like this:
* <http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b>
* <http://msdn.microsoft.com/en-us/vstudio/bb688085>
|
Something along these lines:
```
var result = from a in context.Orders
join b in (context.Orders.Where(o => o.ProductID == 5).GroupBy(o => o.CustomerID).Select(g => new { CustomerID = g.Key, Price = g.Max(o => o.Price)))
on new {a.CustomerID, a.Price} equals new {b.CustomerID, b.Price}
where a.ProductID == 5
select a.ID;
```
|
10,522,343 |
I need to write following query in Linq to SQL but not sure what is the best way of doing, given it has two derived tables. Any suggestions.
```
SELECT A.ID
FROM
(
SELECT *
FROM Orders
WHERE ProductID = 5
) A
JOIN
(
SELECT CustomerID, MAX(Price) Price
FROM Orders
WHERE ProductID = 5
GROUP BY CustomerID
) B
ON A.CustomerID = B.CustomerID and A.Price = B.Price
```
|
2012/05/09
|
[
"https://Stackoverflow.com/questions/10522343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459876/"
] |
Can you simplify this with LINQ, especially if you use method syntax instead of query syntax.
```
orders.Where(o => o.ProductID == 5)
.GroupBy(o => o.CustomerID)
.SelectMany(g => g.Where(o => o.Price == g.Max(m => m.Price)));
```
My advice when writing LINQ, do not simply attempt to convert a SQL statement exactly. Think about the desired result and develop a solution designed for LINQ.
|
Something along these lines:
```
var result = from a in context.Orders
join b in (context.Orders.Where(o => o.ProductID == 5).GroupBy(o => o.CustomerID).Select(g => new { CustomerID = g.Key, Price = g.Max(o => o.Price)))
on new {a.CustomerID, a.Price} equals new {b.CustomerID, b.Price}
where a.ProductID == 5
select a.ID;
```
|
10,522,343 |
I need to write following query in Linq to SQL but not sure what is the best way of doing, given it has two derived tables. Any suggestions.
```
SELECT A.ID
FROM
(
SELECT *
FROM Orders
WHERE ProductID = 5
) A
JOIN
(
SELECT CustomerID, MAX(Price) Price
FROM Orders
WHERE ProductID = 5
GROUP BY CustomerID
) B
ON A.CustomerID = B.CustomerID and A.Price = B.Price
```
|
2012/05/09
|
[
"https://Stackoverflow.com/questions/10522343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459876/"
] |
```
var b = (
from o in db.Orders
where o.ProductID == 5
group o by o.CustomerID into og
select new {
CustomerID = og.Key
Price = Max(og.Price)
}
);
var a = (
from o in db.Orders
join p in b on new {a.CustomerID, a.Price} equals
new {b.CustomerID, b.Price}
where o.ProductID == 5
select a.ID
);
var r = a.ToString();
```
These two links are invaluable when forming things like this:
* <http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b>
* <http://msdn.microsoft.com/en-us/vstudio/bb688085>
|
Can you simplify this with LINQ, especially if you use method syntax instead of query syntax.
```
orders.Where(o => o.ProductID == 5)
.GroupBy(o => o.CustomerID)
.SelectMany(g => g.Where(o => o.Price == g.Max(m => m.Price)));
```
My advice when writing LINQ, do not simply attempt to convert a SQL statement exactly. Think about the desired result and develop a solution designed for LINQ.
|
437,565 |
I am trying to make a circuit using a 3V3 Arduino and other modules working on 3V3, but I have a problem with [an analog water sensor](https://www.thingbits.net/products/dfrobot-gravity-analog-water-pressure-sensor) I need to use. The output is a voltage range is from 0.5V to 4.5V.
I think I cannot use 4.5V signal on an analog pin of an Arduino working at 3V3.
So I have a basic idea like solution.
- Use a 5V step-up voltage regulator from 3V7 li-on battery for the water sensor
- Then using a voltage resistor divider to convert from 5V (sensor output) to 3V3.
- Then connect to the Arduino and inside make line code with a simple equation where I can recover the 5Volt value.
For example
[](https://i.stack.imgur.com/fbnvN.png)
Will I will lose resolution doing this? Is it a bad idea?
EXTRA QUESTION
To ensure that I will not lose resolution, what do I need to check? Maybe the minimum step voltage in the ouput of sensor? For example 5mv minimum of variation, then 5mv\*voltage\_divider = 3.3mv ... Then 10 bit of resolution of ADC in Arduino is enough? I got a 3.22mv resolution (3.3/1023)
|
2019/05/08
|
[
"https://electronics.stackexchange.com/questions/437565",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/221002/"
] |
That's the standard way to do it but you might consider lowering your resistors so that the net effective impedance seen by the Arduino's ADC input is only a few kohm. Maybe use 5k1 and 10 kohm. You'll find in the data sheet that the ATMEGA328 chip likes to have a source impedance not greater than 10 kohm.
You might also consider adding a capacitor across the (now) 10 kohm resistor to offer some anti alias filtering. If you can manage 100 nF that would be a good default choice but it depends on the bandwidth of the signals you wish to convert.
|
>
> Scaling a 5V sensor with offset into a 3.3V full scale A/D
>
>
>
Since the sensor has a large offset (approximately 0.5V) and a span of 4V you have to scale the input and provide an adjustable offset control.
One possible solution is to use a single rail to rail op-amp powered by the 3.3V supply. This provides self limiting since the VCC rail and ground become the input limit.

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fMrL1U.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
The [TLV9001](http://www.ti.com/lit/ds/symlink/tlv9001.pdf) or [TLV6001](http://www.ti.com/lit/ds/symlink/tlv6001.pdf) are good low cost opamp candidates.
R1 and R2 give a scale factor of 0.825.
R4 and R5 provide offset control.
Full scale resolution is 4V/1024 = 3.9mV (input voltage resolution)
Update: added element to allow the simulator to run. The output looks just fine. The small amount of clipping on the output is due to the incorrect value of the offset Rin (R4 and R5)
[](https://i.stack.imgur.com/RoPQP.png)
Note that this is of course an inverting configuration, so at zero (0.5v) sensor output the input to the A/D is 3.3V. I assume you can cope with this inversion.
Think of the circuit like this:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fMAZFf.png)
To understand the circuit read [this](http://web.mit.edu/6.101/www/reference/op_amps_everyone.pdf). Particularly read section 3.3 and 3.4.
If you don't understand opamps as attenuators (this one is stable at less than unity gain) you might read [this](https://www.edn.com/design/analog/4461648/Unique-compensation-technique-tames-high-bandwidth-voltage-feedback-op-amps-) excellent article.
|
437,565 |
I am trying to make a circuit using a 3V3 Arduino and other modules working on 3V3, but I have a problem with [an analog water sensor](https://www.thingbits.net/products/dfrobot-gravity-analog-water-pressure-sensor) I need to use. The output is a voltage range is from 0.5V to 4.5V.
I think I cannot use 4.5V signal on an analog pin of an Arduino working at 3V3.
So I have a basic idea like solution.
- Use a 5V step-up voltage regulator from 3V7 li-on battery for the water sensor
- Then using a voltage resistor divider to convert from 5V (sensor output) to 3V3.
- Then connect to the Arduino and inside make line code with a simple equation where I can recover the 5Volt value.
For example
[](https://i.stack.imgur.com/fbnvN.png)
Will I will lose resolution doing this? Is it a bad idea?
EXTRA QUESTION
To ensure that I will not lose resolution, what do I need to check? Maybe the minimum step voltage in the ouput of sensor? For example 5mv minimum of variation, then 5mv\*voltage\_divider = 3.3mv ... Then 10 bit of resolution of ADC in Arduino is enough? I got a 3.22mv resolution (3.3/1023)
|
2019/05/08
|
[
"https://electronics.stackexchange.com/questions/437565",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/221002/"
] |
That's the standard way to do it but you might consider lowering your resistors so that the net effective impedance seen by the Arduino's ADC input is only a few kohm. Maybe use 5k1 and 10 kohm. You'll find in the data sheet that the ATMEGA328 chip likes to have a source impedance not greater than 10 kohm.
You might also consider adding a capacitor across the (now) 10 kohm resistor to offer some anti alias filtering. If you can manage 100 nF that would be a good default choice but it depends on the bandwidth of the signals you wish to convert.
|
With 4.7K and 10K the values (3v3 Arduino 1023 max) are:
```
+5V Source
^
| 4.7K AX 10K
----/\/\/\----*----/\/\/\------GND
5V Source AX Analog AX
-------- ------ ------------
4.8 3.31 1023
4.5 3.12 964
4.0 2.80 865
3.5 2.45 757
3.3 2.30 711
3.0 2.13 658
2.5 1.76 544
```
```
|
437,565 |
I am trying to make a circuit using a 3V3 Arduino and other modules working on 3V3, but I have a problem with [an analog water sensor](https://www.thingbits.net/products/dfrobot-gravity-analog-water-pressure-sensor) I need to use. The output is a voltage range is from 0.5V to 4.5V.
I think I cannot use 4.5V signal on an analog pin of an Arduino working at 3V3.
So I have a basic idea like solution.
- Use a 5V step-up voltage regulator from 3V7 li-on battery for the water sensor
- Then using a voltage resistor divider to convert from 5V (sensor output) to 3V3.
- Then connect to the Arduino and inside make line code with a simple equation where I can recover the 5Volt value.
For example
[](https://i.stack.imgur.com/fbnvN.png)
Will I will lose resolution doing this? Is it a bad idea?
EXTRA QUESTION
To ensure that I will not lose resolution, what do I need to check? Maybe the minimum step voltage in the ouput of sensor? For example 5mv minimum of variation, then 5mv\*voltage\_divider = 3.3mv ... Then 10 bit of resolution of ADC in Arduino is enough? I got a 3.22mv resolution (3.3/1023)
|
2019/05/08
|
[
"https://electronics.stackexchange.com/questions/437565",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/221002/"
] |
With 4.7K and 10K the values (3v3 Arduino 1023 max) are:
```
+5V Source
^
| 4.7K AX 10K
----/\/\/\----*----/\/\/\------GND
5V Source AX Analog AX
-------- ------ ------------
4.8 3.31 1023
4.5 3.12 964
4.0 2.80 865
3.5 2.45 757
3.3 2.30 711
3.0 2.13 658
2.5 1.76 544
```
```
|
>
> Scaling a 5V sensor with offset into a 3.3V full scale A/D
>
>
>
Since the sensor has a large offset (approximately 0.5V) and a span of 4V you have to scale the input and provide an adjustable offset control.
One possible solution is to use a single rail to rail op-amp powered by the 3.3V supply. This provides self limiting since the VCC rail and ground become the input limit.

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fMrL1U.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
The [TLV9001](http://www.ti.com/lit/ds/symlink/tlv9001.pdf) or [TLV6001](http://www.ti.com/lit/ds/symlink/tlv6001.pdf) are good low cost opamp candidates.
R1 and R2 give a scale factor of 0.825.
R4 and R5 provide offset control.
Full scale resolution is 4V/1024 = 3.9mV (input voltage resolution)
Update: added element to allow the simulator to run. The output looks just fine. The small amount of clipping on the output is due to the incorrect value of the offset Rin (R4 and R5)
[](https://i.stack.imgur.com/RoPQP.png)
Note that this is of course an inverting configuration, so at zero (0.5v) sensor output the input to the A/D is 3.3V. I assume you can cope with this inversion.
Think of the circuit like this:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fMAZFf.png)
To understand the circuit read [this](http://web.mit.edu/6.101/www/reference/op_amps_everyone.pdf). Particularly read section 3.3 and 3.4.
If you don't understand opamps as attenuators (this one is stable at less than unity gain) you might read [this](https://www.edn.com/design/analog/4461648/Unique-compensation-technique-tames-high-bandwidth-voltage-feedback-op-amps-) excellent article.
|
3,086,481 |
How to find the value this sum converges to?$$\sum\_{n=2}^{\infty}\frac{n+1}{n(2n-1)(2n+1)} $$
I've tried separating it like
$$\sum\_{n=2}^{\infty}\frac{1/2}{(2n+1)}+\frac{3/2}{(2n-1)}-\frac{1}{n}$$
and writing some terms and I get
$$1/6·(1+1/2+...+1/6n+3)+1/2·(1/3+1+1/2+...+1/6n-3)-(1+1/2+...1/n)$$
but I don't know how to end summing it all! Any hint!
FYI I haven't learnt integration and differentation.
|
2019/01/24
|
[
"https://math.stackexchange.com/questions/3086481",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/602323/"
] |
Hint: $\frac {n+1} {n(2n-1)(2n+1)}=\frac 3 4 \frac 1 {n(2n-1)} -\frac 1 4 \frac 1 {n(2n+1)}$. So what is left is to find the sums $\sum \frac 1 {n(2n-1)}$ and $\sum \frac 1 {n(2n+1)}$.
|
Proceeding on the partial fraction decomposition you already got
$$
\eqalign{
& S = \sum\limits\_{2\, \le \,n} {{{n + 1} \over {n\left( {2n - 1} \right)\left( {2n + 1} \right)}}} = \cr
& = \sum\limits\_{2\, \le \,n} {{{1/2} \over {\left( {2n + 1} \right)}} + {{3/2} \over {\left( {2n - 1} \right)}} + {1 \over n}} = \cr
& = \sum\limits\_{0\, \le \,n} {{{1/2} \over {\left( {2n + 5} \right)}} + {{3/2} \over {\left( {2n + 3} \right)}} - {1 \over {n + 2}}} = \cr
& = \sum\limits\_{0\, \le \,n} {{{1/4} \over {\left( {n + 5/2} \right)}} + {{3/4} \over {\left( {n + 3/2} \right)}} - {1 \over {n + 2}}} \cr}
$$
Since
$$
\sum\nolimits\_{n = 0}^N {{1 \over {n + a}}} = \sum\nolimits\_{n = a}^{N + a} {{1 \over n}} = \psi (N + a) - \psi (a)
$$
then
$$
\eqalign{
& S = \mathop {\lim }\limits\_{N\, \to \,\infty } \left( \matrix{
{1 \over 4}\psi (N + 5/2) + {3 \over 4}\psi (N + 3/2) - \psi (N + 2) + \hfill \cr
+ \psi (2) - {1 \over 4}\psi (5/2) - {3 \over 4}\psi (3/2) \hfill \cr} \right) = \cr
& = \psi (2) - {1 \over 4}\psi (5/2) - {3 \over 4}\psi (3/2) = \cr
& = 1 - \gamma - {1 \over 4}\left( {{8 \over 3} - 2\ln 2 - \gamma } \right) - {3 \over 4}\left( {2 - 2\ln 2 - \gamma } \right) = \cr
& = 2\ln 2 - {7 \over 6} \cr}
$$
|
3,086,481 |
How to find the value this sum converges to?$$\sum\_{n=2}^{\infty}\frac{n+1}{n(2n-1)(2n+1)} $$
I've tried separating it like
$$\sum\_{n=2}^{\infty}\frac{1/2}{(2n+1)}+\frac{3/2}{(2n-1)}-\frac{1}{n}$$
and writing some terms and I get
$$1/6·(1+1/2+...+1/6n+3)+1/2·(1/3+1+1/2+...+1/6n-3)-(1+1/2+...1/n)$$
but I don't know how to end summing it all! Any hint!
FYI I haven't learnt integration and differentation.
|
2019/01/24
|
[
"https://math.stackexchange.com/questions/3086481",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/602323/"
] |
Hint: $\frac {n+1} {n(2n-1)(2n+1)}=\frac 3 4 \frac 1 {n(2n-1)} -\frac 1 4 \frac 1 {n(2n+1)}$. So what is left is to find the sums $\sum \frac 1 {n(2n-1)}$ and $\sum \frac 1 {n(2n+1)}$.
|
Here is a way to find those two sums @Kavi Rama Murthy refers to in his answer. They are found by first converting them to double integrals.
Let
$$S = \sum\_{n = 2}^\infty \frac{n + 1}{n(2n - 1)(2n + 1)} = \frac{3}{4} \sum\_{n = 2}^\infty \frac{1}{n (2n - 1)} - \frac{1}{4} \sum\_{n = 1}^\infty \frac{1}{n(2n + 1)} + \frac{1}{12}. \qquad (\*)$$
For the first of the sums appearing to the right in ($\*$), observe that
$$\frac{1}{n} = \int\_0^1 x^{n - 1} \, dx \quad \text{and} \quad \frac{1}{2n - 1} = \int\_0^1 y^{2n - 2} \, dy.$$
The sum may now be rewritten as
\begin{align}
\sum\_{n = 2}^\infty \frac{1}{n(2n - 1)} &= \sum\_{n = 2}^\infty \int\_0^1 \int\_0^1 x^{n - 1} y^{2n - 2} \, dx \, dy\\
&= \int\_0^1 \int\_0^1 \frac{1}{xy^2} \sum\_{n = 2}^\infty (xy^2)^n \, dx \,dy \tag1\\
&= \int\_0^1 \int\_0^1 \frac{1}{xy^2} \cdot \frac{(xy^2)^2}{1 - xy^2} \, dx \, dy \tag2\\
&= \int\_0^1 \frac{1}{y^2} \int\_0^{y^2} \frac{u}{1 - u} \, du \, dy \tag3\\
&= -\int\_0^1 \frac{1}{y^2} \int\_0^{y^2} \left (1 - \frac{1}{1 - u} \right ) \, du \, dy\\
&= -\int\_0^1 \left (1 + \frac{\ln (1 - y^2)}{y^2} \right ) \, dy\\
&= -1 + 2 \int\_0^1 \frac{1 - y}{1 - y^2} \, dy \tag4\\
&= -1 + 2 \int\_0^1 \frac{dy}{1 + y}\\
&= -1 + 2 \ln 2.
\end{align}
**Explanation**
(1) Interchange of the sum and integral signs is justified by the dominated convergence theorem.
(2) Summing of a geometric series.
(3) Change of variable $u = xy^2$ is made.
(4) Integration by parts has been used.
The second of the sums appearing in ($\*$) can be found in a similar manner (see [here](https://math.stackexchange.com/questions/1334870/how-to-find-sum-of-the-infinite-series-sum-n-1-infty-frac1-n2n1/2615666#2615666)). The result is:
$$\sum\_{n = 1}^\infty \frac{1}{n(2n + 1)} = 2 - 2\ln 2.$$
Thus
$$S = \frac{3}{4} (2 \ln 2 - 1) - \frac{1}{4} (2 - 2 \ln 2) + \frac{1}{12},$$
or
$$\sum\_{n = 2}^\infty \frac{n + 1}{n(2n - 1)(2n + 1)} = 2 \ln 2 - \frac{7}{6}.$$
|
3,086,481 |
How to find the value this sum converges to?$$\sum\_{n=2}^{\infty}\frac{n+1}{n(2n-1)(2n+1)} $$
I've tried separating it like
$$\sum\_{n=2}^{\infty}\frac{1/2}{(2n+1)}+\frac{3/2}{(2n-1)}-\frac{1}{n}$$
and writing some terms and I get
$$1/6·(1+1/2+...+1/6n+3)+1/2·(1/3+1+1/2+...+1/6n-3)-(1+1/2+...1/n)$$
but I don't know how to end summing it all! Any hint!
FYI I haven't learnt integration and differentation.
|
2019/01/24
|
[
"https://math.stackexchange.com/questions/3086481",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/602323/"
] |
Proceeding on the partial fraction decomposition you already got
$$
\eqalign{
& S = \sum\limits\_{2\, \le \,n} {{{n + 1} \over {n\left( {2n - 1} \right)\left( {2n + 1} \right)}}} = \cr
& = \sum\limits\_{2\, \le \,n} {{{1/2} \over {\left( {2n + 1} \right)}} + {{3/2} \over {\left( {2n - 1} \right)}} + {1 \over n}} = \cr
& = \sum\limits\_{0\, \le \,n} {{{1/2} \over {\left( {2n + 5} \right)}} + {{3/2} \over {\left( {2n + 3} \right)}} - {1 \over {n + 2}}} = \cr
& = \sum\limits\_{0\, \le \,n} {{{1/4} \over {\left( {n + 5/2} \right)}} + {{3/4} \over {\left( {n + 3/2} \right)}} - {1 \over {n + 2}}} \cr}
$$
Since
$$
\sum\nolimits\_{n = 0}^N {{1 \over {n + a}}} = \sum\nolimits\_{n = a}^{N + a} {{1 \over n}} = \psi (N + a) - \psi (a)
$$
then
$$
\eqalign{
& S = \mathop {\lim }\limits\_{N\, \to \,\infty } \left( \matrix{
{1 \over 4}\psi (N + 5/2) + {3 \over 4}\psi (N + 3/2) - \psi (N + 2) + \hfill \cr
+ \psi (2) - {1 \over 4}\psi (5/2) - {3 \over 4}\psi (3/2) \hfill \cr} \right) = \cr
& = \psi (2) - {1 \over 4}\psi (5/2) - {3 \over 4}\psi (3/2) = \cr
& = 1 - \gamma - {1 \over 4}\left( {{8 \over 3} - 2\ln 2 - \gamma } \right) - {3 \over 4}\left( {2 - 2\ln 2 - \gamma } \right) = \cr
& = 2\ln 2 - {7 \over 6} \cr}
$$
|
Here is a way to find those two sums @Kavi Rama Murthy refers to in his answer. They are found by first converting them to double integrals.
Let
$$S = \sum\_{n = 2}^\infty \frac{n + 1}{n(2n - 1)(2n + 1)} = \frac{3}{4} \sum\_{n = 2}^\infty \frac{1}{n (2n - 1)} - \frac{1}{4} \sum\_{n = 1}^\infty \frac{1}{n(2n + 1)} + \frac{1}{12}. \qquad (\*)$$
For the first of the sums appearing to the right in ($\*$), observe that
$$\frac{1}{n} = \int\_0^1 x^{n - 1} \, dx \quad \text{and} \quad \frac{1}{2n - 1} = \int\_0^1 y^{2n - 2} \, dy.$$
The sum may now be rewritten as
\begin{align}
\sum\_{n = 2}^\infty \frac{1}{n(2n - 1)} &= \sum\_{n = 2}^\infty \int\_0^1 \int\_0^1 x^{n - 1} y^{2n - 2} \, dx \, dy\\
&= \int\_0^1 \int\_0^1 \frac{1}{xy^2} \sum\_{n = 2}^\infty (xy^2)^n \, dx \,dy \tag1\\
&= \int\_0^1 \int\_0^1 \frac{1}{xy^2} \cdot \frac{(xy^2)^2}{1 - xy^2} \, dx \, dy \tag2\\
&= \int\_0^1 \frac{1}{y^2} \int\_0^{y^2} \frac{u}{1 - u} \, du \, dy \tag3\\
&= -\int\_0^1 \frac{1}{y^2} \int\_0^{y^2} \left (1 - \frac{1}{1 - u} \right ) \, du \, dy\\
&= -\int\_0^1 \left (1 + \frac{\ln (1 - y^2)}{y^2} \right ) \, dy\\
&= -1 + 2 \int\_0^1 \frac{1 - y}{1 - y^2} \, dy \tag4\\
&= -1 + 2 \int\_0^1 \frac{dy}{1 + y}\\
&= -1 + 2 \ln 2.
\end{align}
**Explanation**
(1) Interchange of the sum and integral signs is justified by the dominated convergence theorem.
(2) Summing of a geometric series.
(3) Change of variable $u = xy^2$ is made.
(4) Integration by parts has been used.
The second of the sums appearing in ($\*$) can be found in a similar manner (see [here](https://math.stackexchange.com/questions/1334870/how-to-find-sum-of-the-infinite-series-sum-n-1-infty-frac1-n2n1/2615666#2615666)). The result is:
$$\sum\_{n = 1}^\infty \frac{1}{n(2n + 1)} = 2 - 2\ln 2.$$
Thus
$$S = \frac{3}{4} (2 \ln 2 - 1) - \frac{1}{4} (2 - 2 \ln 2) + \frac{1}{12},$$
or
$$\sum\_{n = 2}^\infty \frac{n + 1}{n(2n - 1)(2n + 1)} = 2 \ln 2 - \frac{7}{6}.$$
|
51,739,255 |
Say if there's a class attribute that is calculated depending on another class attribute:
```
class ClassA(object):
attr1=5
attr2=attr1+10
>>ClassA.attr2
15
```
And then in a child class I want to update the first class attribute to cause a change in the second one, without re-defining the second. e.g:
```
class ClassB(ClassA):
attr1=10
```
What I would like to happen is:
```
>>ClassB.attr2
20
```
However this isn't the case since attr2 gets calculated before attr1 is re-defined. Is there a way to obtain this behaviour without redefining the second attribute?
(My particular use case is defining WTForms with Field attributes (format, choices, etc) that are derived from the Form class attributes, so I can subclass a base Form and change these attributes without having to re-define the entire Field.)
|
2018/08/08
|
[
"https://Stackoverflow.com/questions/51739255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5977437/"
] |
You can use a `@classproperty` descriptor (similar to `@property`) if you don't want to use metaclasses.
Here's a simple implementation of a `classproperty` decorator
```
class classproperty(object):
def __init__(self, fget):
self.fget = classmethod(fget)
def __get__(self, obj, owner):
return self.fget.__get__(None, owner)()
```
And some sample usage:
```
class A(object):
attr1 = 10
@classproperty
def attr2(cls):
return cls.attr1 + 10
class B(A):
attr1 = 8991
```
And usage of that:
```
>>> A.attr1
10
>>> A.attr2
20
>>> B.attr2
9001
>>> A().attr2
20
>>> B().attr2
9001
```
|
Well, you can do those calculations in metaclass' `__new__` method:
```
class MyCalculatedClassAttrsMeta(type):
def __new__(cls, name, bases, dct):
c = super().__new__(cls, name, bases, dct)
c.y = c.x + 100
return c
class A(metaclass=MyCalculatedClassAttrsMeta):
x = 1
class B(A):
x = 2
print(A.x, A.y)
print(B.x, B.y)
```
The output will be:
```
1 101
2 202
```
|
51,739,255 |
Say if there's a class attribute that is calculated depending on another class attribute:
```
class ClassA(object):
attr1=5
attr2=attr1+10
>>ClassA.attr2
15
```
And then in a child class I want to update the first class attribute to cause a change in the second one, without re-defining the second. e.g:
```
class ClassB(ClassA):
attr1=10
```
What I would like to happen is:
```
>>ClassB.attr2
20
```
However this isn't the case since attr2 gets calculated before attr1 is re-defined. Is there a way to obtain this behaviour without redefining the second attribute?
(My particular use case is defining WTForms with Field attributes (format, choices, etc) that are derived from the Form class attributes, so I can subclass a base Form and change these attributes without having to re-define the entire Field.)
|
2018/08/08
|
[
"https://Stackoverflow.com/questions/51739255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5977437/"
] |
There's no way to do this directly.
For instance attributes, rather than class attributes, you can simulate it pretty easily by using [`@property`](https://docs.python.org/3/library/functions.html#property). Either calculate `attr2` on the fly every time you ask for it:
```
class Spam:
def __init__(self, a):
self.a = a
@property
def twoa(self):
return 2*self.a
```
(possibly adding a cache if calculation is expensive), or recalculate `attr2` whenever anyone modifies `attr1`:
```
class Spam:
def __init__(self, a):
self.a = a
@property
def a(self):
return self._a
@a.setter
def a(self):
self._a = a
self.twoa = 2*a
```
---
That only works because `property` creates a descriptor that you store in the class object, rather than the instance, so when someone looks up `twoa` (in the first example) or `a` (in the second) on a `Spam` instance, it falls back to finding the descriptor on the class.
If you want the first one for a class attribute, it works as-is when looking up values on instances, but not on the class itself (which, unfortunately, is what you're doing in your examples).
And if you need the second one, it won't work at all.
For example:
```
>>> class Spam:
... a = 10
... @property
... def twoa(self):
... return 2*self.a
>>> spam = Spam()
>>> spam.twoa
20
>>> Spam.twoa
<property at 0x12345678>
>>> class Eggs(Spam):
... a = 5
>>> eggs = Eggs()
>>> eggs.twoa
10
>>> Eggs.twoa
<property at 0x12345678>
```
If that's not a problem, great. But if it is, you need to put the descriptor on the class's class—that is, a metaclass:
```
class MetaSpam(type):
@property
def twoa(cls):
return 2 * cls.a
class Spam(metaclass=MetaSpam):
a = 2
class Eggs(Spam):
a = 3
```
For a simple case like `twoa` (or your `attr2`), dragging in a metaclass is horrible overkill.
But for a case where there's a good chance you're already dragging in custom metaclasses, like a complex forms-and-fields system, it might be appropriate.
|
Well, you can do those calculations in metaclass' `__new__` method:
```
class MyCalculatedClassAttrsMeta(type):
def __new__(cls, name, bases, dct):
c = super().__new__(cls, name, bases, dct)
c.y = c.x + 100
return c
class A(metaclass=MyCalculatedClassAttrsMeta):
x = 1
class B(A):
x = 2
print(A.x, A.y)
print(B.x, B.y)
```
The output will be:
```
1 101
2 202
```
|
34,761,051 |
I'm trying to upload an image using codeigniter and no matter what
I keep getting "You did not select a file to upload" error.
Here's my Controller:
```
<?php
class Post extends CI_Controller {
function __construct(){
parent::__construct();
}
function index(){
$this->load->view('upload_form', array('error' => ''));
}
function upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$file_data = array('upload_data' => $this->upload->data());
$data['img'] = base_url().'/images/'.$file_data['file_name'];
echo json_encode($data);
}
}
}
?>
```
Here is my View:
```
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE-9"/>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data" >
Select File To Upload:<br />
<input type="file" name="userfile" />
<br /><br />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
</body>
</html>
```
Can anyone help me to solve this problem? I appreciate any help :)
|
2016/01/13
|
[
"https://Stackoverflow.com/questions/34761051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4800314/"
] |
As per the Jenkins [command line interface documentation](https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+CLI), you need to use the **client** JAR file (not the **server** WAR file you're using), which you can obtain directly from Jenkins, e.g. via the links on <http://localhost:8080/cli>
Then you can run the command using this JAR:
```
java -jar jenkins-cli.jar -s http://127.0.0.1:8080/ install-plugin <name>
```
This will download install the plugin you want, along with any of its dependencies.
|
If you don't find some straight forward command for installing plugins.
Please take a look at this link: [How to install a plugin in Jenkins manually?](https://stackoverflow.com/questions/14950408/how-to-install-a-plugin-in-jenkins-manually)
But it needs to download the plugin first(\*.hpi file) and run it manually.
|
34,761,051 |
I'm trying to upload an image using codeigniter and no matter what
I keep getting "You did not select a file to upload" error.
Here's my Controller:
```
<?php
class Post extends CI_Controller {
function __construct(){
parent::__construct();
}
function index(){
$this->load->view('upload_form', array('error' => ''));
}
function upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$file_data = array('upload_data' => $this->upload->data());
$data['img'] = base_url().'/images/'.$file_data['file_name'];
echo json_encode($data);
}
}
}
?>
```
Here is my View:
```
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE-9"/>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data" >
Select File To Upload:<br />
<input type="file" name="userfile" />
<br /><br />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
</body>
</html>
```
Can anyone help me to solve this problem? I appreciate any help :)
|
2016/01/13
|
[
"https://Stackoverflow.com/questions/34761051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4800314/"
] |
```
import jenkins.model.*
import java.util.logging.Logger
def logger = Logger.getLogger("")
def installed = false
def initialized = false
def pluginParameter="gitlab-plugin hipchat swarm"
def plugins =pluginParameter.split()
logger.info("" + plugins)
def instance =Jenkins.getInstance()
def pm = instance.getPluginManager()
def uc =instance.getUpdateCenter()
uc.updateAllSites()
plugins.each { logger.info("Checking " + it) if
(!pm.getPlugin(it)) {
logger.info("Looking UpdateCenter for " + it)
if (!initialized) {
uc.updateAllSites()
initialized = true
}
def plugin = uc.getPlugin(it)
if (plugin) {
logger.info("Installing " + it)
plugin.deploy()
installed = true
} } }
if (installed)
{
logger.info("Plugins installed, initializing a restart!")
instance.save()
instance.doSafeRestart()
}
```
|
If you don't find some straight forward command for installing plugins.
Please take a look at this link: [How to install a plugin in Jenkins manually?](https://stackoverflow.com/questions/14950408/how-to-install-a-plugin-in-jenkins-manually)
But it needs to download the plugin first(\*.hpi file) and run it manually.
|
34,761,051 |
I'm trying to upload an image using codeigniter and no matter what
I keep getting "You did not select a file to upload" error.
Here's my Controller:
```
<?php
class Post extends CI_Controller {
function __construct(){
parent::__construct();
}
function index(){
$this->load->view('upload_form', array('error' => ''));
}
function upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$file_data = array('upload_data' => $this->upload->data());
$data['img'] = base_url().'/images/'.$file_data['file_name'];
echo json_encode($data);
}
}
}
?>
```
Here is my View:
```
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE-9"/>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data" >
Select File To Upload:<br />
<input type="file" name="userfile" />
<br /><br />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
</body>
</html>
```
Can anyone help me to solve this problem? I appreciate any help :)
|
2016/01/13
|
[
"https://Stackoverflow.com/questions/34761051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4800314/"
] |
Since Sept 2019, you can also use the [Plugin Installation Manager Tool](https://github.com/jenkinsci/plugin-installation-manager-tool). It takes a yaml file listing the plugins, and downloads plugins to a folder of your choice. There is no need to have a running Jenkins instance. You can specify the plugin versions in the yaml file, but be aware of [JENKINS-60205](https://issues.jenkins-ci.org/browse/JENKINS-60205).
Get the plugin manager:
```
version=1.0.1
curl \
-L \
-X GET "https://github.com/jenkinsci/plugin-installation-manager-tool/releases/download/plugin-management-parent-pom-$version/jenkins-plugin-manager-$version.jar" \
-o jenkins-plugin-manager-$version.jar
```
Download the plugins:
```
java -jar jenkins-plugin-manager-$version.jar \
--plugin-download-directory pluginsFolder \
--plugin-file plugins.yml \
--war jenkins.war
```
The plugins are in the `pluginsFolder`.
|
If you don't find some straight forward command for installing plugins.
Please take a look at this link: [How to install a plugin in Jenkins manually?](https://stackoverflow.com/questions/14950408/how-to-install-a-plugin-in-jenkins-manually)
But it needs to download the plugin first(\*.hpi file) and run it manually.
|
34,761,051 |
I'm trying to upload an image using codeigniter and no matter what
I keep getting "You did not select a file to upload" error.
Here's my Controller:
```
<?php
class Post extends CI_Controller {
function __construct(){
parent::__construct();
}
function index(){
$this->load->view('upload_form', array('error' => ''));
}
function upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$file_data = array('upload_data' => $this->upload->data());
$data['img'] = base_url().'/images/'.$file_data['file_name'];
echo json_encode($data);
}
}
}
?>
```
Here is my View:
```
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE-9"/>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data" >
Select File To Upload:<br />
<input type="file" name="userfile" />
<br /><br />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
</body>
</html>
```
Can anyone help me to solve this problem? I appreciate any help :)
|
2016/01/13
|
[
"https://Stackoverflow.com/questions/34761051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4800314/"
] |
You will need jenkins-cli.jar file.
It can be downloaded from ${JENKINSURL}/jnlpJars/jenkins-cli.jar
```
wget http://localhost:8080/jnlpJars/jenkins-cli.jar
```
To install a plugin :
```
java -jar jenkins-cli.jar -auth ${USER}:${PASSWORD} -s ${JENKINSURL} install-plugin ${PLUGIN_NAME}
```
If you dont provide auth you will get error:
>
> ERROR: anonymous is missing the Overall/Read permission
>
>
>
|
If you don't find some straight forward command for installing plugins.
Please take a look at this link: [How to install a plugin in Jenkins manually?](https://stackoverflow.com/questions/14950408/how-to-install-a-plugin-in-jenkins-manually)
But it needs to download the plugin first(\*.hpi file) and run it manually.
|
34,761,051 |
I'm trying to upload an image using codeigniter and no matter what
I keep getting "You did not select a file to upload" error.
Here's my Controller:
```
<?php
class Post extends CI_Controller {
function __construct(){
parent::__construct();
}
function index(){
$this->load->view('upload_form', array('error' => ''));
}
function upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$file_data = array('upload_data' => $this->upload->data());
$data['img'] = base_url().'/images/'.$file_data['file_name'];
echo json_encode($data);
}
}
}
?>
```
Here is my View:
```
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE-9"/>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data" >
Select File To Upload:<br />
<input type="file" name="userfile" />
<br /><br />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
</body>
</html>
```
Can anyone help me to solve this problem? I appreciate any help :)
|
2016/01/13
|
[
"https://Stackoverflow.com/questions/34761051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4800314/"
] |
As per the Jenkins [command line interface documentation](https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+CLI), you need to use the **client** JAR file (not the **server** WAR file you're using), which you can obtain directly from Jenkins, e.g. via the links on <http://localhost:8080/cli>
Then you can run the command using this JAR:
```
java -jar jenkins-cli.jar -s http://127.0.0.1:8080/ install-plugin <name>
```
This will download install the plugin you want, along with any of its dependencies.
|
```
import jenkins.model.*
import java.util.logging.Logger
def logger = Logger.getLogger("")
def installed = false
def initialized = false
def pluginParameter="gitlab-plugin hipchat swarm"
def plugins =pluginParameter.split()
logger.info("" + plugins)
def instance =Jenkins.getInstance()
def pm = instance.getPluginManager()
def uc =instance.getUpdateCenter()
uc.updateAllSites()
plugins.each { logger.info("Checking " + it) if
(!pm.getPlugin(it)) {
logger.info("Looking UpdateCenter for " + it)
if (!initialized) {
uc.updateAllSites()
initialized = true
}
def plugin = uc.getPlugin(it)
if (plugin) {
logger.info("Installing " + it)
plugin.deploy()
installed = true
} } }
if (installed)
{
logger.info("Plugins installed, initializing a restart!")
instance.save()
instance.doSafeRestart()
}
```
|
34,761,051 |
I'm trying to upload an image using codeigniter and no matter what
I keep getting "You did not select a file to upload" error.
Here's my Controller:
```
<?php
class Post extends CI_Controller {
function __construct(){
parent::__construct();
}
function index(){
$this->load->view('upload_form', array('error' => ''));
}
function upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$file_data = array('upload_data' => $this->upload->data());
$data['img'] = base_url().'/images/'.$file_data['file_name'];
echo json_encode($data);
}
}
}
?>
```
Here is my View:
```
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE-9"/>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data" >
Select File To Upload:<br />
<input type="file" name="userfile" />
<br /><br />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
</body>
</html>
```
Can anyone help me to solve this problem? I appreciate any help :)
|
2016/01/13
|
[
"https://Stackoverflow.com/questions/34761051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4800314/"
] |
As per the Jenkins [command line interface documentation](https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+CLI), you need to use the **client** JAR file (not the **server** WAR file you're using), which you can obtain directly from Jenkins, e.g. via the links on <http://localhost:8080/cli>
Then you can run the command using this JAR:
```
java -jar jenkins-cli.jar -s http://127.0.0.1:8080/ install-plugin <name>
```
This will download install the plugin you want, along with any of its dependencies.
|
Since Sept 2019, you can also use the [Plugin Installation Manager Tool](https://github.com/jenkinsci/plugin-installation-manager-tool). It takes a yaml file listing the plugins, and downloads plugins to a folder of your choice. There is no need to have a running Jenkins instance. You can specify the plugin versions in the yaml file, but be aware of [JENKINS-60205](https://issues.jenkins-ci.org/browse/JENKINS-60205).
Get the plugin manager:
```
version=1.0.1
curl \
-L \
-X GET "https://github.com/jenkinsci/plugin-installation-manager-tool/releases/download/plugin-management-parent-pom-$version/jenkins-plugin-manager-$version.jar" \
-o jenkins-plugin-manager-$version.jar
```
Download the plugins:
```
java -jar jenkins-plugin-manager-$version.jar \
--plugin-download-directory pluginsFolder \
--plugin-file plugins.yml \
--war jenkins.war
```
The plugins are in the `pluginsFolder`.
|
34,761,051 |
I'm trying to upload an image using codeigniter and no matter what
I keep getting "You did not select a file to upload" error.
Here's my Controller:
```
<?php
class Post extends CI_Controller {
function __construct(){
parent::__construct();
}
function index(){
$this->load->view('upload_form', array('error' => ''));
}
function upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$file_data = array('upload_data' => $this->upload->data());
$data['img'] = base_url().'/images/'.$file_data['file_name'];
echo json_encode($data);
}
}
}
?>
```
Here is my View:
```
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE-9"/>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data" >
Select File To Upload:<br />
<input type="file" name="userfile" />
<br /><br />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
</body>
</html>
```
Can anyone help me to solve this problem? I appreciate any help :)
|
2016/01/13
|
[
"https://Stackoverflow.com/questions/34761051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4800314/"
] |
As per the Jenkins [command line interface documentation](https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+CLI), you need to use the **client** JAR file (not the **server** WAR file you're using), which you can obtain directly from Jenkins, e.g. via the links on <http://localhost:8080/cli>
Then you can run the command using this JAR:
```
java -jar jenkins-cli.jar -s http://127.0.0.1:8080/ install-plugin <name>
```
This will download install the plugin you want, along with any of its dependencies.
|
You will need jenkins-cli.jar file.
It can be downloaded from ${JENKINSURL}/jnlpJars/jenkins-cli.jar
```
wget http://localhost:8080/jnlpJars/jenkins-cli.jar
```
To install a plugin :
```
java -jar jenkins-cli.jar -auth ${USER}:${PASSWORD} -s ${JENKINSURL} install-plugin ${PLUGIN_NAME}
```
If you dont provide auth you will get error:
>
> ERROR: anonymous is missing the Overall/Read permission
>
>
>
|
34,761,051 |
I'm trying to upload an image using codeigniter and no matter what
I keep getting "You did not select a file to upload" error.
Here's my Controller:
```
<?php
class Post extends CI_Controller {
function __construct(){
parent::__construct();
}
function index(){
$this->load->view('upload_form', array('error' => ''));
}
function upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$file_data = array('upload_data' => $this->upload->data());
$data['img'] = base_url().'/images/'.$file_data['file_name'];
echo json_encode($data);
}
}
}
?>
```
Here is my View:
```
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE-9"/>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data" >
Select File To Upload:<br />
<input type="file" name="userfile" />
<br /><br />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
</body>
</html>
```
Can anyone help me to solve this problem? I appreciate any help :)
|
2016/01/13
|
[
"https://Stackoverflow.com/questions/34761051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4800314/"
] |
```
import jenkins.model.*
import java.util.logging.Logger
def logger = Logger.getLogger("")
def installed = false
def initialized = false
def pluginParameter="gitlab-plugin hipchat swarm"
def plugins =pluginParameter.split()
logger.info("" + plugins)
def instance =Jenkins.getInstance()
def pm = instance.getPluginManager()
def uc =instance.getUpdateCenter()
uc.updateAllSites()
plugins.each { logger.info("Checking " + it) if
(!pm.getPlugin(it)) {
logger.info("Looking UpdateCenter for " + it)
if (!initialized) {
uc.updateAllSites()
initialized = true
}
def plugin = uc.getPlugin(it)
if (plugin) {
logger.info("Installing " + it)
plugin.deploy()
installed = true
} } }
if (installed)
{
logger.info("Plugins installed, initializing a restart!")
instance.save()
instance.doSafeRestart()
}
```
|
You will need jenkins-cli.jar file.
It can be downloaded from ${JENKINSURL}/jnlpJars/jenkins-cli.jar
```
wget http://localhost:8080/jnlpJars/jenkins-cli.jar
```
To install a plugin :
```
java -jar jenkins-cli.jar -auth ${USER}:${PASSWORD} -s ${JENKINSURL} install-plugin ${PLUGIN_NAME}
```
If you dont provide auth you will get error:
>
> ERROR: anonymous is missing the Overall/Read permission
>
>
>
|
34,761,051 |
I'm trying to upload an image using codeigniter and no matter what
I keep getting "You did not select a file to upload" error.
Here's my Controller:
```
<?php
class Post extends CI_Controller {
function __construct(){
parent::__construct();
}
function index(){
$this->load->view('upload_form', array('error' => ''));
}
function upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$file_data = array('upload_data' => $this->upload->data());
$data['img'] = base_url().'/images/'.$file_data['file_name'];
echo json_encode($data);
}
}
}
?>
```
Here is my View:
```
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE-9"/>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data" >
Select File To Upload:<br />
<input type="file" name="userfile" />
<br /><br />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
</body>
</html>
```
Can anyone help me to solve this problem? I appreciate any help :)
|
2016/01/13
|
[
"https://Stackoverflow.com/questions/34761051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4800314/"
] |
Since Sept 2019, you can also use the [Plugin Installation Manager Tool](https://github.com/jenkinsci/plugin-installation-manager-tool). It takes a yaml file listing the plugins, and downloads plugins to a folder of your choice. There is no need to have a running Jenkins instance. You can specify the plugin versions in the yaml file, but be aware of [JENKINS-60205](https://issues.jenkins-ci.org/browse/JENKINS-60205).
Get the plugin manager:
```
version=1.0.1
curl \
-L \
-X GET "https://github.com/jenkinsci/plugin-installation-manager-tool/releases/download/plugin-management-parent-pom-$version/jenkins-plugin-manager-$version.jar" \
-o jenkins-plugin-manager-$version.jar
```
Download the plugins:
```
java -jar jenkins-plugin-manager-$version.jar \
--plugin-download-directory pluginsFolder \
--plugin-file plugins.yml \
--war jenkins.war
```
The plugins are in the `pluginsFolder`.
|
You will need jenkins-cli.jar file.
It can be downloaded from ${JENKINSURL}/jnlpJars/jenkins-cli.jar
```
wget http://localhost:8080/jnlpJars/jenkins-cli.jar
```
To install a plugin :
```
java -jar jenkins-cli.jar -auth ${USER}:${PASSWORD} -s ${JENKINSURL} install-plugin ${PLUGIN_NAME}
```
If you dont provide auth you will get error:
>
> ERROR: anonymous is missing the Overall/Read permission
>
>
>
|
7,781,155 |
What's the difference between GTK+ and GTK# and which one is "more multiplatform" ?
Which one is best supported - with the least effort by a mac osx final user ?
Important for me to get out of confusion:
Does .net use gtk# to show forms on non windows platforms ?
|
2011/10/15
|
[
"https://Stackoverflow.com/questions/7781155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/988591/"
] |
GTK# is .net wrapper for GTK+,
GKT# sharp can run on mono or .net.
.net runs on windows platforms only.
mono is an opensource implementation of .net, it is cross platform and can run on linux, Mac OSX, windows, android and IOS. However the GTK+ is only available on linux, windows and Mac
[MonoDevelop](http://monodevelop.com/) is a great example of a GTK# application which runs on Linux, Windows and Mac OSX. On windows it uses .net on Linux and Mac OSX it uses mono.
Because GTK# is a wrapper for GTK+, GTK# can only run on platforms which are supported by GTK+.
However unlike GTK+ program written in c or c++, GTK# applications do not need to be rebuilt for each operating system. So you can deploy the same binaries to all three platforms and run them on either mono or .net.
GTK# applications are more cross platform then GTK+ applications because the same binaries can be run on all three platforms and both runtimes (mono and .net) without needing a recompile.
|
Gtk# is just a set of bindings for Mono/.NET that allows you to use Gtk+.
.NET does not use GTK#, however, Mono does use Gtk#. You can use Gtk# with .NET, but .NET does not run on any other platforms. Mono != .NET, it is close but they are not equal.
|
1,053,252 |
My server time is in GMT, and I do the following whenever someone comes online.
```
// Set a default timezone
$defaultTimeZone = 'America/Toronto';
// load the user, if they are online...
$onlineUser = new user();
if (isset($_SESSION['user_id']))
{
if ($onlineUser->loadUser($_SESSION['user_id']))
{
$defaultTimeZone = $onlineUser->timeZone;
}
}
// set time zones
date_default_timezone_set($defaultTimeZone);
$db->query("SET SESSION time_zone = '".$defaultTimeZone."'");
```
So, my problem is this... whenever someone does something it stores the date/time in the users local time... causing me a whole wack of issues.
All I want is for everything to be stored in GMT, but have the users see & interact with the data in their local time zone.
**EDIT:**
Here is how I am updating the users status:
```
public function updateStatus()
{
global $db, $common, $config;
// update the user record
$data = array(
'date_last_active' => new Zend_Db_Expr('NOW()')
);
$db->update('users', $data, 'user_id='.$this->userId);
}
```
Here is my function to turn a date stamp into seconds...
```
public function dateTimeToUnixTime($dateString)
{
if (strlen($dateString) < 10)
{
return "";
}
$parseDateTime = split(" ", $dateString);
$parseDate = split("-", $parseDateTime[0]);
if (isset($parseDateTime[1]))
{
$parseTime = split(":", $parseDateTime[1]);
}
else
{
$parseTime = split(":", "00:00:00");
}
return mktime($parseTime[0], $parseTime[1], $parseTime[2], $parseDate[1], $parseDate[2], $parseDate[0]);
}
```
And finally, how I am comparing the dates:
```
$date = $oUser->dateLastActive;
$lastSeen = abs($common->dateTimeToUnixTime(date('Y-m-d H:i:s')) - $common->dateTimeToUnixTime($date));
if ($lastSeen < 300 )
{
echo "<font size='1' color='green'><strong>Online</strong></font>";
}
if ($lastSeen >= 300)
{
echo "<font size='1' color='black'><strong>Offline</strong></font>";
}
```
|
2009/06/27
|
[
"https://Stackoverflow.com/questions/1053252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68452/"
] |
The trick here is to know what column type `date_last_active` is. I've had enough experience with `TIMESTAMP` and `DATETIME` to know that one translates (and honors) the MySQL time\_zone session variable, the other doesn't.
```
mysql> SET SESSION time_zone = 'America/New_York';
Query OK, 0 rows affected (0.00 sec)
mysql> create table timetest ( dt datetime NULL, ts timestamp NOT NULL DEFAULT 0 );
Query OK, 0 rows affected (0.06 sec)
mysql> INSERT INTO timetest ( dt, ts ) VALUES ( UTC_TIMESTAMP(), UTC_TIMESTAMP() );
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO timetest ( dt, ts ) VALUES ( NOW(), NOW() );
Query OK, 1 row affected (0.00 sec)
mysql> SELECT * FROM timetest;
+---------------------+---------------------+
| dt | ts |
+---------------------+---------------------+
| 2009-06-27 17:53:51 | 2009-06-27 17:53:51 |
| 2009-06-27 13:53:54 | 2009-06-27 13:53:54 |
+---------------------+---------------------+
2 rows in set (0.00 sec)
mysql> set session time_zone='UTC';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT * FROM timetest;
+---------------------+---------------------+
| dt | ts |
+---------------------+---------------------+
| 2009-06-27 17:53:51 | 2009-06-27 21:53:51 |
| 2009-06-27 13:53:54 | 2009-06-27 17:53:54 |
+---------------------+---------------------+
2 rows in set (0.00 sec)
```
So, here is what I do:
* When inserting into the database, use UTC in PHP and in MySQL. In `my.cnf` I have: `time_zone=UTC` to avoid any issues in MySQL, and in PHP I `date_default_timezone_set('UTC')`.
* Use `UTC_TIMESTAMP()` instead of `NOW()` - one is UTC, one uses the local (session) time zone. If you're following the first point, above, use UTC\_TIMESTAMP().
* When selecting to display to the user, `set time_zone='`*local\_time\_zone*`'` before displaying anything.
* If you have to display stuff, then update, make sure to bracket your calls with the appropriate timezone changes in PHP and MySQL.
Hopefully that's enough to figure out how to approach this. Let me know if you have further questions.
|
I think Mysql's NOW() function stores the current time zone, which is definitely a hassle, I would check out CONVERT\_TZ(dt,from\_tz,to\_tz), this could solve your issue, also I believe php's time() returns server time, you could store this instead. the only drawback is you'd either have to convert the returned value to a datetime/timestamp compatible value, or store it as a varchar. the drawback to using convert\_tz is you could end up with some ugly queries, and you'd have to figure out the current time zone every time you used it.
|
1,053,252 |
My server time is in GMT, and I do the following whenever someone comes online.
```
// Set a default timezone
$defaultTimeZone = 'America/Toronto';
// load the user, if they are online...
$onlineUser = new user();
if (isset($_SESSION['user_id']))
{
if ($onlineUser->loadUser($_SESSION['user_id']))
{
$defaultTimeZone = $onlineUser->timeZone;
}
}
// set time zones
date_default_timezone_set($defaultTimeZone);
$db->query("SET SESSION time_zone = '".$defaultTimeZone."'");
```
So, my problem is this... whenever someone does something it stores the date/time in the users local time... causing me a whole wack of issues.
All I want is for everything to be stored in GMT, but have the users see & interact with the data in their local time zone.
**EDIT:**
Here is how I am updating the users status:
```
public function updateStatus()
{
global $db, $common, $config;
// update the user record
$data = array(
'date_last_active' => new Zend_Db_Expr('NOW()')
);
$db->update('users', $data, 'user_id='.$this->userId);
}
```
Here is my function to turn a date stamp into seconds...
```
public function dateTimeToUnixTime($dateString)
{
if (strlen($dateString) < 10)
{
return "";
}
$parseDateTime = split(" ", $dateString);
$parseDate = split("-", $parseDateTime[0]);
if (isset($parseDateTime[1]))
{
$parseTime = split(":", $parseDateTime[1]);
}
else
{
$parseTime = split(":", "00:00:00");
}
return mktime($parseTime[0], $parseTime[1], $parseTime[2], $parseDate[1], $parseDate[2], $parseDate[0]);
}
```
And finally, how I am comparing the dates:
```
$date = $oUser->dateLastActive;
$lastSeen = abs($common->dateTimeToUnixTime(date('Y-m-d H:i:s')) - $common->dateTimeToUnixTime($date));
if ($lastSeen < 300 )
{
echo "<font size='1' color='green'><strong>Online</strong></font>";
}
if ($lastSeen >= 300)
{
echo "<font size='1' color='black'><strong>Offline</strong></font>";
}
```
|
2009/06/27
|
[
"https://Stackoverflow.com/questions/1053252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68452/"
] |
The trick here is to know what column type `date_last_active` is. I've had enough experience with `TIMESTAMP` and `DATETIME` to know that one translates (and honors) the MySQL time\_zone session variable, the other doesn't.
```
mysql> SET SESSION time_zone = 'America/New_York';
Query OK, 0 rows affected (0.00 sec)
mysql> create table timetest ( dt datetime NULL, ts timestamp NOT NULL DEFAULT 0 );
Query OK, 0 rows affected (0.06 sec)
mysql> INSERT INTO timetest ( dt, ts ) VALUES ( UTC_TIMESTAMP(), UTC_TIMESTAMP() );
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO timetest ( dt, ts ) VALUES ( NOW(), NOW() );
Query OK, 1 row affected (0.00 sec)
mysql> SELECT * FROM timetest;
+---------------------+---------------------+
| dt | ts |
+---------------------+---------------------+
| 2009-06-27 17:53:51 | 2009-06-27 17:53:51 |
| 2009-06-27 13:53:54 | 2009-06-27 13:53:54 |
+---------------------+---------------------+
2 rows in set (0.00 sec)
mysql> set session time_zone='UTC';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT * FROM timetest;
+---------------------+---------------------+
| dt | ts |
+---------------------+---------------------+
| 2009-06-27 17:53:51 | 2009-06-27 21:53:51 |
| 2009-06-27 13:53:54 | 2009-06-27 17:53:54 |
+---------------------+---------------------+
2 rows in set (0.00 sec)
```
So, here is what I do:
* When inserting into the database, use UTC in PHP and in MySQL. In `my.cnf` I have: `time_zone=UTC` to avoid any issues in MySQL, and in PHP I `date_default_timezone_set('UTC')`.
* Use `UTC_TIMESTAMP()` instead of `NOW()` - one is UTC, one uses the local (session) time zone. If you're following the first point, above, use UTC\_TIMESTAMP().
* When selecting to display to the user, `set time_zone='`*local\_time\_zone*`'` before displaying anything.
* If you have to display stuff, then update, make sure to bracket your calls with the appropriate timezone changes in PHP and MySQL.
Hopefully that's enough to figure out how to approach this. Let me know if you have further questions.
|
I have spend almost half day to solve this problem and I think I need to help others. So I am providing you some guide line to avoid problem regarding timezone.
>
> First of all you have two options either use **MYSQL TIMEZONE** or **PHP
> TIMEZONE** don't mix it with each other if you want stay away from timezone nightmares.
>
>
>
IF YOU CHOOSE **MYSQL TIMEZONE:**
FOR INSERTION:
```
fieldname: yourfieldname
datatype: timestamp
default: CURRENT_TIMESTAMP
```
FOR UPDATION:
```
UPDATE YOUR_TABLE SET youfieldname = NOW() WHERE CONDITION;
```
FOR SELECTION:
The only thing you need to do is set your require timezone for your application needs mysql automatically convert stored timestamp to your specified timezone.
```
mysql>SET SESSION time_zone='offset';
mysql>SELECT NOW();
```
offset example: **+05:30** for India same way find offset for your area region.
Now you will get your desired date and time from mysql.
IF YOU CHOOSE **PHP TIMEZONE**:
Simply just set your desire timezone using this function:
```
date_default_timezone_set('America/Los_Angeles');
```
FOR INSERTION:
**fieldname:** yourfieldname
**datatype:** datetime
Use PHP date function to store date and time:
```
$sql = "INSERT INTO timetest ( YOURDATETIMEFIELD ) VALUES ('".date('Y-m-d H:i:s')."')";
```
FOR UPDATION:
```
$sql = "UPDATE YOUR_TABLE SET yourdatetimefield = '".date('Y-m-d H:i:s')."'";
```
FOR SELECTION:
```
$sql = "SELECT yourdatetimefield FROM yourtable";
```
I hope this help you.
|
13,018,081 |
I have a REST service running on ASP.NET 3.5 and I have multiple concurrent asynchronous calls from the client hitting the WCF service. They all get serialized (sequential) instead of parallel calls. Here are my settings
`InstanceContextMode = InstanceContextMode.PerSession`
`ConcurrencyMode = ConcurrencyMode.Multiple`
web.config - throttling values
`<serviceThrottling maxConcurrentCalls="64" maxConcurrentInstances="64" maxConcurrentSessions="64"/>`
There are no session writes in the code.
What am I missing to make my WCF concurrent?
|
2012/10/22
|
[
"https://Stackoverflow.com/questions/13018081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84793/"
] |
Well if you don't mind passing the entity as a generic type instead of a string parameter you could try:
For Linq-to-Entities:
```
public void Distribute<TEntity>(ComboBox cb,
DbContext db,
string valueField,
string displayField)
where TEntity : class
{
//Publishers table
var data = db.Set<TEntity>() as IEnumerable;
cb.ValueMember = valueField;
cb.DisplayMember = displayField;
cb.DataSource = data;
}
```
For Linq-to-SQL:
```
public void Distribute<TEntity>(ComboBox cb,
DataContext db,
string valueField,
string displayField)
where TEntity : class
{
//Publishers table
var data = db.GetTable<TEntity>() as IEnumerable;
cb.ValueMember = valueField;
cb.DisplayMember = displayField;
cb.DataSource = data;
}
```
|
i tried few things and it works but i'm sure about it's code:
```
public void Distribute<TEntity>(ComboBox cb, BooksDBDataContext db, string valueField, string displayField)
where TEntity : class
{
var data = db.GetTable<TEntity>();
cb.ValueMember = valueField;
cb.DisplayMember = displayField;
cb.DataSource = data;
}
```
|
47,535,753 |
I am at a loss as how to complete this task. I need to count a range in a sheet if at least one of the words in a cell in that range matches an array. For example, if cell `"B2"` has a sentence with one of the words that is in the array then count as one, and simply `countif` a range if it matches with an array. My code will better display my question, so I apologize if this is at all confusing.
```
With ThisWorkbook
Dim Keywords As Variant
Dim iVal As Double
keyword = Array("*cold*", "*hot*", "*warm*", "*cool*", _
"*temp*", "*thermostat*", "*heat*", "*temperature*", _
"*not working*", "*see above*", "*broken*", "*freezing*", _
"*warmer*", "*air conditioning*", "*humidity*", _
"*humid*")
iVal=Application.WorksheetFunction.CountIf(Range("B2",Range("B2").End(xlDown)),keyword)
Dim rep As Worksheet
Set rep = Worksheets("Report")
rep.Range("A1") = iVal
End With
```
As I show, If one of those words in the array match in a cell in the range defined, `Range("B2", Range("B2").End(xlDown))`, then count and display value in the `Worksheets("Report").Range("A1")`. Any and all help is appreciated, thank you.
|
2017/11/28
|
[
"https://Stackoverflow.com/questions/47535753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8396248/"
] |
You need to compare two lists for values within each other - your `Range` and the `Array`. The easiest way to do so is through nested loop. Like this:
```
Sub TestMe()
With ThisWorkbook
Dim Keywords As Variant
Dim iVal As Long
Dim myRange As Range
Dim myCell As Range
Dim bCount As Boolean
Dim myVal As Variant
keyword = Array("cold", "hot", "warm", "cool", _
"temp", "thermostat", "heat", "temperature", _
"not working", "see above", "broken", "freezing", _
"warmer", "air conditioning", "humidity", _
"humid")
Set myRange = Columns(2).SpecialCells(2)
For Each myCell In myRange
bCount = False
For Each myVal In keyword
If InStr(1, myCell, myVal, vbTextCompare) Then bCount = True
Next myVal
If bCount Then iVal = iVal + 1
Next myCell
Debug.Print iVal
End With
End Sub
```
The count is done whenever the flag `bCount` is set to `True`. It is reset to `False` by every iteration of the outer loop.
I would remove the `*`, as far as I am using the `InStr()` to make the check and the stars are a bit useless there.
Furthermore `Columns(2).SpecialCells(2)` returns a range, consisting only of values, which are non-formulas and non-empty in Column `B`.
|
This was my answer much the same as @Vityata. Note you can use his suggestion of SpecialCells to ignore blanks when reading the range into the Array.
Note it looks for `"*Cold*"` if that is what is in the array. Put simply `"Cold"` etc ,in the array, if that is the word being looked for within the cell.
```
Option Explicit
Public Sub test()
Dim Keywords As Variant
Dim iVal As Long
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Sheets(2)
Keywords = Array("*cold*", "*hot*", "*warm*", "*cool*", _
"*temp*", "*thermostat*", "*heat*", "*temperature*", _
"*not working*", "*see above*", "*broken*", "*freezing*", _
"*warmer*", "*air conditioning*", "*humidity*", _
"*humid*")
With ws
Dim rangetoCheck()
Dim counter1 As Long
Dim counter2 As Long
Dim totalCount As Long
iVal = 0
rangetoCheck = .Range("B2", .Range("B2").End(xlDown)).value
For counter1 = LBound(rangetoCheck, 1) To UBound(rangetoCheck, 1)
For counter2 = LBound(Keywords) To UBound(Keywords)
If InStr(1, rangetoCheck(counter1, 1), Keywords(counter2), vbBinaryCompare) Then
iVal = iVal + 1
Exit For
End If
Next counter2
Next counter1
End With
MsgBox iVal
End Sub
```
|
69,367,914 |
Validator struct
```
type RegisterValidator struct {
Name string `form:"name" json:"name" binding:"required,min=4,max=50"`
Email string `form:"email" json:"email" binding:"required,email,min=4,max=50"`
Password string `form:"password" json:"password" binding:"required,min=8,max=50"`
MobileCountryCode int `form:"mobile_country_code" json:"mobile_country_code" binding:"required,gte=2,lt=5"`
Mobile int `form:"mobile" json:"mobile" binding:"required,gte=5,lt=15"`
UserModel users.User `json:"-"`
}
```
Formatting a custom error as below:
```
type CustomError struct {
Errors map[string]interface{} `json:"errors"`
}
func NewValidatorError(err error) CustomError {
res := CustomError{}
res.Errors = make(map[string]interface{})
errs := err.(validator.ValidationErrors)
for _, v := range errs {
param := v.Param()
field := v.Field()
tag := v.Tag()
if param != "" {
res.Errors[field] = fmt.Sprintf("{%v: %v}", tag, param)
} else {
res.Errors[field] = fmt.Sprintf("{key: %v}", tag)
}
}
return res
}
```
works when data sent is
```
{
"email": "[email protected]",
"name": "John Doe",
"mobile_country_code": 1,
"mobile": 1234567
}
```
but sending an invalid type
```
{
"email": "[email protected]",
"name": "John Doe",
"mobile_country_code": "1",
"mobile": 1234567
}
```
throws the error `interface conversion: error is *json.UnmarshalTypeError, not validator.ValidationErrors`
This question is related to this one: [How to assert error type json.UnmarshalTypeError when caught by gin c.BindJSON](https://stackoverflow.com/questions/64278486/how-to-assert-error-type-json-unmarshaltypeerror-when-caught-by-gin-c-bindjson)
however the answers do not make sense.
|
2021/09/28
|
[
"https://Stackoverflow.com/questions/69367914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1110309/"
] |
As the exception suggests, the following line failed type conversion
```
errs := err.(validator.ValidationErrors)
```
A different type of error must have got passed into the function that is not *`validator.ValidationErrors`*.
So either make sure other errors won't be passed into `NewValidatorError`. Or do a safer type check like:
```
errs, ok := err.(validator.ValidationErrors)
if !ok {
// handles other err type
}
```
More info: [A Tour of Go - type assertions](https://tour.golang.org/methods/15), [A Tour of Go - type switches](https://tour.golang.org/methods/16)
|
I added a check for the UnmarshalTypeError as below:
```
if reflect.TypeOf(err).Elem().String() == "json.UnmarshalTypeError" {
errs := err.(*json.UnmarshalTypeError)
res.Errors[errs.Field] = fmt.Sprintf("{key: %v}", errs.Error())
return res
}
errs := err.(validator.ValidationErrors)
```
I guess Golang is strict when json is type-hinted. It has to be the exact type otherwise it will throw an `UnmarshalTypeError` error.
|
1,157,209 |
How to connect to a new WiFi by entering a password using CMD?
For my school project I have decided to make a WiFi\_manager program using cmd.
I know to display all WiFi networks (in cmd):
```
netsh wlan show networks
```
Now let's say I want to connect to a WiFi network that I never connected to before. And that WiFi is not added any profiles also.
But I know the password for the WiFi.
**What will be the command line for that.**
Given the information on WiFi network below:
```
SSID 3 : Ismail
Network type : Infrastructure
Authentication : WPA-Personal
Encryption : CCMP
and password is "Thanks_bro".
```
I search this question already in google but none of them say the right way and most of them are related to hacking and connecting a WiFi without password etc. So I posted this question to the BEST programmers out here to answer!
If not possible, can we do using C++?
|
2016/12/16
|
[
"https://superuser.com/questions/1157209",
"https://superuser.com",
"https://superuser.com/users/675905/"
] |
Unfortunately if you want to connect to a wireless network from command prompt that requires a passcode it won't happen.
First of all to connect to a wireless network with a password you need to setup a profile or you need to have an already set up profile you can check that profile by using
```
Netsh wlan show profiles
```
To see your profile you need to be connected to that wifi at least once .
The alternative way is to have a generated created xml profile and use the following command to connect to it :
```
netsh wlan connect ssid=YOURSSID name=PROFILENAME interface="WIRELESS NETWORK CONNECTION"
```
More info could be found [here](http://www.hanselman.com/blog/HowToConnectToAWirelessWIFINetworkFromTheCommandLineInWindows7.aspx) in this article
|
You can definitely connect to a password-protected wireless network using only the command prompt.
First, create an XML file with your Wi-Fi connection details. Use this as a template, replacing `{SSID}` (appears twice) and `{PASSWORD}` with your own:
```
<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>{SSID}</name>
<SSIDConfig>
<SSID>
<name>{SSID}</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>{PASSWORD}</keyMaterial>
</sharedKey>
</security>
</MSM>
<MacRandomization xmlns="http://www.microsoft.com/networking/WLAN/profile/v3">
<enableRandomization>false</enableRandomization>
</MacRandomization>
</WLANProfile>
```
Next, create your batch file (again, replace `{SSID}` with your own):
```
@echo off
netsh wlan add profile filename="{whatever you named the file}.xml"
netsh wlan connect name="{SSID}"
echo.
pause
```
Inspired by this Q&A here (and my own need to do this today):
<https://superuser.com/a/1275748/243707>
|
68,037,946 |
\*\*for eg
123==
312
how to move the last digit in the first position in C++ without using if statement
```
#include <iostream>
using namespace std;
int main(){
int n=123;
while(n!=0){
}
cout<<n;//==312
}
```
|
2021/06/18
|
[
"https://Stackoverflow.com/questions/68037946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15355017/"
] |
We can rewrite the file writing using Win32 API:
```
void writeRaw(unsigned int thread)
{
const auto str = "test_" + std::to_string(thread) + ".txt";
auto hFile = CreateFileA(str.c_str(), GENERIC_WRITE,
FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, 0, nullptr);
DWORD ret{};
WriteFile(hFile, str.data(), str.size(), &ret, nullptr);
CloseHandle(hFile);
}
```
Running the test still gives a file share violation due to the way windows works. When the last handle is closed, filesystem driver performs IRP\_MJ\_CLEANUP IOCTL to finish processing anything related to the file.
Antivirus software, for instance, would attempt to scan the file (and incidentally holds the lock on it =) ). Additionally documentation [MSDN IRP\_MJ\_CLEANUP](https://learn.microsoft.com/en-us/windows-hardware/drivers/ifs/irp-mj-cleanup) states that:
>
> It is important to note that when all handles to a file object have been closed, this does not necessarily mean that the file object is no longer being used. System components, such as the Cache Manager and the Memory Manager, might hold outstanding references to the file object. These components can still read to or write from a file, even after an IRP\_MJ\_CLEANUP request is received.
>
>
>
Conclusion: It is expected that to receive a file share violation in windows if a process tries to do something with the file shortly after closing the handle as the underlying system components are still processing the file close request.
|
At least on VS 2017, I can confirm the file is closed from your snippet. (In destructor of ofstream, the code calls fclose on the handle).
I think however, that the issue is not in the C++ code, but the behavior of the OS.
With Windows, the act of removing a file which the OS thinks is open, will be blocked. In Unix the behavior of unlinking a file from a directory, is to allow existing handles to continue acting the orphaned files. So in unix the operation could never be a sharing violation, as the act of unlinking a file is a different operation. linux semantics can be opted into for recent windows 10 builds.
procmon on Windows has a given altitude. That means that any operation which is perfformed by virus scanners may be hidden to procmon, and it would give a false answer.
A process can also duplicate a handle on the open file, and that would also cause this issue, but not show the handle being closed.
|
68,037,946 |
\*\*for eg
123==
312
how to move the last digit in the first position in C++ without using if statement
```
#include <iostream>
using namespace std;
int main(){
int n=123;
while(n!=0){
}
cout<<n;//==312
}
```
|
2021/06/18
|
[
"https://Stackoverflow.com/questions/68037946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15355017/"
] |
At least on VS 2017, I can confirm the file is closed from your snippet. (In destructor of ofstream, the code calls fclose on the handle).
I think however, that the issue is not in the C++ code, but the behavior of the OS.
With Windows, the act of removing a file which the OS thinks is open, will be blocked. In Unix the behavior of unlinking a file from a directory, is to allow existing handles to continue acting the orphaned files. So in unix the operation could never be a sharing violation, as the act of unlinking a file is a different operation. linux semantics can be opted into for recent windows 10 builds.
procmon on Windows has a given altitude. That means that any operation which is perfformed by virus scanners may be hidden to procmon, and it would give a false answer.
A process can also duplicate a handle on the open file, and that would also cause this issue, but not show the handle being closed.
|
The most probable cause of the problem is that when you delete a file in windows ,it isn't immediatly deleted (it's just flagged for deletion). It can/will take some milliseconds (up to seconds if you're very unlucky) for it to be actually deleted.
Source : Niall Douglas in “Better mutual exclusion on the filesystem using Boost.AFIO" about 10m:10s <https://www.youtube.com/watch?v=9l28ax3Zq0w>
|
68,037,946 |
\*\*for eg
123==
312
how to move the last digit in the first position in C++ without using if statement
```
#include <iostream>
using namespace std;
int main(){
int n=123;
while(n!=0){
}
cout<<n;//==312
}
```
|
2021/06/18
|
[
"https://Stackoverflow.com/questions/68037946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15355017/"
] |
We can rewrite the file writing using Win32 API:
```
void writeRaw(unsigned int thread)
{
const auto str = "test_" + std::to_string(thread) + ".txt";
auto hFile = CreateFileA(str.c_str(), GENERIC_WRITE,
FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, 0, nullptr);
DWORD ret{};
WriteFile(hFile, str.data(), str.size(), &ret, nullptr);
CloseHandle(hFile);
}
```
Running the test still gives a file share violation due to the way windows works. When the last handle is closed, filesystem driver performs IRP\_MJ\_CLEANUP IOCTL to finish processing anything related to the file.
Antivirus software, for instance, would attempt to scan the file (and incidentally holds the lock on it =) ). Additionally documentation [MSDN IRP\_MJ\_CLEANUP](https://learn.microsoft.com/en-us/windows-hardware/drivers/ifs/irp-mj-cleanup) states that:
>
> It is important to note that when all handles to a file object have been closed, this does not necessarily mean that the file object is no longer being used. System components, such as the Cache Manager and the Memory Manager, might hold outstanding references to the file object. These components can still read to or write from a file, even after an IRP\_MJ\_CLEANUP request is received.
>
>
>
Conclusion: It is expected that to receive a file share violation in windows if a process tries to do something with the file shortly after closing the handle as the underlying system components are still processing the file close request.
|
The most probable cause of the problem is that when you delete a file in windows ,it isn't immediatly deleted (it's just flagged for deletion). It can/will take some milliseconds (up to seconds if you're very unlucky) for it to be actually deleted.
Source : Niall Douglas in “Better mutual exclusion on the filesystem using Boost.AFIO" about 10m:10s <https://www.youtube.com/watch?v=9l28ax3Zq0w>
|
30,451,782 |
Here is the jsFiddle for what I have at the moment: <https://jsfiddle.net/vst5fky5/>
I am redoing a Flash section in jQuery. There is a logo and 7 inline list items (navigation) that I need to animate from the top. I want to use jQuery to add top:-5em at the beginning, then have them come down one by one.
Nothing is working. Note: the logo click function is only to test, I would like to have it change CSS, then run through the animations on page load.
```
$(document).ready(function(){
$('.nav a li').css("top:","-5em");
$('#logo').click(function(){
$(".nav a li").animate({top:$(this).offset().top}, 'slow');
});
});
```
|
2015/05/26
|
[
"https://Stackoverflow.com/questions/30451782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959040/"
] |
You can use [ngClass](https://docs.angularjs.org/api/ng/directive/ngClass)
>
> The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.
>
>
>
Since You are using [angularjs](/questions/tagged/angularjs "show questions tagged 'angularjs'") I would recommend you to to achieive it using Angular
*HTML*
```
<ul>
<li ng-repeat="ls in list" ng-class="{ 'active' : ls == selectedItem }" ng-click="activeMenu(ls)">{{ls}}</li>
</ul>
```
*Script*
```
$scope.list = ["JHON", "Tom", "Dove", "Sam"]
$scope.selectedItem = "Dove";
$scope.activeMenu = function(ls){
$scope.selectedItem = ls;
}
```
[**DEMO**](http://jsfiddle.net/satpalsingh/q67gz7d8/)
|
Assuming that you are trying to search Dove in your `li` markup. For that Try below code.
```
var yourQuery ="dove";
$('.nav').on('click', 'li', function(){
$('.nav li').removeClass('active');
$("li:contains('" + yourQuery + "')").addClass('active');
});
```
|
17,834,604 |
I have a simple question for You.
It is possible to return to top after click on image, which is reference to jquery content?
For example: When I choose an image in "Portfolio" on <http://dash.com.pl/> I need to return to top of this (#portfolio). Thank You for Your help.
|
2013/07/24
|
[
"https://Stackoverflow.com/questions/17834604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148811/"
] |
You don't really need javascript for that, anchors will scroll to an ID if you supply a hash as the href ?
```
<a href="#portfolio"><img src="image/to/click.png" /></a>
```
doing just `<a href="#"></a>` scrolls to the top, and for other pages it's the same
`<a href="http://mysite.com/some/other/page/#divToScrollTo"></a>`
|
You could just use a link attribute
```
<div id="portfolio">...</div>
<a href="#portfolio">
<img src="screen.png">
</a>
```
With jquery you can get element's position and scorll to the top
```
scroll(0, $('#portfolio').position().top)
```
Update:
Correct the jquery scroll example it need the x value.
|
17,834,604 |
I have a simple question for You.
It is possible to return to top after click on image, which is reference to jquery content?
For example: When I choose an image in "Portfolio" on <http://dash.com.pl/> I need to return to top of this (#portfolio). Thank You for Your help.
|
2013/07/24
|
[
"https://Stackoverflow.com/questions/17834604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148811/"
] |
You don't really need javascript for that, anchors will scroll to an ID if you supply a hash as the href ?
```
<a href="#portfolio"><img src="image/to/click.png" /></a>
```
doing just `<a href="#"></a>` scrolls to the top, and for other pages it's the same
`<a href="http://mysite.com/some/other/page/#divToScrollTo"></a>`
|
Done. Thank You everybody for Your help.
This code helped me:
```
$(document).ready(function(){
$(this).scrollTop(3200);
});
```
|
17,834,604 |
I have a simple question for You.
It is possible to return to top after click on image, which is reference to jquery content?
For example: When I choose an image in "Portfolio" on <http://dash.com.pl/> I need to return to top of this (#portfolio). Thank You for Your help.
|
2013/07/24
|
[
"https://Stackoverflow.com/questions/17834604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148811/"
] |
You could just use a link attribute
```
<div id="portfolio">...</div>
<a href="#portfolio">
<img src="screen.png">
</a>
```
With jquery you can get element's position and scorll to the top
```
scroll(0, $('#portfolio').position().top)
```
Update:
Correct the jquery scroll example it need the x value.
|
Done. Thank You everybody for Your help.
This code helped me:
```
$(document).ready(function(){
$(this).scrollTop(3200);
});
```
|
1,453,934 |
First off I wasn't sure if I am just stating that I am posting this question here because it appears in my differential equations course. (Although it seems rather like a physics question).
**Question**
After a mass m is attached to a spring is stretches s units and then hangs at rest in the equilibrium position. The spring is then set in motion. Let x(t) denote the directed distance of the mass beyond equilibrium position. If x(t) > 0 then the spring is stretched, if x(t) < 0 then the string is compressed. Assume that the only forces acting on the system are the weight of the mass and the restoring force of the stretched spring. Determine a differential equation for the displacement x(t) at time t.
**Attempt**
I drew a free body diagram and got $F\_{net} = ma = F\_{weight} + F\_{spring}$
From the question we have $F\_{weight} = +mg, F\_{spring} = -kx(t), k>0$
So obviously we should have $ma = -kx(t) + mg \equiv \frac{d^2}{dt^2}x(t) = -\frac{k}{m}x(t)+g$
But I am confused, because the answer is $\frac{d^2}{dt^2}x(t) = -\frac{k}{m}x(t)$
What happened to gravity? It is almost as if they only considered the spring force, and not weight at all!
|
2015/09/27
|
[
"https://math.stackexchange.com/questions/1453934",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/97407/"
] |
At equilibrium, the spring’s restorative force cancels that of gravity, so you have $mg=-ks$. Then $\ddot x=-(k/m)s-(k/m)x=-(k/m)(x+s)$. However, we want displacement from the (new) equilibrium position, so we move the origin to $s$, which doesn’t change the $\ddot x$ term. The spring behaves the same way as it would without the constant gravitational force (as long as the displacement stays in the region in which Hooke’s Law holds, of course), but with a new equilibrium point.
|
This really isn't an answer, but I am trying to help. If the mass is in the equilibrium position then the $F\_{net} = 0,$ i.e. the mass is not accelerating. Are you sure the answer is as you state it? I do not see a D.E. here.
|
46,561,381 |
**Scenario ->**
1. I am working on a branch different from master lets called it `Different`.
2. As I have created a pull request to review `Different` branch to all the team members.
3. One of the members checked in certain piece of code in the pull request and checked in the changes.
**Question 1:** What should I do here in order so that the changes made in the particular code should reflect with my workspace and local repo.
4. Lets suppose I forgot to do Question 1 and made some changes in my workspace according to the reviews of the other team members and changed many files as per the reviews.
5. Now when after committing those changes in the local repo I realized that I need to change the file which is changed by one of the reviewer, If I push this without doing the process then It will be unable to push to the remote repo, and major conflicts will occur.
**Question:2** How will I deal with point 5 without merging?
|
2017/10/04
|
[
"https://Stackoverflow.com/questions/46561381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2994849/"
] |
If you are trying to make this button act the same as the regular back button on the Android device itself you can make use of the onBackPressed() method
So your code would be something like this:
```
backbutton = (Button) findViewById(R.id.back_button);
backbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed(); //OPTION 1: If in an activity
getActivity().onBackPressed(); //OPTION 2: If in a fragment
}
});
```
Choose whichever line of code suits your needs depending on where you are, in activity vs in fragment.
|
Just finish activity
```
backbutton = (Button) findViewById(R.id.back_button);
backbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
```
|
46,561,381 |
**Scenario ->**
1. I am working on a branch different from master lets called it `Different`.
2. As I have created a pull request to review `Different` branch to all the team members.
3. One of the members checked in certain piece of code in the pull request and checked in the changes.
**Question 1:** What should I do here in order so that the changes made in the particular code should reflect with my workspace and local repo.
4. Lets suppose I forgot to do Question 1 and made some changes in my workspace according to the reviews of the other team members and changed many files as per the reviews.
5. Now when after committing those changes in the local repo I realized that I need to change the file which is changed by one of the reviewer, If I push this without doing the process then It will be unable to push to the remote repo, and major conflicts will occur.
**Question:2** How will I deal with point 5 without merging?
|
2017/10/04
|
[
"https://Stackoverflow.com/questions/46561381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2994849/"
] |
If you are trying to make this button act the same as the regular back button on the Android device itself you can make use of the onBackPressed() method
So your code would be something like this:
```
backbutton = (Button) findViewById(R.id.back_button);
backbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed(); //OPTION 1: If in an activity
getActivity().onBackPressed(); //OPTION 2: If in a fragment
}
});
```
Choose whichever line of code suits your needs depending on where you are, in activity vs in fragment.
|
You can simple call the `onBackPressed()` system method inside your `onClickListener` interface.
something like this:
```
backbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
```
|
46,561,381 |
**Scenario ->**
1. I am working on a branch different from master lets called it `Different`.
2. As I have created a pull request to review `Different` branch to all the team members.
3. One of the members checked in certain piece of code in the pull request and checked in the changes.
**Question 1:** What should I do here in order so that the changes made in the particular code should reflect with my workspace and local repo.
4. Lets suppose I forgot to do Question 1 and made some changes in my workspace according to the reviews of the other team members and changed many files as per the reviews.
5. Now when after committing those changes in the local repo I realized that I need to change the file which is changed by one of the reviewer, If I push this without doing the process then It will be unable to push to the remote repo, and major conflicts will occur.
**Question:2** How will I deal with point 5 without merging?
|
2017/10/04
|
[
"https://Stackoverflow.com/questions/46561381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2994849/"
] |
If you are trying to make this button act the same as the regular back button on the Android device itself you can make use of the onBackPressed() method
So your code would be something like this:
```
backbutton = (Button) findViewById(R.id.back_button);
backbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed(); //OPTION 1: If in an activity
getActivity().onBackPressed(); //OPTION 2: If in a fragment
}
});
```
Choose whichever line of code suits your needs depending on where you are, in activity vs in fragment.
|
Call this method `onBackPressed();` when you are click button.
```
backbutton = (Button) findViewById(R.id.back_button);
backbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});`
```
|
419,406 |
How to prevent chrome to take more than for example 4GB of ram. From time to time he decides to take something like 7GB (with 8GB RAM total) and makes my computer unusable.
Do you have any help.
PS: I even didn't have more than 10 tabs opened.
Edit: maybe I did ... something like 15. Anyway I want chrome to freeze or shutdown not to freeze the whole system.
|
2018/01/24
|
[
"https://unix.stackexchange.com/questions/419406",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/206961/"
] |
I believe you would want to use something like `cgroups` to limit resource usage for a individual process.
So you might want to do something like [this](https://askubuntu.com/questions/510913/how-to-set-a-memory-limit-for-a-specific-process#510936) except with
`cgcreate -g memory,cpu:chromegroup
cgset -r memory.limit_in_bytes=2048 chromegroup`
to create chromegroup and restrict the memory usage for the group to 2048 bytes
`cgclassify -g memory,cpu:chromegroup $(pidof chrome)`
to move the current chrome processes into the group and restrict their memory usage to the set limit
or just launch chrome within the group like
`cgexec -g memory,cpu:chromegroup chrome`
However, it's pretty insane that chrome is using that much memory in the first place. Try purging reinstalling / recompiling first to see if that doesn't fix the issue, because it really should not be using that much memory to begin with, and this solution is only a band-aid over the real problem.
|
I believe that you can use the **ulimit** utility.
The **-d** option:
[ulimit(3) man page](https://ss64.com/bash/ulimit.html)
You can lower your soft limit even without **root** access to the server.
|
419,406 |
How to prevent chrome to take more than for example 4GB of ram. From time to time he decides to take something like 7GB (with 8GB RAM total) and makes my computer unusable.
Do you have any help.
PS: I even didn't have more than 10 tabs opened.
Edit: maybe I did ... something like 15. Anyway I want chrome to freeze or shutdown not to freeze the whole system.
|
2018/01/24
|
[
"https://unix.stackexchange.com/questions/419406",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/206961/"
] |
I believe that you can use the **ulimit** utility.
The **-d** option:
[ulimit(3) man page](https://ss64.com/bash/ulimit.html)
You can lower your soft limit even without **root** access to the server.
|
Another way to improve Chrome's behavior is to simply configure the JavaScript heap limits. Add this to the command line when starting Chrome:
`--js-flags="--max_old_space_size=80 --max_semi_space_size=80"`
This tells the JavaScript GC to limit memory usage to under 160M
Of course you can change the numbers for your specific situation.
|
419,406 |
How to prevent chrome to take more than for example 4GB of ram. From time to time he decides to take something like 7GB (with 8GB RAM total) and makes my computer unusable.
Do you have any help.
PS: I even didn't have more than 10 tabs opened.
Edit: maybe I did ... something like 15. Anyway I want chrome to freeze or shutdown not to freeze the whole system.
|
2018/01/24
|
[
"https://unix.stackexchange.com/questions/419406",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/206961/"
] |
I believe you would want to use something like `cgroups` to limit resource usage for a individual process.
So you might want to do something like [this](https://askubuntu.com/questions/510913/how-to-set-a-memory-limit-for-a-specific-process#510936) except with
`cgcreate -g memory,cpu:chromegroup
cgset -r memory.limit_in_bytes=2048 chromegroup`
to create chromegroup and restrict the memory usage for the group to 2048 bytes
`cgclassify -g memory,cpu:chromegroup $(pidof chrome)`
to move the current chrome processes into the group and restrict their memory usage to the set limit
or just launch chrome within the group like
`cgexec -g memory,cpu:chromegroup chrome`
However, it's pretty insane that chrome is using that much memory in the first place. Try purging reinstalling / recompiling first to see if that doesn't fix the issue, because it really should not be using that much memory to begin with, and this solution is only a band-aid over the real problem.
|
Another way to improve Chrome's behavior is to simply configure the JavaScript heap limits. Add this to the command line when starting Chrome:
`--js-flags="--max_old_space_size=80 --max_semi_space_size=80"`
This tells the JavaScript GC to limit memory usage to under 160M
Of course you can change the numbers for your specific situation.
|
15,707,354 |

I'm having trouble with a custom header in my UITableView.
In InterfaceBuilder, I'm creating a XIB file with a view, and then subclassing it to UITableViewHeaderFooterView. I'm adding in some subviews. Nothing special.
In my viewDidLoad routine, I'm calling "registerNib:forHeaderFooterViewReuseIdentifier".
Then, in my delegate method, tableView:viewForHeaderInSection, I'm calling:
```
UITableViewHeaderFooterView* theView = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
```
The weird thing, is that I'm getting some extra lines of graphic, at the bottom edge of my header. It actually looks like the "normal" header view peeking through. I have no idea how to fix this. I've checked the size of the header view, vs the height of the section header. I've also put in code to force the size of the section-header to be the same as the the view's height. Yet, I still can't explain this.
The thing to notice, in the "Simulator - Bad" image is the gray color in between my custom header, and the red area. The red area is my first cell. So there are these gray lines that aren't in my custom header, nor in my first cell.
Thanks for any help.
|
2013/03/29
|
[
"https://Stackoverflow.com/questions/15707354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1435520/"
] |
>
> How do you control the index of a python for loop? (or can you? or should you?)
>
>
>
You *can't / shouldn't* - the loop control variable will be reassigned at the end of each iteration to the next element of whatever it is you are iterating over (so that `i = i + 1` has no effect, since `i` will be reassigned to something different for the next iteration anyway). If you want to control the index like that, you should use a `while`-loop:
```
i = 0
while i < 10:
print i
i = i + 1
```
Although, Python's [`range`](http://docs.python.org/2/library/functions.html#range) function is more flexible than you might realize. For instance, to iterate in steps of 2 you can simply use something like
```
for i in range(0, 10, 2):
print i
```
|
Check out the docs on `range` [here](http://docs.python.org/2/library/functions.html#range), or from the docstr:
```
range([start,] stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
```
To get range from 0-10, just do:
```
> for i in range(0, 11):
> print i
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
> 10
```
By the way, it's pointless to do the `i = i + 1`, cause every iteration in the for loop will change i again. Whatever you set it to in the loop, will get overwritten every time the loop starts over.
|
3,397,980 |
I'm trying to load all the collections eagerly, using [NHibernate 3 alpha 1](http://nhforge.org/media/p/690.aspx). I'm wondering if this the right way of using ThenFetch()?
Properties with plural names are collections. The others are just a single object.
```
IQueryable<T> milestoneInstances = Db.Find<T, IQueryable<T>>(db =>
from mi in db
where mi.RunDate == runDate
select mi).Fetch(mi => mi.Milestone)
.ThenFetch(m => m.PrimaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.SecondaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Predecessors)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Function)
.Fetch(mi => mi.Milestone)
.ThenFetchMany(m => m.Jobs)
.ThenFetch(j => j.Source)
;
```
I thought of asking this in the [NHibernate forums](http://groups.google.com/group/nhusers) but unfortunately access to google groups is forbidden from where I am. I know [Fabio](https://stackoverflow.com/users/360080/fabio-maulo) is here, so maybe the guys from the NHibernate team can shed some light on this?
Thanks
|
2010/08/03
|
[
"https://Stackoverflow.com/questions/3397980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23920/"
] |
Apparently, there's no "right" way to use `ThenFetch` in such a case. Your example works fine but SQL produced contains many joins to `Milestone`, which isn't that right.
Using `IQueryOver` instead of `IQueryable` allows you to use [complex syntax](https://nhibernate.jira.com/browse/NH-2972?focusedCommentId=22151#comment-22151) in `Fetch`:
```
Fetch(p => p.B)
Fetch(p => p.B.C) // if B is not a collection ... or
Fetch(p => p.B[0].C) // if B is a collection ... or
Fetch(p => p.B.First().C) // if B is an IEnumerable (using .First() extension method)
```
So in your case it would be:
```
query // = session.QueryOver<X>()
.Fetch(mi => mi.Milestone).Eager
.Fetch(mi => mi.Milestone.PrimaryOwners).Eager
.Fetch(mi => mi.Milestone.SecondaryOwners).Eager
.Fetch(mi => mi.Milestone.Predecessors).Eager
.Fetch(mi => mi.Milestone.Function).Eager
.Fetch(mi => mi.Milestone.Jobs).Eager
.Fetch(mi => mi.Milestone.Jobs.First().Source).Eager
```
|
The one thing you are missing is that you should use FetchMany() and ThenFetchMany() is the child property is a collection.
|
3,397,980 |
I'm trying to load all the collections eagerly, using [NHibernate 3 alpha 1](http://nhforge.org/media/p/690.aspx). I'm wondering if this the right way of using ThenFetch()?
Properties with plural names are collections. The others are just a single object.
```
IQueryable<T> milestoneInstances = Db.Find<T, IQueryable<T>>(db =>
from mi in db
where mi.RunDate == runDate
select mi).Fetch(mi => mi.Milestone)
.ThenFetch(m => m.PrimaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.SecondaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Predecessors)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Function)
.Fetch(mi => mi.Milestone)
.ThenFetchMany(m => m.Jobs)
.ThenFetch(j => j.Source)
;
```
I thought of asking this in the [NHibernate forums](http://groups.google.com/group/nhusers) but unfortunately access to google groups is forbidden from where I am. I know [Fabio](https://stackoverflow.com/users/360080/fabio-maulo) is here, so maybe the guys from the NHibernate team can shed some light on this?
Thanks
|
2010/08/03
|
[
"https://Stackoverflow.com/questions/3397980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23920/"
] |
The one thing you are missing is that you should use FetchMany() and ThenFetchMany() is the child property is a collection.
|
As leora said, make sure when fetching children collections that you use
```
FetchMany()
ThenFetchMany()
```
A new Fetch, should pick up from the root, but this does not always happen. Sometimes you need to create them as separate queries or use Criteria Futures to batch up a multiple fetch.
|
3,397,980 |
I'm trying to load all the collections eagerly, using [NHibernate 3 alpha 1](http://nhforge.org/media/p/690.aspx). I'm wondering if this the right way of using ThenFetch()?
Properties with plural names are collections. The others are just a single object.
```
IQueryable<T> milestoneInstances = Db.Find<T, IQueryable<T>>(db =>
from mi in db
where mi.RunDate == runDate
select mi).Fetch(mi => mi.Milestone)
.ThenFetch(m => m.PrimaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.SecondaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Predecessors)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Function)
.Fetch(mi => mi.Milestone)
.ThenFetchMany(m => m.Jobs)
.ThenFetch(j => j.Source)
;
```
I thought of asking this in the [NHibernate forums](http://groups.google.com/group/nhusers) but unfortunately access to google groups is forbidden from where I am. I know [Fabio](https://stackoverflow.com/users/360080/fabio-maulo) is here, so maybe the guys from the NHibernate team can shed some light on this?
Thanks
|
2010/08/03
|
[
"https://Stackoverflow.com/questions/3397980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23920/"
] |
The one thing you are missing is that you should use FetchMany() and ThenFetchMany() is the child property is a collection.
|
```
IQueryable<T> milestoneInstances = Db.Find<T, IQueryable<T>>(db =>
from mi in db
where mi.RunDate == runDate
select mi);
var fetch = milestoneInstances.Fetch(f => f.Milestone);
fetch.ThenFetch(f => f.PrimaryOwners);
fetch.ThenFetch(f => f.SecondaryOwners);
//...
```
|
3,397,980 |
I'm trying to load all the collections eagerly, using [NHibernate 3 alpha 1](http://nhforge.org/media/p/690.aspx). I'm wondering if this the right way of using ThenFetch()?
Properties with plural names are collections. The others are just a single object.
```
IQueryable<T> milestoneInstances = Db.Find<T, IQueryable<T>>(db =>
from mi in db
where mi.RunDate == runDate
select mi).Fetch(mi => mi.Milestone)
.ThenFetch(m => m.PrimaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.SecondaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Predecessors)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Function)
.Fetch(mi => mi.Milestone)
.ThenFetchMany(m => m.Jobs)
.ThenFetch(j => j.Source)
;
```
I thought of asking this in the [NHibernate forums](http://groups.google.com/group/nhusers) but unfortunately access to google groups is forbidden from where I am. I know [Fabio](https://stackoverflow.com/users/360080/fabio-maulo) is here, so maybe the guys from the NHibernate team can shed some light on this?
Thanks
|
2010/08/03
|
[
"https://Stackoverflow.com/questions/3397980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23920/"
] |
Apparently, there's no "right" way to use `ThenFetch` in such a case. Your example works fine but SQL produced contains many joins to `Milestone`, which isn't that right.
Using `IQueryOver` instead of `IQueryable` allows you to use [complex syntax](https://nhibernate.jira.com/browse/NH-2972?focusedCommentId=22151#comment-22151) in `Fetch`:
```
Fetch(p => p.B)
Fetch(p => p.B.C) // if B is not a collection ... or
Fetch(p => p.B[0].C) // if B is a collection ... or
Fetch(p => p.B.First().C) // if B is an IEnumerable (using .First() extension method)
```
So in your case it would be:
```
query // = session.QueryOver<X>()
.Fetch(mi => mi.Milestone).Eager
.Fetch(mi => mi.Milestone.PrimaryOwners).Eager
.Fetch(mi => mi.Milestone.SecondaryOwners).Eager
.Fetch(mi => mi.Milestone.Predecessors).Eager
.Fetch(mi => mi.Milestone.Function).Eager
.Fetch(mi => mi.Milestone.Jobs).Eager
.Fetch(mi => mi.Milestone.Jobs.First().Source).Eager
```
|
As leora said, make sure when fetching children collections that you use
```
FetchMany()
ThenFetchMany()
```
A new Fetch, should pick up from the root, but this does not always happen. Sometimes you need to create them as separate queries or use Criteria Futures to batch up a multiple fetch.
|
3,397,980 |
I'm trying to load all the collections eagerly, using [NHibernate 3 alpha 1](http://nhforge.org/media/p/690.aspx). I'm wondering if this the right way of using ThenFetch()?
Properties with plural names are collections. The others are just a single object.
```
IQueryable<T> milestoneInstances = Db.Find<T, IQueryable<T>>(db =>
from mi in db
where mi.RunDate == runDate
select mi).Fetch(mi => mi.Milestone)
.ThenFetch(m => m.PrimaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.SecondaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Predecessors)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Function)
.Fetch(mi => mi.Milestone)
.ThenFetchMany(m => m.Jobs)
.ThenFetch(j => j.Source)
;
```
I thought of asking this in the [NHibernate forums](http://groups.google.com/group/nhusers) but unfortunately access to google groups is forbidden from where I am. I know [Fabio](https://stackoverflow.com/users/360080/fabio-maulo) is here, so maybe the guys from the NHibernate team can shed some light on this?
Thanks
|
2010/08/03
|
[
"https://Stackoverflow.com/questions/3397980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23920/"
] |
Apparently, there's no "right" way to use `ThenFetch` in such a case. Your example works fine but SQL produced contains many joins to `Milestone`, which isn't that right.
Using `IQueryOver` instead of `IQueryable` allows you to use [complex syntax](https://nhibernate.jira.com/browse/NH-2972?focusedCommentId=22151#comment-22151) in `Fetch`:
```
Fetch(p => p.B)
Fetch(p => p.B.C) // if B is not a collection ... or
Fetch(p => p.B[0].C) // if B is a collection ... or
Fetch(p => p.B.First().C) // if B is an IEnumerable (using .First() extension method)
```
So in your case it would be:
```
query // = session.QueryOver<X>()
.Fetch(mi => mi.Milestone).Eager
.Fetch(mi => mi.Milestone.PrimaryOwners).Eager
.Fetch(mi => mi.Milestone.SecondaryOwners).Eager
.Fetch(mi => mi.Milestone.Predecessors).Eager
.Fetch(mi => mi.Milestone.Function).Eager
.Fetch(mi => mi.Milestone.Jobs).Eager
.Fetch(mi => mi.Milestone.Jobs.First().Source).Eager
```
|
```
IQueryable<T> milestoneInstances = Db.Find<T, IQueryable<T>>(db =>
from mi in db
where mi.RunDate == runDate
select mi);
var fetch = milestoneInstances.Fetch(f => f.Milestone);
fetch.ThenFetch(f => f.PrimaryOwners);
fetch.ThenFetch(f => f.SecondaryOwners);
//...
```
|
3,397,980 |
I'm trying to load all the collections eagerly, using [NHibernate 3 alpha 1](http://nhforge.org/media/p/690.aspx). I'm wondering if this the right way of using ThenFetch()?
Properties with plural names are collections. The others are just a single object.
```
IQueryable<T> milestoneInstances = Db.Find<T, IQueryable<T>>(db =>
from mi in db
where mi.RunDate == runDate
select mi).Fetch(mi => mi.Milestone)
.ThenFetch(m => m.PrimaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.SecondaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Predecessors)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Function)
.Fetch(mi => mi.Milestone)
.ThenFetchMany(m => m.Jobs)
.ThenFetch(j => j.Source)
;
```
I thought of asking this in the [NHibernate forums](http://groups.google.com/group/nhusers) but unfortunately access to google groups is forbidden from where I am. I know [Fabio](https://stackoverflow.com/users/360080/fabio-maulo) is here, so maybe the guys from the NHibernate team can shed some light on this?
Thanks
|
2010/08/03
|
[
"https://Stackoverflow.com/questions/3397980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23920/"
] |
```
IQueryable<T> milestoneInstances = Db.Find<T, IQueryable<T>>(db =>
from mi in db
where mi.RunDate == runDate
select mi);
var fetch = milestoneInstances.Fetch(f => f.Milestone);
fetch.ThenFetch(f => f.PrimaryOwners);
fetch.ThenFetch(f => f.SecondaryOwners);
//...
```
|
As leora said, make sure when fetching children collections that you use
```
FetchMany()
ThenFetchMany()
```
A new Fetch, should pick up from the root, but this does not always happen. Sometimes you need to create them as separate queries or use Criteria Futures to batch up a multiple fetch.
|
14,574,239 |
I'm building a child play application for Android. I need to disable all keys when it is in use.
I have set the Application as the Home App and disabled the back key (that takes care of the Home and Back button).
In order to clear the recent tasks list I've created a list of Dummy Activites which start and then finish when the application starts. The Dummy Activites look like:
```
public class Dummy1 extends Activity
{
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
finish();
}
}
```
And then in my onCreate of the application I perform:
```
this.pm.setComponentEnabledSetting(new ComponentName(this, Dummy1.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent localIntent1 = new Intent(this, Dummy1.class);
localIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(localIntent1);
```
This takes care of when someone tries to hold the Home key to display the recent tasks as I create 8 of these and they're all empty so the user can't click to change apps.
Now the only button I can't seem to disable is the "Recent Tasks/Apps" button (available mainlyon HTC devices, i.e. One X, One S, etc.). This button seems to still bring up all the recent tasks (even though my dummy tasks were created) and I can't seem to find a "hook" for the event that is fired when this button is pressed?
Note: I know it's do-able since apps like ToddlerLock have done it....I just can't seem to figure it out.
|
2013/01/29
|
[
"https://Stackoverflow.com/questions/14574239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020064/"
] |
Have you tried this code?
```
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d("Focus debug", "Focus changed !");
if(!hasFocus) {
Log.d("Focus debug", "Lost focus !");
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
```
From: <http://www.juliencavandoli.com/how-to-disable-recent-apps-dialog-on-long-press-home-button/>
|
To the best of my knowledge, you cannot override the behavior of the home button (like the way you can override the behavior of the BACK button) without the user confirming it. In other words, the defaults of the app that currently handles the home button -- which is whatever the current home launcher is -- would have to be cleared first.
|
14,574,239 |
I'm building a child play application for Android. I need to disable all keys when it is in use.
I have set the Application as the Home App and disabled the back key (that takes care of the Home and Back button).
In order to clear the recent tasks list I've created a list of Dummy Activites which start and then finish when the application starts. The Dummy Activites look like:
```
public class Dummy1 extends Activity
{
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
finish();
}
}
```
And then in my onCreate of the application I perform:
```
this.pm.setComponentEnabledSetting(new ComponentName(this, Dummy1.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent localIntent1 = new Intent(this, Dummy1.class);
localIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(localIntent1);
```
This takes care of when someone tries to hold the Home key to display the recent tasks as I create 8 of these and they're all empty so the user can't click to change apps.
Now the only button I can't seem to disable is the "Recent Tasks/Apps" button (available mainlyon HTC devices, i.e. One X, One S, etc.). This button seems to still bring up all the recent tasks (even though my dummy tasks were created) and I can't seem to find a "hook" for the event that is fired when this button is pressed?
Note: I know it's do-able since apps like ToddlerLock have done it....I just can't seem to figure it out.
|
2013/01/29
|
[
"https://Stackoverflow.com/questions/14574239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020064/"
] |
This will close the RecentActivity dialog. Put it in your activity class.
```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
windowCloseHandler.postDelayed(windowCloserRunnable, 250);
}
}
private void toggleRecents() {
Intent closeRecents = new Intent("com.android.systemui.recent.action.TOGGLE_RECENTS");
closeRecents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
ComponentName recents = new ComponentName("com.android.systemui", "com.android.systemui.recent.RecentsActivity");
closeRecents.setComponent(recents);
this.startActivity(closeRecents);
}
private Handler windowCloseHandler = new Handler();
private Runnable windowCloserRunnable = new Runnable() {
@Override
public void run() {
ActivityManager am = (ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
if (cn != null && cn.getClassName().equals("com.android.systemui.recent.RecentsActivity")) {
toggleRecents();
}
}
}
```
You will need to put the following permission in your manifest.
```
<uses-permission android:name="android.permission.GET_TASKS" />
```
|
To the best of my knowledge, you cannot override the behavior of the home button (like the way you can override the behavior of the BACK button) without the user confirming it. In other words, the defaults of the app that currently handles the home button -- which is whatever the current home launcher is -- would have to be cleared first.
|
14,574,239 |
I'm building a child play application for Android. I need to disable all keys when it is in use.
I have set the Application as the Home App and disabled the back key (that takes care of the Home and Back button).
In order to clear the recent tasks list I've created a list of Dummy Activites which start and then finish when the application starts. The Dummy Activites look like:
```
public class Dummy1 extends Activity
{
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
finish();
}
}
```
And then in my onCreate of the application I perform:
```
this.pm.setComponentEnabledSetting(new ComponentName(this, Dummy1.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent localIntent1 = new Intent(this, Dummy1.class);
localIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(localIntent1);
```
This takes care of when someone tries to hold the Home key to display the recent tasks as I create 8 of these and they're all empty so the user can't click to change apps.
Now the only button I can't seem to disable is the "Recent Tasks/Apps" button (available mainlyon HTC devices, i.e. One X, One S, etc.). This button seems to still bring up all the recent tasks (even though my dummy tasks were created) and I can't seem to find a "hook" for the event that is fired when this button is pressed?
Note: I know it's do-able since apps like ToddlerLock have done it....I just can't seem to figure it out.
|
2013/01/29
|
[
"https://Stackoverflow.com/questions/14574239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020064/"
] |
To the best of my knowledge, you cannot override the behavior of the home button (like the way you can override the behavior of the BACK button) without the user confirming it. In other words, the defaults of the app that currently handles the home button -- which is whatever the current home launcher is -- would have to be cleared first.
|
You can disable StatusBar popups:
```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
try {
if (!hasFocus) {
Object service = getSystemService("statusbar");
Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
Method collapse = statusbarManager.getMethod("collapse");
collapse.setAccessible(true);
collapse.invoke(service);
}
} catch (Exception e) {
Log.e(TAG, "onWindowFocusChanged - " + e.getCause());
}
}
```
Also you should add this permission in AndroidManifest.xml
```
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
```
Hope this helps.
|
14,574,239 |
I'm building a child play application for Android. I need to disable all keys when it is in use.
I have set the Application as the Home App and disabled the back key (that takes care of the Home and Back button).
In order to clear the recent tasks list I've created a list of Dummy Activites which start and then finish when the application starts. The Dummy Activites look like:
```
public class Dummy1 extends Activity
{
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
finish();
}
}
```
And then in my onCreate of the application I perform:
```
this.pm.setComponentEnabledSetting(new ComponentName(this, Dummy1.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent localIntent1 = new Intent(this, Dummy1.class);
localIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(localIntent1);
```
This takes care of when someone tries to hold the Home key to display the recent tasks as I create 8 of these and they're all empty so the user can't click to change apps.
Now the only button I can't seem to disable is the "Recent Tasks/Apps" button (available mainlyon HTC devices, i.e. One X, One S, etc.). This button seems to still bring up all the recent tasks (even though my dummy tasks were created) and I can't seem to find a "hook" for the event that is fired when this button is pressed?
Note: I know it's do-able since apps like ToddlerLock have done it....I just can't seem to figure it out.
|
2013/01/29
|
[
"https://Stackoverflow.com/questions/14574239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020064/"
] |
Actually, you cannot disable task button. When you press it, your activity calls `onPause()` method and you can move your task to the front in this method. See my [answer](https://stackoverflow.com/a/34680899/5506252) for related question.
|
To the best of my knowledge, you cannot override the behavior of the home button (like the way you can override the behavior of the BACK button) without the user confirming it. In other words, the defaults of the app that currently handles the home button -- which is whatever the current home launcher is -- would have to be cleared first.
|
14,574,239 |
I'm building a child play application for Android. I need to disable all keys when it is in use.
I have set the Application as the Home App and disabled the back key (that takes care of the Home and Back button).
In order to clear the recent tasks list I've created a list of Dummy Activites which start and then finish when the application starts. The Dummy Activites look like:
```
public class Dummy1 extends Activity
{
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
finish();
}
}
```
And then in my onCreate of the application I perform:
```
this.pm.setComponentEnabledSetting(new ComponentName(this, Dummy1.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent localIntent1 = new Intent(this, Dummy1.class);
localIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(localIntent1);
```
This takes care of when someone tries to hold the Home key to display the recent tasks as I create 8 of these and they're all empty so the user can't click to change apps.
Now the only button I can't seem to disable is the "Recent Tasks/Apps" button (available mainlyon HTC devices, i.e. One X, One S, etc.). This button seems to still bring up all the recent tasks (even though my dummy tasks were created) and I can't seem to find a "hook" for the event that is fired when this button is pressed?
Note: I know it's do-able since apps like ToddlerLock have done it....I just can't seem to figure it out.
|
2013/01/29
|
[
"https://Stackoverflow.com/questions/14574239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020064/"
] |
This will close the RecentActivity dialog. Put it in your activity class.
```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
windowCloseHandler.postDelayed(windowCloserRunnable, 250);
}
}
private void toggleRecents() {
Intent closeRecents = new Intent("com.android.systemui.recent.action.TOGGLE_RECENTS");
closeRecents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
ComponentName recents = new ComponentName("com.android.systemui", "com.android.systemui.recent.RecentsActivity");
closeRecents.setComponent(recents);
this.startActivity(closeRecents);
}
private Handler windowCloseHandler = new Handler();
private Runnable windowCloserRunnable = new Runnable() {
@Override
public void run() {
ActivityManager am = (ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
if (cn != null && cn.getClassName().equals("com.android.systemui.recent.RecentsActivity")) {
toggleRecents();
}
}
}
```
You will need to put the following permission in your manifest.
```
<uses-permission android:name="android.permission.GET_TASKS" />
```
|
Have you tried this code?
```
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d("Focus debug", "Focus changed !");
if(!hasFocus) {
Log.d("Focus debug", "Lost focus !");
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
```
From: <http://www.juliencavandoli.com/how-to-disable-recent-apps-dialog-on-long-press-home-button/>
|
14,574,239 |
I'm building a child play application for Android. I need to disable all keys when it is in use.
I have set the Application as the Home App and disabled the back key (that takes care of the Home and Back button).
In order to clear the recent tasks list I've created a list of Dummy Activites which start and then finish when the application starts. The Dummy Activites look like:
```
public class Dummy1 extends Activity
{
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
finish();
}
}
```
And then in my onCreate of the application I perform:
```
this.pm.setComponentEnabledSetting(new ComponentName(this, Dummy1.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent localIntent1 = new Intent(this, Dummy1.class);
localIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(localIntent1);
```
This takes care of when someone tries to hold the Home key to display the recent tasks as I create 8 of these and they're all empty so the user can't click to change apps.
Now the only button I can't seem to disable is the "Recent Tasks/Apps" button (available mainlyon HTC devices, i.e. One X, One S, etc.). This button seems to still bring up all the recent tasks (even though my dummy tasks were created) and I can't seem to find a "hook" for the event that is fired when this button is pressed?
Note: I know it's do-able since apps like ToddlerLock have done it....I just can't seem to figure it out.
|
2013/01/29
|
[
"https://Stackoverflow.com/questions/14574239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020064/"
] |
Have you tried this code?
```
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d("Focus debug", "Focus changed !");
if(!hasFocus) {
Log.d("Focus debug", "Lost focus !");
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
```
From: <http://www.juliencavandoli.com/how-to-disable-recent-apps-dialog-on-long-press-home-button/>
|
You can disable StatusBar popups:
```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
try {
if (!hasFocus) {
Object service = getSystemService("statusbar");
Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
Method collapse = statusbarManager.getMethod("collapse");
collapse.setAccessible(true);
collapse.invoke(service);
}
} catch (Exception e) {
Log.e(TAG, "onWindowFocusChanged - " + e.getCause());
}
}
```
Also you should add this permission in AndroidManifest.xml
```
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
```
Hope this helps.
|
14,574,239 |
I'm building a child play application for Android. I need to disable all keys when it is in use.
I have set the Application as the Home App and disabled the back key (that takes care of the Home and Back button).
In order to clear the recent tasks list I've created a list of Dummy Activites which start and then finish when the application starts. The Dummy Activites look like:
```
public class Dummy1 extends Activity
{
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
finish();
}
}
```
And then in my onCreate of the application I perform:
```
this.pm.setComponentEnabledSetting(new ComponentName(this, Dummy1.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent localIntent1 = new Intent(this, Dummy1.class);
localIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(localIntent1);
```
This takes care of when someone tries to hold the Home key to display the recent tasks as I create 8 of these and they're all empty so the user can't click to change apps.
Now the only button I can't seem to disable is the "Recent Tasks/Apps" button (available mainlyon HTC devices, i.e. One X, One S, etc.). This button seems to still bring up all the recent tasks (even though my dummy tasks were created) and I can't seem to find a "hook" for the event that is fired when this button is pressed?
Note: I know it's do-able since apps like ToddlerLock have done it....I just can't seem to figure it out.
|
2013/01/29
|
[
"https://Stackoverflow.com/questions/14574239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020064/"
] |
Have you tried this code?
```
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Log.d("Focus debug", "Focus changed !");
if(!hasFocus) {
Log.d("Focus debug", "Lost focus !");
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
```
From: <http://www.juliencavandoli.com/how-to-disable-recent-apps-dialog-on-long-press-home-button/>
|
Actually, you cannot disable task button. When you press it, your activity calls `onPause()` method and you can move your task to the front in this method. See my [answer](https://stackoverflow.com/a/34680899/5506252) for related question.
|
14,574,239 |
I'm building a child play application for Android. I need to disable all keys when it is in use.
I have set the Application as the Home App and disabled the back key (that takes care of the Home and Back button).
In order to clear the recent tasks list I've created a list of Dummy Activites which start and then finish when the application starts. The Dummy Activites look like:
```
public class Dummy1 extends Activity
{
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
finish();
}
}
```
And then in my onCreate of the application I perform:
```
this.pm.setComponentEnabledSetting(new ComponentName(this, Dummy1.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent localIntent1 = new Intent(this, Dummy1.class);
localIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(localIntent1);
```
This takes care of when someone tries to hold the Home key to display the recent tasks as I create 8 of these and they're all empty so the user can't click to change apps.
Now the only button I can't seem to disable is the "Recent Tasks/Apps" button (available mainlyon HTC devices, i.e. One X, One S, etc.). This button seems to still bring up all the recent tasks (even though my dummy tasks were created) and I can't seem to find a "hook" for the event that is fired when this button is pressed?
Note: I know it's do-able since apps like ToddlerLock have done it....I just can't seem to figure it out.
|
2013/01/29
|
[
"https://Stackoverflow.com/questions/14574239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020064/"
] |
This will close the RecentActivity dialog. Put it in your activity class.
```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
windowCloseHandler.postDelayed(windowCloserRunnable, 250);
}
}
private void toggleRecents() {
Intent closeRecents = new Intent("com.android.systemui.recent.action.TOGGLE_RECENTS");
closeRecents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
ComponentName recents = new ComponentName("com.android.systemui", "com.android.systemui.recent.RecentsActivity");
closeRecents.setComponent(recents);
this.startActivity(closeRecents);
}
private Handler windowCloseHandler = new Handler();
private Runnable windowCloserRunnable = new Runnable() {
@Override
public void run() {
ActivityManager am = (ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
if (cn != null && cn.getClassName().equals("com.android.systemui.recent.RecentsActivity")) {
toggleRecents();
}
}
}
```
You will need to put the following permission in your manifest.
```
<uses-permission android:name="android.permission.GET_TASKS" />
```
|
You can disable StatusBar popups:
```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
try {
if (!hasFocus) {
Object service = getSystemService("statusbar");
Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
Method collapse = statusbarManager.getMethod("collapse");
collapse.setAccessible(true);
collapse.invoke(service);
}
} catch (Exception e) {
Log.e(TAG, "onWindowFocusChanged - " + e.getCause());
}
}
```
Also you should add this permission in AndroidManifest.xml
```
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
```
Hope this helps.
|
14,574,239 |
I'm building a child play application for Android. I need to disable all keys when it is in use.
I have set the Application as the Home App and disabled the back key (that takes care of the Home and Back button).
In order to clear the recent tasks list I've created a list of Dummy Activites which start and then finish when the application starts. The Dummy Activites look like:
```
public class Dummy1 extends Activity
{
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
finish();
}
}
```
And then in my onCreate of the application I perform:
```
this.pm.setComponentEnabledSetting(new ComponentName(this, Dummy1.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent localIntent1 = new Intent(this, Dummy1.class);
localIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(localIntent1);
```
This takes care of when someone tries to hold the Home key to display the recent tasks as I create 8 of these and they're all empty so the user can't click to change apps.
Now the only button I can't seem to disable is the "Recent Tasks/Apps" button (available mainlyon HTC devices, i.e. One X, One S, etc.). This button seems to still bring up all the recent tasks (even though my dummy tasks were created) and I can't seem to find a "hook" for the event that is fired when this button is pressed?
Note: I know it's do-able since apps like ToddlerLock have done it....I just can't seem to figure it out.
|
2013/01/29
|
[
"https://Stackoverflow.com/questions/14574239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020064/"
] |
This will close the RecentActivity dialog. Put it in your activity class.
```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (!hasFocus) {
windowCloseHandler.postDelayed(windowCloserRunnable, 250);
}
}
private void toggleRecents() {
Intent closeRecents = new Intent("com.android.systemui.recent.action.TOGGLE_RECENTS");
closeRecents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
ComponentName recents = new ComponentName("com.android.systemui", "com.android.systemui.recent.RecentsActivity");
closeRecents.setComponent(recents);
this.startActivity(closeRecents);
}
private Handler windowCloseHandler = new Handler();
private Runnable windowCloserRunnable = new Runnable() {
@Override
public void run() {
ActivityManager am = (ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
if (cn != null && cn.getClassName().equals("com.android.systemui.recent.RecentsActivity")) {
toggleRecents();
}
}
}
```
You will need to put the following permission in your manifest.
```
<uses-permission android:name="android.permission.GET_TASKS" />
```
|
Actually, you cannot disable task button. When you press it, your activity calls `onPause()` method and you can move your task to the front in this method. See my [answer](https://stackoverflow.com/a/34680899/5506252) for related question.
|
14,574,239 |
I'm building a child play application for Android. I need to disable all keys when it is in use.
I have set the Application as the Home App and disabled the back key (that takes care of the Home and Back button).
In order to clear the recent tasks list I've created a list of Dummy Activites which start and then finish when the application starts. The Dummy Activites look like:
```
public class Dummy1 extends Activity
{
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
finish();
}
}
```
And then in my onCreate of the application I perform:
```
this.pm.setComponentEnabledSetting(new ComponentName(this, Dummy1.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent localIntent1 = new Intent(this, Dummy1.class);
localIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(localIntent1);
```
This takes care of when someone tries to hold the Home key to display the recent tasks as I create 8 of these and they're all empty so the user can't click to change apps.
Now the only button I can't seem to disable is the "Recent Tasks/Apps" button (available mainlyon HTC devices, i.e. One X, One S, etc.). This button seems to still bring up all the recent tasks (even though my dummy tasks were created) and I can't seem to find a "hook" for the event that is fired when this button is pressed?
Note: I know it's do-able since apps like ToddlerLock have done it....I just can't seem to figure it out.
|
2013/01/29
|
[
"https://Stackoverflow.com/questions/14574239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020064/"
] |
Actually, you cannot disable task button. When you press it, your activity calls `onPause()` method and you can move your task to the front in this method. See my [answer](https://stackoverflow.com/a/34680899/5506252) for related question.
|
You can disable StatusBar popups:
```
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
try {
if (!hasFocus) {
Object service = getSystemService("statusbar");
Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
Method collapse = statusbarManager.getMethod("collapse");
collapse.setAccessible(true);
collapse.invoke(service);
}
} catch (Exception e) {
Log.e(TAG, "onWindowFocusChanged - " + e.getCause());
}
}
```
Also you should add this permission in AndroidManifest.xml
```
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
```
Hope this helps.
|
7,227,910 |
We need to make a `branch` on **Subverison** in these days on our project.
One time `branch` made, we need to manage in practise 2 projects contemporary. This means, that if we resolve a bug on the `branch` we should make it also on `trunk`. First times it would basically easy merging, but more time pass, more `trunk` will defer from `branch`, so will be need to make specific fixes to resolve a problem on trunk and on branch.
The problem:
To ensure that none forgets to bring the fix from `branch` to `trunk`, I was thinking to write simple program that checks commits on `branch`, reads a comments and try to find *exactly the same* comments on `trunk`. Roughe one.
Is there any more clever solution for this ?
|
2011/08/29
|
[
"https://Stackoverflow.com/questions/7227910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156695/"
] |
Do you have Simple XML checked under "*Order and Export*" in the Build Path configuration?
I just ran across this problem after updating to the latest `SDK` and *Eclipse plugins for Android*, having been successfully using Simple for months.
For some reason, after the update, I had to go and:
* Check `simple-xml-2.6.2.jar` under "*Order and Export*"
* Clean my project (**important**)
After those two steps, the problem went away.
|
you got this error because might be you do not have declare any of your Activity in to the manifest file. So please add it into your manifest file as like below:
```
<activity android:name=".DatabaseActivity"></activity>
```
here DatabaseActivity is my Activity of the application.
try it.
|
7,227,910 |
We need to make a `branch` on **Subverison** in these days on our project.
One time `branch` made, we need to manage in practise 2 projects contemporary. This means, that if we resolve a bug on the `branch` we should make it also on `trunk`. First times it would basically easy merging, but more time pass, more `trunk` will defer from `branch`, so will be need to make specific fixes to resolve a problem on trunk and on branch.
The problem:
To ensure that none forgets to bring the fix from `branch` to `trunk`, I was thinking to write simple program that checks commits on `branch`, reads a comments and try to find *exactly the same* comments on `trunk`. Roughe one.
Is there any more clever solution for this ?
|
2011/08/29
|
[
"https://Stackoverflow.com/questions/7227910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156695/"
] |
Do you have Simple XML checked under "*Order and Export*" in the Build Path configuration?
I just ran across this problem after updating to the latest `SDK` and *Eclipse plugins for Android*, having been successfully using Simple for months.
For some reason, after the update, I had to go and:
* Check `simple-xml-2.6.2.jar` under "*Order and Export*"
* Clean my project (**important**)
After those two steps, the problem went away.
|
It's little strange, but this works for me.
```
Serializer serializer;
Persister persiter = new Persister();
serializer = persiter;
```
|
7,227,910 |
We need to make a `branch` on **Subverison** in these days on our project.
One time `branch` made, we need to manage in practise 2 projects contemporary. This means, that if we resolve a bug on the `branch` we should make it also on `trunk`. First times it would basically easy merging, but more time pass, more `trunk` will defer from `branch`, so will be need to make specific fixes to resolve a problem on trunk and on branch.
The problem:
To ensure that none forgets to bring the fix from `branch` to `trunk`, I was thinking to write simple program that checks commits on `branch`, reads a comments and try to find *exactly the same* comments on `trunk`. Roughe one.
Is there any more clever solution for this ?
|
2011/08/29
|
[
"https://Stackoverflow.com/questions/7227910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156695/"
] |
Do you have Simple XML checked under "*Order and Export*" in the Build Path configuration?
I just ran across this problem after updating to the latest `SDK` and *Eclipse plugins for Android*, having been successfully using Simple for months.
For some reason, after the update, I had to go and:
* Check `simple-xml-2.6.2.jar` under "*Order and Export*"
* Clean my project (**important**)
After those two steps, the problem went away.
|
I resolved same problem like yours modifying Java Build path.
I installed `Android DDMS 17.0.0.v201203161636-291853` today and `NoClassDefFoundError` appeared.
**How to fix** -> Check check box against `simple-xml` dependency and give it higher priority than `yourproject/src/main/java`

|
7,227,910 |
We need to make a `branch` on **Subverison** in these days on our project.
One time `branch` made, we need to manage in practise 2 projects contemporary. This means, that if we resolve a bug on the `branch` we should make it also on `trunk`. First times it would basically easy merging, but more time pass, more `trunk` will defer from `branch`, so will be need to make specific fixes to resolve a problem on trunk and on branch.
The problem:
To ensure that none forgets to bring the fix from `branch` to `trunk`, I was thinking to write simple program that checks commits on `branch`, reads a comments and try to find *exactly the same* comments on `trunk`. Roughe one.
Is there any more clever solution for this ?
|
2011/08/29
|
[
"https://Stackoverflow.com/questions/7227910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156695/"
] |
You don't need those three other jars in your classpath.
Make sure your classpath looks like this and that you puth the jar file in the lib folder (for conventions sake):

Add the library to the build path

|
when you deploy your app to your device (or emulator) do you get any errors about the jar that you are trying to include? Not all jars will work on Android. Older code may present a problem You may need to get source and recompile the jar you are interested in. This ensures that the bytecode is compatible with Android. I got this error before with some jars, that said they worked for me even with the errors. They were also xml related (not SimpleXML).
|
7,227,910 |
We need to make a `branch` on **Subverison** in these days on our project.
One time `branch` made, we need to manage in practise 2 projects contemporary. This means, that if we resolve a bug on the `branch` we should make it also on `trunk`. First times it would basically easy merging, but more time pass, more `trunk` will defer from `branch`, so will be need to make specific fixes to resolve a problem on trunk and on branch.
The problem:
To ensure that none forgets to bring the fix from `branch` to `trunk`, I was thinking to write simple program that checks commits on `branch`, reads a comments and try to find *exactly the same* comments on `trunk`. Roughe one.
Is there any more clever solution for this ?
|
2011/08/29
|
[
"https://Stackoverflow.com/questions/7227910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156695/"
] |
You don't need those three other jars in your classpath.
Make sure your classpath looks like this and that you puth the jar file in the lib folder (for conventions sake):

Add the library to the build path

|
you got this error because might be you do not have declare any of your Activity in to the manifest file. So please add it into your manifest file as like below:
```
<activity android:name=".DatabaseActivity"></activity>
```
here DatabaseActivity is my Activity of the application.
try it.
|
7,227,910 |
We need to make a `branch` on **Subverison** in these days on our project.
One time `branch` made, we need to manage in practise 2 projects contemporary. This means, that if we resolve a bug on the `branch` we should make it also on `trunk`. First times it would basically easy merging, but more time pass, more `trunk` will defer from `branch`, so will be need to make specific fixes to resolve a problem on trunk and on branch.
The problem:
To ensure that none forgets to bring the fix from `branch` to `trunk`, I was thinking to write simple program that checks commits on `branch`, reads a comments and try to find *exactly the same* comments on `trunk`. Roughe one.
Is there any more clever solution for this ?
|
2011/08/29
|
[
"https://Stackoverflow.com/questions/7227910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156695/"
] |
I resolved same problem like yours modifying Java Build path.
I installed `Android DDMS 17.0.0.v201203161636-291853` today and `NoClassDefFoundError` appeared.
**How to fix** -> Check check box against `simple-xml` dependency and give it higher priority than `yourproject/src/main/java`

|
you got this error because might be you do not have declare any of your Activity in to the manifest file. So please add it into your manifest file as like below:
```
<activity android:name=".DatabaseActivity"></activity>
```
here DatabaseActivity is my Activity of the application.
try it.
|
7,227,910 |
We need to make a `branch` on **Subverison** in these days on our project.
One time `branch` made, we need to manage in practise 2 projects contemporary. This means, that if we resolve a bug on the `branch` we should make it also on `trunk`. First times it would basically easy merging, but more time pass, more `trunk` will defer from `branch`, so will be need to make specific fixes to resolve a problem on trunk and on branch.
The problem:
To ensure that none forgets to bring the fix from `branch` to `trunk`, I was thinking to write simple program that checks commits on `branch`, reads a comments and try to find *exactly the same* comments on `trunk`. Roughe one.
Is there any more clever solution for this ?
|
2011/08/29
|
[
"https://Stackoverflow.com/questions/7227910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156695/"
] |
I resolved same problem like yours modifying Java Build path.
I installed `Android DDMS 17.0.0.v201203161636-291853` today and `NoClassDefFoundError` appeared.
**How to fix** -> Check check box against `simple-xml` dependency and give it higher priority than `yourproject/src/main/java`

|
You don't need those three other jars in your classpath.
Make sure your classpath looks like this and that you puth the jar file in the lib folder (for conventions sake):

Add the library to the build path

|
7,227,910 |
We need to make a `branch` on **Subverison** in these days on our project.
One time `branch` made, we need to manage in practise 2 projects contemporary. This means, that if we resolve a bug on the `branch` we should make it also on `trunk`. First times it would basically easy merging, but more time pass, more `trunk` will defer from `branch`, so will be need to make specific fixes to resolve a problem on trunk and on branch.
The problem:
To ensure that none forgets to bring the fix from `branch` to `trunk`, I was thinking to write simple program that checks commits on `branch`, reads a comments and try to find *exactly the same* comments on `trunk`. Roughe one.
Is there any more clever solution for this ?
|
2011/08/29
|
[
"https://Stackoverflow.com/questions/7227910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156695/"
] |
I resolved same problem like yours modifying Java Build path.
I installed `Android DDMS 17.0.0.v201203161636-291853` today and `NoClassDefFoundError` appeared.
**How to fix** -> Check check box against `simple-xml` dependency and give it higher priority than `yourproject/src/main/java`

|
It's little strange, but this works for me.
```
Serializer serializer;
Persister persiter = new Persister();
serializer = persiter;
```
|
7,227,910 |
We need to make a `branch` on **Subverison** in these days on our project.
One time `branch` made, we need to manage in practise 2 projects contemporary. This means, that if we resolve a bug on the `branch` we should make it also on `trunk`. First times it would basically easy merging, but more time pass, more `trunk` will defer from `branch`, so will be need to make specific fixes to resolve a problem on trunk and on branch.
The problem:
To ensure that none forgets to bring the fix from `branch` to `trunk`, I was thinking to write simple program that checks commits on `branch`, reads a comments and try to find *exactly the same* comments on `trunk`. Roughe one.
Is there any more clever solution for this ?
|
2011/08/29
|
[
"https://Stackoverflow.com/questions/7227910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156695/"
] |
Do you have Simple XML checked under "*Order and Export*" in the Build Path configuration?
I just ran across this problem after updating to the latest `SDK` and *Eclipse plugins for Android*, having been successfully using Simple for months.
For some reason, after the update, I had to go and:
* Check `simple-xml-2.6.2.jar` under "*Order and Export*"
* Clean my project (**important**)
After those two steps, the problem went away.
|
when you deploy your app to your device (or emulator) do you get any errors about the jar that you are trying to include? Not all jars will work on Android. Older code may present a problem You may need to get source and recompile the jar you are interested in. This ensures that the bytecode is compatible with Android. I got this error before with some jars, that said they worked for me even with the errors. They were also xml related (not SimpleXML).
|
7,227,910 |
We need to make a `branch` on **Subverison** in these days on our project.
One time `branch` made, we need to manage in practise 2 projects contemporary. This means, that if we resolve a bug on the `branch` we should make it also on `trunk`. First times it would basically easy merging, but more time pass, more `trunk` will defer from `branch`, so will be need to make specific fixes to resolve a problem on trunk and on branch.
The problem:
To ensure that none forgets to bring the fix from `branch` to `trunk`, I was thinking to write simple program that checks commits on `branch`, reads a comments and try to find *exactly the same* comments on `trunk`. Roughe one.
Is there any more clever solution for this ?
|
2011/08/29
|
[
"https://Stackoverflow.com/questions/7227910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156695/"
] |
You don't need those three other jars in your classpath.
Make sure your classpath looks like this and that you puth the jar file in the lib folder (for conventions sake):

Add the library to the build path

|
It's little strange, but this works for me.
```
Serializer serializer;
Persister persiter = new Persister();
serializer = persiter;
```
|
25,212 |
This question rather stems from my last question about inspiration vs copying from another authors work. While the suggestions I got there haven't completed resolved my issues and doubts, they have started me thinking differently about it.
As a recap, this whole issue started when I read a piece of fiction that moved me in ways a piece of writing never had done before. It was fresh, it was exciting, it was groundbreaking writing in a way I had never considered. And maybe that was my problem. Could I have been too close to it when I wanted to start writing it?
A few people have suggested that waiting for the idea to chill down before even thinking about writing it could be an idea to try. Which I certainly didn't do and maybe lead to my stewing over it and over analysing how it was written instead of being able to sit down and write it.
All I do know is that this seems to have lead to an almost phobic response when I try to read this piece or even see a link or an advert for it accidentally, usually in my hastily shutting that page down. Which I know I'm reinforcing but honestly I'm scared to read it in case the feelings of doubt about it come back. Has anyone been through anything like this? Any advice or suggestions would be greatly appreciated. White.
|
2016/11/12
|
[
"https://writers.stackexchange.com/questions/25212",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/22178/"
] |
My Personal Experience with Copy-Phobia
---------------------------------------
**I know exactly what you're talking about.**
Because I had exactly the same thing. For example, I love the video game *Dark Souls 3* very much, and I took it as inspiration for my own writing. I heavily inspired a character arc based of 'Anri of Astora', but I didn't exactly copy it or steal it. I kept thinking that my writing was too similar because I was taking too much inspiration, and critics would jump all over me if I ever got it published.
However, as I started to write, and I continued to write, I realised that my work became more disconnected from it and realised that perhaps I shouldn't have been scared.
Let me give you another real example. This is likely what is going on with you, because you sound like you are currently viewing your inspiration as you try to write.
**I hold Justin Cronin's The Passage and the rest of the series very close to my heart.** Obviously, because of that, I took loads of inspiration from it. I thought that 'oh my god, I have the same kind of foreshadowing' and 'oh my god, I have *unnamed* that's similar to The Twelve'. I had these thoughts and feelings *while I was reading the series*. The second I finished the trilogy, a few months after that of continued work on my writing, I realised that actually, my work wasn't that similar. I realised that because I'd taken so much inspiration from so many sources it couldn't possibly be similar.
I actually think a lot of that happened while I couldn't differentiate between *copying* and *inspiration.*
How Not to Have Copy-Phobia
---------------------------
My main point is:
>
> Take inspiration from many sources. Mix, create, devise, just throw in tons of inspiration. It'll be great!
>
>
>
And then, just write. **Do not** think you can get past this problem without actually writing. You are going to have to write at some point, and from writing, you will come to the realisation that you are not copying exactly and your work is fine. I know you will because *I did*.
Here's another thing that has happened in my personal experience with a similar problem to the one you have:
>
> Read something, and later read something better. It almost always happens.
>
>
>
I think that's self explanatory enough.
The Big Question
----------------
>
> How do I know that if I start writing, I won't just be copying? How can I actually start writing?
>
>
>
Okay, *there isn't really a way around this*. But seriously. As long as your not copying these things:
* Names
* Exactly copying story arcs
* Place names
* Basically copying it exactly
You're fine. I think that just because this work was groundbreaking, doesn't necessarily mean that you have to copy it precisely to make yours groundbreaking. Taking inspiration from something is totally fine.
You need to just write. I cannot stress this enough: **it is fine to take inspiration!!!**
I hope my personal experience with this problem helped you. Trust me, *you will overcome it. You'll realise it as you write. I don't believe you can realise this before writing, you can only realise it during writing.* By the way, please leave a comment telling me what that groundbreaking work is. I'm really interested now and want to read it. I might even take a bit as... **inspiration!** :P
---
**Edit:**
As Thomas Myron said, just write anything. You ought to get yourself used to writing and used to the thought of inspiration and copying. Just write your fears, perhaps even write what you did today. A great way to be able to actually bring yourself to start is to be really into writing, having the ability to see your own writing and realise that its fine and groundbreaking in its own way.
Another good technique that Thomas didn't mention is to **OBSESS** over what you're writing. This is really good because it helps you get into your *own* ideas and story rather than *someone else's*.
Also, you could get some more insight from: [What are some tricks for managing debilitating writing anxiety/phobia?](https://writers.stackexchange.com/questions/14085/what-are-some-tricks-for-managing-debilitating-writing-anxiety-phobia)
|
One solution is to try and write a story backwards...literally.
Obliterate the very idea of making sense and this helps me at least to think in terms of creating and not so much writing...thus being called "not yours" or stolen.
There is nothing wrong at all with creating in the mold of another but yes the eternal struggle of copy/paste is the bane of every artist's existence.
"How do I make this my own story"...especially when it's not about you or your personal life is very hard. I wish you luck. Perhaps something fortuitous will happen...
|
25,212 |
This question rather stems from my last question about inspiration vs copying from another authors work. While the suggestions I got there haven't completed resolved my issues and doubts, they have started me thinking differently about it.
As a recap, this whole issue started when I read a piece of fiction that moved me in ways a piece of writing never had done before. It was fresh, it was exciting, it was groundbreaking writing in a way I had never considered. And maybe that was my problem. Could I have been too close to it when I wanted to start writing it?
A few people have suggested that waiting for the idea to chill down before even thinking about writing it could be an idea to try. Which I certainly didn't do and maybe lead to my stewing over it and over analysing how it was written instead of being able to sit down and write it.
All I do know is that this seems to have lead to an almost phobic response when I try to read this piece or even see a link or an advert for it accidentally, usually in my hastily shutting that page down. Which I know I'm reinforcing but honestly I'm scared to read it in case the feelings of doubt about it come back. Has anyone been through anything like this? Any advice or suggestions would be greatly appreciated. White.
|
2016/11/12
|
[
"https://writers.stackexchange.com/questions/25212",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/22178/"
] |
My Personal Experience with Copy-Phobia
---------------------------------------
**I know exactly what you're talking about.**
Because I had exactly the same thing. For example, I love the video game *Dark Souls 3* very much, and I took it as inspiration for my own writing. I heavily inspired a character arc based of 'Anri of Astora', but I didn't exactly copy it or steal it. I kept thinking that my writing was too similar because I was taking too much inspiration, and critics would jump all over me if I ever got it published.
However, as I started to write, and I continued to write, I realised that my work became more disconnected from it and realised that perhaps I shouldn't have been scared.
Let me give you another real example. This is likely what is going on with you, because you sound like you are currently viewing your inspiration as you try to write.
**I hold Justin Cronin's The Passage and the rest of the series very close to my heart.** Obviously, because of that, I took loads of inspiration from it. I thought that 'oh my god, I have the same kind of foreshadowing' and 'oh my god, I have *unnamed* that's similar to The Twelve'. I had these thoughts and feelings *while I was reading the series*. The second I finished the trilogy, a few months after that of continued work on my writing, I realised that actually, my work wasn't that similar. I realised that because I'd taken so much inspiration from so many sources it couldn't possibly be similar.
I actually think a lot of that happened while I couldn't differentiate between *copying* and *inspiration.*
How Not to Have Copy-Phobia
---------------------------
My main point is:
>
> Take inspiration from many sources. Mix, create, devise, just throw in tons of inspiration. It'll be great!
>
>
>
And then, just write. **Do not** think you can get past this problem without actually writing. You are going to have to write at some point, and from writing, you will come to the realisation that you are not copying exactly and your work is fine. I know you will because *I did*.
Here's another thing that has happened in my personal experience with a similar problem to the one you have:
>
> Read something, and later read something better. It almost always happens.
>
>
>
I think that's self explanatory enough.
The Big Question
----------------
>
> How do I know that if I start writing, I won't just be copying? How can I actually start writing?
>
>
>
Okay, *there isn't really a way around this*. But seriously. As long as your not copying these things:
* Names
* Exactly copying story arcs
* Place names
* Basically copying it exactly
You're fine. I think that just because this work was groundbreaking, doesn't necessarily mean that you have to copy it precisely to make yours groundbreaking. Taking inspiration from something is totally fine.
You need to just write. I cannot stress this enough: **it is fine to take inspiration!!!**
I hope my personal experience with this problem helped you. Trust me, *you will overcome it. You'll realise it as you write. I don't believe you can realise this before writing, you can only realise it during writing.* By the way, please leave a comment telling me what that groundbreaking work is. I'm really interested now and want to read it. I might even take a bit as... **inspiration!** :P
---
**Edit:**
As Thomas Myron said, just write anything. You ought to get yourself used to writing and used to the thought of inspiration and copying. Just write your fears, perhaps even write what you did today. A great way to be able to actually bring yourself to start is to be really into writing, having the ability to see your own writing and realise that its fine and groundbreaking in its own way.
Another good technique that Thomas didn't mention is to **OBSESS** over what you're writing. This is really good because it helps you get into your *own* ideas and story rather than *someone else's*.
Also, you could get some more insight from: [What are some tricks for managing debilitating writing anxiety/phobia?](https://writers.stackexchange.com/questions/14085/what-are-some-tricks-for-managing-debilitating-writing-anxiety-phobia)
|
Honestly, if you have not yet the read the writer who makes you say, oh no, I will never ever be able to be that good, you are not ready to start writing. Despair has to be the starting point, because only despair at imitation will break you out of the beginner's habit of pastiche and hesitation and get you to the point where you can do something that is genuinely your own.
It may not be immediately obvious at the time it happens, but that despair is liberating. Once you get past it, you will no longer be intimidated, nor will you feel the need to imitate, any other writer you read. Then you can be yourself, which may be good, bad, or indifferent, but will at least be you.
|
25,212 |
This question rather stems from my last question about inspiration vs copying from another authors work. While the suggestions I got there haven't completed resolved my issues and doubts, they have started me thinking differently about it.
As a recap, this whole issue started when I read a piece of fiction that moved me in ways a piece of writing never had done before. It was fresh, it was exciting, it was groundbreaking writing in a way I had never considered. And maybe that was my problem. Could I have been too close to it when I wanted to start writing it?
A few people have suggested that waiting for the idea to chill down before even thinking about writing it could be an idea to try. Which I certainly didn't do and maybe lead to my stewing over it and over analysing how it was written instead of being able to sit down and write it.
All I do know is that this seems to have lead to an almost phobic response when I try to read this piece or even see a link or an advert for it accidentally, usually in my hastily shutting that page down. Which I know I'm reinforcing but honestly I'm scared to read it in case the feelings of doubt about it come back. Has anyone been through anything like this? Any advice or suggestions would be greatly appreciated. White.
|
2016/11/12
|
[
"https://writers.stackexchange.com/questions/25212",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/22178/"
] |
Honestly, if you have not yet the read the writer who makes you say, oh no, I will never ever be able to be that good, you are not ready to start writing. Despair has to be the starting point, because only despair at imitation will break you out of the beginner's habit of pastiche and hesitation and get you to the point where you can do something that is genuinely your own.
It may not be immediately obvious at the time it happens, but that despair is liberating. Once you get past it, you will no longer be intimidated, nor will you feel the need to imitate, any other writer you read. Then you can be yourself, which may be good, bad, or indifferent, but will at least be you.
|
One solution is to try and write a story backwards...literally.
Obliterate the very idea of making sense and this helps me at least to think in terms of creating and not so much writing...thus being called "not yours" or stolen.
There is nothing wrong at all with creating in the mold of another but yes the eternal struggle of copy/paste is the bane of every artist's existence.
"How do I make this my own story"...especially when it's not about you or your personal life is very hard. I wish you luck. Perhaps something fortuitous will happen...
|
52,004,676 |
I am trying to pass an ArrayList to a method in Java. But it gives me the error:
```
incompatible types: java.lang.String cannot be converted to java.util.List<java.lang.String>"
```
Here is the code:
```
class hello
{
public static void main()
{
List<String> iname = new ArrayList<>();
iname.add("1");
iname.add("2");
iname.add("3");
hello obj = new hello();
iname = obj.changeName(iname); //<- problem here
}
public String changeName(List<String> iname){
//...
return "some String result";
}
}
```
And it gives me the aforementioned error in this statement at "iname" in parenthesis:
```
iname = obj.changeName(iname);
```
Somebody please help me out.
|
2018/08/24
|
[
"https://Stackoverflow.com/questions/52004676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269569/"
] |
Your method returns a simple String which is about to be assigned to a List.
Change changename to `public List<String> changeName(...)` or use a new varible which is of type String and assign the return value.
|
Your method `public String changeName(List<String> iname){}` is returning a String instead of a list of Strings. Try `public List<String> changeName(List<String> iname){}` instead. The method changeName is trying to fit an entire list into a single String. If you left your program as it, then you would have to return a single item from your iname List back into the main method.
|
52,004,676 |
I am trying to pass an ArrayList to a method in Java. But it gives me the error:
```
incompatible types: java.lang.String cannot be converted to java.util.List<java.lang.String>"
```
Here is the code:
```
class hello
{
public static void main()
{
List<String> iname = new ArrayList<>();
iname.add("1");
iname.add("2");
iname.add("3");
hello obj = new hello();
iname = obj.changeName(iname); //<- problem here
}
public String changeName(List<String> iname){
//...
return "some String result";
}
}
```
And it gives me the aforementioned error in this statement at "iname" in parenthesis:
```
iname = obj.changeName(iname);
```
Somebody please help me out.
|
2018/08/24
|
[
"https://Stackoverflow.com/questions/52004676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269569/"
] |
`iname` is `List<String>`, while the return type of method `changeName` is `String`.
If you want to return `List<String>`, you can declare it this way:
```
public List<String> changeName(List<String> iname){
// ... you should return a List<String> in this method
}
```
|
Your method `public String changeName(List<String> iname){}` is returning a String instead of a list of Strings. Try `public List<String> changeName(List<String> iname){}` instead. The method changeName is trying to fit an entire list into a single String. If you left your program as it, then you would have to return a single item from your iname List back into the main method.
|
52,004,676 |
I am trying to pass an ArrayList to a method in Java. But it gives me the error:
```
incompatible types: java.lang.String cannot be converted to java.util.List<java.lang.String>"
```
Here is the code:
```
class hello
{
public static void main()
{
List<String> iname = new ArrayList<>();
iname.add("1");
iname.add("2");
iname.add("3");
hello obj = new hello();
iname = obj.changeName(iname); //<- problem here
}
public String changeName(List<String> iname){
//...
return "some String result";
}
}
```
And it gives me the aforementioned error in this statement at "iname" in parenthesis:
```
iname = obj.changeName(iname);
```
Somebody please help me out.
|
2018/08/24
|
[
"https://Stackoverflow.com/questions/52004676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269569/"
] |
`iname` is `List<String>`, while the return type of method `changeName` is `String`.
If you want to return `List<String>`, you can declare it this way:
```
public List<String> changeName(List<String> iname){
// ... you should return a List<String> in this method
}
```
|
Your variable `iname` is of type `List<String>` but you are attempting to return type `String` from your method `changeName(...)`.
You need to either update the method to return a type `List<String>`:
`public List<String> changeName(List<String> iname){ ... }`
Or change the variable the method is returned into like:
`String variable = obj.changeName(iname);`
|
52,004,676 |
I am trying to pass an ArrayList to a method in Java. But it gives me the error:
```
incompatible types: java.lang.String cannot be converted to java.util.List<java.lang.String>"
```
Here is the code:
```
class hello
{
public static void main()
{
List<String> iname = new ArrayList<>();
iname.add("1");
iname.add("2");
iname.add("3");
hello obj = new hello();
iname = obj.changeName(iname); //<- problem here
}
public String changeName(List<String> iname){
//...
return "some String result";
}
}
```
And it gives me the aforementioned error in this statement at "iname" in parenthesis:
```
iname = obj.changeName(iname);
```
Somebody please help me out.
|
2018/08/24
|
[
"https://Stackoverflow.com/questions/52004676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10269569/"
] |
`iname` is `List<String>`, while the return type of method `changeName` is `String`.
If you want to return `List<String>`, you can declare it this way:
```
public List<String> changeName(List<String> iname){
// ... you should return a List<String> in this method
}
```
|
The problem is that you try to store the return of your `changeName` function (a `String`) in the `iname` variable, which can only hold `List<String>`. This should work:
```
String result = obj.changeName(iname);
```
The alternative would be, to change the `changeName` to return `List<String>`, and change the function's implementation accordingly.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.