qid
int64 1
74.7M
| question
stringlengths 17
39.2k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
41.1k
| response_k
stringlengths 2
47.9k
|
---|---|---|---|---|---|
11,202,950 | I have a big `String` that was once converted to a `ByteBuffer` & then while reading later several times, only a portion of the `String`(overview of the text) needs to be presented, so I want to convert only a part of the `ByteBuffer` to `String`.
Is it possible to convert only a part of bytebuffer to string rather than [converting entire `Bytebuffer` to `String` & then using `substring()`] | 2012/06/26 | [
"https://Stackoverflow.com/questions/11202950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/530153/"
] | ```
try {
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(yourstr));
bbuf.position(0);
bbuf.limit(200);
CharBuffer cbuf = decoder.decode(bbuf);
String s = cbuf.toString();
System.out.println(s);
} catch (CharacterCodingException e) {
}
```
Which should return chars from the byte buffer starting at 0. byte and ending in 200.
Or rather:
```
ByteBuffer bbuf = ByteBuffer.wrap(yourstr.getBytes());
bbuf.position(0);
bbuf.limit(200);
byte[] bytearr = new byte[bbuf.remaining()];
bbuf.get(bytearr);
String s = new String(bytearr);
```
Which does the same but without explicit character decoding/encoding.
Decoding of course does happen in constructor of `String s` and it is platform dependent, so watch out. | ```
// convert all byteBuffer to string
String fullByteBuffer = new String(byteBuffer.array());
// convert part of byteBuffer to string
byte[] partOfByteBuffer = new byte[PART_LENGTH];
System.arraycopy(fullByteBuffer.array(), 0, partOfByteBuffer, 0, partOfByteBuffer.length);
String partOfByteBufferString = new String(partOfByteBuffer.array());
``` |
144,356 | I've only had a very brief introduction to Lagrangian mechanics. In a physics course I took last year, we briefly covered the principle of stationary action --- we looked at it, derived some equations of motion with it, and moved on.
While the lecturer often referred to it as the [principle of least action](http://en.wikipedia.org/wiki/Principle_of_least_action), he always reminded us that it wasn't actually *least* action, but *stationary* action --- a minimum, maximum, or point of inflexion, rather than just a minimum. He never, however, gave an example of a system where we didn't seek the least action.
Why is it, then, the principle of stationary action, instead of least action? What is an example of a system which we would seek a maximum instead of a minimum? | 2014/11/02 | [
"https://physics.stackexchange.com/questions/144356",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/36978/"
] | If we solve equations of motion for a particle with mass $m=1$ in some potential, e.g. $U=x^4-4x^3+4.5x^2$, fixing two points like $x(0)=0$ and $x(1)=2.651$, we'll get infinite number of solutions, here're some of them:
![enter image description here](https://i.stack.imgur.com/dT7tM.png)
They differ by initial velocity. Now each of them satisfies equations of motion, but only one makes the action minimal, here's how $S$ depends on $v\_0$ for such paths in this example:
![enter image description here](https://i.stack.imgur.com/NF0gQ.png)
As all they satisfy equations of motion, they make the action stationary, and it'd be wrong to just throw them away because they don't minimize the action. | In optics, you can take the example of a concave mirror : the optical path chosen by the light to join two fixed points A and B is a maximum. |
191,958 | Walls divide rooms but what do you call what divides stories?
Looking from below it would be the *ceiling*, looking from above it would be the *floor*. But when looking at it from the outside? Is there a common word?
I am looking for a word which describes structures that divide a space vertically as opposed to *walls* which divide the space horizontally. | 2014/08/18 | [
"https://english.stackexchange.com/questions/191958",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/88577/"
] | You could use the word *Partition*. It is even more general and doesn't specify vertically or horizontally. It defines an object which separates something into parts.
So: For a building, a partition separates the building into floors, stories, rooms, or whatever your preference is. As TheFreeDictionary.com says,
>
> [partition](http://www.thefreedictionary.com/partition): a division into parts; separation
>
>
> | If you look at Wiki, for architectural use, the phrase you're looking for is "
"Interstitial space". |
191,958 | Walls divide rooms but what do you call what divides stories?
Looking from below it would be the *ceiling*, looking from above it would be the *floor*. But when looking at it from the outside? Is there a common word?
I am looking for a word which describes structures that divide a space vertically as opposed to *walls* which divide the space horizontally. | 2014/08/18 | [
"https://english.stackexchange.com/questions/191958",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/88577/"
] | Believe it or not, the word you are looking for is floor.
It refers to **both** the space between and the actual divisions. But the space between can have other names like story ("storey" in British English).
If it were a house it would be the *roof*.
I think you could use *"floor slab"* or deck.
![enter image description here](https://i.stack.imgur.com/Znoaa.gif) | I think this may be what you're looking for:
Definition from WhatIs.com
searchdatacenter.techtarget.com/definition/plenum
In building construction, a **plenum** (pronounced PLEH-nuhm, from Latin meaning full) is a separate space provided for air circulation for heating, ventilation, and air-conditioning (sometimes referred to as HVAC) and typically provided in the space between the structural ceiling and a drop-down ceiling, or between floors. |
191,958 | Walls divide rooms but what do you call what divides stories?
Looking from below it would be the *ceiling*, looking from above it would be the *floor*. But when looking at it from the outside? Is there a common word?
I am looking for a word which describes structures that divide a space vertically as opposed to *walls* which divide the space horizontally. | 2014/08/18 | [
"https://english.stackexchange.com/questions/191958",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/88577/"
] | You could use the word *Partition*. It is even more general and doesn't specify vertically or horizontally. It defines an object which separates something into parts.
So: For a building, a partition separates the building into floors, stories, rooms, or whatever your preference is. As TheFreeDictionary.com says,
>
> [partition](http://www.thefreedictionary.com/partition): a division into parts; separation
>
>
> | How about *layer*? Or *dividing layer* Or *separating layer* — something like that?
*Stratum* is related to layer, but I think *layer* is less scientific sounding. |
191,958 | Walls divide rooms but what do you call what divides stories?
Looking from below it would be the *ceiling*, looking from above it would be the *floor*. But when looking at it from the outside? Is there a common word?
I am looking for a word which describes structures that divide a space vertically as opposed to *walls* which divide the space horizontally. | 2014/08/18 | [
"https://english.stackexchange.com/questions/191958",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/88577/"
] | A common English term is *stories:*
"This building is seven stories tall."
**EDIT#1**
and alternative is *floor:*
"All the bedrooms are on the fourth floor."
See [3-A](http://www.merriam-webster.com/dictionary/floor) | I think this may be what you're looking for:
Definition from WhatIs.com
searchdatacenter.techtarget.com/definition/plenum
In building construction, a **plenum** (pronounced PLEH-nuhm, from Latin meaning full) is a separate space provided for air circulation for heating, ventilation, and air-conditioning (sometimes referred to as HVAC) and typically provided in the space between the structural ceiling and a drop-down ceiling, or between floors. |
191,958 | Walls divide rooms but what do you call what divides stories?
Looking from below it would be the *ceiling*, looking from above it would be the *floor*. But when looking at it from the outside? Is there a common word?
I am looking for a word which describes structures that divide a space vertically as opposed to *walls* which divide the space horizontally. | 2014/08/18 | [
"https://english.stackexchange.com/questions/191958",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/88577/"
] | The actual word for a vertical partition between two stories is called a **Party Structure**.
Wanted to create a different answer because my other answer was related but different.
* NOTE: This word is used more in the UK than it is in the US.
>
> Party Structure Diagram
>
>
>
![Vertical Partition](https://i.stack.imgur.com/1I6bq.jpg) | If you look at Wiki, for architectural use, the phrase you're looking for is "
"Interstitial space". |
191,958 | Walls divide rooms but what do you call what divides stories?
Looking from below it would be the *ceiling*, looking from above it would be the *floor*. But when looking at it from the outside? Is there a common word?
I am looking for a word which describes structures that divide a space vertically as opposed to *walls* which divide the space horizontally. | 2014/08/18 | [
"https://english.stackexchange.com/questions/191958",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/88577/"
] | Believe it or not, the word you are looking for is floor.
It refers to **both** the space between and the actual divisions. But the space between can have other names like story ("storey" in British English).
If it were a house it would be the *roof*.
I think you could use *"floor slab"* or deck.
![enter image description here](https://i.stack.imgur.com/Znoaa.gif) | You could use the word *Partition*. It is even more general and doesn't specify vertically or horizontally. It defines an object which separates something into parts.
So: For a building, a partition separates the building into floors, stories, rooms, or whatever your preference is. As TheFreeDictionary.com says,
>
> [partition](http://www.thefreedictionary.com/partition): a division into parts; separation
>
>
> |
191,958 | Walls divide rooms but what do you call what divides stories?
Looking from below it would be the *ceiling*, looking from above it would be the *floor*. But when looking at it from the outside? Is there a common word?
I am looking for a word which describes structures that divide a space vertically as opposed to *walls* which divide the space horizontally. | 2014/08/18 | [
"https://english.stackexchange.com/questions/191958",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/88577/"
] | You could use the word *Partition*. It is even more general and doesn't specify vertically or horizontally. It defines an object which separates something into parts.
So: For a building, a partition separates the building into floors, stories, rooms, or whatever your preference is. As TheFreeDictionary.com says,
>
> [partition](http://www.thefreedictionary.com/partition): a division into parts; separation
>
>
> | I think this may be what you're looking for:
Definition from WhatIs.com
searchdatacenter.techtarget.com/definition/plenum
In building construction, a **plenum** (pronounced PLEH-nuhm, from Latin meaning full) is a separate space provided for air circulation for heating, ventilation, and air-conditioning (sometimes referred to as HVAC) and typically provided in the space between the structural ceiling and a drop-down ceiling, or between floors. |
191,958 | Walls divide rooms but what do you call what divides stories?
Looking from below it would be the *ceiling*, looking from above it would be the *floor*. But when looking at it from the outside? Is there a common word?
I am looking for a word which describes structures that divide a space vertically as opposed to *walls* which divide the space horizontally. | 2014/08/18 | [
"https://english.stackexchange.com/questions/191958",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/88577/"
] | Believe it or not, the word you are looking for is floor.
It refers to **both** the space between and the actual divisions. But the space between can have other names like story ("storey" in British English).
If it were a house it would be the *roof*.
I think you could use *"floor slab"* or deck.
![enter image description here](https://i.stack.imgur.com/Znoaa.gif) | The actual word for a vertical partition between two stories is called a **Party Structure**.
Wanted to create a different answer because my other answer was related but different.
* NOTE: This word is used more in the UK than it is in the US.
>
> Party Structure Diagram
>
>
>
![Vertical Partition](https://i.stack.imgur.com/1I6bq.jpg) |
191,958 | Walls divide rooms but what do you call what divides stories?
Looking from below it would be the *ceiling*, looking from above it would be the *floor*. But when looking at it from the outside? Is there a common word?
I am looking for a word which describes structures that divide a space vertically as opposed to *walls* which divide the space horizontally. | 2014/08/18 | [
"https://english.stackexchange.com/questions/191958",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/88577/"
] | The actual word for a vertical partition between two stories is called a **Party Structure**.
Wanted to create a different answer because my other answer was related but different.
* NOTE: This word is used more in the UK than it is in the US.
>
> Party Structure Diagram
>
>
>
![Vertical Partition](https://i.stack.imgur.com/1I6bq.jpg) | I think this may be what you're looking for:
Definition from WhatIs.com
searchdatacenter.techtarget.com/definition/plenum
In building construction, a **plenum** (pronounced PLEH-nuhm, from Latin meaning full) is a separate space provided for air circulation for heating, ventilation, and air-conditioning (sometimes referred to as HVAC) and typically provided in the space between the structural ceiling and a drop-down ceiling, or between floors. |
191,958 | Walls divide rooms but what do you call what divides stories?
Looking from below it would be the *ceiling*, looking from above it would be the *floor*. But when looking at it from the outside? Is there a common word?
I am looking for a word which describes structures that divide a space vertically as opposed to *walls* which divide the space horizontally. | 2014/08/18 | [
"https://english.stackexchange.com/questions/191958",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/88577/"
] | Believe it or not, the word you are looking for is floor.
It refers to **both** the space between and the actual divisions. But the space between can have other names like story ("storey" in British English).
If it were a house it would be the *roof*.
I think you could use *"floor slab"* or deck.
![enter image description here](https://i.stack.imgur.com/Znoaa.gif) | How about *layer*? Or *dividing layer* Or *separating layer* — something like that?
*Stratum* is related to layer, but I think *layer* is less scientific sounding. |
8,480 | I'm making some test for a bitcoin merchant webpage. I want to test different actions without paying transaction fees everytime, but I can't since I use the same few bitcoins for everything.
Sooo how long should I wait for my bitcoins to be transfered wihout fee? | 2013/03/18 | [
"https://bitcoin.stackexchange.com/questions/8480",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/3418/"
] | As the coins "age" they will have a higher priority.
I don't know the algorithm, but believe it is roughly like a day or so and then the age of the coin no longer is a factor.
So if you are seeing minimum fees for coins more than a day after you've received them, it is because of other reasons, such as having outputs at amounts below 0.01 BTC. | In the Bitcoin protocol, fees are totally optional. You can have a fee of 0btc or 10btc.
Once there are more transactions then what fits into a block, which isn't now, miners will choose what transactions to include into their block, and they will prefer transactions with a fee attached, because they get that fee.
Right now, fees don't help process a transaction any sooner or better, but in the future it's likely to make a difference. This totally depends on what happens in the future, and is very much up for debate. |
28,694,509 | I am developing a web application.which contains multiple web forms.
What i need is :-one of my web form contains IFrame (which will open another aspx page with few Textbox and button controls) with close button.
```
If i click on the button in the child form(Iframe form), once complete its action it should call the close button function of the parent form.
here is the code.
```
Parent form code
```
protected void BTNCClose_Click(object sender, EventArgs e)
{
MethodToExecute();
}
public void MethodToExecute() //call this method
{
UPCCharges.Update();
if (HttpContext.Current.Session["CCost"] != null)
{
TxtCCost.Text = Session["CCost"].ToString();
}
if (HttpContext.Current.Session["CYeild"] != null)
{
TxtCYeild.Text = Session["CYeild"].ToString();
}
if (HttpContext.Current.Session["CName"] != null)
{
TxtCName.Text = Session["CName"].ToString();
}
if (TxtCName.Text != "" && TxtCYeild.Text != "" && TxtCCost.Text != "")
{
TxtCrJobId.Text = Session["CJobID"].ToString();
Session.Remove("CCost"); Session.Remove("CYeild");
Session.Remove("CName"); Session.Remove("CJobID");
}
Diva.Visible = false;
IFMC.Visible = false;
}
```
and this is child form(inside the IFrame)
```
protected void BTNCCloseChild_Click(object sender, EventArgs e)
{
for (int vLoop2 = 0; vLoop2 < gvInner.Items.Count; vLoop2++)
{
if (TxtTotalCFrom1 != null && TxtTotalCFrom2 != null)
{
TextBox TxtTotalCFrom = (TextBox)gvInner.Items[vLoop2].FindControl("TxtTCFrom");
TextBox TxtTotalCYeild = (TextBox)gvInner.Items[vLoop2].FindControl("TxtTCYeild");
Session["CCost"] = (mobjGenlib.ConvertDecimal(TxtTFrom1.Text) + mobjGenlib.ConvertDecimal(TxtTFrom2.Text)).ToString();
Session["CYeild"] = (mobjGenlib.ConvertDecimal(TxtRO.Text) - mobjGenlib.ConvertDecimal(TxtTFrom.Text)).ToString();
Session["CName"] = gvInner.Items.Count.Items[vLoop2].Cells[1].Text;
Session["CJobID"] = gvInner.Items.Count.Items[vLoop2].Cells[2].Text;
}
}
//after this i want to call that parent form BTNCClose_Click
}
```
can any one help me to solve this thanks in advance. | 2015/02/24 | [
"https://Stackoverflow.com/questions/28694509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312615/"
] | This is one way that you can handle
in the `BTNCCloseChild_Click` event of the child form, add the following code at the end
```
string script =@"$('the selector of your parent window button',
window.parent.document).click();";
Page.ClientScript.RegisterStartupScript(this.GetType(), "CloseParent", script);
```
You have to change the 'the selector of your parent window button', to appropreate jquery selector to uniquely select the button of the parent form.
You may have to use `window.top` instead of `window.parent`, if there are nested iframes. | Add this line:
ScriptManager.RegisterStartupScript(this, typeof(string), "script", " parent.location.href = parent.location.href;", false);
after this or instead of this
//after this i want to call that parent form BTNCClose\_Click
After storing the values in session object it will refresh the parent page and the values will be updated. |
25,776,613 | I want to loop through a query, but also retain the actual record for the next loop, so I can compare two adjacent rows.
```
CREATE OR REPLACE FUNCTION public.test ()
RETURNS void AS
$body$
DECLARE
previous RECORD;
actual RECORD;
query TEXT;
isdistinct BOOLEAN;
tablename VARCHAR;
columnname VARCHAR;
firstrow BOOLEAN DEFAULT TRUE;
BEGIN
tablename = 'naplo.esemeny';
columnname = 'esemeny_id';
query = 'SELECT * FROM ' || tablename || ' LIMIT 2';
FOR actual IN EXECUTE query LOOP
--do stuff
--save previous record
IF NOT firstrow THEN
EXECUTE 'SELECT ($1).' || columnname || ' IS DISTINCT FROM ($2).' || columnname
INTO isdistinct USING previous, actual;
RAISE NOTICE 'previous: %', previous.esemeny_id;
RAISE NOTICE 'actual: %', actual.esemeny_id;
RAISE NOTICE 'isdistinct: %', isdistinct;
ELSE
firstrow = false;
END IF;
previous = actual;
END LOOP;
RETURN;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;
```
The table:
```
CREATE TABLE naplo.esemeny (
esemeny_id SERIAL,
felhasznalo_id VARCHAR DEFAULT "current_user"() NOT NULL,
kotesszam VARCHAR(10),
idegen_azonosito INTEGER,
esemenytipus_id VARCHAR(10),
letrehozva TIMESTAMP WITHOUT TIME ZONE DEFAULT now() NOT NULL,
szoveg VARCHAR,
munkalap_id VARCHAR(13),
ajanlat_id INTEGER,
CONSTRAINT esemeny_pkey PRIMARY KEY(esemeny_id),
CONSTRAINT esemeny_fk_esemenytipus FOREIGN KEY (esemenytipus_id)
REFERENCES naplo.esemenytipus(esemenytipus_id)
ON DELETE RESTRICT
ON UPDATE RESTRICT
NOT DEFERRABLE
)
WITH (oids = true);
```
The code above doesn't work, the following error message is thrown:
```
ERROR: could not identify column "esemeny_id" in record data type
LINE 1: SELECT ($1).esemeny_id IS DISTINCT FROM ($2).esemeny_id
^
QUERY: SELECT ($1).esemeny_id IS DISTINCT FROM ($2).esemeny_id
CONTEXT: PL/pgSQL function "test" line 18 at EXECUTE statement
LOG: duration: 0.000 ms statement: SET DateStyle TO 'ISO'
```
What am I missing?
Disclaimer: I know the code doesn't make too much sense, I only created so I can demonstrate the problem. | 2014/09/10 | [
"https://Stackoverflow.com/questions/25776613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/733440/"
] | This does not directly answer your question, and may be of no use at all, since you did not really describe your end goal.
If the end goal is to be able to compare the value of a column in the current row with the value of the same column in the previous row, then you might be much better off using a windowing query:
```
SELECT actual, previous
FROM (
SELECT mycolumn AS actual,
lag(mycolumn) OVER () AS previous
FROM mytable
ORDER BY somecriteria
) as q
WHERE previous IS NOT NULL
AND actual IS DISTINCT FROM previous
```
This example prints the rows where the current row is different from the previous row.
Note that I added an ORDER BY clause - it does not make sense to talk about "the previous row" without specifying ordering, otherwise you would get random results.
This is plain SQL, not PlPgSQL, but if you can wrap it in a function if you want to dynamically generate the query. | I am pretty sure, there is a better solution for your actual problem. But to answer the question asked, here is a solution with polymorphic types:
The main problem is that you need **well known composite types** to work with. the structure of anonymous records is undefined until assigned.
```
CREATE OR REPLACE FUNCTION public.test (actual anyelement, _col text
, OUT previous anyelement) AS
$func$
DECLARE
isdistinct bool;
BEGIN
FOR actual IN
EXECUTE format('SELECT * FROM %s LIMIT 3', pg_typeof(actual))
LOOP
EXECUTE format('SELECT ($1).%1$I IS DISTINCT FROM ($2).%1$I', _col)
INTO isdistinct
USING previous, actual;
RAISE NOTICE 'previous: %; actual: %; isdistinct: %'
, previous, actual, isdistinct;
previous := actual;
END LOOP;
previous := NULL; -- reset dummy output (optional)
END
$func$ LANGUAGE plpgsql;
```
Call:
```
SELECT public.test(NULL::naplo.esemeny, 'esemeny_id')
```
I am abusing an `OUT` parameter, since it's not possible to declare additional variables with a polymorphic *composite* type (at least I have failed repeatedly).
If your column name is stable you can replace the second `EXECUTE` with a simple expression.
I am running out of time, explanation in these related answers:
* [Declare variable of composite type in PostgreSQL using %TYPE](https://stackoverflow.com/questions/7634704/declare-variable-of-composite-type-in-postgresql-using-type/7635605#7635605)
* [Refactor a PL/pgSQL function to return the output of various SELECT queries](https://stackoverflow.com/questions/11740256/refactor-a-pl-pgsql-function-to-return-the-output-of-various-select-queries/11751557#11751557)
Asides:
* Don't quote the language name, it's an identifier, not a string.
* Do you really need `WITH (oids = true)` in your table? This is still allowed, but largely deprecated in modern Postgres. |
39,761,098 | how to make a batch number per day,
for example, TODAY I manufacture products with no batch:
1. produk A With batch number => 29092016-1
2. produk B With batch number => 29092016-2
3. produk C With batch number => 29092016-3
TOMORROW no batch should be:
1. produk A With batch number => 30092016-1
2. produk B With batch number => 30092016-2
3. produk C With batch number => 30092016-3
DAY AFTER TOMORROW no batch should be:
1. produk A With batch number => 01102016-1
2. produk B With batch number => 01102016-2
3. produk C With batch number => 01102016-3
How do I have to write a code in PHP ??
i have code but no working :
```
$data_oto = mysql_fetch_array(mysql_query("select max(id_batch2) as maksi from batch2"));
function buatkode($nomor_terakhir, $kunci, $jumlah_karakter = 0){
$nomor_baru = intval(substr($nomor_terakhir, strlen($kunci))) + 1;
$nomor_baru_plus_nol = str_pad($nomor_baru, $jumlah_karakter, "0", STR_PAD_LEFT);
$kode = $kunci . $nomor_baru_plus_nol;
return $kode;}
$date_now=date('dmY');
$batch=buatkode($data_oto['maksi'],$date_now, 1);
mysql_query("INSERT INTO batch2(id_batch2,id_item) VALUES('$batch','$_POST[item]')");
``` | 2016/09/29 | [
"https://Stackoverflow.com/questions/39761098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6845090/"
] | You can use the logical vector produced by grepl() to index vec.
```
txt_paths <- vec[grepl(".txt$", vec)]
``` | We can `split` the `vector` into a `list` of `vector`s
```
lst <- split(vec, tools::file_ext(vec))
names(lst) <- paste0(names(lst), "_paths")
```
It is not recommended to have individual objects in the global environment, but if we prefer that way, use `list2env`
```
list2env(lst, envir = .GlobalEnv)
```
---
If we need to `split` by the file name,
```
lst2 <- split(vec, tools::file_path_sans_ext(basename(vec)))
```
### data
```
vec <- c("\\dir\\subdir\\pathname1\\file.txt",
"\\dir\\subdir\\pathname1\\file.pdf",
"\\dir\\subdir\\pathname9\\file.jpg")
``` |
37,298,586 | Let's say you want to prevent the user from navigating away from your Xamarin.Forms.WebView to an external page.
```
public App ()
{
var webView = new WebView
{
Source = new HtmlWebViewSource
{
Html = "<h1>Hello world</h1><a href='http://example.com'>Can't escape!</a><iframe width='420' height='315' src='https://www.youtube.com/embed/oHg5SJYRHA0' frameborder='0' allowfullscreen></iframe>"
}
};
webView.Navigating += WebView_Navigating;
MainPage = new ContentPage {
Content = webView
};
}
private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
{
// we don't want to navigate away from our page
// open it in a new page instead etc.
e.Cancel = true;
}
```
This works fine on Windows and Android. But on iOS, it doesn't load at all!
On iOS, the Navigating event gets raised even when loading the source from a HtmlWebViewSource, with a URL that looks something like `file:///Users/[user]/Library/Developer/CoreSimulator/Devices/[deviceID]/data/Containers/Bundle/Application/[appID]/[appName].app/`
Alright, so you can get around that with something like this:
```
private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
{
if (e.Url.StartsWith("file:") == false)
e.Cancel = true;
}
```
The page finally loads on iOS. Yay. But wait! The embedded YouTube video doesn't load! That's because the **Navigating event gets raised for the internal navigation** of embedded resources like iframes and even external scripts (like Twitter's `<script charset="utf-8" type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>`), but only on iOS!
I couldn't find a way to determine if the Navigating event was raised from internal navigation or because the user clicked a link.
How to get around this? | 2016/05/18 | [
"https://Stackoverflow.com/questions/37298586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242317/"
] | I am not sure if it is possible to detect in Xamarin Forms out of the box but the navigation type is easily determined using a custom renderer. In your custom iOS renderer, assign a WebViewDelegate and within that Delegate class, override `ShouldStartLoad()` like so:
```
public class CustomWebViewRenderer : WebViewRenderer {
#region Properties
public CustomWebView CustomWebViewItem { get { return Element as CustomWebView; } }
#endregion
protected override void OnElementChanged(VisualElementChangedEventArgs e) {
base.OnElementChanged(e);
if(e.OldElement == null) {
Delegate = new CustomWebViewDelegate(); //Assigning the delegate
}
}
}
internal class CustomWebViewDelegate : UIWebViewDelegate {
public override bool ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType) {
if(navigationType == UIWebViewNavigationType.LinkClicked) {
//To prevent navigation when a link is click, return false
return false;
}
return true;
}
}
```
You could also surface a bool property or even an enum back up to your Xamarin Forms `WebView` which would say whether the `Navigating` event was from a link being clicked or from something else, though a custom renderer would be needed for that as well. | ```
private bool isNavigated = false;
public CustomWebView()
{
if (Device.OS == TargetPlatform.Android)
{
// always true for android
isNavigated = true;
}
Navigated += (sender, e) =>
{
isNavigated = true;
};
Navigating += (sender, e) =>
{
if (isNavigated)
{
try
{
var uri = new Uri(e.Url);
Device.OpenUri(uri);
}
catch (Exception)
{
}
e.Cancel = true;
}
};
}
``` |
54,504,520 | *I am fairly new to Angular and came from React.js background.*
I have made a simple grid component like below:
`grid.component.js`
```js
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-grid',
template: `
<div [ngStyle]="styles()" [ngClass]="passClass">
<ng-content></ng-content>
</div>
`,
styles: [`
div {
display: flex;
}
`]
})
export class GridComponent implements OnInit {
@Input() direction: string;
@Input() justify: string;
@Input() align: string;
@Input() width: string;
@Input() passClass: string;
constructor() { }
ngOnInit() {
}
styles() {
return {
'flex-direction': this.direction || 'row',
'justify-content': this.justify || 'flex-start',
'align-items': this.align || 'flex-start',
...(this.width && { width: this.width })
};
}
}
```
And I want to use it in other components like below:
`aboutus.component.html`
```html
<app-grid passClass="about-us page-container">
<app-grid direction="column" passClass="left">
<div class="title blue bold">
An open community For Everyone
</div>
<div class="large-desc grey">
This conference is brought to you by
the Go Language Community in
India together with the Emerging
Technology Trust (ETT). ETT is a non-
profit organization, established to
organize and conduct technology
conferences in India. It’s current
portfolio includes
</div>
</app-grid>
</app-grid>
```
`aboutus.component.sass`
```css
.about-us
position: relative
.left
width: 50%
&:after
bottom: 0
right: 0
z-index: 0
margin-right: -5vw
position: absolute
content: url(../../assets/images/footer.svg)
```
But, what happens is the CSS attached with the second component will not work.
I know a little bit about CSS isolation but could not understand if it affects here.
P.S.: Please feel free to provide feedback to things outside of scope this question as well. | 2019/02/03 | [
"https://Stackoverflow.com/questions/54504520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6880789/"
] | It is not possible to pass CSS classes as variables in your template. So if your expectation in `aboutus.component.html` was to be able to pass the `left` CSS class as a variable in your template, that will not work.
There are a few things I can point out that will hopefully help:
1. If you want to modify a CSS class that is internal to a component from outside that component, one option is to use [ng-deep](https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep).
2. In your particular case, I don't think `ng-deep` is necessary. I'd suggest to drop the `div` element within the `app-grid` component and instead apply the styles to the host element using `@HostBinding` decorator. With that approach you can drop the `passCss` altogether because now wherever you use your`app-grid` component you can style that component in CSS using the `app-grid` selector.
grid.component.ts:
```
import { Component, OnInit, Input, HostBinding, SafeStyle } from '@angular/core';
@Component({
selector: 'app-grid',
template: `<ng-content></ng-content>`,
styles: [`
:host {
display: flex;
}
`]
})
export class GridComponent implements OnInit {
@Input() direction: string;
@Input() justify: string;
@Input() align: string;
@Input() width: string;
constructor(private sanitizer:DomSanitizer) { }
ngOnInit() {
}
@HostBinding('style')
styles(): SafeStyle {
const styles = `
flex-direction: ${this.direction || 'row'};
justify-content: ${this.justify || 'flex-start'};
align-items: ${this.align || 'flex-start'};
`;
return this.sanitizer.bypassSecurityTrustStyle(styles);
}
}
```
aboutus.component.sass:
```
app-grid {
// You can style the host element of a component
// just like any native HTML element and without
// needing to use `ng-deep`
}
```
3. You may also want to look into [CSS Custom Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables#Basic_usage). Custom CSS properties are not shielded by view-encapsulation. This gives you the ability to create a CSS API for a component, if you will, and those properties can be used anywhere within a component.
aboutus.component.sass
```
app-grid {
--image: url(../../assets/images/footer.svg)
}
```
grid.component.sass
```
div {
content: var(--image);
}
``` | If you want style some element in other component use `:host` and `/deep/` modifiers(deprecated - [Alternative to /deep/](https://stackoverflow.com/questions/51708972/alternative-to-deep)). More about this feature you can read in [documentation](https://angular.io/guide/component-styles#special-selectors)
In your case this should work:
```css
:host /deep/ {
.left {
width: 50%
&:after {
bottom: 0
right: 0
z-index: 0
margin-right: -5vw
position: absolute
content: url(../../assets/images/footer.svg)
}
}
}
```
You can also disable encapsulation for this component:
```
@Component({
selector: 'app-grid',
template: `
<div [ngStyle]="styles()" [ngClass]="passClass">
<ng-content></ng-content>
</div>
`,
styles: [`
div {
display: flex;
}
`],
encapsulation: ViewEncapsulation.None
})
``` |
5,412,724 | I have been playing around with different filesystems and comparing the performance of the various filesystems when using mmap.
I am suprised that changing to JFS doubled the write performance straight off.
I thought writes were done to the page cache and so when a write is done the app keeps moving on quickly? is it actually a synchronous operation under linux?
A slight increase in read performance, but not as significant. | 2011/03/23 | [
"https://Stackoverflow.com/questions/5412724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134702/"
] | Writes *are* done straight to the page cache, but the first time you hit each page with a write will cause a minor fault to mark the page as dirty. At this point the filesystem has the chance to perform some work - in the case of `xfs`, this involves delayed allocation accounting and extent creation. You could try preallocating the entire file beforehand to see how/if this changes things. (`jfs` uses the generic mmap operations, which does not supply a callback used when a page is made writeable).
Note also that once the proportion of dirty pagecache pages exceeds `/proc/sys/vm/dirty_ratio`, the kernel will switch from background asynchronous writeback to synchronous writeback of dirty pages by the process that dirtied them. | Perhaps you should look at the benchmarks for each filesystem. Each FS is fast at certain conditions AFAIK.
<http://fsbench.netnation.com/> was one of the first hits in my Google for xfs jfs benchmarks. Skimming at the results appears to suggest xfs fares better at speed on many occasions.
I suggest you run the benchmarks on the target machines to find out for yourself.
One guess is, the speedup you noticed could very well be in the best case areas of jfs. |
5,412,724 | I have been playing around with different filesystems and comparing the performance of the various filesystems when using mmap.
I am suprised that changing to JFS doubled the write performance straight off.
I thought writes were done to the page cache and so when a write is done the app keeps moving on quickly? is it actually a synchronous operation under linux?
A slight increase in read performance, but not as significant. | 2011/03/23 | [
"https://Stackoverflow.com/questions/5412724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134702/"
] | One significant difference between XFS and JFS is that XFS supports barriers and enables them by default, but JFS doesn't support barriers at all. Hence JFS is unsafe (but fast!) when running on disks with write-back cache.
JFS having better write performance in your tests might be an effect of this. | Perhaps you should look at the benchmarks for each filesystem. Each FS is fast at certain conditions AFAIK.
<http://fsbench.netnation.com/> was one of the first hits in my Google for xfs jfs benchmarks. Skimming at the results appears to suggest xfs fares better at speed on many occasions.
I suggest you run the benchmarks on the target machines to find out for yourself.
One guess is, the speedup you noticed could very well be in the best case areas of jfs. |
5,412,724 | I have been playing around with different filesystems and comparing the performance of the various filesystems when using mmap.
I am suprised that changing to JFS doubled the write performance straight off.
I thought writes were done to the page cache and so when a write is done the app keeps moving on quickly? is it actually a synchronous operation under linux?
A slight increase in read performance, but not as significant. | 2011/03/23 | [
"https://Stackoverflow.com/questions/5412724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134702/"
] | Writes *are* done straight to the page cache, but the first time you hit each page with a write will cause a minor fault to mark the page as dirty. At this point the filesystem has the chance to perform some work - in the case of `xfs`, this involves delayed allocation accounting and extent creation. You could try preallocating the entire file beforehand to see how/if this changes things. (`jfs` uses the generic mmap operations, which does not supply a callback used when a page is made writeable).
Note also that once the proportion of dirty pagecache pages exceeds `/proc/sys/vm/dirty_ratio`, the kernel will switch from background asynchronous writeback to synchronous writeback of dirty pages by the process that dirtied them. | One significant difference between XFS and JFS is that XFS supports barriers and enables them by default, but JFS doesn't support barriers at all. Hence JFS is unsafe (but fast!) when running on disks with write-back cache.
JFS having better write performance in your tests might be an effect of this. |
846,395 | I would like to be able to display a `DateTimePicker` that has a default value of nothing, i.e. no date.
For example, I have a start date `dtTaskStart` and an end date `dtTaskEnd` for a task, but the end date is not known, and not populated initially.
I have specified a custom format of `yyyy-MM-dd` for both controls.
Setting the value to `null`, or an empty string at runtime causes an error, so how can I accomplish this?
I have considered using a checkbox to control the enabling of this field, but there is still the issue of displaying an initial value..
*Edit:*
Arguably a duplicate of the question [DateTimePicker Null Value (.NET)](https://stackoverflow.com/questions/284364/datetimepicker-null-value-net), but the solution I found for my problem is not a solution for that question, so I think it should remain here for others to find.. | 2009/05/11 | [
"https://Stackoverflow.com/questions/846395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | In case anybody has an issue with setting datetimepicker control to blank during the form load event, and then show the current date as needed, here is an example:
MAKE SURE THAT `CustomFormat = " "` has same number of spaces (at least one space) in both methods
```
Private Sub setDateTimePickerBlank(ByVal dateTimePicker As DateTimePicker)
dateTimePicker.Visible = True
dateTimePicker.Format = DateTimePickerFormat.Custom
dateTimePicker.CustomFormat = " "
End Sub
Private Sub dateTimePicker_MouseHover(ByVal sender As Object, ByVal e As
System.EventArgs) Handles dateTimePicker.MouseHover
Dim dateTimePicker As DateTimePicker = CType(sender, DateTimePicker)
If dateTimePicker.Text = " " Then
dateTimePicker.Text = Format(DateTime.Now, "MM/dd/yyyy")
End If
End Sub
``` | Better to use text box for calling/displaying date and while saving use DateTimePicker.
Make visible property true or false as per requirement.
For eg : During form load make Load date in Textbox and make DTPIcker invisible and while adding vice versa |
846,395 | I would like to be able to display a `DateTimePicker` that has a default value of nothing, i.e. no date.
For example, I have a start date `dtTaskStart` and an end date `dtTaskEnd` for a task, but the end date is not known, and not populated initially.
I have specified a custom format of `yyyy-MM-dd` for both controls.
Setting the value to `null`, or an empty string at runtime causes an error, so how can I accomplish this?
I have considered using a checkbox to control the enabling of this field, but there is still the issue of displaying an initial value..
*Edit:*
Arguably a duplicate of the question [DateTimePicker Null Value (.NET)](https://stackoverflow.com/questions/284364/datetimepicker-null-value-net), but the solution I found for my problem is not a solution for that question, so I think it should remain here for others to find.. | 2009/05/11 | [
"https://Stackoverflow.com/questions/846395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | Obfuscating the value by using the `CustomFormat` property, using checkbox `cbEnableEndDate` as the flag to indicate whether other code should ignore the value:
```vb
If dateTaskEnd > Date.FromOADate(0) Then
dtTaskEnd.Format = DateTimePickerFormat.Custom
dtTaskEnd.CustomFormat = "yyyy-MM-dd"
dtTaskEnd.Value = dateTaskEnd
dtTaskEnd.Enabled = True
cbEnableEndDate.Checked = True
Else
dtTaskEnd.Format = DateTimePickerFormat.Custom
dtTaskEnd.CustomFormat = " "
dtTaskEnd.Value = Date.FromOADate(0)
dtTaskEnd.Enabled = False
cbEnableEndDate.Checked = False
End If
``` | Better to use text box for calling/displaying date and while saving use DateTimePicker.
Make visible property true or false as per requirement.
For eg : During form load make Load date in Textbox and make DTPIcker invisible and while adding vice versa |
846,395 | I would like to be able to display a `DateTimePicker` that has a default value of nothing, i.e. no date.
For example, I have a start date `dtTaskStart` and an end date `dtTaskEnd` for a task, but the end date is not known, and not populated initially.
I have specified a custom format of `yyyy-MM-dd` for both controls.
Setting the value to `null`, or an empty string at runtime causes an error, so how can I accomplish this?
I have considered using a checkbox to control the enabling of this field, but there is still the issue of displaying an initial value..
*Edit:*
Arguably a duplicate of the question [DateTimePicker Null Value (.NET)](https://stackoverflow.com/questions/284364/datetimepicker-null-value-net), but the solution I found for my problem is not a solution for that question, so I think it should remain here for others to find.. | 2009/05/11 | [
"https://Stackoverflow.com/questions/846395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | this worked for me for c#
```
if (enableEndDateCheckBox.Checked == true)
{
endDateDateTimePicker.Enabled = true;
endDateDateTimePicker.Format = DateTimePickerFormat.Short;
}
else
{
endDateDateTimePicker.Enabled = false;
endDateDateTimePicker.Format = DateTimePickerFormat.Custom;
endDateDateTimePicker.CustomFormat = " ";
}
```
nice one guys! | In case anybody has an issue with setting datetimepicker control to blank during the form load event, and then show the current date as needed, here is an example:
MAKE SURE THAT `CustomFormat = " "` has same number of spaces (at least one space) in both methods
```
Private Sub setDateTimePickerBlank(ByVal dateTimePicker As DateTimePicker)
dateTimePicker.Visible = True
dateTimePicker.Format = DateTimePickerFormat.Custom
dateTimePicker.CustomFormat = " "
End Sub
Private Sub dateTimePicker_MouseHover(ByVal sender As Object, ByVal e As
System.EventArgs) Handles dateTimePicker.MouseHover
Dim dateTimePicker As DateTimePicker = CType(sender, DateTimePicker)
If dateTimePicker.Text = " " Then
dateTimePicker.Text = Format(DateTime.Now, "MM/dd/yyyy")
End If
End Sub
``` |
846,395 | I would like to be able to display a `DateTimePicker` that has a default value of nothing, i.e. no date.
For example, I have a start date `dtTaskStart` and an end date `dtTaskEnd` for a task, but the end date is not known, and not populated initially.
I have specified a custom format of `yyyy-MM-dd` for both controls.
Setting the value to `null`, or an empty string at runtime causes an error, so how can I accomplish this?
I have considered using a checkbox to control the enabling of this field, but there is still the issue of displaying an initial value..
*Edit:*
Arguably a duplicate of the question [DateTimePicker Null Value (.NET)](https://stackoverflow.com/questions/284364/datetimepicker-null-value-net), but the solution I found for my problem is not a solution for that question, so I think it should remain here for others to find.. | 2009/05/11 | [
"https://Stackoverflow.com/questions/846395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | Obfuscating the value by using the `CustomFormat` property, using checkbox `cbEnableEndDate` as the flag to indicate whether other code should ignore the value:
```vb
If dateTaskEnd > Date.FromOADate(0) Then
dtTaskEnd.Format = DateTimePickerFormat.Custom
dtTaskEnd.CustomFormat = "yyyy-MM-dd"
dtTaskEnd.Value = dateTaskEnd
dtTaskEnd.Enabled = True
cbEnableEndDate.Checked = True
Else
dtTaskEnd.Format = DateTimePickerFormat.Custom
dtTaskEnd.CustomFormat = " "
dtTaskEnd.Value = Date.FromOADate(0)
dtTaskEnd.Enabled = False
cbEnableEndDate.Checked = False
End If
``` | this worked for me for c#
```
if (enableEndDateCheckBox.Checked == true)
{
endDateDateTimePicker.Enabled = true;
endDateDateTimePicker.Format = DateTimePickerFormat.Short;
}
else
{
endDateDateTimePicker.Enabled = false;
endDateDateTimePicker.Format = DateTimePickerFormat.Custom;
endDateDateTimePicker.CustomFormat = " ";
}
```
nice one guys! |
846,395 | I would like to be able to display a `DateTimePicker` that has a default value of nothing, i.e. no date.
For example, I have a start date `dtTaskStart` and an end date `dtTaskEnd` for a task, but the end date is not known, and not populated initially.
I have specified a custom format of `yyyy-MM-dd` for both controls.
Setting the value to `null`, or an empty string at runtime causes an error, so how can I accomplish this?
I have considered using a checkbox to control the enabling of this field, but there is still the issue of displaying an initial value..
*Edit:*
Arguably a duplicate of the question [DateTimePicker Null Value (.NET)](https://stackoverflow.com/questions/284364/datetimepicker-null-value-net), but the solution I found for my problem is not a solution for that question, so I think it should remain here for others to find.. | 2009/05/11 | [
"https://Stackoverflow.com/questions/846395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | In case anybody has an issue with setting datetimepicker control to blank during the form load event, and then show the current date as needed, here is an example:
MAKE SURE THAT `CustomFormat = " "` has same number of spaces (at least one space) in both methods
```
Private Sub setDateTimePickerBlank(ByVal dateTimePicker As DateTimePicker)
dateTimePicker.Visible = True
dateTimePicker.Format = DateTimePickerFormat.Custom
dateTimePicker.CustomFormat = " "
End Sub
Private Sub dateTimePicker_MouseHover(ByVal sender As Object, ByVal e As
System.EventArgs) Handles dateTimePicker.MouseHover
Dim dateTimePicker As DateTimePicker = CType(sender, DateTimePicker)
If dateTimePicker.Text = " " Then
dateTimePicker.Text = Format(DateTime.Now, "MM/dd/yyyy")
End If
End Sub
``` | When I want to display an empty date value I do this
```
if (sStrDate != "")
{
dateCreated.Value = DateTime.Parse(sStrDate);
}
else
{
dateCreated.CustomFormat = " ";
dateCreated.Format = DateTimePickerFormat.Custom;
}
```
Then when the user clicks on the control I have this:
```
private void dateControl_MouseDown(object sender, MouseEventArgs e)
{
((DateTimePicker)sender).Format = DateTimePickerFormat.Long;
}
```
This allows you to display and use an empty date value, but still allow the user to be able to change the date to something when they wish.
Keep in mind that sStrDate has already been validated as a valid date string. |
846,395 | I would like to be able to display a `DateTimePicker` that has a default value of nothing, i.e. no date.
For example, I have a start date `dtTaskStart` and an end date `dtTaskEnd` for a task, but the end date is not known, and not populated initially.
I have specified a custom format of `yyyy-MM-dd` for both controls.
Setting the value to `null`, or an empty string at runtime causes an error, so how can I accomplish this?
I have considered using a checkbox to control the enabling of this field, but there is still the issue of displaying an initial value..
*Edit:*
Arguably a duplicate of the question [DateTimePicker Null Value (.NET)](https://stackoverflow.com/questions/284364/datetimepicker-null-value-net), but the solution I found for my problem is not a solution for that question, so I think it should remain here for others to find.. | 2009/05/11 | [
"https://Stackoverflow.com/questions/846395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | this worked for me for c#
```
if (enableEndDateCheckBox.Checked == true)
{
endDateDateTimePicker.Enabled = true;
endDateDateTimePicker.Format = DateTimePickerFormat.Short;
}
else
{
endDateDateTimePicker.Enabled = false;
endDateDateTimePicker.Format = DateTimePickerFormat.Custom;
endDateDateTimePicker.CustomFormat = " ";
}
```
nice one guys! | The basic concept is the same told by others. But its easier to implement this way when you have multiple dateTimePicker.
```
dateTimePicker1.Value = DateTime.Now;
dateTimePicker1.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker1.ShowCheckBox=true;
dateTimePicker1.Checked=false;
dateTimePicker2.Value = DateTime.Now;
dateTimePicker2.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker2.ShowCheckBox=true;
dateTimePicker2.Checked=false;
```
the value changed event function
```
void Dtp_ValueChanged(object sender, EventArgs e)
{
if(((DateTimePicker)sender).ShowCheckBox==true)
{
if(((DateTimePicker)sender).Checked==false)
{
((DateTimePicker)sender).CustomFormat = " ";
((DateTimePicker)sender).Format = DateTimePickerFormat.Custom;
}
else
{
((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
}
}
else
{
((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
}
}
```
When unchecked
[![enter image description here](https://i.stack.imgur.com/9VkxR.png)](https://i.stack.imgur.com/9VkxR.png)
When checked
[![enter image description here](https://i.stack.imgur.com/W9QGw.png)](https://i.stack.imgur.com/W9QGw.png) |
846,395 | I would like to be able to display a `DateTimePicker` that has a default value of nothing, i.e. no date.
For example, I have a start date `dtTaskStart` and an end date `dtTaskEnd` for a task, but the end date is not known, and not populated initially.
I have specified a custom format of `yyyy-MM-dd` for both controls.
Setting the value to `null`, or an empty string at runtime causes an error, so how can I accomplish this?
I have considered using a checkbox to control the enabling of this field, but there is still the issue of displaying an initial value..
*Edit:*
Arguably a duplicate of the question [DateTimePicker Null Value (.NET)](https://stackoverflow.com/questions/284364/datetimepicker-null-value-net), but the solution I found for my problem is not a solution for that question, so I think it should remain here for others to find.. | 2009/05/11 | [
"https://Stackoverflow.com/questions/846395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | Obfuscating the value by using the `CustomFormat` property, using checkbox `cbEnableEndDate` as the flag to indicate whether other code should ignore the value:
```vb
If dateTaskEnd > Date.FromOADate(0) Then
dtTaskEnd.Format = DateTimePickerFormat.Custom
dtTaskEnd.CustomFormat = "yyyy-MM-dd"
dtTaskEnd.Value = dateTaskEnd
dtTaskEnd.Enabled = True
cbEnableEndDate.Checked = True
Else
dtTaskEnd.Format = DateTimePickerFormat.Custom
dtTaskEnd.CustomFormat = " "
dtTaskEnd.Value = Date.FromOADate(0)
dtTaskEnd.Enabled = False
cbEnableEndDate.Checked = False
End If
``` | In case anybody has an issue with setting datetimepicker control to blank during the form load event, and then show the current date as needed, here is an example:
MAKE SURE THAT `CustomFormat = " "` has same number of spaces (at least one space) in both methods
```
Private Sub setDateTimePickerBlank(ByVal dateTimePicker As DateTimePicker)
dateTimePicker.Visible = True
dateTimePicker.Format = DateTimePickerFormat.Custom
dateTimePicker.CustomFormat = " "
End Sub
Private Sub dateTimePicker_MouseHover(ByVal sender As Object, ByVal e As
System.EventArgs) Handles dateTimePicker.MouseHover
Dim dateTimePicker As DateTimePicker = CType(sender, DateTimePicker)
If dateTimePicker.Text = " " Then
dateTimePicker.Text = Format(DateTime.Now, "MM/dd/yyyy")
End If
End Sub
``` |
846,395 | I would like to be able to display a `DateTimePicker` that has a default value of nothing, i.e. no date.
For example, I have a start date `dtTaskStart` and an end date `dtTaskEnd` for a task, but the end date is not known, and not populated initially.
I have specified a custom format of `yyyy-MM-dd` for both controls.
Setting the value to `null`, or an empty string at runtime causes an error, so how can I accomplish this?
I have considered using a checkbox to control the enabling of this field, but there is still the issue of displaying an initial value..
*Edit:*
Arguably a duplicate of the question [DateTimePicker Null Value (.NET)](https://stackoverflow.com/questions/284364/datetimepicker-null-value-net), but the solution I found for my problem is not a solution for that question, so I think it should remain here for others to find.. | 2009/05/11 | [
"https://Stackoverflow.com/questions/846395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | this worked for me for c#
```
if (enableEndDateCheckBox.Checked == true)
{
endDateDateTimePicker.Enabled = true;
endDateDateTimePicker.Format = DateTimePickerFormat.Short;
}
else
{
endDateDateTimePicker.Enabled = false;
endDateDateTimePicker.Format = DateTimePickerFormat.Custom;
endDateDateTimePicker.CustomFormat = " ";
}
```
nice one guys! | When I want to display an empty date value I do this
```
if (sStrDate != "")
{
dateCreated.Value = DateTime.Parse(sStrDate);
}
else
{
dateCreated.CustomFormat = " ";
dateCreated.Format = DateTimePickerFormat.Custom;
}
```
Then when the user clicks on the control I have this:
```
private void dateControl_MouseDown(object sender, MouseEventArgs e)
{
((DateTimePicker)sender).Format = DateTimePickerFormat.Long;
}
```
This allows you to display and use an empty date value, but still allow the user to be able to change the date to something when they wish.
Keep in mind that sStrDate has already been validated as a valid date string. |
846,395 | I would like to be able to display a `DateTimePicker` that has a default value of nothing, i.e. no date.
For example, I have a start date `dtTaskStart` and an end date `dtTaskEnd` for a task, but the end date is not known, and not populated initially.
I have specified a custom format of `yyyy-MM-dd` for both controls.
Setting the value to `null`, or an empty string at runtime causes an error, so how can I accomplish this?
I have considered using a checkbox to control the enabling of this field, but there is still the issue of displaying an initial value..
*Edit:*
Arguably a duplicate of the question [DateTimePicker Null Value (.NET)](https://stackoverflow.com/questions/284364/datetimepicker-null-value-net), but the solution I found for my problem is not a solution for that question, so I think it should remain here for others to find.. | 2009/05/11 | [
"https://Stackoverflow.com/questions/846395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | Just set the property as follows:
When the user press "clear button" or "delete key" do
```vb
dtpData.CustomFormat = " " 'An empty SPACE
dtpData.Format = DateTimePickerFormat.Custom
```
On `DateTimePicker1_ValueChanged` event do
```vb
dtpData.CustomFormat = "dd/MM/yyyy hh:mm:ss"
``` | The basic concept is the same told by others. But its easier to implement this way when you have multiple dateTimePicker.
```
dateTimePicker1.Value = DateTime.Now;
dateTimePicker1.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker1.ShowCheckBox=true;
dateTimePicker1.Checked=false;
dateTimePicker2.Value = DateTime.Now;
dateTimePicker2.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
dateTimePicker2.ShowCheckBox=true;
dateTimePicker2.Checked=false;
```
the value changed event function
```
void Dtp_ValueChanged(object sender, EventArgs e)
{
if(((DateTimePicker)sender).ShowCheckBox==true)
{
if(((DateTimePicker)sender).Checked==false)
{
((DateTimePicker)sender).CustomFormat = " ";
((DateTimePicker)sender).Format = DateTimePickerFormat.Custom;
}
else
{
((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
}
}
else
{
((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
}
}
```
When unchecked
[![enter image description here](https://i.stack.imgur.com/9VkxR.png)](https://i.stack.imgur.com/9VkxR.png)
When checked
[![enter image description here](https://i.stack.imgur.com/W9QGw.png)](https://i.stack.imgur.com/W9QGw.png) |
846,395 | I would like to be able to display a `DateTimePicker` that has a default value of nothing, i.e. no date.
For example, I have a start date `dtTaskStart` and an end date `dtTaskEnd` for a task, but the end date is not known, and not populated initially.
I have specified a custom format of `yyyy-MM-dd` for both controls.
Setting the value to `null`, or an empty string at runtime causes an error, so how can I accomplish this?
I have considered using a checkbox to control the enabling of this field, but there is still the issue of displaying an initial value..
*Edit:*
Arguably a duplicate of the question [DateTimePicker Null Value (.NET)](https://stackoverflow.com/questions/284364/datetimepicker-null-value-net), but the solution I found for my problem is not a solution for that question, so I think it should remain here for others to find.. | 2009/05/11 | [
"https://Stackoverflow.com/questions/846395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | this worked for me for c#
```
if (enableEndDateCheckBox.Checked == true)
{
endDateDateTimePicker.Enabled = true;
endDateDateTimePicker.Format = DateTimePickerFormat.Short;
}
else
{
endDateDateTimePicker.Enabled = false;
endDateDateTimePicker.Format = DateTimePickerFormat.Custom;
endDateDateTimePicker.CustomFormat = " ";
}
```
nice one guys! | Better to use text box for calling/displaying date and while saving use DateTimePicker.
Make visible property true or false as per requirement.
For eg : During form load make Load date in Textbox and make DTPIcker invisible and while adding vice versa |
9,258,048 | This question applies to executables on Windows.
What are some alternative ways of storing data in an executable, then read it later at runtime.
I only know one, which is Win32 resources. Other options?
I honestly don't know how to search on this one, so sorry if this seems like a bad question. | 2012/02/13 | [
"https://Stackoverflow.com/questions/9258048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203391/"
] | Check that the search filter used is consistent with your active directory records.
I had the same exception in my web app recently. The user credential were correct and the ActiveDirectoryLdapAuthenticationProvider was binding/authenticating correctly. The failure occurred after binding when searching for groups and other attributes for the authenticated record.
If you look at the code in ActiveDirectoryLdapAuthenticationProvider it has hard coded values for the search filter and it always uses the bind principal to search.
this method
```
private DirContextOperations searchForUser(DirContext ctx, String username) throws NamingException {
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=user)(userPrincipalName={0}))";
final String bindPrincipal = createBindPrincipal(username);
String searchRoot = rootDn != null ? rootDn : searchRootFromPrincipal(bindPrincipal);
return SpringSecurityLdapTemplate.searchForSingleEntryInternal(ctx, searchCtls, searchRoot, searchFilter,
new Object[]{bindPrincipal});
}
```
A [Jira issue](https://jira.springsource.org/browse/SEC-1915) has been submitted and already has a patch. | I had the same problem `IncorrectResultSizeDataAccessException` whilst trying to authenticate against Active Directory. I haven't solved this particular issue directly, but I have implemented a workaround, which is fully functional, but does mean you need to have a "service account" username and password to establish communication with AD. I guess it uses the "general" Spring LDAP approach, rather than a special AD one.
I followed the recipe here:
[Active Directory Spring Security XML config, on the SpringSource forum](http://forum.springsource.org/showthread.php?125336-Spring-Security-with-Active-Directory&p=411213#post411213 "Active Directory Spring Security XML config")
Here's my `security-context.xml` file, for reference:
```
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
">
<!-- There is some Java based config here, don't forget. -->
<!-- Its not important for this example-->
<context:component-scan base-package="uk.ac.example.ldaptest.security" />
<!-- This is for our Active Dir LDAP implementation -->
<beans:bean id="contextSource"
class="org.springframework.ldap.core.support.LdapContextSource">
<beans:property name="url"
value="LDAP://ads.ntd.example.ac.uk:389" />
<beans:property name="base" value="dc=ntd,dc=example,dc=ac,dc=uk" />
<beans:property name="userDn" value="cn=ldap,ou=Service Accounts,ou=Management,ou=example,dc=ntd,dc=example,dc=ac,dc=uk" />
<beans:property name="password" value="XXXXXXXXX" />
<beans:property name="pooled" value="true" />
<!-- AD Specific Setting for avoiding the partial exception error -->
<beans:property name="referral" value="follow" />
</beans:bean>
<beans:bean id="ldapAuthenticationProvider"
class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
<beans:constructor-arg>
<beans:bean
class="org.springframework.security.ldap.authentication.BindAuthenticator">
<beans:constructor-arg ref="contextSource" />
<beans:property name="userSearch">
<beans:bean id="userSearch"
class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
<beans:constructor-arg index="0" value="" />
<beans:constructor-arg index="1" value="(sAMAccountName={0})" />
<beans:constructor-arg index="2" ref="contextSource" />
</beans:bean>
</beans:property>
</beans:bean>
</beans:constructor-arg>
<beans:constructor-arg>
<beans:bean
class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
<beans:constructor-arg ref="contextSource" />
<beans:constructor-arg value="" />
<beans:property name="groupSearchFilter" value="(member={0})" />
<beans:property name="searchSubtree" value="true" />
<!-- Below Settings convert the adds the prefix ROLE_ to roles returned
from AD -->
</beans:bean>
</beans:constructor-arg>
<!-- Create the Mapper object that returns our customised User object -->
<!-- Set up in the Java based config mentioned earlier -->
<beans:property name="userDetailsContextMapper" ref="myUdcm" />
</beans:bean>
<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:constructor-arg>
<beans:list>
<beans:ref local="ldapAuthenticationProvider" />
</beans:list>
</beans:constructor-arg>
</beans:bean>
<!-- we want all URLs within our application to be secured, requiring the
role ROLE_STAFF to access them. LDAP supplies this -->
<http auto-config="true" use-expressions="true"
authentication-manager-ref="authenticationManager">
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_STAFF')" />
<session-management>
<concurrency-control max-sessions="1" />
</session-management>
</http>
``` |
9,258,048 | This question applies to executables on Windows.
What are some alternative ways of storing data in an executable, then read it later at runtime.
I only know one, which is Win32 resources. Other options?
I honestly don't know how to search on this one, so sorry if this seems like a bad question. | 2012/02/13 | [
"https://Stackoverflow.com/questions/9258048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203391/"
] | The error IncorrectResultSizeDataAccessException was caused by a bug within org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl
if you look into the following code, when the token seriesId doesn't exist, should not throw the error "more than one value".
```
public PersistentRememberMeToken getTokenForSeries(String seriesId) {
try {
return (PersistentRememberMeToken) tokensBySeriesMapping.findObject(seriesId);
} catch(IncorrectResultSizeDataAccessException moreThanOne) {
logger.error("Querying token for series '" + seriesId + "' returned more than one value. Series" +
" should be unique");
} catch(DataAccessException e) {
logger.error("Failed to load token for series " + seriesId, e);
}
return null;
}
```
You can implement you own token repository dao, here is mine:
```
/**
* Save/cache the login token, retrieve or update it for remember-me feature.
*
* create table persistent_logins (username varchar(64) not null, series varchar(64) primary key,
* token varchar(64) not null, last_used timestamp not null)
*
* @author lchen
*
*/
public class TokenRepositoryDao extends BaseDao implements PersistentTokenRepository {
@Override
public void createNewToken(PersistentRememberMeToken token) {
String sql = "insert into persistent_logins (username, series, token, last_used) values(?,?,?,?)";
getJdbcTemplate().update(sql, token.getUsername(), token.getSeries(), token.getTokenValue(), token.getDate());
}
@Override
public PersistentRememberMeToken getTokenForSeries(String series) {
String sql = "select username,series,token,last_used from persistent_logins where series = ?";
try {
return getJdbcTemplate().queryForObject(sql, new PersistentRememberMeTokenMapper(), series);
} catch (IncorrectResultSizeDataAccessException moreThanOne) {
if (moreThanOne.getActualSize() > 1)
logger.error("Querying token for series '" + series + "' returned more than one value. Series" + " should be unique");
} catch (DataAccessException e) {
logger.error("Failed to load token for series " + series, e);
}
return null;
}
@Override
public void removeUserTokens(String username) {
String sql = "delete from persistent_logins where username = ?";
getJdbcTemplate().update(sql, username);
}
@Override
public void updateToken(String series, String tokenValue, Date lastUsed) {
String sql = "update persistent_logins set token = ?, last_used = ? where series = ?";
getJdbcTemplate().update(sql, tokenValue, new Date(), series);
}
private class PersistentRememberMeTokenMapper implements RowMapper<PersistentRememberMeToken> {
@Override
public PersistentRememberMeToken mapRow(ResultSet rs, int rowNum) throws SQLException {
String username = rs.getString("username");
String series = rs.getString("series");
String token = rs.getString("token");
Date date = rs.getDate("last_used");
return new PersistentRememberMeToken(username, series, token, date);
}
}
}
```
Following is the workable configs for spring security:
```
<security:http pattern="/common/**" security="none" />
<security:http pattern="/styles/**" security="none" />
<security:http pattern="/images/**" security="none" />
<security:http pattern="/scripts/**" security="none" />
<security:http pattern="/layouts/**" security="none" />
<security:http use-expressions="true">
<security:intercept-url pattern="/login.do" access="permitAll" />
<security:intercept-url pattern="/logout.do" access="permitAll" />
<security:intercept-url pattern="/login/failure.do" access="permitAll" />
<security:intercept-url pattern="/index.jsp" access="permitAll" />
<security:intercept-url pattern="/home/**" access="isAuthenticated()" />
<security:intercept-url pattern="/upload/**" access="hasRole('ROLE_USER')" />
<security:intercept-url pattern="/**" access="denyAll" />
<security:form-login login-page="/login.do" authentication-failure-url="/login/failure.do" default-target-url="/" />
<security:logout logout-url="/logout.do" logout-success-url="/" delete-cookies="JSESSIONID" />
<security:remember-me user-service-ref="userDetailsService" token-repository-ref="tokenRepository" token-validity-seconds="1296000" />
</security:http>
<bean id="tokenRepository" class="com.abc.dao.TokenRepositoryDao" />
<security:authentication-manager>
<security:authentication-provider ref="ldapAuthProvider" />
</security:authentication-manager>
<bean id="userDetailsService" class="org.springframework.security.ldap.userdetails.LdapUserDetailsService">
<constructor-arg ref="userSearch" />
<constructor-arg ref="authoritiesPopulator" />
</bean>
<bean id="contextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="ldap://corp.abc.com:389/dc=Corp,dc=abc,dc=com" />
<property name="userDn" value="***" />
<property name="password" value="***" />
<property name="baseEnvironmentProperties">
<map>
<entry key="java.naming.referral">
<value>follow</value> <!-- Avoid error: Unprocessed Continuation Reference(s); remaining name '' -->
</entry>
</map>
</property>
</bean>
<bean id="userSearch" class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
<constructor-arg>
<value></value> <!-- blank value is required here! -->
</constructor-arg>
<constructor-arg>
<value>(sAMAccountName={0})</value>
</constructor-arg>
<constructor-arg ref="contextSource" />
<property name="searchSubtree">
<value>true</value>
</property>
</bean>
<bean id="ldapAuthProvider" class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
<constructor-arg ref="authenticator" />
<constructor-arg ref="authoritiesPopulator" />
</bean>
<bean id="authenticator" class="org.springframework.security.ldap.authentication.BindAuthenticator">
<constructor-arg ref="contextSource" />
<property name="userDnPatterns">
<list>
<value>sAMAccountName={0}</value>
</list>
</property>
<property name="userSearch" ref="userSearch" />
</bean>
<bean id="authoritiesPopulator" class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
<constructor-arg ref="contextSource" />
<constructor-arg value="" /> <!-- From the root DN of the context factory -->
<property name="groupRoleAttribute" value="cn" />
<property name="rolePrefix" value="ROLE_" />
<property name="searchSubtree" value="true" />
<property name="convertToUpperCase" value="true" />
<property name="ignorePartialResultException">
<value>false</value>
</property>
</bean>
``` | I had the same problem `IncorrectResultSizeDataAccessException` whilst trying to authenticate against Active Directory. I haven't solved this particular issue directly, but I have implemented a workaround, which is fully functional, but does mean you need to have a "service account" username and password to establish communication with AD. I guess it uses the "general" Spring LDAP approach, rather than a special AD one.
I followed the recipe here:
[Active Directory Spring Security XML config, on the SpringSource forum](http://forum.springsource.org/showthread.php?125336-Spring-Security-with-Active-Directory&p=411213#post411213 "Active Directory Spring Security XML config")
Here's my `security-context.xml` file, for reference:
```
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
">
<!-- There is some Java based config here, don't forget. -->
<!-- Its not important for this example-->
<context:component-scan base-package="uk.ac.example.ldaptest.security" />
<!-- This is for our Active Dir LDAP implementation -->
<beans:bean id="contextSource"
class="org.springframework.ldap.core.support.LdapContextSource">
<beans:property name="url"
value="LDAP://ads.ntd.example.ac.uk:389" />
<beans:property name="base" value="dc=ntd,dc=example,dc=ac,dc=uk" />
<beans:property name="userDn" value="cn=ldap,ou=Service Accounts,ou=Management,ou=example,dc=ntd,dc=example,dc=ac,dc=uk" />
<beans:property name="password" value="XXXXXXXXX" />
<beans:property name="pooled" value="true" />
<!-- AD Specific Setting for avoiding the partial exception error -->
<beans:property name="referral" value="follow" />
</beans:bean>
<beans:bean id="ldapAuthenticationProvider"
class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
<beans:constructor-arg>
<beans:bean
class="org.springframework.security.ldap.authentication.BindAuthenticator">
<beans:constructor-arg ref="contextSource" />
<beans:property name="userSearch">
<beans:bean id="userSearch"
class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
<beans:constructor-arg index="0" value="" />
<beans:constructor-arg index="1" value="(sAMAccountName={0})" />
<beans:constructor-arg index="2" ref="contextSource" />
</beans:bean>
</beans:property>
</beans:bean>
</beans:constructor-arg>
<beans:constructor-arg>
<beans:bean
class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
<beans:constructor-arg ref="contextSource" />
<beans:constructor-arg value="" />
<beans:property name="groupSearchFilter" value="(member={0})" />
<beans:property name="searchSubtree" value="true" />
<!-- Below Settings convert the adds the prefix ROLE_ to roles returned
from AD -->
</beans:bean>
</beans:constructor-arg>
<!-- Create the Mapper object that returns our customised User object -->
<!-- Set up in the Java based config mentioned earlier -->
<beans:property name="userDetailsContextMapper" ref="myUdcm" />
</beans:bean>
<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:constructor-arg>
<beans:list>
<beans:ref local="ldapAuthenticationProvider" />
</beans:list>
</beans:constructor-arg>
</beans:bean>
<!-- we want all URLs within our application to be secured, requiring the
role ROLE_STAFF to access them. LDAP supplies this -->
<http auto-config="true" use-expressions="true"
authentication-manager-ref="authenticationManager">
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_STAFF')" />
<session-management>
<concurrency-control max-sessions="1" />
</session-management>
</http>
``` |
58,906,193 | I am newbie in R.
Below is the sample of what I want.
I want to calculate the index, which is referring to ( 1 - the squre of prop's sigma by each "Country"
For example, in the case of Afghanistan, 1 - (0.006^2 + 0.009^2 + 0.32^2 + 0.008^2 + 0.006^2 + 0.524^2 + 0.19^2 + 0.88^2 + 0.19) = 0.6141.How can I make a code in R?
```
Source Date Country Language Number prop index
1 eb 2001 Afghanistan Pashai 160000 0.006 0.6141
2 eb 2001 Afghanistan Balochi 240000 0.009
3 eb 2001 Afghanistan Dari (Persian) 8290000 0.32
4 eb 2001 Afghanistan "Nuristani group" 200000 0.008
5 eb 2001 Afghanistan Pamir group 160000 0.006
6 eb 2001 Afghanistan Pashto 13560000 0.524
7 eb 2001 Afghanistan Turkmen 500000 0.019
8 eb 2001 Afghanistan Uzbek 2280000 0.088
9 eb 2001 Afghanistan Other 490000 0.019
10 eb 2001 Albania "Albanian " 2419000 0.38 Index(what I want above)
11 eb 2001 Albania "Albanian " 5369000 0.65
12 eb 2001 Albania "Albanian " 2259000 0.46
13 eb 2001 Albania "Albanian " 3392000 0.78
14 eb 2001 Albania "Albanian " 3468000 0.26
15 eb 2001 Korea "Korean " 7891900 0.38 Index(what I want above)
16 eb 2001 Korea "Korean " 3485200 0.65
17 eb 2001 Korea "Korean " 1413400 0.46
18 eb 2001 Korea "Korean " 6419000 0.78
19 eb 2001 Korea "Korean " 2419000 0.26
``` | 2019/11/17 | [
"https://Stackoverflow.com/questions/58906193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388610/"
] | In my case, it wasn't sufficient to delete and recreate the venv, to select the venv from within VS Code, or to update the pythonPath to point to the venv. VS Code was still unable to find the venv or discover the unit tests. The issue turned out to be that I had reorganized my project folders so my project was no longer in the same location where I originally created its previous virtual environment. The only solution that worked was to delete the venv, move the project back to the same parent folder it was in before, then create a new venv. | The simple solution which worked for me is as follow:
1. Open the VS Code Terminal
2. Navigate (from your project folder) to folder containing the environment and activate as follow:
>
>
> ```
> source your_evn/bin/activate
>
> ```
>
>
3.Navigate back to your project folder |
58,906,193 | I am newbie in R.
Below is the sample of what I want.
I want to calculate the index, which is referring to ( 1 - the squre of prop's sigma by each "Country"
For example, in the case of Afghanistan, 1 - (0.006^2 + 0.009^2 + 0.32^2 + 0.008^2 + 0.006^2 + 0.524^2 + 0.19^2 + 0.88^2 + 0.19) = 0.6141.How can I make a code in R?
```
Source Date Country Language Number prop index
1 eb 2001 Afghanistan Pashai 160000 0.006 0.6141
2 eb 2001 Afghanistan Balochi 240000 0.009
3 eb 2001 Afghanistan Dari (Persian) 8290000 0.32
4 eb 2001 Afghanistan "Nuristani group" 200000 0.008
5 eb 2001 Afghanistan Pamir group 160000 0.006
6 eb 2001 Afghanistan Pashto 13560000 0.524
7 eb 2001 Afghanistan Turkmen 500000 0.019
8 eb 2001 Afghanistan Uzbek 2280000 0.088
9 eb 2001 Afghanistan Other 490000 0.019
10 eb 2001 Albania "Albanian " 2419000 0.38 Index(what I want above)
11 eb 2001 Albania "Albanian " 5369000 0.65
12 eb 2001 Albania "Albanian " 2259000 0.46
13 eb 2001 Albania "Albanian " 3392000 0.78
14 eb 2001 Albania "Albanian " 3468000 0.26
15 eb 2001 Korea "Korean " 7891900 0.38 Index(what I want above)
16 eb 2001 Korea "Korean " 3485200 0.65
17 eb 2001 Korea "Korean " 1413400 0.46
18 eb 2001 Korea "Korean " 6419000 0.78
19 eb 2001 Korea "Korean " 2419000 0.26
``` | 2019/11/17 | [
"https://Stackoverflow.com/questions/58906193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388610/"
] | Drop the `"python.venvPath"` setting (it doesn't do what you seem to think it does), don't specify these settings in your user settings, and change your `"python.pythonPath"` to be relative to your project, e.g.:
```
"python.pythonPath": "venv/Scripts/python.exe"
``` | I found a solution for wsl users and maybe it's happening to some of you.
If you did create the virtual enviroment in wsl mode Windows will never find the python file because there is not .exe in Linux systems, so the way to activate is
```
cd [folder where you have your venv]
activate folder -> source venv/bin/activate
```
Once you have your venv activated then open vs code
```
code .
```
And you will have the enviroment activated. |
58,906,193 | I am newbie in R.
Below is the sample of what I want.
I want to calculate the index, which is referring to ( 1 - the squre of prop's sigma by each "Country"
For example, in the case of Afghanistan, 1 - (0.006^2 + 0.009^2 + 0.32^2 + 0.008^2 + 0.006^2 + 0.524^2 + 0.19^2 + 0.88^2 + 0.19) = 0.6141.How can I make a code in R?
```
Source Date Country Language Number prop index
1 eb 2001 Afghanistan Pashai 160000 0.006 0.6141
2 eb 2001 Afghanistan Balochi 240000 0.009
3 eb 2001 Afghanistan Dari (Persian) 8290000 0.32
4 eb 2001 Afghanistan "Nuristani group" 200000 0.008
5 eb 2001 Afghanistan Pamir group 160000 0.006
6 eb 2001 Afghanistan Pashto 13560000 0.524
7 eb 2001 Afghanistan Turkmen 500000 0.019
8 eb 2001 Afghanistan Uzbek 2280000 0.088
9 eb 2001 Afghanistan Other 490000 0.019
10 eb 2001 Albania "Albanian " 2419000 0.38 Index(what I want above)
11 eb 2001 Albania "Albanian " 5369000 0.65
12 eb 2001 Albania "Albanian " 2259000 0.46
13 eb 2001 Albania "Albanian " 3392000 0.78
14 eb 2001 Albania "Albanian " 3468000 0.26
15 eb 2001 Korea "Korean " 7891900 0.38 Index(what I want above)
16 eb 2001 Korea "Korean " 3485200 0.65
17 eb 2001 Korea "Korean " 1413400 0.46
18 eb 2001 Korea "Korean " 6419000 0.78
19 eb 2001 Korea "Korean " 2419000 0.26
``` | 2019/11/17 | [
"https://Stackoverflow.com/questions/58906193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388610/"
] | The only solution I found was to delete the `venv` and recreate it. I followed [these steps](https://help.pythonanywhere.com/pages/RebuildingVirtualenvs/) but I'll provide a brief summary for Windows:
1. Activate your virtualenv. Go to the parent folder where your Virtual Environment is located and run `venv\scripts\activate`. Keep in mind that the first name "venv" can vary.
2. Create a requirements.txt file. `pip freeze requirements.txt`
3. `deactivate` to exit the venv
4. `rm venv` to delete the venv
5. `py -m venv venv` to create a new one
6. `pip install -r requirements.txt` to install the requirements. | The simple solution which worked for me is as follow:
1. Open the VS Code Terminal
2. Navigate (from your project folder) to folder containing the environment and activate as follow:
>
>
> ```
> source your_evn/bin/activate
>
> ```
>
>
3.Navigate back to your project folder |
58,906,193 | I am newbie in R.
Below is the sample of what I want.
I want to calculate the index, which is referring to ( 1 - the squre of prop's sigma by each "Country"
For example, in the case of Afghanistan, 1 - (0.006^2 + 0.009^2 + 0.32^2 + 0.008^2 + 0.006^2 + 0.524^2 + 0.19^2 + 0.88^2 + 0.19) = 0.6141.How can I make a code in R?
```
Source Date Country Language Number prop index
1 eb 2001 Afghanistan Pashai 160000 0.006 0.6141
2 eb 2001 Afghanistan Balochi 240000 0.009
3 eb 2001 Afghanistan Dari (Persian) 8290000 0.32
4 eb 2001 Afghanistan "Nuristani group" 200000 0.008
5 eb 2001 Afghanistan Pamir group 160000 0.006
6 eb 2001 Afghanistan Pashto 13560000 0.524
7 eb 2001 Afghanistan Turkmen 500000 0.019
8 eb 2001 Afghanistan Uzbek 2280000 0.088
9 eb 2001 Afghanistan Other 490000 0.019
10 eb 2001 Albania "Albanian " 2419000 0.38 Index(what I want above)
11 eb 2001 Albania "Albanian " 5369000 0.65
12 eb 2001 Albania "Albanian " 2259000 0.46
13 eb 2001 Albania "Albanian " 3392000 0.78
14 eb 2001 Albania "Albanian " 3468000 0.26
15 eb 2001 Korea "Korean " 7891900 0.38 Index(what I want above)
16 eb 2001 Korea "Korean " 3485200 0.65
17 eb 2001 Korea "Korean " 1413400 0.46
18 eb 2001 Korea "Korean " 6419000 0.78
19 eb 2001 Korea "Korean " 2419000 0.26
``` | 2019/11/17 | [
"https://Stackoverflow.com/questions/58906193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388610/"
] | The only solution I found was to delete the `venv` and recreate it. I followed [these steps](https://help.pythonanywhere.com/pages/RebuildingVirtualenvs/) but I'll provide a brief summary for Windows:
1. Activate your virtualenv. Go to the parent folder where your Virtual Environment is located and run `venv\scripts\activate`. Keep in mind that the first name "venv" can vary.
2. Create a requirements.txt file. `pip freeze requirements.txt`
3. `deactivate` to exit the venv
4. `rm venv` to delete the venv
5. `py -m venv venv` to create a new one
6. `pip install -r requirements.txt` to install the requirements. | In my case, I had not yet installed `virtualenv`. You can install it using:
```bash
pip install virtualenv
``` |
58,906,193 | I am newbie in R.
Below is the sample of what I want.
I want to calculate the index, which is referring to ( 1 - the squre of prop's sigma by each "Country"
For example, in the case of Afghanistan, 1 - (0.006^2 + 0.009^2 + 0.32^2 + 0.008^2 + 0.006^2 + 0.524^2 + 0.19^2 + 0.88^2 + 0.19) = 0.6141.How can I make a code in R?
```
Source Date Country Language Number prop index
1 eb 2001 Afghanistan Pashai 160000 0.006 0.6141
2 eb 2001 Afghanistan Balochi 240000 0.009
3 eb 2001 Afghanistan Dari (Persian) 8290000 0.32
4 eb 2001 Afghanistan "Nuristani group" 200000 0.008
5 eb 2001 Afghanistan Pamir group 160000 0.006
6 eb 2001 Afghanistan Pashto 13560000 0.524
7 eb 2001 Afghanistan Turkmen 500000 0.019
8 eb 2001 Afghanistan Uzbek 2280000 0.088
9 eb 2001 Afghanistan Other 490000 0.019
10 eb 2001 Albania "Albanian " 2419000 0.38 Index(what I want above)
11 eb 2001 Albania "Albanian " 5369000 0.65
12 eb 2001 Albania "Albanian " 2259000 0.46
13 eb 2001 Albania "Albanian " 3392000 0.78
14 eb 2001 Albania "Albanian " 3468000 0.26
15 eb 2001 Korea "Korean " 7891900 0.38 Index(what I want above)
16 eb 2001 Korea "Korean " 3485200 0.65
17 eb 2001 Korea "Korean " 1413400 0.46
18 eb 2001 Korea "Korean " 6419000 0.78
19 eb 2001 Korea "Korean " 2419000 0.26
``` | 2019/11/17 | [
"https://Stackoverflow.com/questions/58906193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388610/"
] | In my case, it wasn't sufficient to delete and recreate the venv, to select the venv from within VS Code, or to update the pythonPath to point to the venv. VS Code was still unable to find the venv or discover the unit tests. The issue turned out to be that I had reorganized my project folders so my project was no longer in the same location where I originally created its previous virtual environment. The only solution that worked was to delete the venv, move the project back to the same parent folder it was in before, then create a new venv. | In my case, I had not yet installed `virtualenv`. You can install it using:
```bash
pip install virtualenv
``` |
58,906,193 | I am newbie in R.
Below is the sample of what I want.
I want to calculate the index, which is referring to ( 1 - the squre of prop's sigma by each "Country"
For example, in the case of Afghanistan, 1 - (0.006^2 + 0.009^2 + 0.32^2 + 0.008^2 + 0.006^2 + 0.524^2 + 0.19^2 + 0.88^2 + 0.19) = 0.6141.How can I make a code in R?
```
Source Date Country Language Number prop index
1 eb 2001 Afghanistan Pashai 160000 0.006 0.6141
2 eb 2001 Afghanistan Balochi 240000 0.009
3 eb 2001 Afghanistan Dari (Persian) 8290000 0.32
4 eb 2001 Afghanistan "Nuristani group" 200000 0.008
5 eb 2001 Afghanistan Pamir group 160000 0.006
6 eb 2001 Afghanistan Pashto 13560000 0.524
7 eb 2001 Afghanistan Turkmen 500000 0.019
8 eb 2001 Afghanistan Uzbek 2280000 0.088
9 eb 2001 Afghanistan Other 490000 0.019
10 eb 2001 Albania "Albanian " 2419000 0.38 Index(what I want above)
11 eb 2001 Albania "Albanian " 5369000 0.65
12 eb 2001 Albania "Albanian " 2259000 0.46
13 eb 2001 Albania "Albanian " 3392000 0.78
14 eb 2001 Albania "Albanian " 3468000 0.26
15 eb 2001 Korea "Korean " 7891900 0.38 Index(what I want above)
16 eb 2001 Korea "Korean " 3485200 0.65
17 eb 2001 Korea "Korean " 1413400 0.46
18 eb 2001 Korea "Korean " 6419000 0.78
19 eb 2001 Korea "Korean " 2419000 0.26
``` | 2019/11/17 | [
"https://Stackoverflow.com/questions/58906193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388610/"
] | Drop the `"python.venvPath"` setting (it doesn't do what you seem to think it does), don't specify these settings in your user settings, and change your `"python.pythonPath"` to be relative to your project, e.g.:
```
"python.pythonPath": "venv/Scripts/python.exe"
``` | In my case, it wasn't sufficient to delete and recreate the venv, to select the venv from within VS Code, or to update the pythonPath to point to the venv. VS Code was still unable to find the venv or discover the unit tests. The issue turned out to be that I had reorganized my project folders so my project was no longer in the same location where I originally created its previous virtual environment. The only solution that worked was to delete the venv, move the project back to the same parent folder it was in before, then create a new venv. |
58,906,193 | I am newbie in R.
Below is the sample of what I want.
I want to calculate the index, which is referring to ( 1 - the squre of prop's sigma by each "Country"
For example, in the case of Afghanistan, 1 - (0.006^2 + 0.009^2 + 0.32^2 + 0.008^2 + 0.006^2 + 0.524^2 + 0.19^2 + 0.88^2 + 0.19) = 0.6141.How can I make a code in R?
```
Source Date Country Language Number prop index
1 eb 2001 Afghanistan Pashai 160000 0.006 0.6141
2 eb 2001 Afghanistan Balochi 240000 0.009
3 eb 2001 Afghanistan Dari (Persian) 8290000 0.32
4 eb 2001 Afghanistan "Nuristani group" 200000 0.008
5 eb 2001 Afghanistan Pamir group 160000 0.006
6 eb 2001 Afghanistan Pashto 13560000 0.524
7 eb 2001 Afghanistan Turkmen 500000 0.019
8 eb 2001 Afghanistan Uzbek 2280000 0.088
9 eb 2001 Afghanistan Other 490000 0.019
10 eb 2001 Albania "Albanian " 2419000 0.38 Index(what I want above)
11 eb 2001 Albania "Albanian " 5369000 0.65
12 eb 2001 Albania "Albanian " 2259000 0.46
13 eb 2001 Albania "Albanian " 3392000 0.78
14 eb 2001 Albania "Albanian " 3468000 0.26
15 eb 2001 Korea "Korean " 7891900 0.38 Index(what I want above)
16 eb 2001 Korea "Korean " 3485200 0.65
17 eb 2001 Korea "Korean " 1413400 0.46
18 eb 2001 Korea "Korean " 6419000 0.78
19 eb 2001 Korea "Korean " 2419000 0.26
``` | 2019/11/17 | [
"https://Stackoverflow.com/questions/58906193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388610/"
] | Drop the `"python.venvPath"` setting (it doesn't do what you seem to think it does), don't specify these settings in your user settings, and change your `"python.pythonPath"` to be relative to your project, e.g.:
```
"python.pythonPath": "venv/Scripts/python.exe"
``` | In my case, I had not yet installed `virtualenv`. You can install it using:
```bash
pip install virtualenv
``` |
58,906,193 | I am newbie in R.
Below is the sample of what I want.
I want to calculate the index, which is referring to ( 1 - the squre of prop's sigma by each "Country"
For example, in the case of Afghanistan, 1 - (0.006^2 + 0.009^2 + 0.32^2 + 0.008^2 + 0.006^2 + 0.524^2 + 0.19^2 + 0.88^2 + 0.19) = 0.6141.How can I make a code in R?
```
Source Date Country Language Number prop index
1 eb 2001 Afghanistan Pashai 160000 0.006 0.6141
2 eb 2001 Afghanistan Balochi 240000 0.009
3 eb 2001 Afghanistan Dari (Persian) 8290000 0.32
4 eb 2001 Afghanistan "Nuristani group" 200000 0.008
5 eb 2001 Afghanistan Pamir group 160000 0.006
6 eb 2001 Afghanistan Pashto 13560000 0.524
7 eb 2001 Afghanistan Turkmen 500000 0.019
8 eb 2001 Afghanistan Uzbek 2280000 0.088
9 eb 2001 Afghanistan Other 490000 0.019
10 eb 2001 Albania "Albanian " 2419000 0.38 Index(what I want above)
11 eb 2001 Albania "Albanian " 5369000 0.65
12 eb 2001 Albania "Albanian " 2259000 0.46
13 eb 2001 Albania "Albanian " 3392000 0.78
14 eb 2001 Albania "Albanian " 3468000 0.26
15 eb 2001 Korea "Korean " 7891900 0.38 Index(what I want above)
16 eb 2001 Korea "Korean " 3485200 0.65
17 eb 2001 Korea "Korean " 1413400 0.46
18 eb 2001 Korea "Korean " 6419000 0.78
19 eb 2001 Korea "Korean " 2419000 0.26
``` | 2019/11/17 | [
"https://Stackoverflow.com/questions/58906193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388610/"
] | In my case, it wasn't sufficient to delete and recreate the venv, to select the venv from within VS Code, or to update the pythonPath to point to the venv. VS Code was still unable to find the venv or discover the unit tests. The issue turned out to be that I had reorganized my project folders so my project was no longer in the same location where I originally created its previous virtual environment. The only solution that worked was to delete the venv, move the project back to the same parent folder it was in before, then create a new venv. | I found a solution for wsl users and maybe it's happening to some of you.
If you did create the virtual enviroment in wsl mode Windows will never find the python file because there is not .exe in Linux systems, so the way to activate is
```
cd [folder where you have your venv]
activate folder -> source venv/bin/activate
```
Once you have your venv activated then open vs code
```
code .
```
And you will have the enviroment activated. |
58,906,193 | I am newbie in R.
Below is the sample of what I want.
I want to calculate the index, which is referring to ( 1 - the squre of prop's sigma by each "Country"
For example, in the case of Afghanistan, 1 - (0.006^2 + 0.009^2 + 0.32^2 + 0.008^2 + 0.006^2 + 0.524^2 + 0.19^2 + 0.88^2 + 0.19) = 0.6141.How can I make a code in R?
```
Source Date Country Language Number prop index
1 eb 2001 Afghanistan Pashai 160000 0.006 0.6141
2 eb 2001 Afghanistan Balochi 240000 0.009
3 eb 2001 Afghanistan Dari (Persian) 8290000 0.32
4 eb 2001 Afghanistan "Nuristani group" 200000 0.008
5 eb 2001 Afghanistan Pamir group 160000 0.006
6 eb 2001 Afghanistan Pashto 13560000 0.524
7 eb 2001 Afghanistan Turkmen 500000 0.019
8 eb 2001 Afghanistan Uzbek 2280000 0.088
9 eb 2001 Afghanistan Other 490000 0.019
10 eb 2001 Albania "Albanian " 2419000 0.38 Index(what I want above)
11 eb 2001 Albania "Albanian " 5369000 0.65
12 eb 2001 Albania "Albanian " 2259000 0.46
13 eb 2001 Albania "Albanian " 3392000 0.78
14 eb 2001 Albania "Albanian " 3468000 0.26
15 eb 2001 Korea "Korean " 7891900 0.38 Index(what I want above)
16 eb 2001 Korea "Korean " 3485200 0.65
17 eb 2001 Korea "Korean " 1413400 0.46
18 eb 2001 Korea "Korean " 6419000 0.78
19 eb 2001 Korea "Korean " 2419000 0.26
``` | 2019/11/17 | [
"https://Stackoverflow.com/questions/58906193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388610/"
] | The only solution I found was to delete the `venv` and recreate it. I followed [these steps](https://help.pythonanywhere.com/pages/RebuildingVirtualenvs/) but I'll provide a brief summary for Windows:
1. Activate your virtualenv. Go to the parent folder where your Virtual Environment is located and run `venv\scripts\activate`. Keep in mind that the first name "venv" can vary.
2. Create a requirements.txt file. `pip freeze requirements.txt`
3. `deactivate` to exit the venv
4. `rm venv` to delete the venv
5. `py -m venv venv` to create a new one
6. `pip install -r requirements.txt` to install the requirements. | I found a solution for wsl users and maybe it's happening to some of you.
If you did create the virtual enviroment in wsl mode Windows will never find the python file because there is not .exe in Linux systems, so the way to activate is
```
cd [folder where you have your venv]
activate folder -> source venv/bin/activate
```
Once you have your venv activated then open vs code
```
code .
```
And you will have the enviroment activated. |
58,906,193 | I am newbie in R.
Below is the sample of what I want.
I want to calculate the index, which is referring to ( 1 - the squre of prop's sigma by each "Country"
For example, in the case of Afghanistan, 1 - (0.006^2 + 0.009^2 + 0.32^2 + 0.008^2 + 0.006^2 + 0.524^2 + 0.19^2 + 0.88^2 + 0.19) = 0.6141.How can I make a code in R?
```
Source Date Country Language Number prop index
1 eb 2001 Afghanistan Pashai 160000 0.006 0.6141
2 eb 2001 Afghanistan Balochi 240000 0.009
3 eb 2001 Afghanistan Dari (Persian) 8290000 0.32
4 eb 2001 Afghanistan "Nuristani group" 200000 0.008
5 eb 2001 Afghanistan Pamir group 160000 0.006
6 eb 2001 Afghanistan Pashto 13560000 0.524
7 eb 2001 Afghanistan Turkmen 500000 0.019
8 eb 2001 Afghanistan Uzbek 2280000 0.088
9 eb 2001 Afghanistan Other 490000 0.019
10 eb 2001 Albania "Albanian " 2419000 0.38 Index(what I want above)
11 eb 2001 Albania "Albanian " 5369000 0.65
12 eb 2001 Albania "Albanian " 2259000 0.46
13 eb 2001 Albania "Albanian " 3392000 0.78
14 eb 2001 Albania "Albanian " 3468000 0.26
15 eb 2001 Korea "Korean " 7891900 0.38 Index(what I want above)
16 eb 2001 Korea "Korean " 3485200 0.65
17 eb 2001 Korea "Korean " 1413400 0.46
18 eb 2001 Korea "Korean " 6419000 0.78
19 eb 2001 Korea "Korean " 2419000 0.26
``` | 2019/11/17 | [
"https://Stackoverflow.com/questions/58906193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388610/"
] | The only solution I found was to delete the `venv` and recreate it. I followed [these steps](https://help.pythonanywhere.com/pages/RebuildingVirtualenvs/) but I'll provide a brief summary for Windows:
1. Activate your virtualenv. Go to the parent folder where your Virtual Environment is located and run `venv\scripts\activate`. Keep in mind that the first name "venv" can vary.
2. Create a requirements.txt file. `pip freeze requirements.txt`
3. `deactivate` to exit the venv
4. `rm venv` to delete the venv
5. `py -m venv venv` to create a new one
6. `pip install -r requirements.txt` to install the requirements. | In my case, it wasn't sufficient to delete and recreate the venv, to select the venv from within VS Code, or to update the pythonPath to point to the venv. VS Code was still unable to find the venv or discover the unit tests. The issue turned out to be that I had reorganized my project folders so my project was no longer in the same location where I originally created its previous virtual environment. The only solution that worked was to delete the venv, move the project back to the same parent folder it was in before, then create a new venv. |
55,425,074 | In the page's `head` tag I use 3 external files (CSS, Font, jQuery Library):
```
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet"> <!-- Poppins font -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
```
As I use all the 3 - Page loads very slow. If I omit **one of them (no matter which one)** - page loads immediately. Why is that? | 2019/03/29 | [
"https://Stackoverflow.com/questions/55425074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9105207/"
] | This is because the scripts are being loaded synchronously one after the other.
**How to make them load faster?**
If there is no dependency between the scripts and links load them asynchronously:
**Asynchronously loading JS scripts**
For that you can use [async](https://www.w3schools.com/tags/att_script_async.asp) attribute.
From the docs:
>
> When present, it specifies that the script will be executed
> asynchronously as soon as it is available.
>
>
>
Example:
```
<script src="demo_async.js" async></script>
```
Like @IvanS95 mentioned below - you can also use [defer](http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/).
**Asynchronously loading CSS links**
You can use [preload](https://developers.google.com/web/updates/2016/03/link-rel-preload).
Fro the docs:
>
> Resources loaded via are stored locally in the
> browser, and are effectively inert until they’re referenced in the
> DOM, JavaScript, or CSS. For example, here’s one potential use case in
> which a script file is preloaded, but not executed immediately, as it
> would have been if it were included via a tag in the DOM.
>
>
>
An example:
```
<link href="style.css" rel="preload" as="style">
``` | Try loading the js file at the end.
```
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet"> <!-- Poppins font -->
</head>
<body>
...
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
``` |
55,425,074 | In the page's `head` tag I use 3 external files (CSS, Font, jQuery Library):
```
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet"> <!-- Poppins font -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
```
As I use all the 3 - Page loads very slow. If I omit **one of them (no matter which one)** - page loads immediately. Why is that? | 2019/03/29 | [
"https://Stackoverflow.com/questions/55425074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9105207/"
] | This is because the scripts are being loaded synchronously one after the other.
**How to make them load faster?**
If there is no dependency between the scripts and links load them asynchronously:
**Asynchronously loading JS scripts**
For that you can use [async](https://www.w3schools.com/tags/att_script_async.asp) attribute.
From the docs:
>
> When present, it specifies that the script will be executed
> asynchronously as soon as it is available.
>
>
>
Example:
```
<script src="demo_async.js" async></script>
```
Like @IvanS95 mentioned below - you can also use [defer](http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/).
**Asynchronously loading CSS links**
You can use [preload](https://developers.google.com/web/updates/2016/03/link-rel-preload).
Fro the docs:
>
> Resources loaded via are stored locally in the
> browser, and are effectively inert until they’re referenced in the
> DOM, JavaScript, or CSS. For example, here’s one potential use case in
> which a script file is preloaded, but not executed immediately, as it
> would have been if it were included via a tag in the DOM.
>
>
>
An example:
```
<link href="style.css" rel="preload" as="style">
``` | My recommendation would be to run your site against - <https://www.webpagetest.org/> excellent resource.
Also, I would cache the data for 365 days that way they do not have to call your external scripts again.
To learn about caching check out this site - <https://www.codebyamir.com/blog/a-web-developers-guide-to-browser-caching>
And you can always use your F12 Browser tools to see the waterfall effect of loading all the elements of your Web page. |
55,425,074 | In the page's `head` tag I use 3 external files (CSS, Font, jQuery Library):
```
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet"> <!-- Poppins font -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
```
As I use all the 3 - Page loads very slow. If I omit **one of them (no matter which one)** - page loads immediately. Why is that? | 2019/03/29 | [
"https://Stackoverflow.com/questions/55425074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9105207/"
] | Try loading the js file at the end.
```
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet"> <!-- Poppins font -->
</head>
<body>
...
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
``` | My recommendation would be to run your site against - <https://www.webpagetest.org/> excellent resource.
Also, I would cache the data for 365 days that way they do not have to call your external scripts again.
To learn about caching check out this site - <https://www.codebyamir.com/blog/a-web-developers-guide-to-browser-caching>
And you can always use your F12 Browser tools to see the waterfall effect of loading all the elements of your Web page. |
15,889,978 | hi sorry i searched but didnt find the best answer i could use :(
here is the description:
i have an android project in which there are 55 activities with 55 layouts .(each activity has a layout) .
many of these activities have same style , i mean only their contents change (for example one of them has a picture of a fish and another one has picture of a lion and so on)
**Edit:** i have included the picture for what the matter to be more exact about what i want to do:
<http://i45.tinypic.com/biqmv8.png>
so here is the question:
how can i create this app with less xml layouts? is there a way to have dynamic contents? if so could you please help me or show me the required tutorial to achieve this end?
thanks. | 2013/04/08 | [
"https://Stackoverflow.com/questions/15889978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2259254/"
] | From what you have shown, I think this might be what you want.
```
int main()
{
string comment;
int nr1,nr2;
// Read the first number. It should be the first one always. No comment before number!
cin >> nr1;
// See if we can read the second number Successfully. Which means it is an integer.
if(cin >> nr2) {
}
// Otherwise clear cin and read the rest of the comment line
else {
cin.clear();
getline(cin,comment);
// Now read the second number from the second line
cin >> nr2;
}
// Read the rest of second the line.
getline(cin,comment);
cout << "result: " << nr1 + nr2 << endl;
return 0;
}
``` | Will any number of numbers based on the value you give `reqd`.
Will also work if the first character in a line itself is `#` - will ask again for that line. Will also read another line if there is no number before the `#.
```
#include <iostream>
#include <sstream>
#include <ctype.h>
using namespace std;
int main ()
{
const int reqd = 2;
string sno[reqd];
int no[reqd];
int got = 0;
size_t pos;
istringstream is;
cout<< "Enter "<<reqd<<" numbers to be added:\n";
while(got < reqd)
{
getline(cin, sno[got]);
if((pos = sno[got].find('#')) && isdigit(sno[got][0]))
{
is.str(sno[got]);
is>>no[got];
++got;
}
}
int sum = 0;
for(int i = 0; i < reqd; ++i)
sum+=no[i];
cout<<"Result : "<<sum;
return 0;
}
``` |
15,190,373 | i have query that inserting values into MySQL database with array and for loop.but when i submit form MySQL database showing double entry. First Record is empty and Second Record is with values? Why MySQL database showing First Record Empty Entry.i don't know what is reason behind it?
**HERE My Function Code**
```
<?php
if(isset($_REQUEST['order']))
{
$count=1;
$count++;
$total=$_POST['total'];
for ($i=1; $i<=$count; $i++){
$queryproduct=mysql_query("INSERT INTO shoppingcart VALUES ('','','','$uid','$email','".$_POST['product'][$i]."','".$_POST['userfile_name'] [$i]."','".$_POST['price'][$i]."','".$_POST['qty'][$i]."','".$_POST['amt'][$i]."','$total')") or die("Order Query Problem");
}
}
?>
``` | 2013/03/03 | [
"https://Stackoverflow.com/questions/15190373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I agree with Nader's answer, but to answer your question, the reason the Choice appear next to the Questions appear next to each other as opposed to below the Question is because you are placing them in different cells (using ) within the SAME row (This makes a new column). If you were to make a second row and have 1 cell for all the choices, it would look something more like what you want.
```
<table>
<tr>
<td align="left" style="width:200px;"> Your question here:</td>
<td align="center" style="width:200px;"> Your question here:</td>
<td align="right" style="width:200px;"> Your question here:</td>
</tr>
<tr>
<td align="left">
<input name="choice" type="radio" value="1" />Choice 1 <br />
<input name="choice" type="radio" value="2" checked="checked" />Choice 2</td>
<td align="center">
<input name="choice" type="checkbox" value="choice1" />Choice 1 <br />
<input name="choice" type="checkbox" value="choice2" />Choice 2 <br/>
<input name="choice" type="checkbox" value="choice3" />Choice 3 <br />
<input name="choice" type="checkbox" value="choice4" checked="checked" />Choice 4
</td>
<td><br /><textarea name="other" rows="5" cols="30"></textarea></td>
</tr>
</table>
```
I added a little bit of styling to make it look a little more spaced out. It would be useful to draw the borders of the tables to see how things are spaced out. | Well, I would definitely advise that you use divs instead of tables (Personally, I am not convinced that tables are the appropriate solution), with that being said, have three divs, all floating left, with width 33% each and post the questions and the answers in them.
e.g.
```
<div>
Question 1<br/>
Choice 1
Choice 2
Choice 3
</div>
<div>
Question 2<br/>
Choice 1
Choice 2
Choice 3
</div>
<div>
Question 3<br/>
Choice 1
Choice 2
Choice 3
</div>
<style>
div{
width:33%;
float:left;
}
</style>
``` |
15,190,373 | i have query that inserting values into MySQL database with array and for loop.but when i submit form MySQL database showing double entry. First Record is empty and Second Record is with values? Why MySQL database showing First Record Empty Entry.i don't know what is reason behind it?
**HERE My Function Code**
```
<?php
if(isset($_REQUEST['order']))
{
$count=1;
$count++;
$total=$_POST['total'];
for ($i=1; $i<=$count; $i++){
$queryproduct=mysql_query("INSERT INTO shoppingcart VALUES ('','','','$uid','$email','".$_POST['product'][$i]."','".$_POST['userfile_name'] [$i]."','".$_POST['price'][$i]."','".$_POST['qty'][$i]."','".$_POST['amt'][$i]."','$total')") or die("Order Query Problem");
}
}
?>
``` | 2013/03/03 | [
"https://Stackoverflow.com/questions/15190373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I agree with Nader's answer, but to answer your question, the reason the Choice appear next to the Questions appear next to each other as opposed to below the Question is because you are placing them in different cells (using ) within the SAME row (This makes a new column). If you were to make a second row and have 1 cell for all the choices, it would look something more like what you want.
```
<table>
<tr>
<td align="left" style="width:200px;"> Your question here:</td>
<td align="center" style="width:200px;"> Your question here:</td>
<td align="right" style="width:200px;"> Your question here:</td>
</tr>
<tr>
<td align="left">
<input name="choice" type="radio" value="1" />Choice 1 <br />
<input name="choice" type="radio" value="2" checked="checked" />Choice 2</td>
<td align="center">
<input name="choice" type="checkbox" value="choice1" />Choice 1 <br />
<input name="choice" type="checkbox" value="choice2" />Choice 2 <br/>
<input name="choice" type="checkbox" value="choice3" />Choice 3 <br />
<input name="choice" type="checkbox" value="choice4" checked="checked" />Choice 4
</td>
<td><br /><textarea name="other" rows="5" cols="30"></textarea></td>
</tr>
</table>
```
I added a little bit of styling to make it look a little more spaced out. It would be useful to draw the borders of the tables to see how things are spaced out. | well with your tables as a solution I think you need this...
```
<table>
<tr>
<td > Your question here:</td>
<br />
<td > Your question here:</td>
<br />
<td > Your question here:</td>
</tr>
<tr>
<td>
<input name="choice" type="radio" value="1" />Choice 1
<br />
<input name="choice" type="radio" value="2" checked="checked" />Choice 2
</td>
<td>
<input name="choice" type="checkbox" value="choice1" />Choice 1
<br />
<input name="choice" type="checkbox" value="choice2" />Choice 2
<br />
<input name="choice" type="checkbox" value="choice3" />Choice 3
<br />
<input name="choice" type="checkbox" value="choice4" checked="checked" />Choice 4
</td>
<td>
<textarea name="other" rows="5" cols="25"></textarea>
</td>
</tr>
</table>
``` |
31,017,457 | I have a data set that I got from XML and have it broken out with the following structure:
**[Data Table]**
```
[ID] [Name] [Value]
1 ad1_pk 1
2 ad1_addr1 123 Easy Street
3 ad1_pk 2
4 ad1_addr1 99 US31
5 ad1_atfk 6
6 ad1_pk 3
... {and so on}
```
I have added a column (called recNum) to indicate the distinct record number; however, I have not found a quick way to set the record number for each record. The number of rows that indicate a distinct record can vary, so I want the update statement to be able to handle this. Each "record" has a "column" name that ends with "\_pk", so that's how I'm determining the start of each record in the dataset.
I have done this successfully with a while loop, but it's way too slow and tables can have millions of records. Example:
```
DECLARE @maxRowID INT = (SELECT MAX(ID) FROM myTable)
DECLARE @i INT = 1
DECLARE @currentRecordID INT = 1
WHILE @i<@maxRowID AND @i<100 BEGIN
IF (SELECT RIGHT(name,3) [name] FROM myTable WHERE ID=@i)='_pk' AND @i>1 BEGIN
SET @currentRecordID = (SELECT DISTINCT value FROM myTable WHERE id=@i)
RAISERROR('Record=%i',0,1,@currentRecordID) WITH NOWAIT
UPDATE z2
SET recNum=@currentRecordID
FROM myTable z2
WHERE id=@i
END ELSE BEGIN
UPDATE z2
SET recNum=@currentRecordID
FROM myTable z2
WHERE id=@i
END
SET @i = @i+1
END
```
Does anybody have a suggestion to do this in a quick manner w/o using a cursor?
My ultimate goal is to insert statements into an SQL table (already created) with the following format:
```
insert into myNewTable ({column name list}) VALUES ({value list})
```
...
[updated 2015-06-24 00:26 EDT]
This is how far I have gotten thus far...
<https://drive.google.com/file/d/0B82UP-AIFz_ITlNIb1ZwSFdyODg/view?usp=sharing>
```
SELECT TOP 100
z2.ID,z2.Name,z2.Value,CASE WHEN z2.ID=RecIDs.ID THEN z2.Value ELSE NULL END RecNum
FROM MyTable 2
LEFT JOIN (
SELECT DENSE_RANK() OVER (ORDER BY ID) drn,ID FROM MyTable
WHERE RIGHT(name,3)='_pk'
) RecIDs ON RecIDs.ID = z2.ID
ORDER BY ID
```
... I need to fill in the gaps.
Any suggestions?
[updated 2015-06-25 09:33 EDT]
This is for SQL Server 2008 R2 | 2015/06/24 | [
"https://Stackoverflow.com/questions/31017457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1703825/"
] | First, you want to assign a value for `RecNum` for all `PK` using `ROW_NUMBER`. After that, you want to update the remaining rows with the appropriate `RecNum`
[**SQL Fiddle**](http://sqlfiddle.com/#!6/c39b1/1/0)
```
WITH CtePKs AS(
SELECT *,
RN = ROW_NUMBER() OVER(ORDER BY ID)
FROM z2
WHERE RIGHT(Name, 3) = '_pk'
)
UPDATE CtePKs SET RecNum = RN
UPDATE z
SET RecNum = x.RecNum
FROM z2 z
OUTER APPLY(
SELECT TOP 1 Id, RecNum
FROM z2
WHERE
ID < z.ID
AND RecNum IS NOT NULL
ORDER BY ID DESC
)x
WHERE z.RecNum IS NULL
```
**RESULT**
```
| ID | Name | Value | RecNum |
|----|-----------|-----------------|--------|
| 1 | ad1_pk | 1 | 1 |
| 2 | ad1_addr1 | 123 Easy Street | 1 |
| 3 | ad1_pk | 2 | 2 |
| 4 | ad1_addr1 | 99 US31 | 2 |
| 5 | ad1_atfk | 6 | 2 |
| 6 | ad1_pk | 3 | 3 |
``` | You can use a [cte](https://msdn.microsoft.com/en-us/library/ms175972.aspx) for that:
```
;With cte as (
SELECT [id], Row_number() OVER(Order by [id] As rn
FROM MyTable
)
UPDATE MyTable
SET recNum = rn
FROM MyTable t
INNER JOIN cte ON(t.[id] = cte.[id])
```
However, you since already have an id column that seems to have the values you are asking for, you can simply do this:
```
UPDATE MyTable
SET recNum = [id]
``` |
31,017,457 | I have a data set that I got from XML and have it broken out with the following structure:
**[Data Table]**
```
[ID] [Name] [Value]
1 ad1_pk 1
2 ad1_addr1 123 Easy Street
3 ad1_pk 2
4 ad1_addr1 99 US31
5 ad1_atfk 6
6 ad1_pk 3
... {and so on}
```
I have added a column (called recNum) to indicate the distinct record number; however, I have not found a quick way to set the record number for each record. The number of rows that indicate a distinct record can vary, so I want the update statement to be able to handle this. Each "record" has a "column" name that ends with "\_pk", so that's how I'm determining the start of each record in the dataset.
I have done this successfully with a while loop, but it's way too slow and tables can have millions of records. Example:
```
DECLARE @maxRowID INT = (SELECT MAX(ID) FROM myTable)
DECLARE @i INT = 1
DECLARE @currentRecordID INT = 1
WHILE @i<@maxRowID AND @i<100 BEGIN
IF (SELECT RIGHT(name,3) [name] FROM myTable WHERE ID=@i)='_pk' AND @i>1 BEGIN
SET @currentRecordID = (SELECT DISTINCT value FROM myTable WHERE id=@i)
RAISERROR('Record=%i',0,1,@currentRecordID) WITH NOWAIT
UPDATE z2
SET recNum=@currentRecordID
FROM myTable z2
WHERE id=@i
END ELSE BEGIN
UPDATE z2
SET recNum=@currentRecordID
FROM myTable z2
WHERE id=@i
END
SET @i = @i+1
END
```
Does anybody have a suggestion to do this in a quick manner w/o using a cursor?
My ultimate goal is to insert statements into an SQL table (already created) with the following format:
```
insert into myNewTable ({column name list}) VALUES ({value list})
```
...
[updated 2015-06-24 00:26 EDT]
This is how far I have gotten thus far...
<https://drive.google.com/file/d/0B82UP-AIFz_ITlNIb1ZwSFdyODg/view?usp=sharing>
```
SELECT TOP 100
z2.ID,z2.Name,z2.Value,CASE WHEN z2.ID=RecIDs.ID THEN z2.Value ELSE NULL END RecNum
FROM MyTable 2
LEFT JOIN (
SELECT DENSE_RANK() OVER (ORDER BY ID) drn,ID FROM MyTable
WHERE RIGHT(name,3)='_pk'
) RecIDs ON RecIDs.ID = z2.ID
ORDER BY ID
```
... I need to fill in the gaps.
Any suggestions?
[updated 2015-06-25 09:33 EDT]
This is for SQL Server 2008 R2 | 2015/06/24 | [
"https://Stackoverflow.com/questions/31017457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1703825/"
] | If I understand your question correctly, you can use a correlated subquery like this. If you are using SQL Server 2012 or above, you can use `SUM() OVER()` as well. Check Edit.
**Sample Data**
```
CREATE TABLE Table1
([ID] int,rowid int, [Name] varchar(9), [Value] varchar(15));
INSERT INTO Table1
([ID], [Name], [Value])
VALUES
(1, 'ad1_pk', '1'),
(2, 'ad1_addr1', '123 Easy Street'),
(3, 'ad1_pk', '2'),
(4, 'ad1_addr1', '99 US31'),
(5, 'ad1_atfk', '6'),
(6, 'ad1_pk', '3');
```
**Query**
```
UPDATE Table1
SET rowid =
(SELECT COUNT(ID) FROM Table1 T2 WHERE T2.ID <= Table1.ID AND T2.Name Like '%[_]pk');
SELECT * FROM Table1;
```
**[SQL Fiddle](http://sqlfiddle.com/#!6/2ed78/6)**
**OUTPUT**
```
| ID | rowid | Name | Value |
|----|-------|-----------|-----------------|
| 1 | 1 | ad1_pk | 1 |
| 2 | 1 | ad1_addr1 | 123 Easy Street |
| 3 | 2 | ad1_pk | 2 |
| 4 | 2 | ad1_addr1 | 99 US31 |
| 5 | 2 | ad1_atfk | 6 |
| 6 | 3 | ad1_pk | 3 |
```
**EDIT**
For *SQL Server 2012* or above
**Query**
```
;WITH CTE AS
(
SELECT SUM(CASE WHEN Name LIKE '%[_]pk' THEN 1 ELSE 0 END) OVER(ORDER BY ID) recnum,*
FROM Table1
)
UPDATE CTE
SET rowid = recnum;
SELECT * FROM Table1;
```
**[SQL Fiddle](http://sqlfiddle.com/#!6/2ed78/8)** | You can use a [cte](https://msdn.microsoft.com/en-us/library/ms175972.aspx) for that:
```
;With cte as (
SELECT [id], Row_number() OVER(Order by [id] As rn
FROM MyTable
)
UPDATE MyTable
SET recNum = rn
FROM MyTable t
INNER JOIN cte ON(t.[id] = cte.[id])
```
However, you since already have an id column that seems to have the values you are asking for, you can simply do this:
```
UPDATE MyTable
SET recNum = [id]
``` |
31,017,457 | I have a data set that I got from XML and have it broken out with the following structure:
**[Data Table]**
```
[ID] [Name] [Value]
1 ad1_pk 1
2 ad1_addr1 123 Easy Street
3 ad1_pk 2
4 ad1_addr1 99 US31
5 ad1_atfk 6
6 ad1_pk 3
... {and so on}
```
I have added a column (called recNum) to indicate the distinct record number; however, I have not found a quick way to set the record number for each record. The number of rows that indicate a distinct record can vary, so I want the update statement to be able to handle this. Each "record" has a "column" name that ends with "\_pk", so that's how I'm determining the start of each record in the dataset.
I have done this successfully with a while loop, but it's way too slow and tables can have millions of records. Example:
```
DECLARE @maxRowID INT = (SELECT MAX(ID) FROM myTable)
DECLARE @i INT = 1
DECLARE @currentRecordID INT = 1
WHILE @i<@maxRowID AND @i<100 BEGIN
IF (SELECT RIGHT(name,3) [name] FROM myTable WHERE ID=@i)='_pk' AND @i>1 BEGIN
SET @currentRecordID = (SELECT DISTINCT value FROM myTable WHERE id=@i)
RAISERROR('Record=%i',0,1,@currentRecordID) WITH NOWAIT
UPDATE z2
SET recNum=@currentRecordID
FROM myTable z2
WHERE id=@i
END ELSE BEGIN
UPDATE z2
SET recNum=@currentRecordID
FROM myTable z2
WHERE id=@i
END
SET @i = @i+1
END
```
Does anybody have a suggestion to do this in a quick manner w/o using a cursor?
My ultimate goal is to insert statements into an SQL table (already created) with the following format:
```
insert into myNewTable ({column name list}) VALUES ({value list})
```
...
[updated 2015-06-24 00:26 EDT]
This is how far I have gotten thus far...
<https://drive.google.com/file/d/0B82UP-AIFz_ITlNIb1ZwSFdyODg/view?usp=sharing>
```
SELECT TOP 100
z2.ID,z2.Name,z2.Value,CASE WHEN z2.ID=RecIDs.ID THEN z2.Value ELSE NULL END RecNum
FROM MyTable 2
LEFT JOIN (
SELECT DENSE_RANK() OVER (ORDER BY ID) drn,ID FROM MyTable
WHERE RIGHT(name,3)='_pk'
) RecIDs ON RecIDs.ID = z2.ID
ORDER BY ID
```
... I need to fill in the gaps.
Any suggestions?
[updated 2015-06-25 09:33 EDT]
This is for SQL Server 2008 R2 | 2015/06/24 | [
"https://Stackoverflow.com/questions/31017457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1703825/"
] | First, you want to assign a value for `RecNum` for all `PK` using `ROW_NUMBER`. After that, you want to update the remaining rows with the appropriate `RecNum`
[**SQL Fiddle**](http://sqlfiddle.com/#!6/c39b1/1/0)
```
WITH CtePKs AS(
SELECT *,
RN = ROW_NUMBER() OVER(ORDER BY ID)
FROM z2
WHERE RIGHT(Name, 3) = '_pk'
)
UPDATE CtePKs SET RecNum = RN
UPDATE z
SET RecNum = x.RecNum
FROM z2 z
OUTER APPLY(
SELECT TOP 1 Id, RecNum
FROM z2
WHERE
ID < z.ID
AND RecNum IS NOT NULL
ORDER BY ID DESC
)x
WHERE z.RecNum IS NULL
```
**RESULT**
```
| ID | Name | Value | RecNum |
|----|-----------|-----------------|--------|
| 1 | ad1_pk | 1 | 1 |
| 2 | ad1_addr1 | 123 Easy Street | 1 |
| 3 | ad1_pk | 2 | 2 |
| 4 | ad1_addr1 | 99 US31 | 2 |
| 5 | ad1_atfk | 6 | 2 |
| 6 | ad1_pk | 3 | 3 |
``` | If I understand your question correctly, you can use a correlated subquery like this. If you are using SQL Server 2012 or above, you can use `SUM() OVER()` as well. Check Edit.
**Sample Data**
```
CREATE TABLE Table1
([ID] int,rowid int, [Name] varchar(9), [Value] varchar(15));
INSERT INTO Table1
([ID], [Name], [Value])
VALUES
(1, 'ad1_pk', '1'),
(2, 'ad1_addr1', '123 Easy Street'),
(3, 'ad1_pk', '2'),
(4, 'ad1_addr1', '99 US31'),
(5, 'ad1_atfk', '6'),
(6, 'ad1_pk', '3');
```
**Query**
```
UPDATE Table1
SET rowid =
(SELECT COUNT(ID) FROM Table1 T2 WHERE T2.ID <= Table1.ID AND T2.Name Like '%[_]pk');
SELECT * FROM Table1;
```
**[SQL Fiddle](http://sqlfiddle.com/#!6/2ed78/6)**
**OUTPUT**
```
| ID | rowid | Name | Value |
|----|-------|-----------|-----------------|
| 1 | 1 | ad1_pk | 1 |
| 2 | 1 | ad1_addr1 | 123 Easy Street |
| 3 | 2 | ad1_pk | 2 |
| 4 | 2 | ad1_addr1 | 99 US31 |
| 5 | 2 | ad1_atfk | 6 |
| 6 | 3 | ad1_pk | 3 |
```
**EDIT**
For *SQL Server 2012* or above
**Query**
```
;WITH CTE AS
(
SELECT SUM(CASE WHEN Name LIKE '%[_]pk' THEN 1 ELSE 0 END) OVER(ORDER BY ID) recnum,*
FROM Table1
)
UPDATE CTE
SET rowid = recnum;
SELECT * FROM Table1;
```
**[SQL Fiddle](http://sqlfiddle.com/#!6/2ed78/8)** |
56,751,945 | I am trying to fetch two properties out of each array and then form a array out of this. I have also shown the expected output.
```
columns = [
{Header: ƒ, Cell: ƒ, sortable: false, show: true},
{Header: ƒ, accessor: "firstName", sortable: false, show: true},
{Header: ƒ, accessor: "status", sortable: false, show: true},
{Header: ƒ, accessor: "visits", sortable: false, show: true}
]
```
I want the output to be
```
[{name: "firstName",show: true},{name: "status",show: true},{name:"visits", show: true}]
```
I have tried this approach of getting one field, How do I get two values and then form a new array of objects itslef.
```
let keys = [...new Set(arr.map(arr => arr.accessor))]; // able to get one property, but need two in form of object
``` | 2019/06/25 | [
"https://Stackoverflow.com/questions/56751945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6927748/"
] | Use a simple `Map()`:
```
columns.filter(
col => !!col.accessor).map(
column => ({ name: column.accessor, show: column.show })
)
```
The filter remove columns without `accessor` property.
`Map()` returns formatted array.
```js
const columns = [
{Header:"ƒ", Cell: "ƒ", sortable: false, show: true},
{Header: "ƒ", accessor: "firstName", sortable: false, show: true},
{Header: "ƒ", accessor: "status", sortable: false, show: true},
{Header: "ƒ", accessor: "visits", sortable: false, show: true}
]
const newColumns = columns.filter(
col => !!col.accessor).map(
column => ({ name: column.accessor, show: column.show })
);
console.log(newColumns);
``` | ```
col.map(element => {
return {accessor: element.accessor, show: element.show}
})
```
**edit:**
Instead of looping it twice like other solutions, I prefer to loop through it and add only the needed element.
```
let res = [];
columns.forEach(element => {
if(!!element.accessor) {
res.push({accessor: element.accessor, show: element.show})
}
})
``` |
56,751,945 | I am trying to fetch two properties out of each array and then form a array out of this. I have also shown the expected output.
```
columns = [
{Header: ƒ, Cell: ƒ, sortable: false, show: true},
{Header: ƒ, accessor: "firstName", sortable: false, show: true},
{Header: ƒ, accessor: "status", sortable: false, show: true},
{Header: ƒ, accessor: "visits", sortable: false, show: true}
]
```
I want the output to be
```
[{name: "firstName",show: true},{name: "status",show: true},{name:"visits", show: true}]
```
I have tried this approach of getting one field, How do I get two values and then form a new array of objects itslef.
```
let keys = [...new Set(arr.map(arr => arr.accessor))]; // able to get one property, but need two in form of object
``` | 2019/06/25 | [
"https://Stackoverflow.com/questions/56751945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6927748/"
] | You can use `reduce` to create a one-liner:
```js
const columns = [{Header:"ƒ", Cell: "ƒ", sortable: false, show: true},{Header: "ƒ", accessor: "firstName", sortable: false, show: true},{Header: "ƒ", accessor: "status", sortable: false, show: true},{Header: "ƒ", accessor: "visits", sortable: false, show: true}]
var filtered = columns.reduce((acc, {accessor:a, show}) => a ? [...acc, {name: a, show}] : acc , [])
console.log(filtered)
```
`a ?` will make a check to see if `accessor` exists, and will push the new object if it does, or return the `acc`umulator if is doesn't. | ```
col.map(element => {
return {accessor: element.accessor, show: element.show}
})
```
**edit:**
Instead of looping it twice like other solutions, I prefer to loop through it and add only the needed element.
```
let res = [];
columns.forEach(element => {
if(!!element.accessor) {
res.push({accessor: element.accessor, show: element.show})
}
})
``` |
56,751,945 | I am trying to fetch two properties out of each array and then form a array out of this. I have also shown the expected output.
```
columns = [
{Header: ƒ, Cell: ƒ, sortable: false, show: true},
{Header: ƒ, accessor: "firstName", sortable: false, show: true},
{Header: ƒ, accessor: "status", sortable: false, show: true},
{Header: ƒ, accessor: "visits", sortable: false, show: true}
]
```
I want the output to be
```
[{name: "firstName",show: true},{name: "status",show: true},{name:"visits", show: true}]
```
I have tried this approach of getting one field, How do I get two values and then form a new array of objects itslef.
```
let keys = [...new Set(arr.map(arr => arr.accessor))]; // able to get one property, but need two in form of object
``` | 2019/06/25 | [
"https://Stackoverflow.com/questions/56751945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6927748/"
] | Use a simple `Map()`:
```
columns.filter(
col => !!col.accessor).map(
column => ({ name: column.accessor, show: column.show })
)
```
The filter remove columns without `accessor` property.
`Map()` returns formatted array.
```js
const columns = [
{Header:"ƒ", Cell: "ƒ", sortable: false, show: true},
{Header: "ƒ", accessor: "firstName", sortable: false, show: true},
{Header: "ƒ", accessor: "status", sortable: false, show: true},
{Header: "ƒ", accessor: "visits", sortable: false, show: true}
]
const newColumns = columns.filter(
col => !!col.accessor).map(
column => ({ name: column.accessor, show: column.show })
);
console.log(newColumns);
``` | You can use `reduce` to create a one-liner:
```js
const columns = [{Header:"ƒ", Cell: "ƒ", sortable: false, show: true},{Header: "ƒ", accessor: "firstName", sortable: false, show: true},{Header: "ƒ", accessor: "status", sortable: false, show: true},{Header: "ƒ", accessor: "visits", sortable: false, show: true}]
var filtered = columns.reduce((acc, {accessor:a, show}) => a ? [...acc, {name: a, show}] : acc , [])
console.log(filtered)
```
`a ?` will make a check to see if `accessor` exists, and will push the new object if it does, or return the `acc`umulator if is doesn't. |
56,751,945 | I am trying to fetch two properties out of each array and then form a array out of this. I have also shown the expected output.
```
columns = [
{Header: ƒ, Cell: ƒ, sortable: false, show: true},
{Header: ƒ, accessor: "firstName", sortable: false, show: true},
{Header: ƒ, accessor: "status", sortable: false, show: true},
{Header: ƒ, accessor: "visits", sortable: false, show: true}
]
```
I want the output to be
```
[{name: "firstName",show: true},{name: "status",show: true},{name:"visits", show: true}]
```
I have tried this approach of getting one field, How do I get two values and then form a new array of objects itslef.
```
let keys = [...new Set(arr.map(arr => arr.accessor))]; // able to get one property, but need two in form of object
``` | 2019/06/25 | [
"https://Stackoverflow.com/questions/56751945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6927748/"
] | Use a simple `Map()`:
```
columns.filter(
col => !!col.accessor).map(
column => ({ name: column.accessor, show: column.show })
)
```
The filter remove columns without `accessor` property.
`Map()` returns formatted array.
```js
const columns = [
{Header:"ƒ", Cell: "ƒ", sortable: false, show: true},
{Header: "ƒ", accessor: "firstName", sortable: false, show: true},
{Header: "ƒ", accessor: "status", sortable: false, show: true},
{Header: "ƒ", accessor: "visits", sortable: false, show: true}
]
const newColumns = columns.filter(
col => !!col.accessor).map(
column => ({ name: column.accessor, show: column.show })
);
console.log(newColumns);
``` | You should return object inside the map function
```
columns.map(item => {
return {name: item.accessor, show: item.show}
});
``` |
56,751,945 | I am trying to fetch two properties out of each array and then form a array out of this. I have also shown the expected output.
```
columns = [
{Header: ƒ, Cell: ƒ, sortable: false, show: true},
{Header: ƒ, accessor: "firstName", sortable: false, show: true},
{Header: ƒ, accessor: "status", sortable: false, show: true},
{Header: ƒ, accessor: "visits", sortable: false, show: true}
]
```
I want the output to be
```
[{name: "firstName",show: true},{name: "status",show: true},{name:"visits", show: true}]
```
I have tried this approach of getting one field, How do I get two values and then form a new array of objects itslef.
```
let keys = [...new Set(arr.map(arr => arr.accessor))]; // able to get one property, but need two in form of object
``` | 2019/06/25 | [
"https://Stackoverflow.com/questions/56751945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6927748/"
] | Use a simple `Map()`:
```
columns.filter(
col => !!col.accessor).map(
column => ({ name: column.accessor, show: column.show })
)
```
The filter remove columns without `accessor` property.
`Map()` returns formatted array.
```js
const columns = [
{Header:"ƒ", Cell: "ƒ", sortable: false, show: true},
{Header: "ƒ", accessor: "firstName", sortable: false, show: true},
{Header: "ƒ", accessor: "status", sortable: false, show: true},
{Header: "ƒ", accessor: "visits", sortable: false, show: true}
]
const newColumns = columns.filter(
col => !!col.accessor).map(
column => ({ name: column.accessor, show: column.show })
);
console.log(newColumns);
``` | simple filter() for filtering the proper column which has accessor and show values,
and map() to customize the values.
```js
var ƒ = "dummy"
columns = [
{Header: ƒ, Cell: ƒ, sortable: false, show: true},
{Header: ƒ, accessor: "firstName", sortable: false, show: true},
{Header: ƒ, accessor: "status", sortable: false, show: true},
{Header: ƒ, accessor: "visits", sortable: false, show: true}
]
var finalResult = columns.filter(column => column.accessor && column.show).map(item => {
return {name: item.accessor,show: item.show}
})
console.log(finalResult)
``` |
56,751,945 | I am trying to fetch two properties out of each array and then form a array out of this. I have also shown the expected output.
```
columns = [
{Header: ƒ, Cell: ƒ, sortable: false, show: true},
{Header: ƒ, accessor: "firstName", sortable: false, show: true},
{Header: ƒ, accessor: "status", sortable: false, show: true},
{Header: ƒ, accessor: "visits", sortable: false, show: true}
]
```
I want the output to be
```
[{name: "firstName",show: true},{name: "status",show: true},{name:"visits", show: true}]
```
I have tried this approach of getting one field, How do I get two values and then form a new array of objects itslef.
```
let keys = [...new Set(arr.map(arr => arr.accessor))]; // able to get one property, but need two in form of object
``` | 2019/06/25 | [
"https://Stackoverflow.com/questions/56751945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6927748/"
] | You can use `reduce` to create a one-liner:
```js
const columns = [{Header:"ƒ", Cell: "ƒ", sortable: false, show: true},{Header: "ƒ", accessor: "firstName", sortable: false, show: true},{Header: "ƒ", accessor: "status", sortable: false, show: true},{Header: "ƒ", accessor: "visits", sortable: false, show: true}]
var filtered = columns.reduce((acc, {accessor:a, show}) => a ? [...acc, {name: a, show}] : acc , [])
console.log(filtered)
```
`a ?` will make a check to see if `accessor` exists, and will push the new object if it does, or return the `acc`umulator if is doesn't. | You should return object inside the map function
```
columns.map(item => {
return {name: item.accessor, show: item.show}
});
``` |
56,751,945 | I am trying to fetch two properties out of each array and then form a array out of this. I have also shown the expected output.
```
columns = [
{Header: ƒ, Cell: ƒ, sortable: false, show: true},
{Header: ƒ, accessor: "firstName", sortable: false, show: true},
{Header: ƒ, accessor: "status", sortable: false, show: true},
{Header: ƒ, accessor: "visits", sortable: false, show: true}
]
```
I want the output to be
```
[{name: "firstName",show: true},{name: "status",show: true},{name:"visits", show: true}]
```
I have tried this approach of getting one field, How do I get two values and then form a new array of objects itslef.
```
let keys = [...new Set(arr.map(arr => arr.accessor))]; // able to get one property, but need two in form of object
``` | 2019/06/25 | [
"https://Stackoverflow.com/questions/56751945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6927748/"
] | You can use `reduce` to create a one-liner:
```js
const columns = [{Header:"ƒ", Cell: "ƒ", sortable: false, show: true},{Header: "ƒ", accessor: "firstName", sortable: false, show: true},{Header: "ƒ", accessor: "status", sortable: false, show: true},{Header: "ƒ", accessor: "visits", sortable: false, show: true}]
var filtered = columns.reduce((acc, {accessor:a, show}) => a ? [...acc, {name: a, show}] : acc , [])
console.log(filtered)
```
`a ?` will make a check to see if `accessor` exists, and will push the new object if it does, or return the `acc`umulator if is doesn't. | simple filter() for filtering the proper column which has accessor and show values,
and map() to customize the values.
```js
var ƒ = "dummy"
columns = [
{Header: ƒ, Cell: ƒ, sortable: false, show: true},
{Header: ƒ, accessor: "firstName", sortable: false, show: true},
{Header: ƒ, accessor: "status", sortable: false, show: true},
{Header: ƒ, accessor: "visits", sortable: false, show: true}
]
var finalResult = columns.filter(column => column.accessor && column.show).map(item => {
return {name: item.accessor,show: item.show}
})
console.log(finalResult)
``` |
43,010,428 | I have a table that holds links to websites about particular theaters. I want to retrieve the first link for a given theater. My code to set the variable:
```
Dim link As String = TheaterLinks.Where(Function(x) x.TheaterID = TheaterID).FirstOrDefault().Link
```
If there are no results (some theaters won't have any links), then I get:
```
Object reference not set to an instance of an object.
```
How do I do this? I tried:
```
Dim link As String = Links.Where(Function(x) x.TheaterID = TheaterID.DefaultIfEmpty().First().Link
```
But I can't figure out what to put inside DefaultIfEmpty(). I tried DefaultIfEmpty("") and DefaultIfEmpty(blankstringvariable) but then I get:
```
Value of type 'String' cannot be converted to type 'TheaterLink'.
``` | 2017/03/24 | [
"https://Stackoverflow.com/questions/43010428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5419106/"
] | The problem is that `FirstOrDefault()` is allowed to return `null`, in which case accessing `Link` property would throw an exception.
If you use [VB.NET 14](http://www.informit.com/articles/article.aspx?p=2431727), add question mark for automatic null checking:
```
Dim link As String = TheaterLinks.Where(Function(x) x.TheaterID = TheaterID).FirstOrDefault()?.Link
```
(see `?.Link` instead of `.Link`)
Otherwise, do it in two stages: first, get the object using `FirstOrDefault`, then null-check it manually with an `If` statement. | For my original example, I just had to add a question mark:
```
Dim link As String = Links.Where(Function(x) x.ID = id).FirstOrDefault()?.Link
```
I tried doing this in my model and got a "Nullable object must have a value" error, so I did the two-stage approach:
```
Dim eventDate = Events.Where(Function(x) x.ID = id).FirstOrDefault()?.EventDate
If eventDate.HasValue Then
'some code
Else
'some code
End If
``` |
48,527,171 | **Problem:**
So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other info) or when it is disconnected (over the mobile network). However with the changes in Android 7/N and above, CONNECTIVITY\_CHANGE and CONNECTIVITY\_ACTION no longer work in the background. Now in most cases people misuse this broadcast and as such I can completely understand why the change was made. However, I have no idea how to solve this problem in the current state.
Now I'm not at all much of an Android developer (this is for a Cordova plugin) so I'm counting on you guys!
**Expected behavior:**
App is woken up and request is sent whenever WiFi switches connectivity, even when app is killed/in background.
**Current behavior:**
App only sends request when the app is in the foreground.
**Tried so far:**
So far I've moved the implicit intent to listen to CONNECTIVITY\_ACTION from the manifest to manually registering it in the main part of the app (plugin). This makes it work as long as the app is in memory but not on cold boot or actual background
**Already looked at:**
Most answers talk about using scheduled jobs to substitute for the missing broadcast. I see how this works for, for example, retrying a download or similar, but not for my case (but please correct me if I'm wrong). Below are the SO posts I've already looked at:
[Detect connectivity changes on Android 7.0 Nougat when app is in foreground](https://stackoverflow.com/questions/39210191/detect-connectivity-changes-on-android-7-0-nougat-when-app-is-in-foreground)
[ConnectivityManager.CONNECTIVITY\_ACTION deprecated](https://stackoverflow.com/questions/36421930/connectivitymanager-connectivity-action-deprecated)
[Detect Connectivity change using JobScheduler](https://stackoverflow.com/questions/45430598/detect-connectivity-change-using-jobscheduler)
[Android O - Detect connectivity change in background](https://stackoverflow.com/questions/46163131/android-o-detect-connectivity-change-in-background) | 2018/01/30 | [
"https://Stackoverflow.com/questions/48527171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711059/"
] | **Nougat and Above:**
We have to use JobScheduler and JobService for Connection Changes.
All I can divide this into three steps.
>
> Register JobScheduler inside activity. Also, Start JobService(
> Service to handle callbacks from the JobScheduler. Requests scheduled
> with the JobScheduler ultimately land on this service's "onStartJob"
> method.)
>
>
>
```
public class NetworkConnectionActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network_connection);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scheduleJob();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void scheduleJob() {
JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
.setRequiresCharging(true)
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(myJob);
}
@Override
protected void onStop() {
// A service can be "started" and/or "bound". In this case, it's "started" by this Activity
// and "bound" to the JobScheduler (also called "Scheduled" by the JobScheduler). This call
// to stopService() won't prevent scheduled jobs to be processed. However, failing
// to call stopService() would keep it alive indefinitely.
stopService(new Intent(this, NetworkSchedulerService.class));
super.onStop();
}
@Override
protected void onStart() {
super.onStart();
// Start service and provide it a way to communicate with this class.
Intent startServiceIntent = new Intent(this, NetworkSchedulerService.class);
startService(startServiceIntent);
}
}
```
>
> The service to start and finish the job.
>
>
>
```
public class NetworkSchedulerService extends JobService implements
ConnectivityReceiver.ConnectivityReceiverListener {
private static final String TAG = NetworkSchedulerService.class.getSimpleName();
private ConnectivityReceiver mConnectivityReceiver;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service created");
mConnectivityReceiver = new ConnectivityReceiver(this);
}
/**
* When the app's NetworkConnectionActivity is created, it starts this service. This is so that the
* activity and this service can communicate back and forth. See "setUiCallback()"
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
return START_NOT_STICKY;
}
@Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "onStartJob" + mConnectivityReceiver);
registerReceiver(mConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "onStopJob");
unregisterReceiver(mConnectivityReceiver);
return true;
}
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
String message = isConnected ? "Good! Connected to Internet" : "Sorry! Not connected to internet";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
```
>
> Finally, The receiver class which checks the network connection
> changes.
>
>
>
```
public class ConnectivityReceiver extends BroadcastReceiver {
private ConnectivityReceiverListener mConnectivityReceiverListener;
ConnectivityReceiver(ConnectivityReceiverListener listener) {
mConnectivityReceiverListener = listener;
}
@Override
public void onReceive(Context context, Intent intent) {
mConnectivityReceiverListener.onNetworkConnectionChanged(isConnected(context));
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
}
```
>
> Don't forget to add permission and service inside manifest file.
>
>
>
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourpackagename">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Always required on api < 21, needed to keep a wake lock while your job is running -->
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<!-- Required on api < 21 if you are using setRequiredNetworkType(int) -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Required on all api levels if you are using setPersisted(true) -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".connectivity.NetworkConnectionActivity"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Define your service, make sure to add the permision! -->
<service
android:name=".connectivity.NetworkSchedulerService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>
</manifest>
```
Please refer below links for more info.
<https://github.com/jiteshmohite/Android-Network-Connectivity>
<https://github.com/evant/JobSchedulerCompat>
<https://github.com/googlesamples/android-JobScheduler>
<https://medium.com/@iiro.krankka/its-time-to-kiss-goodbye-to-your-implicit-broadcastreceivers-eefafd9f4f8a> | That's how i did it. I have created a `IntentService` and in `onCreate` method and I have registered `networkBroadacst` which check for internet connection.
```
public class SyncingIntentService extends IntentService {
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
networkBroadcast=new NetworkBroadcast();
registerReceiver(networkBroadcast,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onHandleIntent(intent);
return START_STICKY;
}
}
```
This is my broadcast class
```
public class NetworkBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Constants.isInternetConnected(context)) {
// Toast.makeText(context, "Internet Connect", Toast.LENGTH_SHORT).show();
context.startService(new Intent(context, SyncingIntentService.class));
}
else{}
}
}
```
In this way you can check internet connection in whether your app is in foreground or background in nougat. |
48,527,171 | **Problem:**
So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other info) or when it is disconnected (over the mobile network). However with the changes in Android 7/N and above, CONNECTIVITY\_CHANGE and CONNECTIVITY\_ACTION no longer work in the background. Now in most cases people misuse this broadcast and as such I can completely understand why the change was made. However, I have no idea how to solve this problem in the current state.
Now I'm not at all much of an Android developer (this is for a Cordova plugin) so I'm counting on you guys!
**Expected behavior:**
App is woken up and request is sent whenever WiFi switches connectivity, even when app is killed/in background.
**Current behavior:**
App only sends request when the app is in the foreground.
**Tried so far:**
So far I've moved the implicit intent to listen to CONNECTIVITY\_ACTION from the manifest to manually registering it in the main part of the app (plugin). This makes it work as long as the app is in memory but not on cold boot or actual background
**Already looked at:**
Most answers talk about using scheduled jobs to substitute for the missing broadcast. I see how this works for, for example, retrying a download or similar, but not for my case (but please correct me if I'm wrong). Below are the SO posts I've already looked at:
[Detect connectivity changes on Android 7.0 Nougat when app is in foreground](https://stackoverflow.com/questions/39210191/detect-connectivity-changes-on-android-7-0-nougat-when-app-is-in-foreground)
[ConnectivityManager.CONNECTIVITY\_ACTION deprecated](https://stackoverflow.com/questions/36421930/connectivitymanager-connectivity-action-deprecated)
[Detect Connectivity change using JobScheduler](https://stackoverflow.com/questions/45430598/detect-connectivity-change-using-jobscheduler)
[Android O - Detect connectivity change in background](https://stackoverflow.com/questions/46163131/android-o-detect-connectivity-change-in-background) | 2018/01/30 | [
"https://Stackoverflow.com/questions/48527171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711059/"
] | The best way to grab Connectivity change Android Os 7 and above is register your ConnectivityReceiver broadcast in Application class like below, This helps you to get changes in background as well until your app alive.
```
public class MyApplication extends Application {
private ConnectivityReceiver connectivityReceiver;
private ConnectivityReceiver getConnectivityReceiver() {
if (connectivityReceiver == null)
connectivityReceiver = new ConnectivityReceiver();
return connectivityReceiver;
}
@Override
public void onCreate() {
super.onCreate();
registerConnectivityReceiver();
}
// register here your filtters
private void registerConnectivityReceiver(){
try {
// if (android.os.Build.VERSION.SDK_INT >= 26) {
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
//filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(getConnectivityReceiver(), filter);
} catch (Exception e) {
MLog.e(TAG, e.getMessage());
}
}
}
```
And then in manifest
```
<application
android:name=".app.MyApplication"/>
```
Here is your ConnectivityReceiver.java
```
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
MLog.v(TAG, "onReceive().." + intent.getAction());
}
}
``` | That's how i did it. I have created a `IntentService` and in `onCreate` method and I have registered `networkBroadacst` which check for internet connection.
```
public class SyncingIntentService extends IntentService {
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
networkBroadcast=new NetworkBroadcast();
registerReceiver(networkBroadcast,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onHandleIntent(intent);
return START_STICKY;
}
}
```
This is my broadcast class
```
public class NetworkBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Constants.isInternetConnected(context)) {
// Toast.makeText(context, "Internet Connect", Toast.LENGTH_SHORT).show();
context.startService(new Intent(context, SyncingIntentService.class));
}
else{}
}
}
```
In this way you can check internet connection in whether your app is in foreground or background in nougat. |
48,527,171 | **Problem:**
So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other info) or when it is disconnected (over the mobile network). However with the changes in Android 7/N and above, CONNECTIVITY\_CHANGE and CONNECTIVITY\_ACTION no longer work in the background. Now in most cases people misuse this broadcast and as such I can completely understand why the change was made. However, I have no idea how to solve this problem in the current state.
Now I'm not at all much of an Android developer (this is for a Cordova plugin) so I'm counting on you guys!
**Expected behavior:**
App is woken up and request is sent whenever WiFi switches connectivity, even when app is killed/in background.
**Current behavior:**
App only sends request when the app is in the foreground.
**Tried so far:**
So far I've moved the implicit intent to listen to CONNECTIVITY\_ACTION from the manifest to manually registering it in the main part of the app (plugin). This makes it work as long as the app is in memory but not on cold boot or actual background
**Already looked at:**
Most answers talk about using scheduled jobs to substitute for the missing broadcast. I see how this works for, for example, retrying a download or similar, but not for my case (but please correct me if I'm wrong). Below are the SO posts I've already looked at:
[Detect connectivity changes on Android 7.0 Nougat when app is in foreground](https://stackoverflow.com/questions/39210191/detect-connectivity-changes-on-android-7-0-nougat-when-app-is-in-foreground)
[ConnectivityManager.CONNECTIVITY\_ACTION deprecated](https://stackoverflow.com/questions/36421930/connectivitymanager-connectivity-action-deprecated)
[Detect Connectivity change using JobScheduler](https://stackoverflow.com/questions/45430598/detect-connectivity-change-using-jobscheduler)
[Android O - Detect connectivity change in background](https://stackoverflow.com/questions/46163131/android-o-detect-connectivity-change-in-background) | 2018/01/30 | [
"https://Stackoverflow.com/questions/48527171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711059/"
] | That's how i did it. I have created a `IntentService` and in `onCreate` method and I have registered `networkBroadacst` which check for internet connection.
```
public class SyncingIntentService extends IntentService {
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
networkBroadcast=new NetworkBroadcast();
registerReceiver(networkBroadcast,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onHandleIntent(intent);
return START_STICKY;
}
}
```
This is my broadcast class
```
public class NetworkBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Constants.isInternetConnected(context)) {
// Toast.makeText(context, "Internet Connect", Toast.LENGTH_SHORT).show();
context.startService(new Intent(context, SyncingIntentService.class));
}
else{}
}
}
```
In this way you can check internet connection in whether your app is in foreground or background in nougat. | Another approach which is simpler and easier when you use `registerNetworkCallback (NetworkRequest, PendingIntent)`:
```
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
builder.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Intent intent = new Intent(this, SendAnyRequestService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
if (connectivityManager != null) {
NetworkRequest networkRequest = builder.build();
connectivityManager.registerNetworkCallback(networkRequest, pendingIntent);
}
```
Which is `SendAnyRequestService.class` is your service class, and you can call your API inside it.
This code work for Android 6.0 (API 23) and above
Ref document is [here](https://developer.android.com/reference/android/net/ConnectivityManager.html#registerNetworkCallback(android.net.NetworkRequest,%20android.app.PendingIntent)) |
48,527,171 | **Problem:**
So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other info) or when it is disconnected (over the mobile network). However with the changes in Android 7/N and above, CONNECTIVITY\_CHANGE and CONNECTIVITY\_ACTION no longer work in the background. Now in most cases people misuse this broadcast and as such I can completely understand why the change was made. However, I have no idea how to solve this problem in the current state.
Now I'm not at all much of an Android developer (this is for a Cordova plugin) so I'm counting on you guys!
**Expected behavior:**
App is woken up and request is sent whenever WiFi switches connectivity, even when app is killed/in background.
**Current behavior:**
App only sends request when the app is in the foreground.
**Tried so far:**
So far I've moved the implicit intent to listen to CONNECTIVITY\_ACTION from the manifest to manually registering it in the main part of the app (plugin). This makes it work as long as the app is in memory but not on cold boot or actual background
**Already looked at:**
Most answers talk about using scheduled jobs to substitute for the missing broadcast. I see how this works for, for example, retrying a download or similar, but not for my case (but please correct me if I'm wrong). Below are the SO posts I've already looked at:
[Detect connectivity changes on Android 7.0 Nougat when app is in foreground](https://stackoverflow.com/questions/39210191/detect-connectivity-changes-on-android-7-0-nougat-when-app-is-in-foreground)
[ConnectivityManager.CONNECTIVITY\_ACTION deprecated](https://stackoverflow.com/questions/36421930/connectivitymanager-connectivity-action-deprecated)
[Detect Connectivity change using JobScheduler](https://stackoverflow.com/questions/45430598/detect-connectivity-change-using-jobscheduler)
[Android O - Detect connectivity change in background](https://stackoverflow.com/questions/46163131/android-o-detect-connectivity-change-in-background) | 2018/01/30 | [
"https://Stackoverflow.com/questions/48527171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711059/"
] | **Nougat and Above:**
We have to use JobScheduler and JobService for Connection Changes.
All I can divide this into three steps.
>
> Register JobScheduler inside activity. Also, Start JobService(
> Service to handle callbacks from the JobScheduler. Requests scheduled
> with the JobScheduler ultimately land on this service's "onStartJob"
> method.)
>
>
>
```
public class NetworkConnectionActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network_connection);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scheduleJob();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void scheduleJob() {
JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
.setRequiresCharging(true)
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(myJob);
}
@Override
protected void onStop() {
// A service can be "started" and/or "bound". In this case, it's "started" by this Activity
// and "bound" to the JobScheduler (also called "Scheduled" by the JobScheduler). This call
// to stopService() won't prevent scheduled jobs to be processed. However, failing
// to call stopService() would keep it alive indefinitely.
stopService(new Intent(this, NetworkSchedulerService.class));
super.onStop();
}
@Override
protected void onStart() {
super.onStart();
// Start service and provide it a way to communicate with this class.
Intent startServiceIntent = new Intent(this, NetworkSchedulerService.class);
startService(startServiceIntent);
}
}
```
>
> The service to start and finish the job.
>
>
>
```
public class NetworkSchedulerService extends JobService implements
ConnectivityReceiver.ConnectivityReceiverListener {
private static final String TAG = NetworkSchedulerService.class.getSimpleName();
private ConnectivityReceiver mConnectivityReceiver;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service created");
mConnectivityReceiver = new ConnectivityReceiver(this);
}
/**
* When the app's NetworkConnectionActivity is created, it starts this service. This is so that the
* activity and this service can communicate back and forth. See "setUiCallback()"
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
return START_NOT_STICKY;
}
@Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "onStartJob" + mConnectivityReceiver);
registerReceiver(mConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "onStopJob");
unregisterReceiver(mConnectivityReceiver);
return true;
}
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
String message = isConnected ? "Good! Connected to Internet" : "Sorry! Not connected to internet";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
```
>
> Finally, The receiver class which checks the network connection
> changes.
>
>
>
```
public class ConnectivityReceiver extends BroadcastReceiver {
private ConnectivityReceiverListener mConnectivityReceiverListener;
ConnectivityReceiver(ConnectivityReceiverListener listener) {
mConnectivityReceiverListener = listener;
}
@Override
public void onReceive(Context context, Intent intent) {
mConnectivityReceiverListener.onNetworkConnectionChanged(isConnected(context));
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
}
```
>
> Don't forget to add permission and service inside manifest file.
>
>
>
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourpackagename">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Always required on api < 21, needed to keep a wake lock while your job is running -->
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<!-- Required on api < 21 if you are using setRequiredNetworkType(int) -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Required on all api levels if you are using setPersisted(true) -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".connectivity.NetworkConnectionActivity"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Define your service, make sure to add the permision! -->
<service
android:name=".connectivity.NetworkSchedulerService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>
</manifest>
```
Please refer below links for more info.
<https://github.com/jiteshmohite/Android-Network-Connectivity>
<https://github.com/evant/JobSchedulerCompat>
<https://github.com/googlesamples/android-JobScheduler>
<https://medium.com/@iiro.krankka/its-time-to-kiss-goodbye-to-your-implicit-broadcastreceivers-eefafd9f4f8a> | Below is [excerpt from documentation](https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html)
>
> Apps targeting Android 7.0 (API level 24) and higher do not receive
> CONNECTIVITY\_ACTION broadcasts if they declare the broadcast receiver
> in their manifest. Apps will still receive CONNECTIVITY\_ACTION
> broadcasts if they register their BroadcastReceiver with
> Context.registerReceiver() and that context is still valid.
>
>
>
So you will get this Broadcast till your context is valid in Android N & above by explicitly registering for same.
**Boot Completed:**
You can listen `android.intent.action.BOOT_COMPLETED` broadcast
you will need this permission for same.
```
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
```
**App Killed Scenario:**
**You are not going to receive it.**
That is very much expected and due to **various reasons**
* [**Android Oreo has limitations**](https://developer.android.com/about/versions/oreo/background.html) on running services in background, so you may face this on O devices
* [**Doze mode**](https://developer.android.com/training/monitoring-device-state/doze-standby.html) on Android Marshmallow onwards can cause this, it will stop all network operations itself & take away CPU wake locks
* Though Doze mode have one mechanism for [requesting whitelisting of apps](https://developer.android.com/training/monitoring-device-state/doze-standby.html#whitelisting-cases), this might be useful for you. |
48,527,171 | **Problem:**
So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other info) or when it is disconnected (over the mobile network). However with the changes in Android 7/N and above, CONNECTIVITY\_CHANGE and CONNECTIVITY\_ACTION no longer work in the background. Now in most cases people misuse this broadcast and as such I can completely understand why the change was made. However, I have no idea how to solve this problem in the current state.
Now I'm not at all much of an Android developer (this is for a Cordova plugin) so I'm counting on you guys!
**Expected behavior:**
App is woken up and request is sent whenever WiFi switches connectivity, even when app is killed/in background.
**Current behavior:**
App only sends request when the app is in the foreground.
**Tried so far:**
So far I've moved the implicit intent to listen to CONNECTIVITY\_ACTION from the manifest to manually registering it in the main part of the app (plugin). This makes it work as long as the app is in memory but not on cold boot or actual background
**Already looked at:**
Most answers talk about using scheduled jobs to substitute for the missing broadcast. I see how this works for, for example, retrying a download or similar, but not for my case (but please correct me if I'm wrong). Below are the SO posts I've already looked at:
[Detect connectivity changes on Android 7.0 Nougat when app is in foreground](https://stackoverflow.com/questions/39210191/detect-connectivity-changes-on-android-7-0-nougat-when-app-is-in-foreground)
[ConnectivityManager.CONNECTIVITY\_ACTION deprecated](https://stackoverflow.com/questions/36421930/connectivitymanager-connectivity-action-deprecated)
[Detect Connectivity change using JobScheduler](https://stackoverflow.com/questions/45430598/detect-connectivity-change-using-jobscheduler)
[Android O - Detect connectivity change in background](https://stackoverflow.com/questions/46163131/android-o-detect-connectivity-change-in-background) | 2018/01/30 | [
"https://Stackoverflow.com/questions/48527171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711059/"
] | **Nougat and Above:**
We have to use JobScheduler and JobService for Connection Changes.
All I can divide this into three steps.
>
> Register JobScheduler inside activity. Also, Start JobService(
> Service to handle callbacks from the JobScheduler. Requests scheduled
> with the JobScheduler ultimately land on this service's "onStartJob"
> method.)
>
>
>
```
public class NetworkConnectionActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network_connection);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scheduleJob();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void scheduleJob() {
JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
.setRequiresCharging(true)
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(myJob);
}
@Override
protected void onStop() {
// A service can be "started" and/or "bound". In this case, it's "started" by this Activity
// and "bound" to the JobScheduler (also called "Scheduled" by the JobScheduler). This call
// to stopService() won't prevent scheduled jobs to be processed. However, failing
// to call stopService() would keep it alive indefinitely.
stopService(new Intent(this, NetworkSchedulerService.class));
super.onStop();
}
@Override
protected void onStart() {
super.onStart();
// Start service and provide it a way to communicate with this class.
Intent startServiceIntent = new Intent(this, NetworkSchedulerService.class);
startService(startServiceIntent);
}
}
```
>
> The service to start and finish the job.
>
>
>
```
public class NetworkSchedulerService extends JobService implements
ConnectivityReceiver.ConnectivityReceiverListener {
private static final String TAG = NetworkSchedulerService.class.getSimpleName();
private ConnectivityReceiver mConnectivityReceiver;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service created");
mConnectivityReceiver = new ConnectivityReceiver(this);
}
/**
* When the app's NetworkConnectionActivity is created, it starts this service. This is so that the
* activity and this service can communicate back and forth. See "setUiCallback()"
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
return START_NOT_STICKY;
}
@Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "onStartJob" + mConnectivityReceiver);
registerReceiver(mConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "onStopJob");
unregisterReceiver(mConnectivityReceiver);
return true;
}
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
String message = isConnected ? "Good! Connected to Internet" : "Sorry! Not connected to internet";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
```
>
> Finally, The receiver class which checks the network connection
> changes.
>
>
>
```
public class ConnectivityReceiver extends BroadcastReceiver {
private ConnectivityReceiverListener mConnectivityReceiverListener;
ConnectivityReceiver(ConnectivityReceiverListener listener) {
mConnectivityReceiverListener = listener;
}
@Override
public void onReceive(Context context, Intent intent) {
mConnectivityReceiverListener.onNetworkConnectionChanged(isConnected(context));
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
}
```
>
> Don't forget to add permission and service inside manifest file.
>
>
>
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourpackagename">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Always required on api < 21, needed to keep a wake lock while your job is running -->
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<!-- Required on api < 21 if you are using setRequiredNetworkType(int) -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Required on all api levels if you are using setPersisted(true) -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".connectivity.NetworkConnectionActivity"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Define your service, make sure to add the permision! -->
<service
android:name=".connectivity.NetworkSchedulerService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>
</manifest>
```
Please refer below links for more info.
<https://github.com/jiteshmohite/Android-Network-Connectivity>
<https://github.com/evant/JobSchedulerCompat>
<https://github.com/googlesamples/android-JobScheduler>
<https://medium.com/@iiro.krankka/its-time-to-kiss-goodbye-to-your-implicit-broadcastreceivers-eefafd9f4f8a> | The best way to grab Connectivity change Android Os 7 and above is register your ConnectivityReceiver broadcast in Application class like below, This helps you to get changes in background as well until your app alive.
```
public class MyApplication extends Application {
private ConnectivityReceiver connectivityReceiver;
private ConnectivityReceiver getConnectivityReceiver() {
if (connectivityReceiver == null)
connectivityReceiver = new ConnectivityReceiver();
return connectivityReceiver;
}
@Override
public void onCreate() {
super.onCreate();
registerConnectivityReceiver();
}
// register here your filtters
private void registerConnectivityReceiver(){
try {
// if (android.os.Build.VERSION.SDK_INT >= 26) {
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
//filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(getConnectivityReceiver(), filter);
} catch (Exception e) {
MLog.e(TAG, e.getMessage());
}
}
}
```
And then in manifest
```
<application
android:name=".app.MyApplication"/>
```
Here is your ConnectivityReceiver.java
```
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
MLog.v(TAG, "onReceive().." + intent.getAction());
}
}
``` |
48,527,171 | **Problem:**
So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other info) or when it is disconnected (over the mobile network). However with the changes in Android 7/N and above, CONNECTIVITY\_CHANGE and CONNECTIVITY\_ACTION no longer work in the background. Now in most cases people misuse this broadcast and as such I can completely understand why the change was made. However, I have no idea how to solve this problem in the current state.
Now I'm not at all much of an Android developer (this is for a Cordova plugin) so I'm counting on you guys!
**Expected behavior:**
App is woken up and request is sent whenever WiFi switches connectivity, even when app is killed/in background.
**Current behavior:**
App only sends request when the app is in the foreground.
**Tried so far:**
So far I've moved the implicit intent to listen to CONNECTIVITY\_ACTION from the manifest to manually registering it in the main part of the app (plugin). This makes it work as long as the app is in memory but not on cold boot or actual background
**Already looked at:**
Most answers talk about using scheduled jobs to substitute for the missing broadcast. I see how this works for, for example, retrying a download or similar, but not for my case (but please correct me if I'm wrong). Below are the SO posts I've already looked at:
[Detect connectivity changes on Android 7.0 Nougat when app is in foreground](https://stackoverflow.com/questions/39210191/detect-connectivity-changes-on-android-7-0-nougat-when-app-is-in-foreground)
[ConnectivityManager.CONNECTIVITY\_ACTION deprecated](https://stackoverflow.com/questions/36421930/connectivitymanager-connectivity-action-deprecated)
[Detect Connectivity change using JobScheduler](https://stackoverflow.com/questions/45430598/detect-connectivity-change-using-jobscheduler)
[Android O - Detect connectivity change in background](https://stackoverflow.com/questions/46163131/android-o-detect-connectivity-change-in-background) | 2018/01/30 | [
"https://Stackoverflow.com/questions/48527171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711059/"
] | **Nougat and Above:**
We have to use JobScheduler and JobService for Connection Changes.
All I can divide this into three steps.
>
> Register JobScheduler inside activity. Also, Start JobService(
> Service to handle callbacks from the JobScheduler. Requests scheduled
> with the JobScheduler ultimately land on this service's "onStartJob"
> method.)
>
>
>
```
public class NetworkConnectionActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network_connection);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scheduleJob();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void scheduleJob() {
JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
.setRequiresCharging(true)
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(myJob);
}
@Override
protected void onStop() {
// A service can be "started" and/or "bound". In this case, it's "started" by this Activity
// and "bound" to the JobScheduler (also called "Scheduled" by the JobScheduler). This call
// to stopService() won't prevent scheduled jobs to be processed. However, failing
// to call stopService() would keep it alive indefinitely.
stopService(new Intent(this, NetworkSchedulerService.class));
super.onStop();
}
@Override
protected void onStart() {
super.onStart();
// Start service and provide it a way to communicate with this class.
Intent startServiceIntent = new Intent(this, NetworkSchedulerService.class);
startService(startServiceIntent);
}
}
```
>
> The service to start and finish the job.
>
>
>
```
public class NetworkSchedulerService extends JobService implements
ConnectivityReceiver.ConnectivityReceiverListener {
private static final String TAG = NetworkSchedulerService.class.getSimpleName();
private ConnectivityReceiver mConnectivityReceiver;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service created");
mConnectivityReceiver = new ConnectivityReceiver(this);
}
/**
* When the app's NetworkConnectionActivity is created, it starts this service. This is so that the
* activity and this service can communicate back and forth. See "setUiCallback()"
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
return START_NOT_STICKY;
}
@Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "onStartJob" + mConnectivityReceiver);
registerReceiver(mConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "onStopJob");
unregisterReceiver(mConnectivityReceiver);
return true;
}
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
String message = isConnected ? "Good! Connected to Internet" : "Sorry! Not connected to internet";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
```
>
> Finally, The receiver class which checks the network connection
> changes.
>
>
>
```
public class ConnectivityReceiver extends BroadcastReceiver {
private ConnectivityReceiverListener mConnectivityReceiverListener;
ConnectivityReceiver(ConnectivityReceiverListener listener) {
mConnectivityReceiverListener = listener;
}
@Override
public void onReceive(Context context, Intent intent) {
mConnectivityReceiverListener.onNetworkConnectionChanged(isConnected(context));
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
}
```
>
> Don't forget to add permission and service inside manifest file.
>
>
>
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourpackagename">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Always required on api < 21, needed to keep a wake lock while your job is running -->
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<!-- Required on api < 21 if you are using setRequiredNetworkType(int) -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Required on all api levels if you are using setPersisted(true) -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".connectivity.NetworkConnectionActivity"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Define your service, make sure to add the permision! -->
<service
android:name=".connectivity.NetworkSchedulerService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>
</manifest>
```
Please refer below links for more info.
<https://github.com/jiteshmohite/Android-Network-Connectivity>
<https://github.com/evant/JobSchedulerCompat>
<https://github.com/googlesamples/android-JobScheduler>
<https://medium.com/@iiro.krankka/its-time-to-kiss-goodbye-to-your-implicit-broadcastreceivers-eefafd9f4f8a> | Another approach which is simpler and easier when you use `registerNetworkCallback (NetworkRequest, PendingIntent)`:
```
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
builder.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Intent intent = new Intent(this, SendAnyRequestService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
if (connectivityManager != null) {
NetworkRequest networkRequest = builder.build();
connectivityManager.registerNetworkCallback(networkRequest, pendingIntent);
}
```
Which is `SendAnyRequestService.class` is your service class, and you can call your API inside it.
This code work for Android 6.0 (API 23) and above
Ref document is [here](https://developer.android.com/reference/android/net/ConnectivityManager.html#registerNetworkCallback(android.net.NetworkRequest,%20android.app.PendingIntent)) |
48,527,171 | **Problem:**
So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other info) or when it is disconnected (over the mobile network). However with the changes in Android 7/N and above, CONNECTIVITY\_CHANGE and CONNECTIVITY\_ACTION no longer work in the background. Now in most cases people misuse this broadcast and as such I can completely understand why the change was made. However, I have no idea how to solve this problem in the current state.
Now I'm not at all much of an Android developer (this is for a Cordova plugin) so I'm counting on you guys!
**Expected behavior:**
App is woken up and request is sent whenever WiFi switches connectivity, even when app is killed/in background.
**Current behavior:**
App only sends request when the app is in the foreground.
**Tried so far:**
So far I've moved the implicit intent to listen to CONNECTIVITY\_ACTION from the manifest to manually registering it in the main part of the app (plugin). This makes it work as long as the app is in memory but not on cold boot or actual background
**Already looked at:**
Most answers talk about using scheduled jobs to substitute for the missing broadcast. I see how this works for, for example, retrying a download or similar, but not for my case (but please correct me if I'm wrong). Below are the SO posts I've already looked at:
[Detect connectivity changes on Android 7.0 Nougat when app is in foreground](https://stackoverflow.com/questions/39210191/detect-connectivity-changes-on-android-7-0-nougat-when-app-is-in-foreground)
[ConnectivityManager.CONNECTIVITY\_ACTION deprecated](https://stackoverflow.com/questions/36421930/connectivitymanager-connectivity-action-deprecated)
[Detect Connectivity change using JobScheduler](https://stackoverflow.com/questions/45430598/detect-connectivity-change-using-jobscheduler)
[Android O - Detect connectivity change in background](https://stackoverflow.com/questions/46163131/android-o-detect-connectivity-change-in-background) | 2018/01/30 | [
"https://Stackoverflow.com/questions/48527171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711059/"
] | The best way to grab Connectivity change Android Os 7 and above is register your ConnectivityReceiver broadcast in Application class like below, This helps you to get changes in background as well until your app alive.
```
public class MyApplication extends Application {
private ConnectivityReceiver connectivityReceiver;
private ConnectivityReceiver getConnectivityReceiver() {
if (connectivityReceiver == null)
connectivityReceiver = new ConnectivityReceiver();
return connectivityReceiver;
}
@Override
public void onCreate() {
super.onCreate();
registerConnectivityReceiver();
}
// register here your filtters
private void registerConnectivityReceiver(){
try {
// if (android.os.Build.VERSION.SDK_INT >= 26) {
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
//filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(getConnectivityReceiver(), filter);
} catch (Exception e) {
MLog.e(TAG, e.getMessage());
}
}
}
```
And then in manifest
```
<application
android:name=".app.MyApplication"/>
```
Here is your ConnectivityReceiver.java
```
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
MLog.v(TAG, "onReceive().." + intent.getAction());
}
}
``` | Below is [excerpt from documentation](https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html)
>
> Apps targeting Android 7.0 (API level 24) and higher do not receive
> CONNECTIVITY\_ACTION broadcasts if they declare the broadcast receiver
> in their manifest. Apps will still receive CONNECTIVITY\_ACTION
> broadcasts if they register their BroadcastReceiver with
> Context.registerReceiver() and that context is still valid.
>
>
>
So you will get this Broadcast till your context is valid in Android N & above by explicitly registering for same.
**Boot Completed:**
You can listen `android.intent.action.BOOT_COMPLETED` broadcast
you will need this permission for same.
```
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
```
**App Killed Scenario:**
**You are not going to receive it.**
That is very much expected and due to **various reasons**
* [**Android Oreo has limitations**](https://developer.android.com/about/versions/oreo/background.html) on running services in background, so you may face this on O devices
* [**Doze mode**](https://developer.android.com/training/monitoring-device-state/doze-standby.html) on Android Marshmallow onwards can cause this, it will stop all network operations itself & take away CPU wake locks
* Though Doze mode have one mechanism for [requesting whitelisting of apps](https://developer.android.com/training/monitoring-device-state/doze-standby.html#whitelisting-cases), this might be useful for you. |
48,527,171 | **Problem:**
So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other info) or when it is disconnected (over the mobile network). However with the changes in Android 7/N and above, CONNECTIVITY\_CHANGE and CONNECTIVITY\_ACTION no longer work in the background. Now in most cases people misuse this broadcast and as such I can completely understand why the change was made. However, I have no idea how to solve this problem in the current state.
Now I'm not at all much of an Android developer (this is for a Cordova plugin) so I'm counting on you guys!
**Expected behavior:**
App is woken up and request is sent whenever WiFi switches connectivity, even when app is killed/in background.
**Current behavior:**
App only sends request when the app is in the foreground.
**Tried so far:**
So far I've moved the implicit intent to listen to CONNECTIVITY\_ACTION from the manifest to manually registering it in the main part of the app (plugin). This makes it work as long as the app is in memory but not on cold boot or actual background
**Already looked at:**
Most answers talk about using scheduled jobs to substitute for the missing broadcast. I see how this works for, for example, retrying a download or similar, but not for my case (but please correct me if I'm wrong). Below are the SO posts I've already looked at:
[Detect connectivity changes on Android 7.0 Nougat when app is in foreground](https://stackoverflow.com/questions/39210191/detect-connectivity-changes-on-android-7-0-nougat-when-app-is-in-foreground)
[ConnectivityManager.CONNECTIVITY\_ACTION deprecated](https://stackoverflow.com/questions/36421930/connectivitymanager-connectivity-action-deprecated)
[Detect Connectivity change using JobScheduler](https://stackoverflow.com/questions/45430598/detect-connectivity-change-using-jobscheduler)
[Android O - Detect connectivity change in background](https://stackoverflow.com/questions/46163131/android-o-detect-connectivity-change-in-background) | 2018/01/30 | [
"https://Stackoverflow.com/questions/48527171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711059/"
] | Below is [excerpt from documentation](https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html)
>
> Apps targeting Android 7.0 (API level 24) and higher do not receive
> CONNECTIVITY\_ACTION broadcasts if they declare the broadcast receiver
> in their manifest. Apps will still receive CONNECTIVITY\_ACTION
> broadcasts if they register their BroadcastReceiver with
> Context.registerReceiver() and that context is still valid.
>
>
>
So you will get this Broadcast till your context is valid in Android N & above by explicitly registering for same.
**Boot Completed:**
You can listen `android.intent.action.BOOT_COMPLETED` broadcast
you will need this permission for same.
```
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
```
**App Killed Scenario:**
**You are not going to receive it.**
That is very much expected and due to **various reasons**
* [**Android Oreo has limitations**](https://developer.android.com/about/versions/oreo/background.html) on running services in background, so you may face this on O devices
* [**Doze mode**](https://developer.android.com/training/monitoring-device-state/doze-standby.html) on Android Marshmallow onwards can cause this, it will stop all network operations itself & take away CPU wake locks
* Though Doze mode have one mechanism for [requesting whitelisting of apps](https://developer.android.com/training/monitoring-device-state/doze-standby.html#whitelisting-cases), this might be useful for you. | Another approach which is simpler and easier when you use `registerNetworkCallback (NetworkRequest, PendingIntent)`:
```
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
builder.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Intent intent = new Intent(this, SendAnyRequestService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
if (connectivityManager != null) {
NetworkRequest networkRequest = builder.build();
connectivityManager.registerNetworkCallback(networkRequest, pendingIntent);
}
```
Which is `SendAnyRequestService.class` is your service class, and you can call your API inside it.
This code work for Android 6.0 (API 23) and above
Ref document is [here](https://developer.android.com/reference/android/net/ConnectivityManager.html#registerNetworkCallback(android.net.NetworkRequest,%20android.app.PendingIntent)) |
48,527,171 | **Problem:**
So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other info) or when it is disconnected (over the mobile network). However with the changes in Android 7/N and above, CONNECTIVITY\_CHANGE and CONNECTIVITY\_ACTION no longer work in the background. Now in most cases people misuse this broadcast and as such I can completely understand why the change was made. However, I have no idea how to solve this problem in the current state.
Now I'm not at all much of an Android developer (this is for a Cordova plugin) so I'm counting on you guys!
**Expected behavior:**
App is woken up and request is sent whenever WiFi switches connectivity, even when app is killed/in background.
**Current behavior:**
App only sends request when the app is in the foreground.
**Tried so far:**
So far I've moved the implicit intent to listen to CONNECTIVITY\_ACTION from the manifest to manually registering it in the main part of the app (plugin). This makes it work as long as the app is in memory but not on cold boot or actual background
**Already looked at:**
Most answers talk about using scheduled jobs to substitute for the missing broadcast. I see how this works for, for example, retrying a download or similar, but not for my case (but please correct me if I'm wrong). Below are the SO posts I've already looked at:
[Detect connectivity changes on Android 7.0 Nougat when app is in foreground](https://stackoverflow.com/questions/39210191/detect-connectivity-changes-on-android-7-0-nougat-when-app-is-in-foreground)
[ConnectivityManager.CONNECTIVITY\_ACTION deprecated](https://stackoverflow.com/questions/36421930/connectivitymanager-connectivity-action-deprecated)
[Detect Connectivity change using JobScheduler](https://stackoverflow.com/questions/45430598/detect-connectivity-change-using-jobscheduler)
[Android O - Detect connectivity change in background](https://stackoverflow.com/questions/46163131/android-o-detect-connectivity-change-in-background) | 2018/01/30 | [
"https://Stackoverflow.com/questions/48527171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711059/"
] | The best way to grab Connectivity change Android Os 7 and above is register your ConnectivityReceiver broadcast in Application class like below, This helps you to get changes in background as well until your app alive.
```
public class MyApplication extends Application {
private ConnectivityReceiver connectivityReceiver;
private ConnectivityReceiver getConnectivityReceiver() {
if (connectivityReceiver == null)
connectivityReceiver = new ConnectivityReceiver();
return connectivityReceiver;
}
@Override
public void onCreate() {
super.onCreate();
registerConnectivityReceiver();
}
// register here your filtters
private void registerConnectivityReceiver(){
try {
// if (android.os.Build.VERSION.SDK_INT >= 26) {
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
//filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(getConnectivityReceiver(), filter);
} catch (Exception e) {
MLog.e(TAG, e.getMessage());
}
}
}
```
And then in manifest
```
<application
android:name=".app.MyApplication"/>
```
Here is your ConnectivityReceiver.java
```
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
MLog.v(TAG, "onReceive().." + intent.getAction());
}
}
``` | Another approach which is simpler and easier when you use `registerNetworkCallback (NetworkRequest, PendingIntent)`:
```
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
builder.addTransportType(NetworkCapabilities.TRANSPORT_VPN);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Intent intent = new Intent(this, SendAnyRequestService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
if (connectivityManager != null) {
NetworkRequest networkRequest = builder.build();
connectivityManager.registerNetworkCallback(networkRequest, pendingIntent);
}
```
Which is `SendAnyRequestService.class` is your service class, and you can call your API inside it.
This code work for Android 6.0 (API 23) and above
Ref document is [here](https://developer.android.com/reference/android/net/ConnectivityManager.html#registerNetworkCallback(android.net.NetworkRequest,%20android.app.PendingIntent)) |
13,580,567 | I'm wondering is there a way to send some kind of generics for example `List <float> floatValues = new List<float>()` need to be sent to udp client. I don't know how to do that, any help will be appreciated! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13580567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1817808/"
] | You want to go into your
```
~/Library/Application Support/Sublime Text 2/Packages/Default/Default.sublime-theme
```
(old version) or
```
~/Library/Application Support/Sublime Text 2/Packages/Theme-Default/Default.sublime-theme
```
(new version) and edit these things:
* `"class": "sidebar_container"`
* `"class": "sidebar_tree"`
* `"class": "sidebar_heading"`
* `"class": "sidebar_label"`
Therein you can change the RGB colors until you get what you want.
[Here is a thread that discusses this in greater detail.](http://sublimetext.userecho.com/topic/19274-theming-of-the-sidebar/)
edit: added the correct location provided by @Michael Tunnell
edit: Sample Dark SideBar Configuration.
[![Image with Dark SideBar](https://i.stack.imgur.com/9AZpm.png)](https://i.stack.imgur.com/9AZpm.png)
Click to See Larger Image for Settings
[![Click to See Larger Image for Settings](https://i.stack.imgur.com/NSzsF.png)](https://i.stack.imgur.com/NSzsF.png) | Try installing the Soda theme. The dark theme has a nice dark side bar.
<https://github.com/buymeasoda/soda-theme> |
13,580,567 | I'm wondering is there a way to send some kind of generics for example `List <float> floatValues = new List<float>()` need to be sent to udp client. I don't know how to do that, any help will be appreciated! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13580567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1817808/"
] | Try installing the Soda theme. The dark theme has a nice dark side bar.
<https://github.com/buymeasoda/soda-theme> | **Sublime Text 2** Package Control ~ [Theme Soda SolarizedDark](https://packagecontrol.io/packages/Theme%20-%20Soda%20SolarizedDark). This requires some editing of Preferences Settings. Looks nice with built in Solarized (Dark).tmTheme.
Sublime side bar darkens nicely now, but you may find selection of side bar items is too muted. Settings edit? For example, to make Solarized (Dark).tmTheme code pane selections more visible:
```
<dict>
<key>name</key>
<string>Solarized (dark)</string>
<key>settings</key>
<array>
<dict>
<key>settings</key>
<dict> [edit/insert the following key-string lines]
<key>selection</key>
<string>#03151C</string>
<key>selectionBorder</key>
<string>#99ccff</string>
<key>inactiveSelection</key>
<string>#0099ff30</string>
```
This code pane colors Setting slightly further mutes side bar colors on Mac. Not a PC issue, since on my PC Theme Soda SolarizedDark does not work! But the edit of selection appearance for Solarized (Dark).tmTheme makes PC sidebar slightly brighter, opposite of Mac. Buggy? |
13,580,567 | I'm wondering is there a way to send some kind of generics for example `List <float> floatValues = new List<float>()` need to be sent to udp client. I don't know how to do that, any help will be appreciated! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13580567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1817808/"
] | Try installing the Soda theme. The dark theme has a nice dark side bar.
<https://github.com/buymeasoda/soda-theme> | I found that going to Preferences -> Theme brought up the command pallet for themes. when change to the Adaptive.sublime-theme the side bar changes to black.
This is also accessible through the command pallet. Press ctrl+shift+p then type 'theme' select the option 'UI: Select Theme' and again you can choose the Adaptive theme. |
13,580,567 | I'm wondering is there a way to send some kind of generics for example `List <float> floatValues = new List<float>()` need to be sent to udp client. I don't know how to do that, any help will be appreciated! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13580567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1817808/"
] | Try installing the Soda theme. The dark theme has a nice dark side bar.
<https://github.com/buymeasoda/soda-theme> | Try installing Predawn theme maybe you like the look and feel of its theme <https://github.com/jamiewilson/predawn> |
13,580,567 | I'm wondering is there a way to send some kind of generics for example `List <float> floatValues = new List<float>()` need to be sent to udp client. I don't know how to do that, any help will be appreciated! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13580567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1817808/"
] | Try installing the Soda theme. The dark theme has a nice dark side bar.
<https://github.com/buymeasoda/soda-theme> | packagecontrol.io [DefaultPlus](https://packagecontrol.io/packages/Theme%20-%20DefaultPlus) for quick and easy
packagecontrol.io [Seti\_UX](https://packagecontrol.io/packages/Seti_UX) for adapt sidebar symbols etc ideas |
13,580,567 | I'm wondering is there a way to send some kind of generics for example `List <float> floatValues = new List<float>()` need to be sent to udp client. I don't know how to do that, any help will be appreciated! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13580567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1817808/"
] | AGS is right but they recently changed the location of the default theme file.
As of now it is at **Packages/Theme - Default/Default.sublime-theme**
The "Packages/Default" folder contains other non-theme related files now. | packagecontrol.io [DefaultPlus](https://packagecontrol.io/packages/Theme%20-%20DefaultPlus) for quick and easy
packagecontrol.io [Seti\_UX](https://packagecontrol.io/packages/Seti_UX) for adapt sidebar symbols etc ideas |
13,580,567 | I'm wondering is there a way to send some kind of generics for example `List <float> floatValues = new List<float>()` need to be sent to udp client. I don't know how to do that, any help will be appreciated! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13580567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1817808/"
] | AGS is right but they recently changed the location of the default theme file.
As of now it is at **Packages/Theme - Default/Default.sublime-theme**
The "Packages/Default" folder contains other non-theme related files now. | Try installing Predawn theme maybe you like the look and feel of its theme <https://github.com/jamiewilson/predawn> |
13,580,567 | I'm wondering is there a way to send some kind of generics for example `List <float> floatValues = new List<float>()` need to be sent to udp client. I don't know how to do that, any help will be appreciated! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13580567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1817808/"
] | You want to go into your
```
~/Library/Application Support/Sublime Text 2/Packages/Default/Default.sublime-theme
```
(old version) or
```
~/Library/Application Support/Sublime Text 2/Packages/Theme-Default/Default.sublime-theme
```
(new version) and edit these things:
* `"class": "sidebar_container"`
* `"class": "sidebar_tree"`
* `"class": "sidebar_heading"`
* `"class": "sidebar_label"`
Therein you can change the RGB colors until you get what you want.
[Here is a thread that discusses this in greater detail.](http://sublimetext.userecho.com/topic/19274-theming-of-the-sidebar/)
edit: added the correct location provided by @Michael Tunnell
edit: Sample Dark SideBar Configuration.
[![Image with Dark SideBar](https://i.stack.imgur.com/9AZpm.png)](https://i.stack.imgur.com/9AZpm.png)
Click to See Larger Image for Settings
[![Click to See Larger Image for Settings](https://i.stack.imgur.com/NSzsF.png)](https://i.stack.imgur.com/NSzsF.png) | packagecontrol.io [DefaultPlus](https://packagecontrol.io/packages/Theme%20-%20DefaultPlus) for quick and easy
packagecontrol.io [Seti\_UX](https://packagecontrol.io/packages/Seti_UX) for adapt sidebar symbols etc ideas |
13,580,567 | I'm wondering is there a way to send some kind of generics for example `List <float> floatValues = new List<float>()` need to be sent to udp client. I don't know how to do that, any help will be appreciated! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13580567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1817808/"
] | AGS is right but they recently changed the location of the default theme file.
As of now it is at **Packages/Theme - Default/Default.sublime-theme**
The "Packages/Default" folder contains other non-theme related files now. | **Sublime Text 2** Package Control ~ [Theme Soda SolarizedDark](https://packagecontrol.io/packages/Theme%20-%20Soda%20SolarizedDark). This requires some editing of Preferences Settings. Looks nice with built in Solarized (Dark).tmTheme.
Sublime side bar darkens nicely now, but you may find selection of side bar items is too muted. Settings edit? For example, to make Solarized (Dark).tmTheme code pane selections more visible:
```
<dict>
<key>name</key>
<string>Solarized (dark)</string>
<key>settings</key>
<array>
<dict>
<key>settings</key>
<dict> [edit/insert the following key-string lines]
<key>selection</key>
<string>#03151C</string>
<key>selectionBorder</key>
<string>#99ccff</string>
<key>inactiveSelection</key>
<string>#0099ff30</string>
```
This code pane colors Setting slightly further mutes side bar colors on Mac. Not a PC issue, since on my PC Theme Soda SolarizedDark does not work! But the edit of selection appearance for Solarized (Dark).tmTheme makes PC sidebar slightly brighter, opposite of Mac. Buggy? |
13,580,567 | I'm wondering is there a way to send some kind of generics for example `List <float> floatValues = new List<float>()` need to be sent to udp client. I don't know how to do that, any help will be appreciated! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13580567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1817808/"
] | You want to go into your
```
~/Library/Application Support/Sublime Text 2/Packages/Default/Default.sublime-theme
```
(old version) or
```
~/Library/Application Support/Sublime Text 2/Packages/Theme-Default/Default.sublime-theme
```
(new version) and edit these things:
* `"class": "sidebar_container"`
* `"class": "sidebar_tree"`
* `"class": "sidebar_heading"`
* `"class": "sidebar_label"`
Therein you can change the RGB colors until you get what you want.
[Here is a thread that discusses this in greater detail.](http://sublimetext.userecho.com/topic/19274-theming-of-the-sidebar/)
edit: added the correct location provided by @Michael Tunnell
edit: Sample Dark SideBar Configuration.
[![Image with Dark SideBar](https://i.stack.imgur.com/9AZpm.png)](https://i.stack.imgur.com/9AZpm.png)
Click to See Larger Image for Settings
[![Click to See Larger Image for Settings](https://i.stack.imgur.com/NSzsF.png)](https://i.stack.imgur.com/NSzsF.png) | I found that going to Preferences -> Theme brought up the command pallet for themes. when change to the Adaptive.sublime-theme the side bar changes to black.
This is also accessible through the command pallet. Press ctrl+shift+p then type 'theme' select the option 'UI: Select Theme' and again you can choose the Adaptive theme. |
65,451,112 | I wrote a bot to accept follow requests immediately.
and I tried to upload it to pythonanywhere so it can work 24/7, and with the free plan you're only allowed 100s of 100% CPU usage per day, after that they put you in what they call a tarpit where you use much less cpu if any.
the issue with the bot is that it requires refreshing chrome to check for new requests, and that eats all the cpu in a matter of seconds, and hardly keeps running after that.
[![](https://i.stack.imgur.com/lDMI3.jpg)](https://i.stack.imgur.com/lDMI3.jpg)
here's the portion of the code that i mean:
```
while True:
try:
confirm_buttons = browser.find_elements_by_xpath("//button[text()='Confirm']")
for confirm_button in confirm_buttons:
confirm_button.click()
sleep(5)
print('found')
except NoSuchElementException:
print('none')
browser.refresh()
print('refreshed')
sleep(5)
finally:
browser.refresh()
print("refreshing")
sleep(5)
```
I'm using selenium with Chrome, and pyvirtualdisplay since i can't use headless browser.
**Please tell me if there's any way i can minimize the cpu usage, or if there's a better way to do it**
answer here or dm @*poortxbyy* in ig if you can help.
thanks in advance. | 2020/12/25 | [
"https://Stackoverflow.com/questions/65451112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14885462/"
] | There are multiple issues with the method you're trying to implement. Namely:
1. You're using Selenium. In other words, you've are simulating a web browser—which is an expensive process as it is—and you're expecting to host it online for free.
2. Constant monitoring. I.e. you're continously updating the Selenium browser, which means you're repeatedly overloading point number 1.
An obvious solution to this would be to reduce the number of updates per unit time. Period.
Another solution might be to scrap the infinite loop altogether and build the bot so that it knows *when* to update. I can think of multiple ways to do this, but the point is: you have to find a way for the bot to know you have a new follower without having to use Selenium, and only using Selenium to click the buttons. Perhaps by extracting the site's HTML only and interacting with a string to quickly (and cheaply) retrieve information from it.
Or even better, depending on what social media you're interacting with, using their API to retrieve information on new followers. On top of that, the API might even allow you to accept the request in and of itself. It comes down to reading the documentation and finding out what your options are. Some APIs may let you set up webhooks so that your bot may sleep until you get a new follower. A quick look into [Twitter's API](https://developer.twitter.com/en/docs/twitter-api) and [Instagram's](https://developers.facebook.com/docs/instagram-api/) Graph API seem promising.
In other words, browser automation often feels like the most obvious solution, but more often it isn't. You have to find a way to interact more directly with the data available to you.
Also, let's not forget that social media sites may detect the unusual behavour and block your account to protect it. | There are few work around for it.
1. Simply increase the time for every refresh, it will not accept follow requests immediately but you can set time to update after every 2-3 min.
2. it depends on what you are using it for, use the API to do this work or at least check for any new request before accepting it.
3. I know using --headless is not an option for you but that might be the only other option, so take a look at that. |
215,691 | I have a Dell Studio XPS 1645 laptop, it has 1 microphone and 2 headphone jacks.
Problem is, one of the headphone jacks has became faulty and Windows thinks it's constantly in use, thus I can only have sound coming from the headphones and can't force it to come from the speakers.
Is there a way to disable the faulty jack only or force audio to come from speakers in Vista ?
Driver is: `IDT High Definition CODEC`. | 2010/11/27 | [
"https://superuser.com/questions/215691",
"https://superuser.com",
"https://superuser.com/users/57076/"
] | I'd start by examining X.org log files, located at `/var/log/X.0.log`.
Try reconfiguring X server.
```
sudo dpkg-reconfigure xserver-xorg
``` | Something like this worked for me: <http://mikebeach.org/2010/06/nvidia-proprietary-drivers-and-low-resolution-plymouth-splash-screen/> it doesn't perform perfectly and without glitches on shutdown every time, but you ALWAYS get the boot graphic |
215,691 | I have a Dell Studio XPS 1645 laptop, it has 1 microphone and 2 headphone jacks.
Problem is, one of the headphone jacks has became faulty and Windows thinks it's constantly in use, thus I can only have sound coming from the headphones and can't force it to come from the speakers.
Is there a way to disable the faulty jack only or force audio to come from speakers in Vista ?
Driver is: `IDT High Definition CODEC`. | 2010/11/27 | [
"https://superuser.com/questions/215691",
"https://superuser.com",
"https://superuser.com/users/57076/"
] | You can try to reinstall xorg :
```
sudo apt-get install xorg
```
Then follow by Sathya's suggestion to reconfigure xorg:
```
sudo dpkg-reconfigure xserver-xorg
```
or
```
sudo xorgconfig
```
If that doesn't help, you might check if [Grub2](https://help.ubuntu.com/community/Grub2) was correctly installed by the 9.10 upgrade.
From [How To Check Installed GRUB Version Number](http://members.iinet.net/~herman546/p20/GRUB2%20Bash%20Commands.html#GRUB_Version_Number) :
```
grub-install -v
``` | Something like this worked for me: <http://mikebeach.org/2010/06/nvidia-proprietary-drivers-and-low-resolution-plymouth-splash-screen/> it doesn't perform perfectly and without glitches on shutdown every time, but you ALWAYS get the boot graphic |
215,691 | I have a Dell Studio XPS 1645 laptop, it has 1 microphone and 2 headphone jacks.
Problem is, one of the headphone jacks has became faulty and Windows thinks it's constantly in use, thus I can only have sound coming from the headphones and can't force it to come from the speakers.
Is there a way to disable the faulty jack only or force audio to come from speakers in Vista ?
Driver is: `IDT High Definition CODEC`. | 2010/11/27 | [
"https://superuser.com/questions/215691",
"https://superuser.com",
"https://superuser.com/users/57076/"
] | This seems like the same/very similar question resolved:
[No GUI after upgrade to Ubuntu 9.10 (boots to command line)](https://superuser.com/questions/63759/no-gui-after-upgrade-to-ubuntu-9-10-boots-to-command-line)
Good luck.
[EDIT]: If this doesn't resolve your problem, attempt to replace your xorg.conf from /etc/X11 with one of the standard configurations. Then, once you've restart the x11 server, you can attempt to re-install your graphics drivers. | Something like this worked for me: <http://mikebeach.org/2010/06/nvidia-proprietary-drivers-and-low-resolution-plymouth-splash-screen/> it doesn't perform perfectly and without glitches on shutdown every time, but you ALWAYS get the boot graphic |
29,745,722 | I am making a table to display data from a MySQL database, this table will display all the information for the current date but next day it will be blank again and contain no information so you can see the information only for the current day, the data will exist in the database forever however and all data can be displayed upon request!
Now you know my goal i will present the problem, i dont know how to display information for only the current day in the table. | 2015/04/20 | [
"https://Stackoverflow.com/questions/29745722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4715864/"
] | Use data\_date=CURDATE() in where condition of your select statement. data\_date is your date field separating data for each date...e.g
```
select * from mydata where data_date=CURDATE()
```
this will only give the current date data as required | A quick search will bring up similar questions, with answers.
However you can use PHP's date() formatter.
[Similar question](https://stackoverflow.com/questions/2215354/php-date-format-when-inserting-into-datetime-in-mysql) |
17,430,618 | I have been working on this website: <http://www.adhonis.com>
The banner image at the top is horribly scaling for iPad's, I have used screenfly to test it but it seems its not doing it through the simulator, I assume that is because all it is really simulating is the screen size. All other devices are fine though.
See a screenshot here: <http://i39.tinypic.com/vyts47.jpg>
I don't personally have access to an iPad so it is a tricky issue here.
I am using height:100%;
Would love to hear any thoughts | 2013/07/02 | [
"https://Stackoverflow.com/questions/17430618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018994/"
] | I had the same problem, but with older iPads (1st Gen with iOS 6). No problem with the most recent ones.
The problem is the 100% height. Remove it and it should work. | I had the same problem in one of my project too. Website logo looks stretched on iPad and iPhone devices.
Then i realized, i accidentally add `display: flex;` property to image. That was to problem. Maybe this information will help somebody. |
17,430,618 | I have been working on this website: <http://www.adhonis.com>
The banner image at the top is horribly scaling for iPad's, I have used screenfly to test it but it seems its not doing it through the simulator, I assume that is because all it is really simulating is the screen size. All other devices are fine though.
See a screenshot here: <http://i39.tinypic.com/vyts47.jpg>
I don't personally have access to an iPad so it is a tricky issue here.
I am using height:100%;
Would love to hear any thoughts | 2013/07/02 | [
"https://Stackoverflow.com/questions/17430618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018994/"
] | I had the same problem, but with older iPads (1st Gen with iOS 6). No problem with the most recent ones.
The problem is the 100% height. Remove it and it should work. | I was having this same problem with a bootstrap site I was working on, and here's what I did to fix it:
I moved the image outside of any divs with class of .row, .col, or .container. Then, I removed the height: 100% attribute and added:
```
img {
width: 100vw;
}
```
See if this works! |
4,160,303 | Let $u(t):=t\log t$. This function is convex on $[0,+\infty)$ and $u(0)=0$. How can I prove that$$u(t+h)-u(t)\geq u(h)\quad\forall t,h\in[0,+\infty)?$$
Since $u(0)=0$ using convexity we know that $u(st)\leq s\,u(t)$, where $s\in[0,1]$ but i get confused with the inequalities. | 2021/06/03 | [
"https://math.stackexchange.com/questions/4160303",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/621650/"
] | **Hint**: If $f(\alpha)=0$ then $f(\bar\alpha)=0$, which means that at least one root is in $\Bbb Q$. Now use the rational root test.
---
*Some details to complete the answer*:
### Complex Conjugation
Let $C(\alpha)=\bar\alpha$ denote complex conjugation, then
>
> For $\alpha,\beta\in\Bbb C$ we have
>
>
> * $C(\alpha\beta)=C(\alpha)C(\beta)$
> * $C(\alpha+\beta)=C(\alpha)+C(\beta)$
>
>
>
*Proof*: Let $\alpha=a\_1+a\_2i,\beta=b\_1+b\_2i$
* $C(\alpha+\beta)=C(a\_1+b\_1+(a\_2+b\_2)i)=a\_1+b\_1-(a\_2+b\_2)i=(a\_1-a\_2i)+(b\_1-b\_2i)=C(\alpha)+C(\beta)$
* $C(\alpha\beta)=C(a\_1b\_1-a\_2b\_2+(a\_1b\_2+a\_2b\_1)i)=a\_1b\_1-a\_2b\_2-(a\_1b\_2+a\_2b\_1)i=(a\_1-a\_2i)(b\_1-b\_2i)=C(\alpha)C(\beta)$
This means that $C(f(\alpha))=f(C(\alpha))$, in other words, $\overline{f(\alpha)}=f(\bar\alpha)$. Thus if $f(\alpha)=0$, then $$f(\alpha)=0\\\overline{f(\alpha)}=\overline{0}\\f(\bar\alpha)=0$$ so $\bar\alpha$ is a root as well.
### The Rational Root Test
Let $f(x)=a\_nx^n+\ldots+a\_1x+a\_0\in\Bbb Z[x]$, then we have
>
> Suppose $f\in\Bbb Z[x]$, and suppose there is a rational root $r=\frac{p}{q}\in\Bbb Q$ of $f$ with $\gcd(p,q)=1$. Then $p\mid a\_0$ and $q\mid a\_n$.
>
>
>
*Proof*: Assuming $r\neq 0$ we have $$f\left(\frac{p}{q}\right)=a\_n\left(\frac{p}{q}\right)^n+\ldots+a\_1\left(\frac{p}{q}\right)+a\_0=0$$
Multiplying with $q^n$ we get the equation $$a\_np^n+a\_{n-1}p^{n-1}q+\ldots+a\_1pq^{n-1}+a\_oq^n=0$$
We then observe:
* Every term is divisible by $p$, so $p\mid a\_0q^n$. As $p,q$ have no common factor we have $p\mid a\_0$
* Every term is divisible by $q$, so again $q\mid a\_np^n$. As $p,q$ have no common factor we have $q\mid a\_n$ | The following does not use the existence of complex numbers.
Let's start from the fact that given polynomial $f(x) =x^3+x-6\in\mathbb {Q} [x] $ has no rational roots. This means that the polynomial $f(x) $ is irreducible over $\mathbb{Q} [x] $.
Let $a$ be any root of $f(x) $. Then by the irreducibilty of $f(x) $ over $\mathbb {Q} [x] $ we have $[\mathbb {Q} (a) :\mathbb {Q}] =3$. Similarly if $b$ is a root of $g(x) =x^2+1$ then $[\mathbb {Q} (b) :\mathbb {Q}] =2$.
If $b\in\mathbb {Q} (a) $ then $\mathbb {Q} (b) \subseteq \mathbb{Q} (a) $ and hence $[\mathbb{Q} (b) :\mathbb {Q}] =2$ must divide $[\mathbb{Q} (a) :\mathbb {Q}] =3$ which is absurd. Thus $b\notin\mathbb {Q} (a) $. Hence $g(x) $ is irreducible over $\mathbb{Q} (a) $ and $[\mathbb {Q} (a, b) :\mathbb {Q} (a)] =2$ so that $$[\mathbb {Q} (a, b) :\mathbb {Q}] =[\mathbb {Q} (a, b) :\mathbb {Q} (a)] [\mathbb {Q} (a) :\mathbb {Q}] =2\cdot 3=6$$ Now we can observe that $$[\mathbb{Q} (a, b) :\mathbb{Q} (b)] =\frac{[\mathbb {Q} (a, b) :\mathbb {Q}] } {[\mathbb {Q} (b) :\mathbb {Q}] }=\frac{6}{2}=3$$ Let's note that $a$ is a root of $f(x) $ and if $f(x) $ were reducible over $\mathbb {Q} (b) $ then we would have $$[\mathbb {Q} (a, b) :\mathbb {Q} (b)] <\operatorname {deg} (f(x)) =3$$ and this contradiction proves that $f(x) $ is irreducible over $\mathbb{Q} (b) $. |
15,072 | I'm curious if anyone knows of a good tutorial on color correcting and/or color grading in After Effects(original effects, magic bullet looks, or any other program). Preferably, but not limited to, on YouTube due to its seemingly long process.
I just want to learn more so anything you have to add on the topic is appreciated. | 2015/03/09 | [
"https://avp.stackexchange.com/questions/15072",
"https://avp.stackexchange.com",
"https://avp.stackexchange.com/users/10410/"
] | I found the free (and paid) tutorials at [Color Grading Central](http://www.colorgradingcentral.com/) very helpful. Using a dedicated color grading application is (in my opinion) usually the way to go. The basic version of [Davinci Resolve](https://www.blackmagicdesign.com/uk/products/davinciresolve) is free, incredibly powerful, and offers a lot more control than grading in After Effects with plugins, in my experience.
For more on the theory of color grading, [the Tao of Color Grading](https://vimeo.com/13521399) is a useful video on vimeo, (although the lighting is terrible). (part two is [here](https://vimeo.com/13526945)). | Focus on getting the idea of the general workflow, not the specific tools. If you get that, you'll be able to grade using Lumetri Color, Magic Bullet's Colorista, in Davinci Resolve or whatever set of tools your software will have.
The book that gave me that understanding was "The Color Correction Handbook" by Alexis Van Hurkman. Unfortunately, most tutorials I've seen on YouTube were either made by quite amateur creators (that believe that cinematic look is just about snapping a specific LUT on your footage), or were too focused on the tools (which are good to know, yet knowing just that and without knowing the general principles of color grading makes you a monkey that just randomly pulls all the sliders it sees (that I used to be myself before the book, heh)).
That what makes Alexis's book so great: he shows you that 85% of the look is crafted with the very basic tools like Curves or Offset/Gamma/Gain controls, and what matters most is knowing the basic principles.
Here are a few free sample pages: [link](http://ptgmedia.pearsoncmg.com/images/9780321929662/samplepages/0321929667.pdf) |
27,900,302 | I'm comparing two different values each from different list using JSTL tag, but I keep getting the error. I tried to change the brackets associated with it, but none worked. I searched for comparing two list values in JSTL, but none helps me.
```
<c:forEach items="${commentsList}" var="commentsList">
<c:choose>
<c:when test="${ ${commentsList.user.id} == '${blog.user.id}' }">
<li>
<div class="timeline-panel" style="float:right">
<div class="timeline-heading" align="left">
<b>${commentsList.user.firstName} ${commentsList.user.lastName}</b>
</div><hr>
<div class="timeline-body" style="float: right;">
<p>${commentsList.comment}</p>
</div>
</div>
</li>
</c:when>
<c:otherwise>
<li class="timeline-inverted">
<div class="timeline-panel">
<b>${commentsList.user.firstName} ${commentsList.user.lastName}</b><hr>
<div class="timeline-body">
<p>${commentsList.comment}</p>
</div>
</div>
</li>
</c:otherwise>
</c:choose>
</c:forEach>
```
Error is
```
"${ ${commentsList.user.id} == '${blog.user.id}' }" contains invalid expression(s): javax.el.ELException: Error Parsing: ${ ${commentsList.user.id} == '${blog.user.id}' }
```
I've not compared two list values before, btw I can compare two list values in jstl right? | 2015/01/12 | [
"https://Stackoverflow.com/questions/27900302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4362675/"
] | there is an extra `$`.
try this:
```
<c:when test="${ commentsList.user.id eq blog.user.id}">
``` | You should change to
```
<c:when test="${commentsList.user.id eq blog.user.id}">
``` |
49,316,805 | Is there a difference between different compilers, for example if I use node-sass or gulp-sass, and I've seen a few places with Postcss-nesting, postcss-variables and so on, is this the same thing? Is there a difference between them syntax-wise? | 2018/03/16 | [
"https://Stackoverflow.com/questions/49316805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9103469/"
] | You need to pass the address of the integer you want to read in to `scanf()`.
```
scanf("%[^\n] %d", precord->name, &(precord->age));
```
This will allow the user to type in the value for `name`, hit `RETURN` and then type in the value for `age` and hit `RETURN`.
If you want the user to type in both `name` and `age` on the same line, separated by a space, and `name` is not to include any spaces, you can do
```
scanf("%[^ \n] %d", precord->name, &(precord->age));
```
to have `scanf()` stop reading characters for `name` when it hits a space. | When I built your program, I get the following warnings, which cover what was said in the comments:
```
sc.c: In function ‘main’:
sc.c:15:3: warning: implicit declaration of function ‘input’ [-Wimplicit-function-declaration]
input(&record);
^
sc.c: At top level:
sc.c:19:6: warning: conflicting types for ‘input’
void input(struct student *precord)
^
sc.c:15:3: note: previous implicit declaration of ‘input’ was here
input(&record);
^
sc.c: In function ‘input’:
sc.c:22:10: warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘int’ [-Wformat=]
scanf("%[^\n] %d",precord->name,precord->age);
^
```
There is one more problem, namely that %[^\n] eats up the whole line, so that entering for example "Mike 25" makes "Mike 25" be the name, and then it waits for the age on the next line.
I recommend against ever using 'scanf'. Read lines into a string instead, and then use 'sscanf', and always check the result so you get the number of matched values that you expect. |
49,316,805 | Is there a difference between different compilers, for example if I use node-sass or gulp-sass, and I've seen a few places with Postcss-nesting, postcss-variables and so on, is this the same thing? Is there a difference between them syntax-wise? | 2018/03/16 | [
"https://Stackoverflow.com/questions/49316805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9103469/"
] | You need to pass the address of the integer you want to read in to `scanf()`.
```
scanf("%[^\n] %d", precord->name, &(precord->age));
```
This will allow the user to type in the value for `name`, hit `RETURN` and then type in the value for `age` and hit `RETURN`.
If you want the user to type in both `name` and `age` on the same line, separated by a space, and `name` is not to include any spaces, you can do
```
scanf("%[^ \n] %d", precord->name, &(precord->age));
```
to have `scanf()` stop reading characters for `name` when it hits a space. | In `scanf` function, we have to provide the address of the `variable`. But in your case for the **first argument**, you are providing the `base address of the array but for the second argument`, you are dereferencing the structure member age through the pointer. you have to provide the address of the variable age. Update your `scanf` arguments as follows:
---
```
scanf("%[^\n] %d",precord->name,precord->age);
```
I will print the inputs. |
2,703,065 | While sitting in a determinant class, our Professor, while describing determinants, coined an observation which made me wonder. He stated that the determinant of a square matrix can be represented as a function in the following way -
>
> Let $M$ be the set of all square matrices, then a function, say X, is defined from $M \to \mathbb{R}$ which returns the determinant of any square matrix $C \in M$ i.e.
> $$ X : M \to \mathbb{R}$$ which returns $|M|$
>
>
>
As soon as he said this, I began to wonder about the injectivity, surjectivity and bijectivity of this function.
I was told that for a given $C \in M$, there exists only one unique determinant $|M| \in \mathbb{R}$. But the converse is not true according to me. This can be proved by the following argument -
Let's say that $$\begin{vmatrix}
x &5 \\
x &x\\
\end{vmatrix} = -6 $$
On solving for $x$, we obtain two values i.e $2$ and $3$, therefore the matrix is not unique for the given determinant i.e. for one image ($-6$), there exist multiple preimages. Hence, according to me, the function so defined is not injective, and consequently not bijective as well.
Now checking for surjectivity, we'll have to look for the equality of the codomain and the range of the function. In my opinion, for infinite square matrices, there will be infinite unique determinants belonging to $\mathbb{R}$. Hence the function should be surjective, but only for real entries into the matrix.
For complex entries, I don't think the function remains surjective, as the range will not coincide with the codomain (i.e. $\mathbb{R}$). However, in both cases, I feel that the function is neither injective not bijective.
I would like to know if I am right or not by knowing the views of the math-geeks sitting out there. Thanks! | 2018/03/22 | [
"https://math.stackexchange.com/questions/2703065",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/403028/"
] | These are good questions to ask of newly-encountered functions.
---
If $A$ and $B$ are $n \times n$ matrices, the following properties are valid for the determinant function:
* $\det(cA) = c^n \det(A)$
* $\det(AB) = \det(A) \det(B)$
* Swapping any two columns of $A$ changes the sign of its determinant but not the magnitude.
Using these, we can tackle both injectivity and surjectivity.
* **Surjectivity**: note that $\det(I) = 1$. Therefore, to arrive at a matrix with determinant $d$, simply multiply the identity matrix by $\sqrt[n]{d}$ and / or swap two of its columns.
* **Injectivity**: Let $B$ be any non-identity matrix of determinant $1$, such as a [rotation matrix](https://en.wikipedia.org/wiki/Rotation_matrix). Then, according to the second rule above, we'll have $\det(AB) = \det(A)\det(B) = \det(A)$.
---
You can also approach this question by considering the geometric interpretation of the determinant: it gives the (signed) volume of the $n$-dimensional [parallelepiped](https://en.wikipedia.org/wiki/Parallelepiped) spanned by the column vectors of the matrix. For instance, working in the $2 \times 2$ case, one can see that the determinant cannot be injective because applying a [shear transform](https://en.wikipedia.org/wiki/Shear_mapping) (or rotation or any other area-preserving transformation) to a parallelogram does not change its area; hence, we can get two unique parallelograms of equal area which correspond to two unique matrices of equal determinant$^\dagger$. Moreover, the determinant is surjective as we can construct parallelograms of any prescribed area (the area function varies continuously as we vary the length of a side). These ideas generalize easily to higher dimensions.
---
$^\dagger$If $A$ represents the matrix whose columns span the original parallelogram and $B$ is the matrix representation of the shear transformation, then the columns of $BA$ will span the sheared parallelogram. I.e. $\det(A) = \det(BA)$. | You are right in saying that the function is not injective. To show surjectivity, note that for any real $k$, $k^{\frac{1}{n}}I$ has determinant $k$ (Where $I$ is the $n\times n$ identity matrix) |
2,703,065 | While sitting in a determinant class, our Professor, while describing determinants, coined an observation which made me wonder. He stated that the determinant of a square matrix can be represented as a function in the following way -
>
> Let $M$ be the set of all square matrices, then a function, say X, is defined from $M \to \mathbb{R}$ which returns the determinant of any square matrix $C \in M$ i.e.
> $$ X : M \to \mathbb{R}$$ which returns $|M|$
>
>
>
As soon as he said this, I began to wonder about the injectivity, surjectivity and bijectivity of this function.
I was told that for a given $C \in M$, there exists only one unique determinant $|M| \in \mathbb{R}$. But the converse is not true according to me. This can be proved by the following argument -
Let's say that $$\begin{vmatrix}
x &5 \\
x &x\\
\end{vmatrix} = -6 $$
On solving for $x$, we obtain two values i.e $2$ and $3$, therefore the matrix is not unique for the given determinant i.e. for one image ($-6$), there exist multiple preimages. Hence, according to me, the function so defined is not injective, and consequently not bijective as well.
Now checking for surjectivity, we'll have to look for the equality of the codomain and the range of the function. In my opinion, for infinite square matrices, there will be infinite unique determinants belonging to $\mathbb{R}$. Hence the function should be surjective, but only for real entries into the matrix.
For complex entries, I don't think the function remains surjective, as the range will not coincide with the codomain (i.e. $\mathbb{R}$). However, in both cases, I feel that the function is neither injective not bijective.
I would like to know if I am right or not by knowing the views of the math-geeks sitting out there. Thanks! | 2018/03/22 | [
"https://math.stackexchange.com/questions/2703065",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/403028/"
] | These are good questions to ask of newly-encountered functions.
---
If $A$ and $B$ are $n \times n$ matrices, the following properties are valid for the determinant function:
* $\det(cA) = c^n \det(A)$
* $\det(AB) = \det(A) \det(B)$
* Swapping any two columns of $A$ changes the sign of its determinant but not the magnitude.
Using these, we can tackle both injectivity and surjectivity.
* **Surjectivity**: note that $\det(I) = 1$. Therefore, to arrive at a matrix with determinant $d$, simply multiply the identity matrix by $\sqrt[n]{d}$ and / or swap two of its columns.
* **Injectivity**: Let $B$ be any non-identity matrix of determinant $1$, such as a [rotation matrix](https://en.wikipedia.org/wiki/Rotation_matrix). Then, according to the second rule above, we'll have $\det(AB) = \det(A)\det(B) = \det(A)$.
---
You can also approach this question by considering the geometric interpretation of the determinant: it gives the (signed) volume of the $n$-dimensional [parallelepiped](https://en.wikipedia.org/wiki/Parallelepiped) spanned by the column vectors of the matrix. For instance, working in the $2 \times 2$ case, one can see that the determinant cannot be injective because applying a [shear transform](https://en.wikipedia.org/wiki/Shear_mapping) (or rotation or any other area-preserving transformation) to a parallelogram does not change its area; hence, we can get two unique parallelograms of equal area which correspond to two unique matrices of equal determinant$^\dagger$. Moreover, the determinant is surjective as we can construct parallelograms of any prescribed area (the area function varies continuously as we vary the length of a side). These ideas generalize easily to higher dimensions.
---
$^\dagger$If $A$ represents the matrix whose columns span the original parallelogram and $B$ is the matrix representation of the shear transformation, then the columns of $BA$ will span the sheared parallelogram. I.e. $\det(A) = \det(BA)$. | Clearly there are infite matrices with $\det(A)=0$. (Just scale any singular matrix to get an infinite number).
Therefore you are right about injectivity and bijectivity.
About surjectivity, you must have a matrix $A$ for every $t\in \mathbb{R}$, that has exactly that value das determinant.
You can just use a $1\times 1$ matrix, to set that determinant.
This holds also true for any complex values |
2,703,065 | While sitting in a determinant class, our Professor, while describing determinants, coined an observation which made me wonder. He stated that the determinant of a square matrix can be represented as a function in the following way -
>
> Let $M$ be the set of all square matrices, then a function, say X, is defined from $M \to \mathbb{R}$ which returns the determinant of any square matrix $C \in M$ i.e.
> $$ X : M \to \mathbb{R}$$ which returns $|M|$
>
>
>
As soon as he said this, I began to wonder about the injectivity, surjectivity and bijectivity of this function.
I was told that for a given $C \in M$, there exists only one unique determinant $|M| \in \mathbb{R}$. But the converse is not true according to me. This can be proved by the following argument -
Let's say that $$\begin{vmatrix}
x &5 \\
x &x\\
\end{vmatrix} = -6 $$
On solving for $x$, we obtain two values i.e $2$ and $3$, therefore the matrix is not unique for the given determinant i.e. for one image ($-6$), there exist multiple preimages. Hence, according to me, the function so defined is not injective, and consequently not bijective as well.
Now checking for surjectivity, we'll have to look for the equality of the codomain and the range of the function. In my opinion, for infinite square matrices, there will be infinite unique determinants belonging to $\mathbb{R}$. Hence the function should be surjective, but only for real entries into the matrix.
For complex entries, I don't think the function remains surjective, as the range will not coincide with the codomain (i.e. $\mathbb{R}$). However, in both cases, I feel that the function is neither injective not bijective.
I would like to know if I am right or not by knowing the views of the math-geeks sitting out there. Thanks! | 2018/03/22 | [
"https://math.stackexchange.com/questions/2703065",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/403028/"
] | These are good questions to ask of newly-encountered functions.
---
If $A$ and $B$ are $n \times n$ matrices, the following properties are valid for the determinant function:
* $\det(cA) = c^n \det(A)$
* $\det(AB) = \det(A) \det(B)$
* Swapping any two columns of $A$ changes the sign of its determinant but not the magnitude.
Using these, we can tackle both injectivity and surjectivity.
* **Surjectivity**: note that $\det(I) = 1$. Therefore, to arrive at a matrix with determinant $d$, simply multiply the identity matrix by $\sqrt[n]{d}$ and / or swap two of its columns.
* **Injectivity**: Let $B$ be any non-identity matrix of determinant $1$, such as a [rotation matrix](https://en.wikipedia.org/wiki/Rotation_matrix). Then, according to the second rule above, we'll have $\det(AB) = \det(A)\det(B) = \det(A)$.
---
You can also approach this question by considering the geometric interpretation of the determinant: it gives the (signed) volume of the $n$-dimensional [parallelepiped](https://en.wikipedia.org/wiki/Parallelepiped) spanned by the column vectors of the matrix. For instance, working in the $2 \times 2$ case, one can see that the determinant cannot be injective because applying a [shear transform](https://en.wikipedia.org/wiki/Shear_mapping) (or rotation or any other area-preserving transformation) to a parallelogram does not change its area; hence, we can get two unique parallelograms of equal area which correspond to two unique matrices of equal determinant$^\dagger$. Moreover, the determinant is surjective as we can construct parallelograms of any prescribed area (the area function varies continuously as we vary the length of a side). These ideas generalize easily to higher dimensions.
---
$^\dagger$If $A$ represents the matrix whose columns span the original parallelogram and $B$ is the matrix representation of the shear transformation, then the columns of $BA$ will span the sheared parallelogram. I.e. $\det(A) = \det(BA)$. | Surjectivity follows from considering the matrix
$$
\begin{bmatrix}
a & 0 & 0 & \dots & 0 & 0 \\
0 & 1 & 0 & \dots & 0 & 0 \\
0 & 0 & 1 & \dots & 0 & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\
0 & 0 & 0 & \dots & 1 & 0 \\
0 & 0 & 0 & \dots & 0 & 1
\end{bmatrix}
$$
that is, the identity with just the top left entry changed to $a$ instead of $1$. This has determinant $a$ by multilinearity.
Injectivity can be shown false by considering the identity with the bottom right entry changed into $a$, which has determinant $a$ as well. If your matrices are not $1\times 1$, this falsifies injectivity.
However, the determinant is indeed injective on $1\times1$ matrices, because it's essentially the identity map. |
626,330 | I have an [eMachines T5246](http://www.cnet.com/products/emachines-t5246/specs/) running Ubuntu 14.04 LTS set up as a home media server with Plex.
Everything has been running well (if slowly) up until today when I installed the updates that showed up in the auto-update and restarted.
When I next booted it up, the screen was completely blank until I moved the mouse, at which point the pointer appeared. I have rebooted several times, and a few times the login screen and wallpaper has appeared, and after logging in, the wallpaper disappeared when I clicked onscreen.
I can boot to other devices. I booted to tails on a usb to see if I could access the files, but I don't remember the Admin password, so I couldn't access the files.
I think that when I first installed ubuntu, the computer had some graphics driver issues, but I believe that was from ubuntu automatically using 3rd party drivers.
What can I do?
UPDATE 1: I have not been able to fix the problem, but I can access the terminal from the login screen using CTRL+ALT+F1
UPDATE 2: I have tried booting using nomodeset, but I got the same screen and reaction when I booted up. | 2015/05/21 | [
"https://askubuntu.com/questions/626330",
"https://askubuntu.com",
"https://askubuntu.com/users/412200/"
] | Pretty simple issue -
`libfontconfig1-dev : Depends: libfontconfig1 (= 2.8.0-3ubuntu9.1) but 2.10.1-0ubuntu3 is to be installed`
You have libfontconfig1 2.10.1-0ubuntu3 from 12.10 installed but are on 12.04. So you'd need to replace that package with the 12.04 version & any other 12.10 package(s) you have installed that could cause conflicts. So good luck there...
`apt-cache policy libfontconfig1` & or `apt-cache madison libfontconfig1` should show this clearly | I had the same issue trying to install Wireshark 1.7.0 on my Ubuntu 12.04 - wireshark requires `libgtk2.0-dev`.
Everything is stuck because of the package `libfontconfig1-dev`:
1. Add the precise-updates deb server in your `/etc/apt/sources.list` . For France:
```none
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted
```
2. Refresh `aptitude`:
```none
apt-get update
```
4. Now you can install the broken package
```none
apt-get install libfontconfig1-dev
```
5. Put all problematic packages on the same command line. Here:
```none
apt-get install libgtk2.0-dev libpango1.0-dev libcairo2-dev
``` |
626,330 | I have an [eMachines T5246](http://www.cnet.com/products/emachines-t5246/specs/) running Ubuntu 14.04 LTS set up as a home media server with Plex.
Everything has been running well (if slowly) up until today when I installed the updates that showed up in the auto-update and restarted.
When I next booted it up, the screen was completely blank until I moved the mouse, at which point the pointer appeared. I have rebooted several times, and a few times the login screen and wallpaper has appeared, and after logging in, the wallpaper disappeared when I clicked onscreen.
I can boot to other devices. I booted to tails on a usb to see if I could access the files, but I don't remember the Admin password, so I couldn't access the files.
I think that when I first installed ubuntu, the computer had some graphics driver issues, but I believe that was from ubuntu automatically using 3rd party drivers.
What can I do?
UPDATE 1: I have not been able to fix the problem, but I can access the terminal from the login screen using CTRL+ALT+F1
UPDATE 2: I have tried booting using nomodeset, but I got the same screen and reaction when I booted up. | 2015/05/21 | [
"https://askubuntu.com/questions/626330",
"https://askubuntu.com",
"https://askubuntu.com/users/412200/"
] | Pretty simple issue -
`libfontconfig1-dev : Depends: libfontconfig1 (= 2.8.0-3ubuntu9.1) but 2.10.1-0ubuntu3 is to be installed`
You have libfontconfig1 2.10.1-0ubuntu3 from 12.10 installed but are on 12.04. So you'd need to replace that package with the 12.04 version & any other 12.10 package(s) you have installed that could cause conflicts. So good luck there...
`apt-cache policy libfontconfig1` & or `apt-cache madison libfontconfig1` should show this clearly | I ran into this issue on 16.04 and the reason (for me at least) was that libcairo2-dev required on a specific version of libcairo-gobject2 and I had a newer one:
```
The following packages have unmet dependencies:
libgtk2.0-dev : Depends: libpango1.0-dev (>= 1.20) but it is not going to be installed
Depends: libcairo2-dev (>= 1.6.4-6.1) but it is not going to be installed
```
.
```
The following packages have unmet dependencies:
libcairo2-dev : Depends: libcairo-gobject2 (= 1.14.6-1) but 1.15.2-0intel1 is to be installed
E: Unable to correct problems, you have held broken packages.
```
So the fix was:
```
sudo apt-get install libcairo-gobject2=1.14.6-1
```
Which then allowed me to install libgtk2.0-dev
The real proper fix is for the maintainers of libcairo2-dev/libcairo-gobject2 to properly fix their dependency is that one can use later version of libcairo2-gobject2. |
626,330 | I have an [eMachines T5246](http://www.cnet.com/products/emachines-t5246/specs/) running Ubuntu 14.04 LTS set up as a home media server with Plex.
Everything has been running well (if slowly) up until today when I installed the updates that showed up in the auto-update and restarted.
When I next booted it up, the screen was completely blank until I moved the mouse, at which point the pointer appeared. I have rebooted several times, and a few times the login screen and wallpaper has appeared, and after logging in, the wallpaper disappeared when I clicked onscreen.
I can boot to other devices. I booted to tails on a usb to see if I could access the files, but I don't remember the Admin password, so I couldn't access the files.
I think that when I first installed ubuntu, the computer had some graphics driver issues, but I believe that was from ubuntu automatically using 3rd party drivers.
What can I do?
UPDATE 1: I have not been able to fix the problem, but I can access the terminal from the login screen using CTRL+ALT+F1
UPDATE 2: I have tried booting using nomodeset, but I got the same screen and reaction when I booted up. | 2015/05/21 | [
"https://askubuntu.com/questions/626330",
"https://askubuntu.com",
"https://askubuntu.com/users/412200/"
] | `Unable to correct problems, you have held broken packages.`
That line from the output you received (when trying to install libgtk2.0-dev) seems to indicate you need to fix broken and missing packages.
Try this:
```
sudo apt-get update && sudo apt-get upgrade --fix-missing --fix-broken
```
Then, assuming that was successful, you should be able to run the install command for libgtk2.0-dev without any problems
```
sudo apt-get install libgtk2.0-dev
```
If it still doesn't work, try looking for what packages are being held back:
```
dpkg --get-selections | grep hold
```
If that command gives you any output (should be package names of whatever packages are being held) try this:
```
sudo apt-get install <packagename>
```
Then try to install libgtk2.0-dev again.
If it still fails, perhaps consider doing a dist-upgrade
```
sudo apt-get dist-upgrade
```
I hope this helps! | Test this:
Download this files to 32 bits:
===============================
```
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-dev_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/gir1.2-gtk-2.0_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/a/atk1.0/libatk1.0-dev_2.4.0-0ubuntu1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/c/cairo/libcairo2-dev_1.10.2-6.1ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gdk-pixbuf/libgdk-pixbuf2.0-dev_2.26.1-1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/glib2.0/libglib2.0-dev_2.32.1-0ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-0_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-common_2.24.10-0ubuntu6_all.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pango1.0/libpango1.0-dev_1.30.0-0ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxcomposite/libxcomposite-dev_0.4.3-2build1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxdamage/libxdamage-dev_1.1.3-2build1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pkg-config/pkg-config_0.26-1ubuntu1_i386.deb
```
Or download this files to 64 bit:
=================================
```
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-dev_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/gir1.2-gtk-2.0_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/a/atk1.0/libatk1.0-dev_2.4.0-0ubuntu1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/c/cairo/libcairo2-dev_1.10.2-6.1ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gdk-pixbuf/libgdk-pixbuf2.0-dev_2.26.1-1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/glib2.0/libglib2.0-dev_2.32.1-0ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-0_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-common_2.24.10-0ubuntu6_all.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pango1.0/libpango1.0-dev_1.30.0-0ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxcomposite/libxcomposite-dev_0.4.3-2build1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxdamage/libxdamage-dev_1.1.3-2build1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pkg-config/pkg-config_0.26-1ubuntu1_amd64.deb
```
Install them with the command:
==============================
```
sudo dpkg --force-all -i *.deb
```
Executed in the download directory |
626,330 | I have an [eMachines T5246](http://www.cnet.com/products/emachines-t5246/specs/) running Ubuntu 14.04 LTS set up as a home media server with Plex.
Everything has been running well (if slowly) up until today when I installed the updates that showed up in the auto-update and restarted.
When I next booted it up, the screen was completely blank until I moved the mouse, at which point the pointer appeared. I have rebooted several times, and a few times the login screen and wallpaper has appeared, and after logging in, the wallpaper disappeared when I clicked onscreen.
I can boot to other devices. I booted to tails on a usb to see if I could access the files, but I don't remember the Admin password, so I couldn't access the files.
I think that when I first installed ubuntu, the computer had some graphics driver issues, but I believe that was from ubuntu automatically using 3rd party drivers.
What can I do?
UPDATE 1: I have not been able to fix the problem, but I can access the terminal from the login screen using CTRL+ALT+F1
UPDATE 2: I have tried booting using nomodeset, but I got the same screen and reaction when I booted up. | 2015/05/21 | [
"https://askubuntu.com/questions/626330",
"https://askubuntu.com",
"https://askubuntu.com/users/412200/"
] | Pretty simple issue -
`libfontconfig1-dev : Depends: libfontconfig1 (= 2.8.0-3ubuntu9.1) but 2.10.1-0ubuntu3 is to be installed`
You have libfontconfig1 2.10.1-0ubuntu3 from 12.10 installed but are on 12.04. So you'd need to replace that package with the 12.04 version & any other 12.10 package(s) you have installed that could cause conflicts. So good luck there...
`apt-cache policy libfontconfig1` & or `apt-cache madison libfontconfig1` should show this clearly | Test this:
Download this files to 32 bits:
===============================
```
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-dev_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/gir1.2-gtk-2.0_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/a/atk1.0/libatk1.0-dev_2.4.0-0ubuntu1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/c/cairo/libcairo2-dev_1.10.2-6.1ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gdk-pixbuf/libgdk-pixbuf2.0-dev_2.26.1-1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/glib2.0/libglib2.0-dev_2.32.1-0ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-0_2.24.10-0ubuntu6_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-common_2.24.10-0ubuntu6_all.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pango1.0/libpango1.0-dev_1.30.0-0ubuntu2_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxcomposite/libxcomposite-dev_0.4.3-2build1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxdamage/libxdamage-dev_1.1.3-2build1_i386.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pkg-config/pkg-config_0.26-1ubuntu1_i386.deb
```
Or download this files to 64 bit:
=================================
```
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-dev_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/gir1.2-gtk-2.0_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/a/atk1.0/libatk1.0-dev_2.4.0-0ubuntu1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/c/cairo/libcairo2-dev_1.10.2-6.1ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gdk-pixbuf/libgdk-pixbuf2.0-dev_2.26.1-1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/glib2.0/libglib2.0-dev_2.32.1-0ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-0_2.24.10-0ubuntu6_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/g/gtk+2.0/libgtk2.0-common_2.24.10-0ubuntu6_all.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pango1.0/libpango1.0-dev_1.30.0-0ubuntu2_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxcomposite/libxcomposite-dev_0.4.3-2build1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/libx/libxdamage/libxdamage-dev_1.1.3-2build1_amd64.deb
http://mirrors.kernel.org/ubuntu/pool/main/p/pkg-config/pkg-config_0.26-1ubuntu1_amd64.deb
```
Install them with the command:
==============================
```
sudo dpkg --force-all -i *.deb
```
Executed in the download directory |
626,330 | I have an [eMachines T5246](http://www.cnet.com/products/emachines-t5246/specs/) running Ubuntu 14.04 LTS set up as a home media server with Plex.
Everything has been running well (if slowly) up until today when I installed the updates that showed up in the auto-update and restarted.
When I next booted it up, the screen was completely blank until I moved the mouse, at which point the pointer appeared. I have rebooted several times, and a few times the login screen and wallpaper has appeared, and after logging in, the wallpaper disappeared when I clicked onscreen.
I can boot to other devices. I booted to tails on a usb to see if I could access the files, but I don't remember the Admin password, so I couldn't access the files.
I think that when I first installed ubuntu, the computer had some graphics driver issues, but I believe that was from ubuntu automatically using 3rd party drivers.
What can I do?
UPDATE 1: I have not been able to fix the problem, but I can access the terminal from the login screen using CTRL+ALT+F1
UPDATE 2: I have tried booting using nomodeset, but I got the same screen and reaction when I booted up. | 2015/05/21 | [
"https://askubuntu.com/questions/626330",
"https://askubuntu.com",
"https://askubuntu.com/users/412200/"
] | `Unable to correct problems, you have held broken packages.`
That line from the output you received (when trying to install libgtk2.0-dev) seems to indicate you need to fix broken and missing packages.
Try this:
```
sudo apt-get update && sudo apt-get upgrade --fix-missing --fix-broken
```
Then, assuming that was successful, you should be able to run the install command for libgtk2.0-dev without any problems
```
sudo apt-get install libgtk2.0-dev
```
If it still doesn't work, try looking for what packages are being held back:
```
dpkg --get-selections | grep hold
```
If that command gives you any output (should be package names of whatever packages are being held) try this:
```
sudo apt-get install <packagename>
```
Then try to install libgtk2.0-dev again.
If it still fails, perhaps consider doing a dist-upgrade
```
sudo apt-get dist-upgrade
```
I hope this helps! | I had the same issue trying to install Wireshark 1.7.0 on my Ubuntu 12.04 - wireshark requires `libgtk2.0-dev`.
Everything is stuck because of the package `libfontconfig1-dev`:
1. Add the precise-updates deb server in your `/etc/apt/sources.list` . For France:
```none
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted
```
2. Refresh `aptitude`:
```none
apt-get update
```
4. Now you can install the broken package
```none
apt-get install libfontconfig1-dev
```
5. Put all problematic packages on the same command line. Here:
```none
apt-get install libgtk2.0-dev libpango1.0-dev libcairo2-dev
``` |
626,330 | I have an [eMachines T5246](http://www.cnet.com/products/emachines-t5246/specs/) running Ubuntu 14.04 LTS set up as a home media server with Plex.
Everything has been running well (if slowly) up until today when I installed the updates that showed up in the auto-update and restarted.
When I next booted it up, the screen was completely blank until I moved the mouse, at which point the pointer appeared. I have rebooted several times, and a few times the login screen and wallpaper has appeared, and after logging in, the wallpaper disappeared when I clicked onscreen.
I can boot to other devices. I booted to tails on a usb to see if I could access the files, but I don't remember the Admin password, so I couldn't access the files.
I think that when I first installed ubuntu, the computer had some graphics driver issues, but I believe that was from ubuntu automatically using 3rd party drivers.
What can I do?
UPDATE 1: I have not been able to fix the problem, but I can access the terminal from the login screen using CTRL+ALT+F1
UPDATE 2: I have tried booting using nomodeset, but I got the same screen and reaction when I booted up. | 2015/05/21 | [
"https://askubuntu.com/questions/626330",
"https://askubuntu.com",
"https://askubuntu.com/users/412200/"
] | Sometimes the package dependencies are related to packages out of x86\_64 architecture. Try these following steps:
1. `sudo dpkg --add-architecture i386`
2. `sudo apt-get update`
3. `sudo apt-get install libgtk2.0-dev`
I hope to help you. | I ran into this issue on 16.04 and the reason (for me at least) was that libcairo2-dev required on a specific version of libcairo-gobject2 and I had a newer one:
```
The following packages have unmet dependencies:
libgtk2.0-dev : Depends: libpango1.0-dev (>= 1.20) but it is not going to be installed
Depends: libcairo2-dev (>= 1.6.4-6.1) but it is not going to be installed
```
.
```
The following packages have unmet dependencies:
libcairo2-dev : Depends: libcairo-gobject2 (= 1.14.6-1) but 1.15.2-0intel1 is to be installed
E: Unable to correct problems, you have held broken packages.
```
So the fix was:
```
sudo apt-get install libcairo-gobject2=1.14.6-1
```
Which then allowed me to install libgtk2.0-dev
The real proper fix is for the maintainers of libcairo2-dev/libcairo-gobject2 to properly fix their dependency is that one can use later version of libcairo2-gobject2. |