qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
39,490 | I have a PC where the desktop background options are disabled. I have tried resetting the ActiveDesktop - AllowChangingWallpaper (something like that) to no avail. There is no security enabled on the machine, it is running BitDefender after a recent trojan attack. That is all I know at the moment, but nowhere can I find any way to enable the background options.
Machine is running XP Home. | 2009/09/11 | [
"https://superuser.com/questions/39490",
"https://superuser.com",
"https://superuser.com/users/10670/"
] | Although the recommended method is to install XP and then Windows 7, there is no need to reinstall in your case.
Follow this [guide](http://www.ehow.com/how_4900122_use-easybcd-windows-xp.html) (edited below) using a free tool called [EasyBCD](http://neosmart.net/dl.php?id=1).
>
> 1. Download and install [**EasyBCD**](http://neosmart.net/dl.php?id=1). Click **I Agree** to the license agreement,
> click **Next** to install in the default
> location, and the installation wizard
> will do the rest.
> 2. Click **View Settings**.
> 3. Change the **Default OS** to **Windows 7**. The operating system to
> associate the settings with should be
> Windows 7 too. Select the drive on
> which Windows 7 is installed under
> **Drive**. Type **Windows 7** in the
> Name box and press **Save Settings**.
> 4. Click **Add/Remove Entries**.
> 5. Under **Add an Entry**, choose the **Windows** tab. Select the drive on
> which Windows 7 is installed. Type
> **Windows 7** in the **Name** box and
> press **Add Entry**.
> 6. Under **Add an Entry**, choose the **Windows** tab. Select the drive on
> which Windows XP is installed. Type
> **Windows XP** in the Name box and press
> **Add Entry**.
> 7. Exit EasyBCD and restart your computer to be presented with a
> multi-boot option screen for Windows
> XP and Windows 7.
>
>
> | Also is installing xp completely needed why do you need xp for?
First check if all of the programs if you could use all of those in either vista or win7.
(for me I use a website called FileHippo is has an update checker to check all of you're programs for an update)
Than if there is a reason you have to use win7 than consider virtualization.
For me using [virtualbox](http://www.virtualbox.org/wiki/Downloads) is easy and simple.
For instructions view the [pdf][4]. |
39,490 | I have a PC where the desktop background options are disabled. I have tried resetting the ActiveDesktop - AllowChangingWallpaper (something like that) to no avail. There is no security enabled on the machine, it is running BitDefender after a recent trojan attack. That is all I know at the moment, but nowhere can I find any way to enable the background options.
Machine is running XP Home. | 2009/09/11 | [
"https://superuser.com/questions/39490",
"https://superuser.com",
"https://superuser.com/users/10670/"
] | Why don't you install and run XP from a VHD file?
[Windows 7 is able to natively boot VHD files](http://edge.technet.com/Media/Windows-7-Boot-from-VHD/), so this might be the easiest way to get XP installed.
If you still want to install XP and Win7 side by side, I'd install XP first, then Windows 7. Why? Because XPs installation does not know or recognize the Windows 7 bootloader, while the Windows 7 bootloader will know the XP bootloader. | Also is installing xp completely needed why do you need xp for?
First check if all of the programs if you could use all of those in either vista or win7.
(for me I use a website called FileHippo is has an update checker to check all of you're programs for an update)
Than if there is a reason you have to use win7 than consider virtualization.
For me using [virtualbox](http://www.virtualbox.org/wiki/Downloads) is easy and simple.
For instructions view the [pdf][4]. |
326,595 | I have a university email account which provides access only via IMAP and webmail, and which does not provide a usable email forwarding service. Is there any way of getting emails from this account automatically downloaded to my gmail? The only thing I could think of would be to set up my own POP server to shadow the IMAP server, and then use gmail's POP downloader. This seems a bit baroque, and I was wondering if anyone knows of a more straightforward alternative. | 2011/08/22 | [
"https://superuser.com/questions/326595",
"https://superuser.com",
"https://superuser.com/users/95192/"
] | It will take awhile depending on how many messages you have and how big, but you can set your gmail account to allow an imap connection and connect to both with an application like Thunderbird and simply drag your mail from one to the other. Once you have the two set up, you can setup a filter rule that will move new mail each time you connect.
[Enabling IMAP in Gmail](http://mail.google.com/support/bin/answer.py?answer=77695) | imapsync worked fine for me ...
```
imapsync \
--host1 "${from_host}" --user1 "${from_login}" --password1 "${from_passwd}" \
--ssl1 \
--host2 "${to_host}" --user2 "${to_login}" --password2 "${to_passwd}" \
--ssl2 \
--authuser1 "${from_login}" --authmech1 LOGIN \
--authmech2 LOGIN \
--syncinternaldates --useheader 'Message-Id' --skipsize --allowsizemismatch
```
<http://imapsync.lamiral.info>
imapsync is still floss, available at <https://github.com/imapsync> |
59,004,671 | I am using Visual Studio Code as my IDE and I am a bit of a beginner with Python so I decided to try out the turtle library built into Python to learn some of the syntax. However, when I tried running just a simple script to see if it would work, the window flashed open for less than a second then closed. I have tried using different extensions and re-downloading the python extension for VS Code. This is my code I'm trying to run:
```
import turtle
geoff = turtle.Turtle()
geoff.forward(100)
```
Please help as I really can't figure out why the window won't stay open. Thanks! | 2019/11/23 | [
"https://Stackoverflow.com/questions/59004671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12055356/"
] | The screen flashed on and then closed because when the application is done, Python exits and thus so does the screen. This has nothing to do with VS Code or the Python extension and simply how applications work.
Probably the easiest way to keep the window open is add the following line at the very end:
```py
input("Press any key to exit ...")
```
That way Python won't exit until you press a key in the terminal. | You can create a canvas into **turtle** like a blank space to draw on. Use this code just to import the module an hold on the graphic window open -Pen It will work with Visual Studio Code, Spyder or Python IDLE
```
import turtle
window = turtle.Screen()
geoff = turtle.Turtle()
t = turtle.Pen()
window.exitonclick()
``` |
59,004,671 | I am using Visual Studio Code as my IDE and I am a bit of a beginner with Python so I decided to try out the turtle library built into Python to learn some of the syntax. However, when I tried running just a simple script to see if it would work, the window flashed open for less than a second then closed. I have tried using different extensions and re-downloading the python extension for VS Code. This is my code I'm trying to run:
```
import turtle
geoff = turtle.Turtle()
geoff.forward(100)
```
Please help as I really can't figure out why the window won't stay open. Thanks! | 2019/11/23 | [
"https://Stackoverflow.com/questions/59004671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12055356/"
] | The screen flashed on and then closed because when the application is done, Python exits and thus so does the screen. This has nothing to do with VS Code or the Python extension and simply how applications work.
Probably the easiest way to keep the window open is add the following line at the very end:
```py
input("Press any key to exit ...")
```
That way Python won't exit until you press a key in the terminal. | **The easiest solution is to add the following line in your V.S. Code:-**
```
turtle.done()
```
**This would prevent the window (Python Turtle Graphics) from closing after running the code:)** |
59,004,671 | I am using Visual Studio Code as my IDE and I am a bit of a beginner with Python so I decided to try out the turtle library built into Python to learn some of the syntax. However, when I tried running just a simple script to see if it would work, the window flashed open for less than a second then closed. I have tried using different extensions and re-downloading the python extension for VS Code. This is my code I'm trying to run:
```
import turtle
geoff = turtle.Turtle()
geoff.forward(100)
```
Please help as I really can't figure out why the window won't stay open. Thanks! | 2019/11/23 | [
"https://Stackoverflow.com/questions/59004671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12055356/"
] | You can use exitonclick() to avoid the window from shutting down.
```
import turtle
window = turtle.Screen()
geoff = turtle.Turtle()
geoff.forward(100)
window.exitonclick()
```
This way, the graphics window will shut only after you click. | You can create a canvas into **turtle** like a blank space to draw on. Use this code just to import the module an hold on the graphic window open -Pen It will work with Visual Studio Code, Spyder or Python IDLE
```
import turtle
window = turtle.Screen()
geoff = turtle.Turtle()
t = turtle.Pen()
window.exitonclick()
``` |
59,004,671 | I am using Visual Studio Code as my IDE and I am a bit of a beginner with Python so I decided to try out the turtle library built into Python to learn some of the syntax. However, when I tried running just a simple script to see if it would work, the window flashed open for less than a second then closed. I have tried using different extensions and re-downloading the python extension for VS Code. This is my code I'm trying to run:
```
import turtle
geoff = turtle.Turtle()
geoff.forward(100)
```
Please help as I really can't figure out why the window won't stay open. Thanks! | 2019/11/23 | [
"https://Stackoverflow.com/questions/59004671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12055356/"
] | You can use exitonclick() to avoid the window from shutting down.
```
import turtle
window = turtle.Screen()
geoff = turtle.Turtle()
geoff.forward(100)
window.exitonclick()
```
This way, the graphics window will shut only after you click. | **The easiest solution is to add the following line in your V.S. Code:-**
```
turtle.done()
```
**This would prevent the window (Python Turtle Graphics) from closing after running the code:)** |
59,004,671 | I am using Visual Studio Code as my IDE and I am a bit of a beginner with Python so I decided to try out the turtle library built into Python to learn some of the syntax. However, when I tried running just a simple script to see if it would work, the window flashed open for less than a second then closed. I have tried using different extensions and re-downloading the python extension for VS Code. This is my code I'm trying to run:
```
import turtle
geoff = turtle.Turtle()
geoff.forward(100)
```
Please help as I really can't figure out why the window won't stay open. Thanks! | 2019/11/23 | [
"https://Stackoverflow.com/questions/59004671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12055356/"
] | **The easiest solution is to add the following line in your V.S. Code:-**
```
turtle.done()
```
**This would prevent the window (Python Turtle Graphics) from closing after running the code:)** | You can create a canvas into **turtle** like a blank space to draw on. Use this code just to import the module an hold on the graphic window open -Pen It will work with Visual Studio Code, Spyder or Python IDLE
```
import turtle
window = turtle.Screen()
geoff = turtle.Turtle()
t = turtle.Pen()
window.exitonclick()
``` |
38,766 | I noticed that《汉语大词典》opts for 風景綫 over what most other reference works write as 風景線.
**KEY** does mention that 綫 is a:
>
> 1 (variant of the more commonly used xìan 線) line, thread, wire, string
>
>
>
[zisea](http://zisea.com/zscontent.asp?uni=7EBF) also seems so say that 线 is:
>
> 【綫】的简体字。拼音xian4
>
>
>
[zisea](http://zisea.com/zscontent.asp?uni=7DDA) on the other hand only says that 線:
>
> ①同【线】。
>
>
>
線 is treated more like a variant than the actual traditional character for 线. But this all seems quite contrary to my understanding for this character.
Is there a viable reason why 綫 would be picked over 線? | 2020/04/19 | [
"https://chinese.stackexchange.com/questions/38766",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/4136/"
] | My understanding is that when characters were being simplified in Mainland China, they first had to standardize traditional characters (i.e. What should these new characters be simplified from?). 「綫」 was chosen as the traditional standard, thus in the PRC's [Table of General Standard Chinese Characters (通用規範漢字表)](https://en.wikipedia.org/wiki/Table_of_General_Standard_Chinese_Characters), you can see that 「线」 is considered to be simplified from 「綫」, while 「線」 is listed as a variant of 「綫」 ([「缐」 also exists, but is only used as a surname](https://en.wiktionary.org/wiki/%E7%BC%90)).
[](https://i.stack.imgur.com/BeIRH.png)
Understandably, if the dictionaries you are using are Mainland Chinese, 「綫」 will be treated as the standard character rather than 「線」.
---
In contrast, every other region in the [Sinosphere](https://en.wikipedia.org/wiki/East_Asian_cultural_sphere) that has some standard for Chinese characters (i.e. Hong Kong, Taiwan, Japan, South Korea) list 「線」 as the standard form, which might explain why 「線」 is much more prominent outside of simplified Chinese.
However, as mentioned in the other answer, 「綫」 is quite common in Hong Kong, despite 「線」 being the standard character in Hong Kong's [List of Graphemes of Commonly-Used Chinese Characters (常用字字形表)](https://en.wikipedia.org/wiki/List_of_Graphemes_of_Commonly-Used_Chinese_Characters). This is likely because the standardized character shapes are used as general guidelines for education, rather than used as a strict set of rules to follow.
[](https://i.stack.imgur.com/Q0eEd.png)
*The smaller character here indicates a variant form.*
---
Both these forms have existed as variants of each other for quite some time before the modern era, so aside from regional standards and popularity, one isn't necessarily more correct than the other. I'm not sure about Japan and Korea, but in Chinese-speaking regions, both forms should be equally well-understood. In the end, it boils down to personal preference. | There probably isn’t a preferred choice between 線 and 綫.
In Hong Kong, traditional characters are used. The MTR Corporation officially refers to their MTR lines as XX綫. However, if you take some feeder minibuses, they will often refer to those lines as XX線. This means both characters can be accepted as “official”, since they concurrently appear on various public transport signs. |
38,766 | I noticed that《汉语大词典》opts for 風景綫 over what most other reference works write as 風景線.
**KEY** does mention that 綫 is a:
>
> 1 (variant of the more commonly used xìan 線) line, thread, wire, string
>
>
>
[zisea](http://zisea.com/zscontent.asp?uni=7EBF) also seems so say that 线 is:
>
> 【綫】的简体字。拼音xian4
>
>
>
[zisea](http://zisea.com/zscontent.asp?uni=7DDA) on the other hand only says that 線:
>
> ①同【线】。
>
>
>
線 is treated more like a variant than the actual traditional character for 线. But this all seems quite contrary to my understanding for this character.
Is there a viable reason why 綫 would be picked over 線? | 2020/04/19 | [
"https://chinese.stackexchange.com/questions/38766",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/4136/"
] | There probably isn’t a preferred choice between 線 and 綫.
In Hong Kong, traditional characters are used. The MTR Corporation officially refers to their MTR lines as XX綫. However, if you take some feeder minibuses, they will often refer to those lines as XX線. This means both characters can be accepted as “official”, since they concurrently appear on various public transport signs. | (Not enough reputation to comment, so I am posting this as an answer instead)
In addition to MTR's example,
TVB uses "綫": `無綫電視`/`無綫新聞台`
But another company, i-CABLE TV, uses "線": `有線新聞`.
And "wireless" in "wireless network" is usually written as "無線".
From my observation, nowadays people usually write "線", and "綫" is only used in very few cases. |
38,766 | I noticed that《汉语大词典》opts for 風景綫 over what most other reference works write as 風景線.
**KEY** does mention that 綫 is a:
>
> 1 (variant of the more commonly used xìan 線) line, thread, wire, string
>
>
>
[zisea](http://zisea.com/zscontent.asp?uni=7EBF) also seems so say that 线 is:
>
> 【綫】的简体字。拼音xian4
>
>
>
[zisea](http://zisea.com/zscontent.asp?uni=7DDA) on the other hand only says that 線:
>
> ①同【线】。
>
>
>
線 is treated more like a variant than the actual traditional character for 线. But this all seems quite contrary to my understanding for this character.
Is there a viable reason why 綫 would be picked over 線? | 2020/04/19 | [
"https://chinese.stackexchange.com/questions/38766",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/4136/"
] | My understanding is that when characters were being simplified in Mainland China, they first had to standardize traditional characters (i.e. What should these new characters be simplified from?). 「綫」 was chosen as the traditional standard, thus in the PRC's [Table of General Standard Chinese Characters (通用規範漢字表)](https://en.wikipedia.org/wiki/Table_of_General_Standard_Chinese_Characters), you can see that 「线」 is considered to be simplified from 「綫」, while 「線」 is listed as a variant of 「綫」 ([「缐」 also exists, but is only used as a surname](https://en.wiktionary.org/wiki/%E7%BC%90)).
[](https://i.stack.imgur.com/BeIRH.png)
Understandably, if the dictionaries you are using are Mainland Chinese, 「綫」 will be treated as the standard character rather than 「線」.
---
In contrast, every other region in the [Sinosphere](https://en.wikipedia.org/wiki/East_Asian_cultural_sphere) that has some standard for Chinese characters (i.e. Hong Kong, Taiwan, Japan, South Korea) list 「線」 as the standard form, which might explain why 「線」 is much more prominent outside of simplified Chinese.
However, as mentioned in the other answer, 「綫」 is quite common in Hong Kong, despite 「線」 being the standard character in Hong Kong's [List of Graphemes of Commonly-Used Chinese Characters (常用字字形表)](https://en.wikipedia.org/wiki/List_of_Graphemes_of_Commonly-Used_Chinese_Characters). This is likely because the standardized character shapes are used as general guidelines for education, rather than used as a strict set of rules to follow.
[](https://i.stack.imgur.com/Q0eEd.png)
*The smaller character here indicates a variant form.*
---
Both these forms have existed as variants of each other for quite some time before the modern era, so aside from regional standards and popularity, one isn't necessarily more correct than the other. I'm not sure about Japan and Korea, but in Chinese-speaking regions, both forms should be equally well-understood. In the end, it boils down to personal preference. | (Not enough reputation to comment, so I am posting this as an answer instead)
In addition to MTR's example,
TVB uses "綫": `無綫電視`/`無綫新聞台`
But another company, i-CABLE TV, uses "線": `有線新聞`.
And "wireless" in "wireless network" is usually written as "無線".
From my observation, nowadays people usually write "線", and "綫" is only used in very few cases. |
18,100,516 | I have an array something like below.We need to create three array from this array.We need to seperate all for facebook inside another array and something like other twitter,email.
Is this possible?
```
Array
(
[01] => Array
(
[facebook] => 375
[twitter] => 3276
[email] => 3276
)
[02] => Array
(
[facebook] => 385
[twitter] => 3326
[email] => 3326
)
[03] => Array
(
[facebook] => 391
[twitter] => 3327
[email] => 3327
)
[04] => Array
(
[facebook] => 446
[twitter] => 3327
[email] => 3327
)
[05] => Array
(
[facebook] => 486
[twitter] => 3334
[email] => 3334
)
[06] => Array
(
[facebook] => 2
[twitter] => 6
[email] => 6
)
[07] => Array
(
[facebook] => 1
[twitter] => 7
[email] => 7
)
[08] => Array
(
[facebook] => 3
[twitter] => 11
[email] => 11
)
[09] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
[10] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
[11] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
[12] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
)
```
We need like this for all three(facebook,twitter,email)
```
Array(
[01]=>385,
[02]=>375,
[03]=>391,
[04]=>446,
[05]=>486,
[06]=>2,
[07]=>1,
[08]=>0,
[09]=>0,
[10]=>0,
[11]=>0,
[12]=>0,
}
``` | 2013/08/07 | [
"https://Stackoverflow.com/questions/18100516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2533926/"
] | ```
$your_array = //here you have your original array
$facebook = array();
$twitter = array();
$email = array();
foreach($your_array as $sub_array) {
$facebook[] = $sub_array["facebook"];
$twitter[] = $sub_array["twitter"];
$email[] = $sub_array["email"];
}
``` | You can create three arrays easily :-)
let say main array name is $mainarray
```
$facebookarr = array();
$twitterarr = array();
$emailarr = array();
foreach($mainarray as $socialarray)
{
$facebookarr[] = $socialarray['facebook'];
$twitterarr[] = $socialarray['twitter']
$emailarr[] = $socialarray['email']
}
echo '<pre>';
print_r($facebookarr);
print_r($twitterarr);
print_r($emailarr);
``` |
18,100,516 | I have an array something like below.We need to create three array from this array.We need to seperate all for facebook inside another array and something like other twitter,email.
Is this possible?
```
Array
(
[01] => Array
(
[facebook] => 375
[twitter] => 3276
[email] => 3276
)
[02] => Array
(
[facebook] => 385
[twitter] => 3326
[email] => 3326
)
[03] => Array
(
[facebook] => 391
[twitter] => 3327
[email] => 3327
)
[04] => Array
(
[facebook] => 446
[twitter] => 3327
[email] => 3327
)
[05] => Array
(
[facebook] => 486
[twitter] => 3334
[email] => 3334
)
[06] => Array
(
[facebook] => 2
[twitter] => 6
[email] => 6
)
[07] => Array
(
[facebook] => 1
[twitter] => 7
[email] => 7
)
[08] => Array
(
[facebook] => 3
[twitter] => 11
[email] => 11
)
[09] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
[10] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
[11] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
[12] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
)
```
We need like this for all three(facebook,twitter,email)
```
Array(
[01]=>385,
[02]=>375,
[03]=>391,
[04]=>446,
[05]=>486,
[06]=>2,
[07]=>1,
[08]=>0,
[09]=>0,
[10]=>0,
[11]=>0,
[12]=>0,
}
``` | 2013/08/07 | [
"https://Stackoverflow.com/questions/18100516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2533926/"
] | ```
$your_array = //here you have your original array
$facebook = array();
$twitter = array();
$email = array();
foreach($your_array as $sub_array) {
$facebook[] = $sub_array["facebook"];
$twitter[] = $sub_array["twitter"];
$email[] = $sub_array["email"];
}
``` | Try [array\_column](http://www.php.net/manual/en/function.array-column.php)
```
$fb=array_column($array, 'facebook');
```
OR
```
$fb=array_map( function ($i) { return $i['facebook'];},$array);
``` |
18,100,516 | I have an array something like below.We need to create three array from this array.We need to seperate all for facebook inside another array and something like other twitter,email.
Is this possible?
```
Array
(
[01] => Array
(
[facebook] => 375
[twitter] => 3276
[email] => 3276
)
[02] => Array
(
[facebook] => 385
[twitter] => 3326
[email] => 3326
)
[03] => Array
(
[facebook] => 391
[twitter] => 3327
[email] => 3327
)
[04] => Array
(
[facebook] => 446
[twitter] => 3327
[email] => 3327
)
[05] => Array
(
[facebook] => 486
[twitter] => 3334
[email] => 3334
)
[06] => Array
(
[facebook] => 2
[twitter] => 6
[email] => 6
)
[07] => Array
(
[facebook] => 1
[twitter] => 7
[email] => 7
)
[08] => Array
(
[facebook] => 3
[twitter] => 11
[email] => 11
)
[09] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
[10] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
[11] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
[12] => Array
(
[facebook] => 0
[twitter] => 0
[email] => 0
)
)
```
We need like this for all three(facebook,twitter,email)
```
Array(
[01]=>385,
[02]=>375,
[03]=>391,
[04]=>446,
[05]=>486,
[06]=>2,
[07]=>1,
[08]=>0,
[09]=>0,
[10]=>0,
[11]=>0,
[12]=>0,
}
``` | 2013/08/07 | [
"https://Stackoverflow.com/questions/18100516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2533926/"
] | Try [array\_column](http://www.php.net/manual/en/function.array-column.php)
```
$fb=array_column($array, 'facebook');
```
OR
```
$fb=array_map( function ($i) { return $i['facebook'];},$array);
``` | You can create three arrays easily :-)
let say main array name is $mainarray
```
$facebookarr = array();
$twitterarr = array();
$emailarr = array();
foreach($mainarray as $socialarray)
{
$facebookarr[] = $socialarray['facebook'];
$twitterarr[] = $socialarray['twitter']
$emailarr[] = $socialarray['email']
}
echo '<pre>';
print_r($facebookarr);
print_r($twitterarr);
print_r($emailarr);
``` |
1,856,457 | I am trying to accomplish the following:
```
SELECT col1, col2 FROM table1
UNION
SELECT col2, col3 FROM table2
```
With the result:
```
col1, col2, col3
1 , 1 , NULL
NULL, 1 , 1
```
The union of the columns *and* the rows is returned. You could think of it as the UNION equivalent of a FULL OUTER JOIN.
The simple answer to this question is:
```
SELECT col1, col2, NULL AS col3 FROM table1
UNION
SELECT NULL AS col1, col2, col3 FROM table2
```
This, however, is difficult to do with dynamic T-SQL and dbo.sp\_executesql, and the resulting query could be too long if a large number of UNIONS is involved.
The best solution I could come up with was to create a temporary table with all the possible columns and insert each select into the temporary table in turn, like this:
```
CREATE TABLE #temp ( col1 int, col2 int, col3 int )
INSERT INTO #temp ( col1, col2 ) SELECT col1, col2 FROM table1
INSERT INTO #temp ( col2, col3 ) SELECT col2, col3 FROM table2
```
But this requires knowing ahead of time what the column names are. My particular scenario and this question assumes that if the column names match the types match as well. In fact, the columns that I am trying to manipulate are all of the same type.
Is there a simpler way to do this?
Thanks! | 2009/12/06 | [
"https://Stackoverflow.com/questions/1856457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125292/"
] | My interpretation of your question is that you want to be able to support an ad-hoc query, given the talk about dynamic SQL & column names & data types...
This query will give you a list of columns & their data types for a specific table:
```
SELECT @columnName = c.name AS columnName,
@columnDataType = ty.name AS columnDataType
FROM SYS.TABLES ta
JOIN SYS.COLUMNS c ON c.object_id = ta.object_id
JOIN SYS.TYPES ty ON ty.user_type_id = c.user_type_id
WHERE ta.name = '[your_table_name]'
```
This populates the `@columnName` & `@columnDataType` variables so you can use them elsewhere.
You'll need to supply the column name, and table name that the column resides in at a minimum to get meaningful data for a single column. After that, it's a matter of constructing the logic you want for what to do in order to create the query you want.
A simpler approach would be to determine what is the query needed for the majority of situations.
The sad part is that when you ask, the answer is usually "everything". For that response, I'd lay things out that in order to support everything you need an amount of currency & time. Stress that it is cheaper & faster to break up the requirement into manageable portions - this will also allow you to be able to get feedback. It's possible that no one will ever use a small subset of the functionality, or it's not what the user needs at all. Learn to manage client expectations. | After a quick try, the closest I can get in T-SQL without jumping through loads of flaming hoops of hackiness is using a FULL OUTER JOIN with a false condition...
e.g.
```
DECLARE @TableA TABLE (Col1 INTEGER IDENTITY(1,1), Col2 INTEGER)
DECLARE @TableB TABLE (Col2 INTEGER IDENTITY(1,1), Col3 INTEGER)
INSERT @TableA VALUES (1)
INSERT @TableA VALUES (11)
INSERT @TableB VALUES (2)
INSERT @TableB VALUES (222)
SELECT *
FROM @TableA a
FULL OUTER JOIN @TableB b ON 0 = 1
```
You'll see from the results though, that Col2 is included twice in the resultset...it's not combined into one.
My suggestion would be to handle this in your code that sits over this, instead of trying it in T-SQL - return multiple resultsets to your calling code and have that deal with the different schemas. If you really need it as one resultset, could that calling code not combine the results into one? |
1,856,457 | I am trying to accomplish the following:
```
SELECT col1, col2 FROM table1
UNION
SELECT col2, col3 FROM table2
```
With the result:
```
col1, col2, col3
1 , 1 , NULL
NULL, 1 , 1
```
The union of the columns *and* the rows is returned. You could think of it as the UNION equivalent of a FULL OUTER JOIN.
The simple answer to this question is:
```
SELECT col1, col2, NULL AS col3 FROM table1
UNION
SELECT NULL AS col1, col2, col3 FROM table2
```
This, however, is difficult to do with dynamic T-SQL and dbo.sp\_executesql, and the resulting query could be too long if a large number of UNIONS is involved.
The best solution I could come up with was to create a temporary table with all the possible columns and insert each select into the temporary table in turn, like this:
```
CREATE TABLE #temp ( col1 int, col2 int, col3 int )
INSERT INTO #temp ( col1, col2 ) SELECT col1, col2 FROM table1
INSERT INTO #temp ( col2, col3 ) SELECT col2, col3 FROM table2
```
But this requires knowing ahead of time what the column names are. My particular scenario and this question assumes that if the column names match the types match as well. In fact, the columns that I am trying to manipulate are all of the same type.
Is there a simpler way to do this?
Thanks! | 2009/12/06 | [
"https://Stackoverflow.com/questions/1856457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125292/"
] | I threw in the towel on this one and wrote a bunch of nasty dynamic T-SQL and executed it with sp\_executesql. Thanks for the help! | After a quick try, the closest I can get in T-SQL without jumping through loads of flaming hoops of hackiness is using a FULL OUTER JOIN with a false condition...
e.g.
```
DECLARE @TableA TABLE (Col1 INTEGER IDENTITY(1,1), Col2 INTEGER)
DECLARE @TableB TABLE (Col2 INTEGER IDENTITY(1,1), Col3 INTEGER)
INSERT @TableA VALUES (1)
INSERT @TableA VALUES (11)
INSERT @TableB VALUES (2)
INSERT @TableB VALUES (222)
SELECT *
FROM @TableA a
FULL OUTER JOIN @TableB b ON 0 = 1
```
You'll see from the results though, that Col2 is included twice in the resultset...it's not combined into one.
My suggestion would be to handle this in your code that sits over this, instead of trying it in T-SQL - return multiple resultsets to your calling code and have that deal with the different schemas. If you really need it as one resultset, could that calling code not combine the results into one? |
1,856,457 | I am trying to accomplish the following:
```
SELECT col1, col2 FROM table1
UNION
SELECT col2, col3 FROM table2
```
With the result:
```
col1, col2, col3
1 , 1 , NULL
NULL, 1 , 1
```
The union of the columns *and* the rows is returned. You could think of it as the UNION equivalent of a FULL OUTER JOIN.
The simple answer to this question is:
```
SELECT col1, col2, NULL AS col3 FROM table1
UNION
SELECT NULL AS col1, col2, col3 FROM table2
```
This, however, is difficult to do with dynamic T-SQL and dbo.sp\_executesql, and the resulting query could be too long if a large number of UNIONS is involved.
The best solution I could come up with was to create a temporary table with all the possible columns and insert each select into the temporary table in turn, like this:
```
CREATE TABLE #temp ( col1 int, col2 int, col3 int )
INSERT INTO #temp ( col1, col2 ) SELECT col1, col2 FROM table1
INSERT INTO #temp ( col2, col3 ) SELECT col2, col3 FROM table2
```
But this requires knowing ahead of time what the column names are. My particular scenario and this question assumes that if the column names match the types match as well. In fact, the columns that I am trying to manipulate are all of the same type.
Is there a simpler way to do this?
Thanks! | 2009/12/06 | [
"https://Stackoverflow.com/questions/1856457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125292/"
] | My interpretation of your question is that you want to be able to support an ad-hoc query, given the talk about dynamic SQL & column names & data types...
This query will give you a list of columns & their data types for a specific table:
```
SELECT @columnName = c.name AS columnName,
@columnDataType = ty.name AS columnDataType
FROM SYS.TABLES ta
JOIN SYS.COLUMNS c ON c.object_id = ta.object_id
JOIN SYS.TYPES ty ON ty.user_type_id = c.user_type_id
WHERE ta.name = '[your_table_name]'
```
This populates the `@columnName` & `@columnDataType` variables so you can use them elsewhere.
You'll need to supply the column name, and table name that the column resides in at a minimum to get meaningful data for a single column. After that, it's a matter of constructing the logic you want for what to do in order to create the query you want.
A simpler approach would be to determine what is the query needed for the majority of situations.
The sad part is that when you ask, the answer is usually "everything". For that response, I'd lay things out that in order to support everything you need an amount of currency & time. Stress that it is cheaper & faster to break up the requirement into manageable portions - this will also allow you to be able to get feedback. It's possible that no one will ever use a small subset of the functionality, or it's not what the user needs at all. Learn to manage client expectations. | Will this help(joining upon some dummy column) in giving some insight?
```
declare @t1 table(col1 varchar(10),col2 varchar(10))
declare @t2 table(col2 varchar(10),col3 varchar(10))
insert into @t1 select '1','1' union all select '10','1'
insert into @t2 select '1',null union all select '10','1'
;with cte1 as(select ROW_NUMBER() over(order by getdate()) rn1, t1.* from @t1 t1)
,cte2 as(select ROW_NUMBER() over(order by getdate()) rn2, t2.* from @t2 t2)
select c1.col1,c1.col2,c2.col3
from cte1 c1
full outer join cte2 c2
on c1.rn1 = c2.rn2
```
**Output:**
```
col1 col2 col3
1 1 NULL
10 1 1
``` |
1,856,457 | I am trying to accomplish the following:
```
SELECT col1, col2 FROM table1
UNION
SELECT col2, col3 FROM table2
```
With the result:
```
col1, col2, col3
1 , 1 , NULL
NULL, 1 , 1
```
The union of the columns *and* the rows is returned. You could think of it as the UNION equivalent of a FULL OUTER JOIN.
The simple answer to this question is:
```
SELECT col1, col2, NULL AS col3 FROM table1
UNION
SELECT NULL AS col1, col2, col3 FROM table2
```
This, however, is difficult to do with dynamic T-SQL and dbo.sp\_executesql, and the resulting query could be too long if a large number of UNIONS is involved.
The best solution I could come up with was to create a temporary table with all the possible columns and insert each select into the temporary table in turn, like this:
```
CREATE TABLE #temp ( col1 int, col2 int, col3 int )
INSERT INTO #temp ( col1, col2 ) SELECT col1, col2 FROM table1
INSERT INTO #temp ( col2, col3 ) SELECT col2, col3 FROM table2
```
But this requires knowing ahead of time what the column names are. My particular scenario and this question assumes that if the column names match the types match as well. In fact, the columns that I am trying to manipulate are all of the same type.
Is there a simpler way to do this?
Thanks! | 2009/12/06 | [
"https://Stackoverflow.com/questions/1856457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125292/"
] | I threw in the towel on this one and wrote a bunch of nasty dynamic T-SQL and executed it with sp\_executesql. Thanks for the help! | Will this help(joining upon some dummy column) in giving some insight?
```
declare @t1 table(col1 varchar(10),col2 varchar(10))
declare @t2 table(col2 varchar(10),col3 varchar(10))
insert into @t1 select '1','1' union all select '10','1'
insert into @t2 select '1',null union all select '10','1'
;with cte1 as(select ROW_NUMBER() over(order by getdate()) rn1, t1.* from @t1 t1)
,cte2 as(select ROW_NUMBER() over(order by getdate()) rn2, t2.* from @t2 t2)
select c1.col1,c1.col2,c2.col3
from cte1 c1
full outer join cte2 c2
on c1.rn1 = c2.rn2
```
**Output:**
```
col1 col2 col3
1 1 NULL
10 1 1
``` |
30,608,282 | I have a list of over million tuples and want a list of 100,000 tuples randomly sampled from that original list without replacement. I have read:
[How do I pick 2 random items from a Python set?](https://stackoverflow.com/questions/1262955/how-do-i-pick-2-random-items-from-a-python-set)
but the solution provided (using random.sample while casting list to a set) does not work for tuples.
I am using Python 2.7 | 2015/06/02 | [
"https://Stackoverflow.com/questions/30608282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4757234/"
] | You can sample your list regardless of if the elements are hashable or not:
```python
data = create_dataset() # List of data to be sampled
n_samples = 100000
samples = random.sample(data,n_samples)
``` | Not sure if I fully understand your question, but `random.sample` can accept both lists and tuples:
```
random.sample([1,2,3,4,5],2)
Out[620]: [2, 5]
random.sample((1,2,3,4,5),2)
Out[621]: [4, 1]
``` |
27,907,491 | I've been tasked with cleaning up someone else's code and i'm new to web development stuff and this seems to be a little over my head. I wanted to make the table so that the background of the row and text color change and have looked at examples but could not figure out how to integrate them into this code.
```
var mydiv = $("<div style=\"height:400px;width:750px;overflow-y:auto;\"></div>");
var mytab = $("<table style=\"width:750px;height:300px;overflow-y:auto;background-color:Grey;color:White\"></table>").append($("<th style=\"background-color:Black;\"></th>").text("Company Name")).append($("<th style=\"background-color:Black;\"></th>").text("State")).append($("<th style=\"background-color:Black;\"></th>").text("Street Address")).append($("<th style=\"background-color:Black;\"></th>").text("City"));
for (i = 0; i < companies.length; i++) {
$(mytab).append($("<tr></tr>").append($("<td style=\"cursor:pointer;\"></td>").text(companies[i].CompanyName).attr("cid", companies[i].KeyID).click(function () {
var fcd = new FindCompanyDetails();
fcd.GetRequest("?KeyIDs=" + $(this).attr("cid") + "&AT=" + AT, function (a) {
//alert(a.Msg.Result.Address1);
populateFields(a.Msg.Result);
mydiv.dialog("close");
});
})).append($("<td></td>").text(companies[i].StateRegion)));
}
mydiv.append(mytab);
$(document).find("body").append(mydiv);
mydiv.dialog({ title: "Choose Matching Company" }, { width: 750 }, {height: 400} );
```
Any help would be much appreciated! | 2015/01/12 | [
"https://Stackoverflow.com/questions/27907491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4446294/"
] | Try this with your css:
```
table tr {
background-color: lightblue;
}
table tr:hover {
background-color: blue;
}
```
---
Check here:
<http://jsfiddle.net/dboxs77z/>
--- | Use Css
>
> Put following code in Head section
>
>
>
```
<style type="text/css">
table tr {background-color:Red;}
table tr:hover {background-color:Blue;}
</style>
``` |
27,907,491 | I've been tasked with cleaning up someone else's code and i'm new to web development stuff and this seems to be a little over my head. I wanted to make the table so that the background of the row and text color change and have looked at examples but could not figure out how to integrate them into this code.
```
var mydiv = $("<div style=\"height:400px;width:750px;overflow-y:auto;\"></div>");
var mytab = $("<table style=\"width:750px;height:300px;overflow-y:auto;background-color:Grey;color:White\"></table>").append($("<th style=\"background-color:Black;\"></th>").text("Company Name")).append($("<th style=\"background-color:Black;\"></th>").text("State")).append($("<th style=\"background-color:Black;\"></th>").text("Street Address")).append($("<th style=\"background-color:Black;\"></th>").text("City"));
for (i = 0; i < companies.length; i++) {
$(mytab).append($("<tr></tr>").append($("<td style=\"cursor:pointer;\"></td>").text(companies[i].CompanyName).attr("cid", companies[i].KeyID).click(function () {
var fcd = new FindCompanyDetails();
fcd.GetRequest("?KeyIDs=" + $(this).attr("cid") + "&AT=" + AT, function (a) {
//alert(a.Msg.Result.Address1);
populateFields(a.Msg.Result);
mydiv.dialog("close");
});
})).append($("<td></td>").text(companies[i].StateRegion)));
}
mydiv.append(mytab);
$(document).find("body").append(mydiv);
mydiv.dialog({ title: "Choose Matching Company" }, { width: 750 }, {height: 400} );
```
Any help would be much appreciated! | 2015/01/12 | [
"https://Stackoverflow.com/questions/27907491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4446294/"
] | Try this with your css:
```
table tr {
background-color: lightblue;
}
table tr:hover {
background-color: blue;
}
```
---
Check here:
<http://jsfiddle.net/dboxs77z/>
--- | CSS Is Used for that Purpose
>
> Put following code in Head section
>
>
>
```
<style type="text/css">
table tr {background-color:Blue;}
table tr:hover {background-color:Red;}
</style>
```
Replace Blue & Red With your desired colors |
6,254,793 | I have the following `<div>` inside a `<body>` tag:
```
<div id="AlertDiv"><h1>Yes</h1></div>
```
And these are their CSS classes:
```
#AlertDiv {
position:absolute;
height: 51px;
left: 365px;
top: 198px;
width: 62px;
background-color:black;
color:white;
}
#AlertDiv h1{
margin:auto;
vertical-align:middle;
}
```
How can I vertically and horizontally align an `<h1>` inside of a `<div>`?
`AlertDiv` will be bigger than `<h1>`. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6254793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68571/"
] | You can add `line-height:51px` to `#AlertDiv h1` if you know it's only ever going to be one line. Also add `text-align:center` to `#AlertDiv`.
```
#AlertDiv {
top:198px;
left:365px;
width:62px;
height:51px;
color:white;
position:absolute;
text-align:center;
background-color:black;
}
#AlertDiv h1 {
margin:auto;
line-height:51px;
vertical-align:middle;
}
```
The demo below also uses negative margins to keep the `#AlertDiv` centered on both axis, even when the window is resized.
**Demo: [jsfiddle.net/KaXY5](http://jsfiddle.net/Marcel/KaXY5/)** | ```
<div id="AlertDiv" style="width:600px;height:400px;border:SOLID 1px;">
<h1 style="width:100%;height:10%;text-align:center;position:relative;top:40%;">Yes</h1>
</div>
```
You can try the code here:
<http://htmledit.squarefree.com/> |
6,254,793 | I have the following `<div>` inside a `<body>` tag:
```
<div id="AlertDiv"><h1>Yes</h1></div>
```
And these are their CSS classes:
```
#AlertDiv {
position:absolute;
height: 51px;
left: 365px;
top: 198px;
width: 62px;
background-color:black;
color:white;
}
#AlertDiv h1{
margin:auto;
vertical-align:middle;
}
```
How can I vertically and horizontally align an `<h1>` inside of a `<div>`?
`AlertDiv` will be bigger than `<h1>`. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6254793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68571/"
] | You can add `line-height:51px` to `#AlertDiv h1` if you know it's only ever going to be one line. Also add `text-align:center` to `#AlertDiv`.
```
#AlertDiv {
top:198px;
left:365px;
width:62px;
height:51px;
color:white;
position:absolute;
text-align:center;
background-color:black;
}
#AlertDiv h1 {
margin:auto;
line-height:51px;
vertical-align:middle;
}
```
The demo below also uses negative margins to keep the `#AlertDiv` centered on both axis, even when the window is resized.
**Demo: [jsfiddle.net/KaXY5](http://jsfiddle.net/Marcel/KaXY5/)** | You can use `display: table-cell` in order to render the div as a table cell and then use `vertical-align` like you would do in a normal table cell.
```
#AlertDiv {
display: table-cell;
vertical-align: middle;
text-align: center;
}
```
You can try it here:
<http://jsfiddle.net/KaXY5/424/> |
6,254,793 | I have the following `<div>` inside a `<body>` tag:
```
<div id="AlertDiv"><h1>Yes</h1></div>
```
And these are their CSS classes:
```
#AlertDiv {
position:absolute;
height: 51px;
left: 365px;
top: 198px;
width: 62px;
background-color:black;
color:white;
}
#AlertDiv h1{
margin:auto;
vertical-align:middle;
}
```
How can I vertically and horizontally align an `<h1>` inside of a `<div>`?
`AlertDiv` will be bigger than `<h1>`. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6254793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68571/"
] | There is a new way using transforms. Apply this to the element to centre. It nudges down by half the container height and then 'corrects' by half the element height.
```
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
```
It works most of the time. I did have a problem where a `div` was in a `div` in a `li`. The list item had a height set and the outer `div`s made up 3 columns (Foundation). The 2nd and 3rd column divs contained images, and they centered just fine with this technique, however the heading in the first column needed a wrapping div with an explicit height set.
Now, does anyone know if the CSS people are working on a way to align stuff, like, easily? Seeing that its 2014 and even some of my friends are regularly using the internet, I wondered if anyone had considered that centering would be a useful styling feature yet. Just us then? | ```
<div id="AlertDiv" style="width:600px;height:400px;border:SOLID 1px;">
<h1 style="width:100%;height:10%;text-align:center;position:relative;top:40%;">Yes</h1>
</div>
```
You can try the code here:
<http://htmledit.squarefree.com/> |
6,254,793 | I have the following `<div>` inside a `<body>` tag:
```
<div id="AlertDiv"><h1>Yes</h1></div>
```
And these are their CSS classes:
```
#AlertDiv {
position:absolute;
height: 51px;
left: 365px;
top: 198px;
width: 62px;
background-color:black;
color:white;
}
#AlertDiv h1{
margin:auto;
vertical-align:middle;
}
```
How can I vertically and horizontally align an `<h1>` inside of a `<div>`?
`AlertDiv` will be bigger than `<h1>`. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6254793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68571/"
] | On the hX tag
```
width: 100px;
margin-left: auto;
margin-right: auto;
``` | You could add padding to the `h1`:
```
#AlertDiv h1 {
padding:15px 18px;
}
``` |
6,254,793 | I have the following `<div>` inside a `<body>` tag:
```
<div id="AlertDiv"><h1>Yes</h1></div>
```
And these are their CSS classes:
```
#AlertDiv {
position:absolute;
height: 51px;
left: 365px;
top: 198px;
width: 62px;
background-color:black;
color:white;
}
#AlertDiv h1{
margin:auto;
vertical-align:middle;
}
```
How can I vertically and horizontally align an `<h1>` inside of a `<div>`?
`AlertDiv` will be bigger than `<h1>`. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6254793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68571/"
] | Started a **jsFiddle** [here](http://jsfiddle.net/Jby3m/3/).
It seems the *horizontal alignment* works with a `text-align : center`. Still trying to get the vertical align to work; might have to use `absolute` positioning and something like `top: 50%` or a pre-calculated `padding` from the top. | You can use `display: table-cell` in order to render the div as a table cell and then use `vertical-align` like you would do in a normal table cell.
```
#AlertDiv {
display: table-cell;
vertical-align: middle;
text-align: center;
}
```
You can try it here:
<http://jsfiddle.net/KaXY5/424/> |
6,254,793 | I have the following `<div>` inside a `<body>` tag:
```
<div id="AlertDiv"><h1>Yes</h1></div>
```
And these are their CSS classes:
```
#AlertDiv {
position:absolute;
height: 51px;
left: 365px;
top: 198px;
width: 62px;
background-color:black;
color:white;
}
#AlertDiv h1{
margin:auto;
vertical-align:middle;
}
```
How can I vertically and horizontally align an `<h1>` inside of a `<div>`?
`AlertDiv` will be bigger than `<h1>`. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6254793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68571/"
] | There is a new way using transforms. Apply this to the element to centre. It nudges down by half the container height and then 'corrects' by half the element height.
```
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
```
It works most of the time. I did have a problem where a `div` was in a `div` in a `li`. The list item had a height set and the outer `div`s made up 3 columns (Foundation). The 2nd and 3rd column divs contained images, and they centered just fine with this technique, however the heading in the first column needed a wrapping div with an explicit height set.
Now, does anyone know if the CSS people are working on a way to align stuff, like, easily? Seeing that its 2014 and even some of my friends are regularly using the internet, I wondered if anyone had considered that centering would be a useful styling feature yet. Just us then? | Started a **jsFiddle** [here](http://jsfiddle.net/Jby3m/3/).
It seems the *horizontal alignment* works with a `text-align : center`. Still trying to get the vertical align to work; might have to use `absolute` positioning and something like `top: 50%` or a pre-calculated `padding` from the top. |
6,254,793 | I have the following `<div>` inside a `<body>` tag:
```
<div id="AlertDiv"><h1>Yes</h1></div>
```
And these are their CSS classes:
```
#AlertDiv {
position:absolute;
height: 51px;
left: 365px;
top: 198px;
width: 62px;
background-color:black;
color:white;
}
#AlertDiv h1{
margin:auto;
vertical-align:middle;
}
```
How can I vertically and horizontally align an `<h1>` inside of a `<div>`?
`AlertDiv` will be bigger than `<h1>`. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6254793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68571/"
] | On the hX tag
```
width: 100px;
margin-left: auto;
margin-right: auto;
``` | Started a **jsFiddle** [here](http://jsfiddle.net/Jby3m/3/).
It seems the *horizontal alignment* works with a `text-align : center`. Still trying to get the vertical align to work; might have to use `absolute` positioning and something like `top: 50%` or a pre-calculated `padding` from the top. |
6,254,793 | I have the following `<div>` inside a `<body>` tag:
```
<div id="AlertDiv"><h1>Yes</h1></div>
```
And these are their CSS classes:
```
#AlertDiv {
position:absolute;
height: 51px;
left: 365px;
top: 198px;
width: 62px;
background-color:black;
color:white;
}
#AlertDiv h1{
margin:auto;
vertical-align:middle;
}
```
How can I vertically and horizontally align an `<h1>` inside of a `<div>`?
`AlertDiv` will be bigger than `<h1>`. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6254793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68571/"
] | There is a new way using transforms. Apply this to the element to centre. It nudges down by half the container height and then 'corrects' by half the element height.
```
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
```
It works most of the time. I did have a problem where a `div` was in a `div` in a `li`. The list item had a height set and the outer `div`s made up 3 columns (Foundation). The 2nd and 3rd column divs contained images, and they centered just fine with this technique, however the heading in the first column needed a wrapping div with an explicit height set.
Now, does anyone know if the CSS people are working on a way to align stuff, like, easily? Seeing that its 2014 and even some of my friends are regularly using the internet, I wondered if anyone had considered that centering would be a useful styling feature yet. Just us then? | You can use `display: table-cell` in order to render the div as a table cell and then use `vertical-align` like you would do in a normal table cell.
```
#AlertDiv {
display: table-cell;
vertical-align: middle;
text-align: center;
}
```
You can try it here:
<http://jsfiddle.net/KaXY5/424/> |
6,254,793 | I have the following `<div>` inside a `<body>` tag:
```
<div id="AlertDiv"><h1>Yes</h1></div>
```
And these are their CSS classes:
```
#AlertDiv {
position:absolute;
height: 51px;
left: 365px;
top: 198px;
width: 62px;
background-color:black;
color:white;
}
#AlertDiv h1{
margin:auto;
vertical-align:middle;
}
```
How can I vertically and horizontally align an `<h1>` inside of a `<div>`?
`AlertDiv` will be bigger than `<h1>`. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6254793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68571/"
] | On the hX tag
```
width: 100px;
margin-left: auto;
margin-right: auto;
``` | You can use `display: table-cell` in order to render the div as a table cell and then use `vertical-align` like you would do in a normal table cell.
```
#AlertDiv {
display: table-cell;
vertical-align: middle;
text-align: center;
}
```
You can try it here:
<http://jsfiddle.net/KaXY5/424/> |
6,254,793 | I have the following `<div>` inside a `<body>` tag:
```
<div id="AlertDiv"><h1>Yes</h1></div>
```
And these are their CSS classes:
```
#AlertDiv {
position:absolute;
height: 51px;
left: 365px;
top: 198px;
width: 62px;
background-color:black;
color:white;
}
#AlertDiv h1{
margin:auto;
vertical-align:middle;
}
```
How can I vertically and horizontally align an `<h1>` inside of a `<div>`?
`AlertDiv` will be bigger than `<h1>`. | 2011/06/06 | [
"https://Stackoverflow.com/questions/6254793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68571/"
] | You can add `line-height:51px` to `#AlertDiv h1` if you know it's only ever going to be one line. Also add `text-align:center` to `#AlertDiv`.
```
#AlertDiv {
top:198px;
left:365px;
width:62px;
height:51px;
color:white;
position:absolute;
text-align:center;
background-color:black;
}
#AlertDiv h1 {
margin:auto;
line-height:51px;
vertical-align:middle;
}
```
The demo below also uses negative margins to keep the `#AlertDiv` centered on both axis, even when the window is resized.
**Demo: [jsfiddle.net/KaXY5](http://jsfiddle.net/Marcel/KaXY5/)** | There is a new way using transforms. Apply this to the element to centre. It nudges down by half the container height and then 'corrects' by half the element height.
```
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
```
It works most of the time. I did have a problem where a `div` was in a `div` in a `li`. The list item had a height set and the outer `div`s made up 3 columns (Foundation). The 2nd and 3rd column divs contained images, and they centered just fine with this technique, however the heading in the first column needed a wrapping div with an explicit height set.
Now, does anyone know if the CSS people are working on a way to align stuff, like, easily? Seeing that its 2014 and even some of my friends are regularly using the internet, I wondered if anyone had considered that centering would be a useful styling feature yet. Just us then? |
65,268,300 | I've tried multiple solutions and read some other answers talking about the visibility of the class, but I've no added any private or protected modifier.
The point is, that I'm just have a very simple ViewBinding configuration, but it's showing the following message when I try to run it.
>
> e: /app/src/main/java/com/adalpari/example/view/MainActivity.kt: (16,40): Cannot access '': it is private in 'ActivityMainBinding'
>
>
>
>
> e: /app/src/main/java/com/adalpari/example/view/MainActivity.kt: (16,60): No value passed for parameter 'rootView'
>
>
>
>
> e: /app/src/main/java/com/adalpari/example/view/MainActivity.kt: (16,60): No value passed for parameter 'progressBar'
>
>
>
>
> e: /app/src/main/java/com/adalpari/example/view/MainActivity.kt: (16,60): No value passed for parameter 'storiesView'
>
>
>
The code, as you can see is pretty simple..
MainActivity:
```
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
val binding: ActivityMainBinding = ActivityMainBinding()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
onObserve()
}
...
}
```
xml file:
```
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.MainActivity"
>
<com.adalpari.storiesview.view.StoriesView
android:id="@+id/stories_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="@+id/stories_view"
app:layout_constraintEnd_toEndOf="@+id/stories_view"
app:layout_constraintStart_toStartOf="@+id/stories_view"
app:layout_constraintTop_toTopOf="@+id/stories_view"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
```
And finally the enabling of ViewBinding in app's gradle:
```
apply plugin: 'kotlin-kapt'
android {
...
buildFeatures {
viewBinding true
}
...
}
```
Any help is very appreciated, thanks in advance! | 2020/12/12 | [
"https://Stackoverflow.com/questions/65268300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820599/"
] | You're not supposed to use the constructors of data binding classes (they're private, as your error message says). Use the method `ActivityMainBinding.inflate()` to create your binding object
```
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
```
This is shown in the [official docs](https://developer.android.com/topic/libraries/view-binding) for ViewBinding | I would recommend using `dataBinding` which includs `viewBinding` and other powerful features you may need in the future.
**1. Enable `dataBinding` in Build Gradle File:**
```
apply plugin: 'kotlin-kapt'
android {
...
buildFeatures {
dataBinding true
}
...
}
```
**2. Wrap the Whole Layout inside `<layout>` Tag:**
```
<layout //key point
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:id="@+id/xxx"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
...
</LinearLayout>
</layout>
```
**3. Setup `Activity`/`Fragment`:**
```
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding //may need rebuild project
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
//binding.xxx.xxx
}
}
```
* For `Fragment`:
```
binding: FragmentFirstBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_first, container, false)
``` |
37,492,145 | Usually i do:
```
onclick="myFunction()"
```
on my submit button, but what i want to do now on html is
```
<form id="myForm">
<input type="text" id="myTextBox" required> <!-- we're gonna use this id: myTextBox because we're using the getElementById() -->
<input type="submit" value="Click Me"> <!-- we call the function here -->
</form>
```
on JS
```
document.getElementById("myForm").onsubmit = validateBarForm;
function validateBarForm() {
var myValue = document.getElementById('myTextBox').value; // inside the getElementById, which element we want to get?
if (myValue.length === 0) {
alert('Please enter a real value in the TextBox');
return;
}
```
but it doesn't work? how can i also filter whitespace or blank not using required? | 2016/05/27 | [
"https://Stackoverflow.com/questions/37492145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6366860/"
] | Use the `outer` function:
```
nameMatrix <- outer(LETTERS[1:8], 1:12, paste, sep = "")
nameMatrix
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] "A1" "A2" "A3" "A4" "A5" "A6" "A7" "A8" "A9" "A10" "A11" "A12"
[2,] "B1" "B2" "B3" "B4" "B5" "B6" "B7" "B8" "B9" "B10" "B11" "B12"
[3,] "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "C10" "C11" "C12"
[4,] "D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10" "D11" "D12"
[5,] "E1" "E2" "E3" "E4" "E5" "E6" "E7" "E8" "E9" "E10" "E11" "E12"
[6,] "F1" "F2" "F3" "F4" "F5" "F6" "F7" "F8" "F9" "F10" "F11" "F12"
[7,] "G1" "G2" "G3" "G4" "G5" "G6" "G7" "G8" "G9" "G10" "G11" "G12"
[8,] "H1" "H2" "H3" "H4" "H5" "H6" "H7" "H8" "H9" "H10" "H11" "H12"
```
If you want to further assign them as some variable name, you can create a list:
```
li <- setNames(vector("list", 96), nameMatrix)
head(li)
$A1
NULL
$B1
NULL
$C1
NULL
$D1
NULL
$E1
NULL
$F1
NULL
```
And you can access these variables as `li$A1`, for example. | Something like this?
```
df <- expand.grid(LETTERS[1:8], 1:12)
v <- paste0(df[[1]], df[[2]])
m <- matrix(v, 8, 12)
> m
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] "A1" "A2" "A3" "A4" "A5" "A6" "A7" "A8" "A9" "A10" "A11" "A12"
[2,] "B1" "B2" "B3" "B4" "B5" "B6" "B7" "B8" "B9" "B10" "B11" "B12"
[3,] "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "C10" "C11" "C12"
[4,] "D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10" "D11" "D12"
[5,] "E1" "E2" "E3" "E4" "E5" "E6" "E7" "E8" "E9" "E10" "E11" "E12"
[6,] "F1" "F2" "F3" "F4" "F5" "F6" "F7" "F8" "F9" "F10" "F11" "F12"
[7,] "G1" "G2" "G3" "G4" "G5" "G6" "G7" "G8" "G9" "G10" "G11" "G12"
[8,] "H1" "H2" "H3" "H4" "H5" "H6" "H7" "H8" "H9" "H10" "H11" "H12"
``` |
37,492,145 | Usually i do:
```
onclick="myFunction()"
```
on my submit button, but what i want to do now on html is
```
<form id="myForm">
<input type="text" id="myTextBox" required> <!-- we're gonna use this id: myTextBox because we're using the getElementById() -->
<input type="submit" value="Click Me"> <!-- we call the function here -->
</form>
```
on JS
```
document.getElementById("myForm").onsubmit = validateBarForm;
function validateBarForm() {
var myValue = document.getElementById('myTextBox').value; // inside the getElementById, which element we want to get?
if (myValue.length === 0) {
alert('Please enter a real value in the TextBox');
return;
}
```
but it doesn't work? how can i also filter whitespace or blank not using required? | 2016/05/27 | [
"https://Stackoverflow.com/questions/37492145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6366860/"
] | Firstly, you can do this quickly and easily, in one line, with `sapply()`.
```
m1 <- t(sapply(LETTERS[1:8], paste0, 1:12, USE.NAMES = FALSE))
```
But you want to use a `for()` loop. So for that you can create an empty character matrix with desired dimensions first, then assign the rows in the loop.
```
m2 <- matrix("", 8, 12)
for(i in 1:8) {
m2[i, ] <- paste0(LETTERS[i], 1:12)
}
identical(m1, m2)
# [1] TRUE
```
`m1` and `m2` are the following matrix:
>
>
> ```
> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
> [1,] "A1" "A2" "A3" "A4" "A5" "A6" "A7" "A8" "A9" "A10" "A11" "A12"
> [2,] "B1" "B2" "B3" "B4" "B5" "B6" "B7" "B8" "B9" "B10" "B11" "B12"
> [3,] "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "C10" "C11" "C12"
> [4,] "D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10" "D11" "D12"
> [5,] "E1" "E2" "E3" "E4" "E5" "E6" "E7" "E8" "E9" "E10" "E11" "E12"
> [6,] "F1" "F2" "F3" "F4" "F5" "F6" "F7" "F8" "F9" "F10" "F11" "F12"
> [7,] "G1" "G2" "G3" "G4" "G5" "G6" "G7" "G8" "G9" "G10" "G11" "G12"
> [8,] "H1" "H2" "H3" "H4" "H5" "H6" "H7" "H8" "H9" "H10" "H11" "H12"
>
> ```
>
> | Something like this?
```
df <- expand.grid(LETTERS[1:8], 1:12)
v <- paste0(df[[1]], df[[2]])
m <- matrix(v, 8, 12)
> m
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] "A1" "A2" "A3" "A4" "A5" "A6" "A7" "A8" "A9" "A10" "A11" "A12"
[2,] "B1" "B2" "B3" "B4" "B5" "B6" "B7" "B8" "B9" "B10" "B11" "B12"
[3,] "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "C10" "C11" "C12"
[4,] "D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10" "D11" "D12"
[5,] "E1" "E2" "E3" "E4" "E5" "E6" "E7" "E8" "E9" "E10" "E11" "E12"
[6,] "F1" "F2" "F3" "F4" "F5" "F6" "F7" "F8" "F9" "F10" "F11" "F12"
[7,] "G1" "G2" "G3" "G4" "G5" "G6" "G7" "G8" "G9" "G10" "G11" "G12"
[8,] "H1" "H2" "H3" "H4" "H5" "H6" "H7" "H8" "H9" "H10" "H11" "H12"
``` |
37,492,145 | Usually i do:
```
onclick="myFunction()"
```
on my submit button, but what i want to do now on html is
```
<form id="myForm">
<input type="text" id="myTextBox" required> <!-- we're gonna use this id: myTextBox because we're using the getElementById() -->
<input type="submit" value="Click Me"> <!-- we call the function here -->
</form>
```
on JS
```
document.getElementById("myForm").onsubmit = validateBarForm;
function validateBarForm() {
var myValue = document.getElementById('myTextBox').value; // inside the getElementById, which element we want to get?
if (myValue.length === 0) {
alert('Please enter a real value in the TextBox');
return;
}
```
but it doesn't work? how can i also filter whitespace or blank not using required? | 2016/05/27 | [
"https://Stackoverflow.com/questions/37492145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6366860/"
] | Firstly, you can do this quickly and easily, in one line, with `sapply()`.
```
m1 <- t(sapply(LETTERS[1:8], paste0, 1:12, USE.NAMES = FALSE))
```
But you want to use a `for()` loop. So for that you can create an empty character matrix with desired dimensions first, then assign the rows in the loop.
```
m2 <- matrix("", 8, 12)
for(i in 1:8) {
m2[i, ] <- paste0(LETTERS[i], 1:12)
}
identical(m1, m2)
# [1] TRUE
```
`m1` and `m2` are the following matrix:
>
>
> ```
> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
> [1,] "A1" "A2" "A3" "A4" "A5" "A6" "A7" "A8" "A9" "A10" "A11" "A12"
> [2,] "B1" "B2" "B3" "B4" "B5" "B6" "B7" "B8" "B9" "B10" "B11" "B12"
> [3,] "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "C10" "C11" "C12"
> [4,] "D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10" "D11" "D12"
> [5,] "E1" "E2" "E3" "E4" "E5" "E6" "E7" "E8" "E9" "E10" "E11" "E12"
> [6,] "F1" "F2" "F3" "F4" "F5" "F6" "F7" "F8" "F9" "F10" "F11" "F12"
> [7,] "G1" "G2" "G3" "G4" "G5" "G6" "G7" "G8" "G9" "G10" "G11" "G12"
> [8,] "H1" "H2" "H3" "H4" "H5" "H6" "H7" "H8" "H9" "H10" "H11" "H12"
>
> ```
>
> | Use the `outer` function:
```
nameMatrix <- outer(LETTERS[1:8], 1:12, paste, sep = "")
nameMatrix
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] "A1" "A2" "A3" "A4" "A5" "A6" "A7" "A8" "A9" "A10" "A11" "A12"
[2,] "B1" "B2" "B3" "B4" "B5" "B6" "B7" "B8" "B9" "B10" "B11" "B12"
[3,] "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "C10" "C11" "C12"
[4,] "D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10" "D11" "D12"
[5,] "E1" "E2" "E3" "E4" "E5" "E6" "E7" "E8" "E9" "E10" "E11" "E12"
[6,] "F1" "F2" "F3" "F4" "F5" "F6" "F7" "F8" "F9" "F10" "F11" "F12"
[7,] "G1" "G2" "G3" "G4" "G5" "G6" "G7" "G8" "G9" "G10" "G11" "G12"
[8,] "H1" "H2" "H3" "H4" "H5" "H6" "H7" "H8" "H9" "H10" "H11" "H12"
```
If you want to further assign them as some variable name, you can create a list:
```
li <- setNames(vector("list", 96), nameMatrix)
head(li)
$A1
NULL
$B1
NULL
$C1
NULL
$D1
NULL
$E1
NULL
$F1
NULL
```
And you can access these variables as `li$A1`, for example. |
2,320,553 | I've a custom SplitButton implementation in which contains a ComboBox with several ComboBoxItems bound to commands. I can bind to the Name, and Text properties of the command just fine but have no way of binding the ComboBoxItem's **IsEnabled** property to the result of a Command's **CanExecute** method because it is a method. Is there some syntax that I'm unaware of for binding to methods or is there some trickery that will help me to bind to CanExecute.
By the way, I've thought about using a custom ValueConverter except for that I realized that I probably wouldn't receive any updates when CanExecute is re-evaluated since it is not a property and since my commands are not business objects. It's looking to me that I might have to create a ViewModel for a command at this point to use only within my custom SplitButton control but that seems a little overboard to me. | 2010/02/23 | [
"https://Stackoverflow.com/questions/2320553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83658/"
] | Another solution by ViewModel. Below is how I used a ViewModel to solve my problem. And please note that the nifty NotifyPropertyChanged method is part of my base ViewModel class.
```
public class RoutedUICommandViewModel : ViewModel
{
private RoutedUICommand _command;
private IInputElement _target;
public string Name { get { return _command.Name; } }
public string Text { get { return _command.Text; } }
public bool CanExecute
{
get
{
return _command.CanExecute(null, _target);
}
}
public RoutedUICommand Command { get { return _command; } }
public RoutedUICommandViewModel(ReportCommand command, IInputElement target)
{
_command = command;
_target = target;
_command.CanExecuteChanged += _command_CanExecuteChanged;
}
private void _command_CanExecuteChanged(object sender, EventArgs e)
{
base.NotifyPropertyChanged(() => this.CanExecute);
}
}
``` | You can put a button(if you dont have one in the controltemplate bound to the ICommand) inside ItemContainerStyle(ComboBoxItem style) and Bind the command to it
And add a Trigger to check the Button.IsEnabled and set that value to the ComboBoxItem. So here we used Button as a CommandSource just to get the IsEnabled from CanExeute. You can set the button's height and width to zero
```
<ControlTemplate....>
<Grid ...
<Button x:Name="dummyButton" Command="{Binding YourCommand}" ....
......
</Grid>
<ControlTemplate.Triggers>
<Trigger SourceName="dummyButton" Property="IsEnabled" Value="False">
<Setter Property="IsEnabled" Value="False"/>
</Trigger>
</ControlTemplate.Triggers>
``` |
2,320,553 | I've a custom SplitButton implementation in which contains a ComboBox with several ComboBoxItems bound to commands. I can bind to the Name, and Text properties of the command just fine but have no way of binding the ComboBoxItem's **IsEnabled** property to the result of a Command's **CanExecute** method because it is a method. Is there some syntax that I'm unaware of for binding to methods or is there some trickery that will help me to bind to CanExecute.
By the way, I've thought about using a custom ValueConverter except for that I realized that I probably wouldn't receive any updates when CanExecute is re-evaluated since it is not a property and since my commands are not business objects. It's looking to me that I might have to create a ViewModel for a command at this point to use only within my custom SplitButton control but that seems a little overboard to me. | 2010/02/23 | [
"https://Stackoverflow.com/questions/2320553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83658/"
] | You can put a button(if you dont have one in the controltemplate bound to the ICommand) inside ItemContainerStyle(ComboBoxItem style) and Bind the command to it
And add a Trigger to check the Button.IsEnabled and set that value to the ComboBoxItem. So here we used Button as a CommandSource just to get the IsEnabled from CanExeute. You can set the button's height and width to zero
```
<ControlTemplate....>
<Grid ...
<Button x:Name="dummyButton" Command="{Binding YourCommand}" ....
......
</Grid>
<ControlTemplate.Triggers>
<Trigger SourceName="dummyButton" Property="IsEnabled" Value="False">
<Setter Property="IsEnabled" Value="False"/>
</Trigger>
</ControlTemplate.Triggers>
``` | The way I solved this problem in my code was to add an event handler on the ComboBox for the PreviewMouseDown event. Here's the handler:
```
private void comboBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
ViewModel vm = this.DataContext as ViewModel;
if (vm != null)
{
if (!vm.CanChangeSelection())
{
e.Handled = true;
vm.RespondToFailedAttemptChangeUnits();
}
}
}
```
This works great for me in the case that I only need to do this in one location. It might get a little tedius if I had many pages like this.
Also, though I follow the MVVM pattern, I'm not a purist - I consider this to be a good practical solution that follows the spirit of MVVM, if not the letter. |
2,320,553 | I've a custom SplitButton implementation in which contains a ComboBox with several ComboBoxItems bound to commands. I can bind to the Name, and Text properties of the command just fine but have no way of binding the ComboBoxItem's **IsEnabled** property to the result of a Command's **CanExecute** method because it is a method. Is there some syntax that I'm unaware of for binding to methods or is there some trickery that will help me to bind to CanExecute.
By the way, I've thought about using a custom ValueConverter except for that I realized that I probably wouldn't receive any updates when CanExecute is re-evaluated since it is not a property and since my commands are not business objects. It's looking to me that I might have to create a ViewModel for a command at this point to use only within my custom SplitButton control but that seems a little overboard to me. | 2010/02/23 | [
"https://Stackoverflow.com/questions/2320553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83658/"
] | Another solution by ViewModel. Below is how I used a ViewModel to solve my problem. And please note that the nifty NotifyPropertyChanged method is part of my base ViewModel class.
```
public class RoutedUICommandViewModel : ViewModel
{
private RoutedUICommand _command;
private IInputElement _target;
public string Name { get { return _command.Name; } }
public string Text { get { return _command.Text; } }
public bool CanExecute
{
get
{
return _command.CanExecute(null, _target);
}
}
public RoutedUICommand Command { get { return _command; } }
public RoutedUICommandViewModel(ReportCommand command, IInputElement target)
{
_command = command;
_target = target;
_command.CanExecuteChanged += _command_CanExecuteChanged;
}
private void _command_CanExecuteChanged(object sender, EventArgs e)
{
base.NotifyPropertyChanged(() => this.CanExecute);
}
}
``` | I found [this discussion](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/66e49c70-e705-4019-95ea-c3d9f8937054/?prof=required) on MSDN forums where [Dr. WPF](http://drwpf.com/blog/) had recommended the use of an [attached behavior](http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx) to solve this exact problem. He gave the example below of how it would be used.
```
<Grid behaviors:CommandBehaviors.EnablingCommand="{x:Static commands:testcommand.test}">
. . .
</Grid>
```
Although this solution seems pretty nice I haven't been able to devote the time to understand exactly how this type of behavior would be implemented and what is involved. If anybody would like to elaborate please do otherwise I'll amend this answer with more details if I get the chance to explore this option. |
2,320,553 | I've a custom SplitButton implementation in which contains a ComboBox with several ComboBoxItems bound to commands. I can bind to the Name, and Text properties of the command just fine but have no way of binding the ComboBoxItem's **IsEnabled** property to the result of a Command's **CanExecute** method because it is a method. Is there some syntax that I'm unaware of for binding to methods or is there some trickery that will help me to bind to CanExecute.
By the way, I've thought about using a custom ValueConverter except for that I realized that I probably wouldn't receive any updates when CanExecute is re-evaluated since it is not a property and since my commands are not business objects. It's looking to me that I might have to create a ViewModel for a command at this point to use only within my custom SplitButton control but that seems a little overboard to me. | 2010/02/23 | [
"https://Stackoverflow.com/questions/2320553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83658/"
] | Another solution by ViewModel. Below is how I used a ViewModel to solve my problem. And please note that the nifty NotifyPropertyChanged method is part of my base ViewModel class.
```
public class RoutedUICommandViewModel : ViewModel
{
private RoutedUICommand _command;
private IInputElement _target;
public string Name { get { return _command.Name; } }
public string Text { get { return _command.Text; } }
public bool CanExecute
{
get
{
return _command.CanExecute(null, _target);
}
}
public RoutedUICommand Command { get { return _command; } }
public RoutedUICommandViewModel(ReportCommand command, IInputElement target)
{
_command = command;
_target = target;
_command.CanExecuteChanged += _command_CanExecuteChanged;
}
private void _command_CanExecuteChanged(object sender, EventArgs e)
{
base.NotifyPropertyChanged(() => this.CanExecute);
}
}
``` | The way I solved this problem in my code was to add an event handler on the ComboBox for the PreviewMouseDown event. Here's the handler:
```
private void comboBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
ViewModel vm = this.DataContext as ViewModel;
if (vm != null)
{
if (!vm.CanChangeSelection())
{
e.Handled = true;
vm.RespondToFailedAttemptChangeUnits();
}
}
}
```
This works great for me in the case that I only need to do this in one location. It might get a little tedius if I had many pages like this.
Also, though I follow the MVVM pattern, I'm not a purist - I consider this to be a good practical solution that follows the spirit of MVVM, if not the letter. |
2,320,553 | I've a custom SplitButton implementation in which contains a ComboBox with several ComboBoxItems bound to commands. I can bind to the Name, and Text properties of the command just fine but have no way of binding the ComboBoxItem's **IsEnabled** property to the result of a Command's **CanExecute** method because it is a method. Is there some syntax that I'm unaware of for binding to methods or is there some trickery that will help me to bind to CanExecute.
By the way, I've thought about using a custom ValueConverter except for that I realized that I probably wouldn't receive any updates when CanExecute is re-evaluated since it is not a property and since my commands are not business objects. It's looking to me that I might have to create a ViewModel for a command at this point to use only within my custom SplitButton control but that seems a little overboard to me. | 2010/02/23 | [
"https://Stackoverflow.com/questions/2320553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83658/"
] | I found [this discussion](http://social.msdn.microsoft.com/forums/en-US/wpf/thread/66e49c70-e705-4019-95ea-c3d9f8937054/?prof=required) on MSDN forums where [Dr. WPF](http://drwpf.com/blog/) had recommended the use of an [attached behavior](http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx) to solve this exact problem. He gave the example below of how it would be used.
```
<Grid behaviors:CommandBehaviors.EnablingCommand="{x:Static commands:testcommand.test}">
. . .
</Grid>
```
Although this solution seems pretty nice I haven't been able to devote the time to understand exactly how this type of behavior would be implemented and what is involved. If anybody would like to elaborate please do otherwise I'll amend this answer with more details if I get the chance to explore this option. | The way I solved this problem in my code was to add an event handler on the ComboBox for the PreviewMouseDown event. Here's the handler:
```
private void comboBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
ViewModel vm = this.DataContext as ViewModel;
if (vm != null)
{
if (!vm.CanChangeSelection())
{
e.Handled = true;
vm.RespondToFailedAttemptChangeUnits();
}
}
}
```
This works great for me in the case that I only need to do this in one location. It might get a little tedius if I had many pages like this.
Also, though I follow the MVVM pattern, I'm not a purist - I consider this to be a good practical solution that follows the spirit of MVVM, if not the letter. |
74,388,661 | how can i sort 2D mutable list of array by the first element of array?
```
val books = mutableListOf<Any>(
listof("abc","b",1),
listof("abb","y",2),
listof("abcl"."i",3)
)
```
i want to get sort this mutablelist by alphabetical order of the first element of each list.
output should be
```
[listof("abb","y",2), listof("abc","b",1), listof("abcl"."i",3) ]
``` | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20463529/"
] | Using `sed`
```
$ sed '/e/{s/1 2 3/4 5 6/;h;d};/k/{G}' input_file
a b c d 1 2 3
i j k l 1 2 3
e f g h 4 5 6
m n o p 1 2 3
``` | This `awk` should work for you:
```bash
awk '
/(^| )e( |$)/ {
sub(/1 2 3/, "4 5 6")
p = $0
next
}
1
/(^| )k( |$)/ {
print p
p = ""
}' file
a b c d 1 2 3
i j k l 1 2 3
e f g h 4 5 6
m n o p 1 2 3
``` |
74,388,661 | how can i sort 2D mutable list of array by the first element of array?
```
val books = mutableListOf<Any>(
listof("abc","b",1),
listof("abb","y",2),
listof("abcl"."i",3)
)
```
i want to get sort this mutablelist by alphabetical order of the first element of each list.
output should be
```
[listof("abb","y",2), listof("abc","b",1), listof("abcl"."i",3) ]
``` | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20463529/"
] | Here is a GNU awk solution:
```
awk '
/\<e\>/{
s=$0
sub("1 2 3", "4 5 6", s)
next
}
/\<k\>/ && s {
printf("%s\n%s\n",$0,s)
next
} 1
' file
```
Or POSIX awk:
```
awk '
function has(x) {
for(i=1; i<=NF; i++) if ($i==x) return 1
return 0
}
has("e") {
s=$0
sub("1 2 3", "4 5 6", s)
next
}
has("k") && s {
printf("%s\n%s\n",$0,s)
next
} 1
' file
```
Either prints:
```
a b c d 1 2 3
i j k l 1 2 3
e f g h 4 5 6
m n o p 1 2 3
```
---
This works regardless of the order of `e` and `k` in the file:
```
awk '
function has(x) {
for(i=1; i<=NF; i++) if ($i==x) return 1
return 0
}
has("e") {
s=$0
sub("1 2 3", "4 5 6", s)
next
}
FNR<NR && has("k") && s {
printf("%s\n%s\n",$0,s)
s=""
next
}
FNR<NR
' file file
``` | This `awk` should work for you:
```bash
awk '
/(^| )e( |$)/ {
sub(/1 2 3/, "4 5 6")
p = $0
next
}
1
/(^| )k( |$)/ {
print p
p = ""
}' file
a b c d 1 2 3
i j k l 1 2 3
e f g h 4 5 6
m n o p 1 2 3
``` |
74,388,661 | how can i sort 2D mutable list of array by the first element of array?
```
val books = mutableListOf<Any>(
listof("abc","b",1),
listof("abb","y",2),
listof("abcl"."i",3)
)
```
i want to get sort this mutablelist by alphabetical order of the first element of each list.
output should be
```
[listof("abb","y",2), listof("abc","b",1), listof("abcl"."i",3) ]
``` | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20463529/"
] | Using `sed`
```
$ sed '/e/{s/1 2 3/4 5 6/;h;d};/k/{G}' input_file
a b c d 1 2 3
i j k l 1 2 3
e f g h 4 5 6
m n o p 1 2 3
``` | Here is a GNU awk solution:
```
awk '
/\<e\>/{
s=$0
sub("1 2 3", "4 5 6", s)
next
}
/\<k\>/ && s {
printf("%s\n%s\n",$0,s)
next
} 1
' file
```
Or POSIX awk:
```
awk '
function has(x) {
for(i=1; i<=NF; i++) if ($i==x) return 1
return 0
}
has("e") {
s=$0
sub("1 2 3", "4 5 6", s)
next
}
has("k") && s {
printf("%s\n%s\n",$0,s)
next
} 1
' file
```
Either prints:
```
a b c d 1 2 3
i j k l 1 2 3
e f g h 4 5 6
m n o p 1 2 3
```
---
This works regardless of the order of `e` and `k` in the file:
```
awk '
function has(x) {
for(i=1; i<=NF; i++) if ($i==x) return 1
return 0
}
has("e") {
s=$0
sub("1 2 3", "4 5 6", s)
next
}
FNR<NR && has("k") && s {
printf("%s\n%s\n",$0,s)
s=""
next
}
FNR<NR
' file file
``` |
74,388,661 | how can i sort 2D mutable list of array by the first element of array?
```
val books = mutableListOf<Any>(
listof("abc","b",1),
listof("abb","y",2),
listof("abcl"."i",3)
)
```
i want to get sort this mutablelist by alphabetical order of the first element of each list.
output should be
```
[listof("abb","y",2), listof("abc","b",1), listof("abcl"."i",3) ]
``` | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20463529/"
] | Using `sed`
```
$ sed '/e/{s/1 2 3/4 5 6/;h;d};/k/{G}' input_file
a b c d 1 2 3
i j k l 1 2 3
e f g h 4 5 6
m n o p 1 2 3
``` | This might work for you (GNU sed):
```
sed -n '/e/{s/1 2 3/4 5 6/;s#.*#/e/d;/k/s/.*/\&\\n&/#p};' file | sed -f - file
```
Design a sed script by passing the file twice and applying the sed instructions from the first pass to the second.
---
Another solution is to use ed:
```
cat <<\! | ed file
/e/s/1 2 3/4 5 6/
/e/m/k/
wq
!
```
Or if you prefer:
```
<<<$'/e/s/1 2 3/4 5 6/\n.m/k/\nwq' ed -s file
``` |
74,388,661 | how can i sort 2D mutable list of array by the first element of array?
```
val books = mutableListOf<Any>(
listof("abc","b",1),
listof("abb","y",2),
listof("abcl"."i",3)
)
```
i want to get sort this mutablelist by alphabetical order of the first element of each list.
output should be
```
[listof("abb","y",2), listof("abc","b",1), listof("abcl"."i",3) ]
``` | 2022/11/10 | [
"https://Stackoverflow.com/questions/74388661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20463529/"
] | Here is a GNU awk solution:
```
awk '
/\<e\>/{
s=$0
sub("1 2 3", "4 5 6", s)
next
}
/\<k\>/ && s {
printf("%s\n%s\n",$0,s)
next
} 1
' file
```
Or POSIX awk:
```
awk '
function has(x) {
for(i=1; i<=NF; i++) if ($i==x) return 1
return 0
}
has("e") {
s=$0
sub("1 2 3", "4 5 6", s)
next
}
has("k") && s {
printf("%s\n%s\n",$0,s)
next
} 1
' file
```
Either prints:
```
a b c d 1 2 3
i j k l 1 2 3
e f g h 4 5 6
m n o p 1 2 3
```
---
This works regardless of the order of `e` and `k` in the file:
```
awk '
function has(x) {
for(i=1; i<=NF; i++) if ($i==x) return 1
return 0
}
has("e") {
s=$0
sub("1 2 3", "4 5 6", s)
next
}
FNR<NR && has("k") && s {
printf("%s\n%s\n",$0,s)
s=""
next
}
FNR<NR
' file file
``` | This might work for you (GNU sed):
```
sed -n '/e/{s/1 2 3/4 5 6/;s#.*#/e/d;/k/s/.*/\&\\n&/#p};' file | sed -f - file
```
Design a sed script by passing the file twice and applying the sed instructions from the first pass to the second.
---
Another solution is to use ed:
```
cat <<\! | ed file
/e/s/1 2 3/4 5 6/
/e/m/k/
wq
!
```
Or if you prefer:
```
<<<$'/e/s/1 2 3/4 5 6/\n.m/k/\nwq' ed -s file
``` |
10,858,810 | I am working on a project which requires making discrete values out of numeric quantities all over the place. At present I'm using cascaded if / elseif / else constructs, for example:
```
if M > 6
evidence{2} = 3;
elseif M > 2
evidence{2} = 2;
else
evidence{2} = 1;
end
```
I want to replace this with a more maintainable (and concise) syntax, but before I come up with my own idiom I would like to know if there is already a convenient function or syntax available in MATLAB. Any suggestions? | 2012/06/02 | [
"https://Stackoverflow.com/questions/10858810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415540/"
] | How about:
```
evidence{2} = sum( M > [-inf 2 6] )
```
Basically, you are searching for the interval in which M lies: (-inf,2], (2,6], (6,+inf)
So even if your values were not 1/2/3, you could then map the range index found to some other values... | ```
evidence{2} = 1 + (M > 2) + (M > 6);
```
but in my opinion, it is less maintainable. Yours is better. |
51,388,862 | Basically I want to do a check if a directory exists then run this section, if not exit.
The script I have is:
```
$Path = Test-Path c:\temp\First
if ($Path -eq "False")
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq "true")
{
Write-Host " what the smokes"
}
```
But it returns nothing. | 2018/07/17 | [
"https://Stackoverflow.com/questions/51388862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964812/"
] | The error comes from the fact that the return value of `Test-Path` is a Boolean type.
Hence, **don't compare it to strings representation of Boolean but rather to the actual `$false`/`$true` values.** Like so,
```
$Path = Test-Path c:\temp\First
if ($Path -eq $false)
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq $true)
{
Write-Host " what the smokes"
}
```
Also, note that here you could use an `else` statement here.
Alternatively, you could use the syntax proposed in @user9569124 answer,
```
$Path = Test-Path c:\temp\First
if (!$Path)
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path)
{
Write-Host " what the smokes"
}
``` | If I'm not mistaken, one can simple say:
`if($Path)`
OR
`if(!$Path)`
But I might be wrong as I can't test atm.
Additionally there is the `Test-Path` cmdlet available. Unfortunately I cannot describe the difference or suggest the most suitable method without knowing the case and scenario.
[EDITED TO CLARIFY ANSWER]
```
$Path = "C:\"
if($Path)
{
write-host "The path or file exists"
}
else
{
write-host "The path or file isn't there silly bear!"
}
```
Hope that adds clarity. With this method, no cmdlets needed. The returned boolean is interpreted for you automatically and runs code blocks if it meets the criteria of the test, in this case if the path `C:\` exists. This would be true of files in longer file paths, `C:\...\...\...\...\file.txt` |
51,388,862 | Basically I want to do a check if a directory exists then run this section, if not exit.
The script I have is:
```
$Path = Test-Path c:\temp\First
if ($Path -eq "False")
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq "true")
{
Write-Host " what the smokes"
}
```
But it returns nothing. | 2018/07/17 | [
"https://Stackoverflow.com/questions/51388862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964812/"
] | The error comes from the fact that the return value of `Test-Path` is a Boolean type.
Hence, **don't compare it to strings representation of Boolean but rather to the actual `$false`/`$true` values.** Like so,
```
$Path = Test-Path c:\temp\First
if ($Path -eq $false)
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq $true)
{
Write-Host " what the smokes"
}
```
Also, note that here you could use an `else` statement here.
Alternatively, you could use the syntax proposed in @user9569124 answer,
```
$Path = Test-Path c:\temp\First
if (!$Path)
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path)
{
Write-Host " what the smokes"
}
``` | In a comparison operation PowerShell automatically converts the second operand to the type of the first operand. Since you're comparing a boolean value to a string, the string will be cast to a boolean value. Empty strings will be cast to `$false` and non-empty strings will be cast to `$true`. Jeffrey Snover wrote an article [*"Boolean Values and Operators"*](https://devblogs.microsoft.com/powershell/boolean-values-and-operators/) about these automatic conversions that you can check for further details.
As a result this behavior has the (seemingly paradox) effect that each of your comparisons will evaluate to the value of your variable:
```
PS C:\> **$false -eq 'False'**
False
PS C:\> **$false -eq 'True'**
False
PS C:\> **$true -eq 'False'**
True
PS C:\> **$true -eq 'True'**
True
```
Essentially that means that if your `Test-Path` statements evaluates to `$false` *neither* of your conditions will match.
As others have pointed out you can fix the issue by comparing your variable to actual boolean values, or by just using the variable by itself (since it already contains a boolean value that can be evaluated directly). However, you need to be careful with the latter approach. In this case it won't make a difference, but in other situations automatic conversion of different values to the same boolean value might not be the desired behavior. For instance, `$null`, 0, empty string and empty array are all interpreted as a boolean value `$false`, but can have quite different semantics depending on the logic in your code.
Also, there is no need to store the result of `Test-Path` in a variable first. You can put the expression directly into the condition. And since there are only two possible values (a file/folder either exists or doesn't exist), there is no need to compare twice, so your code could be reduced to something like this:
```
if (Test-Path 'C:\temp\First') {
Write-Host 'what the smokes'
} else {
Write-Host 'notthere' -ForegroundColor Yellow
}
``` |
51,388,862 | Basically I want to do a check if a directory exists then run this section, if not exit.
The script I have is:
```
$Path = Test-Path c:\temp\First
if ($Path -eq "False")
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq "true")
{
Write-Host " what the smokes"
}
```
But it returns nothing. | 2018/07/17 | [
"https://Stackoverflow.com/questions/51388862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964812/"
] | The error comes from the fact that the return value of `Test-Path` is a Boolean type.
Hence, **don't compare it to strings representation of Boolean but rather to the actual `$false`/`$true` values.** Like so,
```
$Path = Test-Path c:\temp\First
if ($Path -eq $false)
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq $true)
{
Write-Host " what the smokes"
}
```
Also, note that here you could use an `else` statement here.
Alternatively, you could use the syntax proposed in @user9569124 answer,
```
$Path = Test-Path c:\temp\First
if (!$Path)
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path)
{
Write-Host " what the smokes"
}
``` | To make some things clear, always use Test-Path (or Test-Path with Leaf to check for a file).
**Examples I've tested:**
```
$File = "c:\path\file.exe"
$IsPath = Test-Path -Path $File -PathType Leaf
# using -Not or ! to check if a file doesn't exist
if (-Not(Test-Path -Path $File -PathType Leaf)) {
Write-Host "1 Not Found!"
}
if (!(Test-Path -Path $File -PathType Leaf)) {
Write-Host "2 Not Found!"
}
# using -Not or ! to check if a file doesn't exist with the result of Test-Path on a file
If (!$IsPath) {
Write-Host "3 Not Found!"
}
If (-Not $IsPath) {
Write-Host "4 Not Found!"
}
# $null checks must be to the left, why not keep same for all?
If ($true -eq $IsPath) {
Write-Host "1 Found!"
}
# Checking if true shorthand method
If ($IsPath) {
Write-Host "2 Found!"
}
if (Test-Path -Path $File -PathType Leaf) {
Write-Host "3 Found!"
}
``` |
51,388,862 | Basically I want to do a check if a directory exists then run this section, if not exit.
The script I have is:
```
$Path = Test-Path c:\temp\First
if ($Path -eq "False")
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq "true")
{
Write-Host " what the smokes"
}
```
But it returns nothing. | 2018/07/17 | [
"https://Stackoverflow.com/questions/51388862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964812/"
] | In a comparison operation PowerShell automatically converts the second operand to the type of the first operand. Since you're comparing a boolean value to a string, the string will be cast to a boolean value. Empty strings will be cast to `$false` and non-empty strings will be cast to `$true`. Jeffrey Snover wrote an article [*"Boolean Values and Operators"*](https://devblogs.microsoft.com/powershell/boolean-values-and-operators/) about these automatic conversions that you can check for further details.
As a result this behavior has the (seemingly paradox) effect that each of your comparisons will evaluate to the value of your variable:
```
PS C:\> **$false -eq 'False'**
False
PS C:\> **$false -eq 'True'**
False
PS C:\> **$true -eq 'False'**
True
PS C:\> **$true -eq 'True'**
True
```
Essentially that means that if your `Test-Path` statements evaluates to `$false` *neither* of your conditions will match.
As others have pointed out you can fix the issue by comparing your variable to actual boolean values, or by just using the variable by itself (since it already contains a boolean value that can be evaluated directly). However, you need to be careful with the latter approach. In this case it won't make a difference, but in other situations automatic conversion of different values to the same boolean value might not be the desired behavior. For instance, `$null`, 0, empty string and empty array are all interpreted as a boolean value `$false`, but can have quite different semantics depending on the logic in your code.
Also, there is no need to store the result of `Test-Path` in a variable first. You can put the expression directly into the condition. And since there are only two possible values (a file/folder either exists or doesn't exist), there is no need to compare twice, so your code could be reduced to something like this:
```
if (Test-Path 'C:\temp\First') {
Write-Host 'what the smokes'
} else {
Write-Host 'notthere' -ForegroundColor Yellow
}
``` | If I'm not mistaken, one can simple say:
`if($Path)`
OR
`if(!$Path)`
But I might be wrong as I can't test atm.
Additionally there is the `Test-Path` cmdlet available. Unfortunately I cannot describe the difference or suggest the most suitable method without knowing the case and scenario.
[EDITED TO CLARIFY ANSWER]
```
$Path = "C:\"
if($Path)
{
write-host "The path or file exists"
}
else
{
write-host "The path or file isn't there silly bear!"
}
```
Hope that adds clarity. With this method, no cmdlets needed. The returned boolean is interpreted for you automatically and runs code blocks if it meets the criteria of the test, in this case if the path `C:\` exists. This would be true of files in longer file paths, `C:\...\...\...\...\file.txt` |
51,388,862 | Basically I want to do a check if a directory exists then run this section, if not exit.
The script I have is:
```
$Path = Test-Path c:\temp\First
if ($Path -eq "False")
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq "true")
{
Write-Host " what the smokes"
}
```
But it returns nothing. | 2018/07/17 | [
"https://Stackoverflow.com/questions/51388862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964812/"
] | If I'm not mistaken, one can simple say:
`if($Path)`
OR
`if(!$Path)`
But I might be wrong as I can't test atm.
Additionally there is the `Test-Path` cmdlet available. Unfortunately I cannot describe the difference or suggest the most suitable method without knowing the case and scenario.
[EDITED TO CLARIFY ANSWER]
```
$Path = "C:\"
if($Path)
{
write-host "The path or file exists"
}
else
{
write-host "The path or file isn't there silly bear!"
}
```
Hope that adds clarity. With this method, no cmdlets needed. The returned boolean is interpreted for you automatically and runs code blocks if it meets the criteria of the test, in this case if the path `C:\` exists. This would be true of files in longer file paths, `C:\...\...\...\...\file.txt` | To make some things clear, always use Test-Path (or Test-Path with Leaf to check for a file).
**Examples I've tested:**
```
$File = "c:\path\file.exe"
$IsPath = Test-Path -Path $File -PathType Leaf
# using -Not or ! to check if a file doesn't exist
if (-Not(Test-Path -Path $File -PathType Leaf)) {
Write-Host "1 Not Found!"
}
if (!(Test-Path -Path $File -PathType Leaf)) {
Write-Host "2 Not Found!"
}
# using -Not or ! to check if a file doesn't exist with the result of Test-Path on a file
If (!$IsPath) {
Write-Host "3 Not Found!"
}
If (-Not $IsPath) {
Write-Host "4 Not Found!"
}
# $null checks must be to the left, why not keep same for all?
If ($true -eq $IsPath) {
Write-Host "1 Found!"
}
# Checking if true shorthand method
If ($IsPath) {
Write-Host "2 Found!"
}
if (Test-Path -Path $File -PathType Leaf) {
Write-Host "3 Found!"
}
``` |
51,388,862 | Basically I want to do a check if a directory exists then run this section, if not exit.
The script I have is:
```
$Path = Test-Path c:\temp\First
if ($Path -eq "False")
{
Write-Host "notthere" -ForegroundColor Yellow
}
elseif ($Path -eq "true")
{
Write-Host " what the smokes"
}
```
But it returns nothing. | 2018/07/17 | [
"https://Stackoverflow.com/questions/51388862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964812/"
] | In a comparison operation PowerShell automatically converts the second operand to the type of the first operand. Since you're comparing a boolean value to a string, the string will be cast to a boolean value. Empty strings will be cast to `$false` and non-empty strings will be cast to `$true`. Jeffrey Snover wrote an article [*"Boolean Values and Operators"*](https://devblogs.microsoft.com/powershell/boolean-values-and-operators/) about these automatic conversions that you can check for further details.
As a result this behavior has the (seemingly paradox) effect that each of your comparisons will evaluate to the value of your variable:
```
PS C:\> **$false -eq 'False'**
False
PS C:\> **$false -eq 'True'**
False
PS C:\> **$true -eq 'False'**
True
PS C:\> **$true -eq 'True'**
True
```
Essentially that means that if your `Test-Path` statements evaluates to `$false` *neither* of your conditions will match.
As others have pointed out you can fix the issue by comparing your variable to actual boolean values, or by just using the variable by itself (since it already contains a boolean value that can be evaluated directly). However, you need to be careful with the latter approach. In this case it won't make a difference, but in other situations automatic conversion of different values to the same boolean value might not be the desired behavior. For instance, `$null`, 0, empty string and empty array are all interpreted as a boolean value `$false`, but can have quite different semantics depending on the logic in your code.
Also, there is no need to store the result of `Test-Path` in a variable first. You can put the expression directly into the condition. And since there are only two possible values (a file/folder either exists or doesn't exist), there is no need to compare twice, so your code could be reduced to something like this:
```
if (Test-Path 'C:\temp\First') {
Write-Host 'what the smokes'
} else {
Write-Host 'notthere' -ForegroundColor Yellow
}
``` | To make some things clear, always use Test-Path (or Test-Path with Leaf to check for a file).
**Examples I've tested:**
```
$File = "c:\path\file.exe"
$IsPath = Test-Path -Path $File -PathType Leaf
# using -Not or ! to check if a file doesn't exist
if (-Not(Test-Path -Path $File -PathType Leaf)) {
Write-Host "1 Not Found!"
}
if (!(Test-Path -Path $File -PathType Leaf)) {
Write-Host "2 Not Found!"
}
# using -Not or ! to check if a file doesn't exist with the result of Test-Path on a file
If (!$IsPath) {
Write-Host "3 Not Found!"
}
If (-Not $IsPath) {
Write-Host "4 Not Found!"
}
# $null checks must be to the left, why not keep same for all?
If ($true -eq $IsPath) {
Write-Host "1 Found!"
}
# Checking if true shorthand method
If ($IsPath) {
Write-Host "2 Found!"
}
if (Test-Path -Path $File -PathType Leaf) {
Write-Host "3 Found!"
}
``` |
611,046 | I have read this question:
<https://physics.stackexchange.com/a/561125/132371>
where cuevobat says:
>
> You will note if you examine the tables on conductors that some metals that are good electrical conductors also conduct heat well for the same reason - heat is also a vibration of electrons and depends on free electrons to easily transmit heat.
>
>
>
This says that (the conduction of) both heat and electricity depend on free electrons.
But we know that metals conduct electricity close to the speed of light.
Now if I have a metal wire, and heat one end of the wire (various ways, for example put it into hot water), the other end will heat up very slowly. Yet if you connect one end of the wire to electricity (outlet), electricity will flow through it and reach the other end (if you connect something to it, like you touch it) with speeds close to the speed of light.
What causes this difference between the speeds of the propagation of those two phenomena (electricity and heat) in metals?
Just to clarify, both depend on free electrons, so why don't both propagate at comparable speeds?
So far, I have two very interesting answers, and we got so far to the point where I see that in the case of:
1. electricity, the electrons "push" each other, and this transfer of momentum propagates close to the speed of light
[](https://i.stack.imgur.com/CybWr.gif)
2. heat, the electrons transfer energy (hot electrons colliding with cold electrons), and this is much slower
[](https://i.stack.imgur.com/nyS07.jpg)
So now basically, the question comes down to why is transfer of momentum faster then transfer of energy between the free electrons?
Question:
1. Why do metals conduct electricity faster than heat? | 2021/01/29 | [
"https://physics.stackexchange.com/questions/611046",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/132371/"
] | >
> Why do metals conduct electricity faster than heat?
>
>
>
If by electricity you mean the flow of current, then the question only makes sense (at least to me) under transient conditions with respect to how quickly steady heat flow is establish vs how quickly steady current flow is established, as discussed below. Under steady state conditions it's an apples and oranges comparison since current is the rate of charge transport and heat is the rate of energy transfer.
**Transient Conditions:**
Take a metal conductor, a wire. At time t=0 you apply a voltage difference between the the ends of the wire. An electric field is almost instantaneously established and electrons almost instantaneously begin moving throughout the conductor with some average drift velocity. So current is almost instantaneous throughout the conductor.
Take the same wire initially at room temperature throughout. The mobile electrons in the wire will have the same random thermal motion throughout the wire roughly proportional to the temperature. Now at time t=0 establish contact between one end of the wire with a high temperature constant temperature source with the other end in contact with a constant lower temperature equal to the room temperature. Thermally insulate the circumference of the wire to prevent heat transfer to the surrounding air.
The difference in temperature between the ends is analogous to the potential difference. The random thermal motion of the electrons near the high temperature end will increase. Through collisions with the electrons farther away from the hot end increased thermal motion will progress towards the lower temperature end until a linear temperature gradient is theoretically established along the length of the conductor. However, unlike the situation for current, this progression of thermal motion will not be instantaneous as in the case of the collective motion of charge. It will take time.
**Steady State Conditions:**
The applicable steady heat flow equation is
$$\dot Q=\frac {k\_{t}A(T\_{H}-T\_{L})}{L}$$
The applicable current flow equation is
$$I=\frac {k\_{e}A(V\_{H}-V\_{L})}{L}$$
The equations are roughly analogous with rate of heat transfer $\dot Q$ analogous to rate of charge transport $I$, thermal conductivity $k\_{t}$ analogous to electrical conductivity $k\_e$, and temperature difference $T\_{H}-T\_{L}$ analogous to potential difference $V\_{H}-V\_{L}$. The length and cross sectional area of the wire being $L$ and $A$, respectively.
But current and rate of heat transfer are different things, so it's comparing apples to oranges.
>
> "However, unlike the situation for current, this progression of
> thermal motion will not be instantaneous as in the case of the
> collective motion of charge. It will take time." Can you please
> elaborate on this a little, why this is, this is key to my question.
>
>
>
First, the motion of electrons in the case of current flow is collective motion, called drift velocity, which is proportional to current. That motion is due to the unidirectional electric force applied by the electric field to the electrons. That electric field travels in the conductor near the speed of light. So all the electrons immediately start moving.
On the other hand, the thermal motion of electrons when the conductor is heated is random. They don't collectively move along the conductor. Electrons with high thermal motion (random velocities) near the heat source collide with nearby electrons away from the source having less thermal motion (lower temperature) transferring kinetic energy to those electrons raising the temperature of conductor further from the source. They in turn collide with electrons nearby them and so forth until the thermal motion of all the electrons in the conductor has increased raising the temperature. All this takes time.
Check out the following video showing how the temperature of a heated conductor slowly increases along the length of the conductor as evidenced by color of the conductor.
<https://www.youtube.com/watch?v=y-ptY0YG9RI>
Hope this helps. | Sippose you have hosepipe full of water, and turn on the tap. You see that water comes out of the nozzle end of the pipe almost immediately. The "push" from the water at the tap end reaches the water at the nozzle end at the speed of sound in water --- more than 1,000 feet per second. The water entering the pipe at the tap takes much longer to reach the far end. It travels at a few feet per second. If the water in the pipe was cold, and it is a hot tap that you have connected, you have to wait the longer time for the hot water to reach the nozzle. In a wire the "speed of sound" for the electrons is the speed of light. At a current of one ampere the electrons drift at a few inches per second. If there is no actual current, the heat travel only by hot electrons hitting cold electrons, and the heat travels even slower. |
611,046 | I have read this question:
<https://physics.stackexchange.com/a/561125/132371>
where cuevobat says:
>
> You will note if you examine the tables on conductors that some metals that are good electrical conductors also conduct heat well for the same reason - heat is also a vibration of electrons and depends on free electrons to easily transmit heat.
>
>
>
This says that (the conduction of) both heat and electricity depend on free electrons.
But we know that metals conduct electricity close to the speed of light.
Now if I have a metal wire, and heat one end of the wire (various ways, for example put it into hot water), the other end will heat up very slowly. Yet if you connect one end of the wire to electricity (outlet), electricity will flow through it and reach the other end (if you connect something to it, like you touch it) with speeds close to the speed of light.
What causes this difference between the speeds of the propagation of those two phenomena (electricity and heat) in metals?
Just to clarify, both depend on free electrons, so why don't both propagate at comparable speeds?
So far, I have two very interesting answers, and we got so far to the point where I see that in the case of:
1. electricity, the electrons "push" each other, and this transfer of momentum propagates close to the speed of light
[](https://i.stack.imgur.com/CybWr.gif)
2. heat, the electrons transfer energy (hot electrons colliding with cold electrons), and this is much slower
[](https://i.stack.imgur.com/nyS07.jpg)
So now basically, the question comes down to why is transfer of momentum faster then transfer of energy between the free electrons?
Question:
1. Why do metals conduct electricity faster than heat? | 2021/01/29 | [
"https://physics.stackexchange.com/questions/611046",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/132371/"
] | In the case of heat transfer, the wire stays electrically neutral, so one electron can only interact with other electrons in it's close vicinity by collisions, but has no effect on electrons far away. So the signal about the increased temperature (i.e. higher thermal velocity) travels by collisions from one electron to the next. In the best case scenario the random collsions happen such that the next electron always travels in the right direction. Then the information about the increased temperature can travel at most with a speed equivalent to the electrons thermal velocity, which is about 100 km/s or 0.3% of the speed of light.
In the case of electricity, you push additional electrons in one side of the wire. This charge surplus will cause an electric field to form which travels at the speed of light. So this electric field can almost instantaneously affect all electrons in the wire, even electrons far away on the other end of the wire. All electrons will start moving in the same direction driven by this electric field.
So in short, heat transfer is analogous to sending a message through a relay race, while electricity transfer is equivalent to cheating in that race by calling the person on the end of the line with your phone and telling him the message. | Sippose you have hosepipe full of water, and turn on the tap. You see that water comes out of the nozzle end of the pipe almost immediately. The "push" from the water at the tap end reaches the water at the nozzle end at the speed of sound in water --- more than 1,000 feet per second. The water entering the pipe at the tap takes much longer to reach the far end. It travels at a few feet per second. If the water in the pipe was cold, and it is a hot tap that you have connected, you have to wait the longer time for the hot water to reach the nozzle. In a wire the "speed of sound" for the electrons is the speed of light. At a current of one ampere the electrons drift at a few inches per second. If there is no actual current, the heat travel only by hot electrons hitting cold electrons, and the heat travels even slower. |
611,046 | I have read this question:
<https://physics.stackexchange.com/a/561125/132371>
where cuevobat says:
>
> You will note if you examine the tables on conductors that some metals that are good electrical conductors also conduct heat well for the same reason - heat is also a vibration of electrons and depends on free electrons to easily transmit heat.
>
>
>
This says that (the conduction of) both heat and electricity depend on free electrons.
But we know that metals conduct electricity close to the speed of light.
Now if I have a metal wire, and heat one end of the wire (various ways, for example put it into hot water), the other end will heat up very slowly. Yet if you connect one end of the wire to electricity (outlet), electricity will flow through it and reach the other end (if you connect something to it, like you touch it) with speeds close to the speed of light.
What causes this difference between the speeds of the propagation of those two phenomena (electricity and heat) in metals?
Just to clarify, both depend on free electrons, so why don't both propagate at comparable speeds?
So far, I have two very interesting answers, and we got so far to the point where I see that in the case of:
1. electricity, the electrons "push" each other, and this transfer of momentum propagates close to the speed of light
[](https://i.stack.imgur.com/CybWr.gif)
2. heat, the electrons transfer energy (hot electrons colliding with cold electrons), and this is much slower
[](https://i.stack.imgur.com/nyS07.jpg)
So now basically, the question comes down to why is transfer of momentum faster then transfer of energy between the free electrons?
Question:
1. Why do metals conduct electricity faster than heat? | 2021/01/29 | [
"https://physics.stackexchange.com/questions/611046",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/132371/"
] | >
> Why do metals conduct electricity faster than heat?
>
>
>
If by electricity you mean the flow of current, then the question only makes sense (at least to me) under transient conditions with respect to how quickly steady heat flow is establish vs how quickly steady current flow is established, as discussed below. Under steady state conditions it's an apples and oranges comparison since current is the rate of charge transport and heat is the rate of energy transfer.
**Transient Conditions:**
Take a metal conductor, a wire. At time t=0 you apply a voltage difference between the the ends of the wire. An electric field is almost instantaneously established and electrons almost instantaneously begin moving throughout the conductor with some average drift velocity. So current is almost instantaneous throughout the conductor.
Take the same wire initially at room temperature throughout. The mobile electrons in the wire will have the same random thermal motion throughout the wire roughly proportional to the temperature. Now at time t=0 establish contact between one end of the wire with a high temperature constant temperature source with the other end in contact with a constant lower temperature equal to the room temperature. Thermally insulate the circumference of the wire to prevent heat transfer to the surrounding air.
The difference in temperature between the ends is analogous to the potential difference. The random thermal motion of the electrons near the high temperature end will increase. Through collisions with the electrons farther away from the hot end increased thermal motion will progress towards the lower temperature end until a linear temperature gradient is theoretically established along the length of the conductor. However, unlike the situation for current, this progression of thermal motion will not be instantaneous as in the case of the collective motion of charge. It will take time.
**Steady State Conditions:**
The applicable steady heat flow equation is
$$\dot Q=\frac {k\_{t}A(T\_{H}-T\_{L})}{L}$$
The applicable current flow equation is
$$I=\frac {k\_{e}A(V\_{H}-V\_{L})}{L}$$
The equations are roughly analogous with rate of heat transfer $\dot Q$ analogous to rate of charge transport $I$, thermal conductivity $k\_{t}$ analogous to electrical conductivity $k\_e$, and temperature difference $T\_{H}-T\_{L}$ analogous to potential difference $V\_{H}-V\_{L}$. The length and cross sectional area of the wire being $L$ and $A$, respectively.
But current and rate of heat transfer are different things, so it's comparing apples to oranges.
>
> "However, unlike the situation for current, this progression of
> thermal motion will not be instantaneous as in the case of the
> collective motion of charge. It will take time." Can you please
> elaborate on this a little, why this is, this is key to my question.
>
>
>
First, the motion of electrons in the case of current flow is collective motion, called drift velocity, which is proportional to current. That motion is due to the unidirectional electric force applied by the electric field to the electrons. That electric field travels in the conductor near the speed of light. So all the electrons immediately start moving.
On the other hand, the thermal motion of electrons when the conductor is heated is random. They don't collectively move along the conductor. Electrons with high thermal motion (random velocities) near the heat source collide with nearby electrons away from the source having less thermal motion (lower temperature) transferring kinetic energy to those electrons raising the temperature of conductor further from the source. They in turn collide with electrons nearby them and so forth until the thermal motion of all the electrons in the conductor has increased raising the temperature. All this takes time.
Check out the following video showing how the temperature of a heated conductor slowly increases along the length of the conductor as evidenced by color of the conductor.
<https://www.youtube.com/watch?v=y-ptY0YG9RI>
Hope this helps. | In the case of heat transfer, the wire stays electrically neutral, so one electron can only interact with other electrons in it's close vicinity by collisions, but has no effect on electrons far away. So the signal about the increased temperature (i.e. higher thermal velocity) travels by collisions from one electron to the next. In the best case scenario the random collsions happen such that the next electron always travels in the right direction. Then the information about the increased temperature can travel at most with a speed equivalent to the electrons thermal velocity, which is about 100 km/s or 0.3% of the speed of light.
In the case of electricity, you push additional electrons in one side of the wire. This charge surplus will cause an electric field to form which travels at the speed of light. So this electric field can almost instantaneously affect all electrons in the wire, even electrons far away on the other end of the wire. All electrons will start moving in the same direction driven by this electric field.
So in short, heat transfer is analogous to sending a message through a relay race, while electricity transfer is equivalent to cheating in that race by calling the person on the end of the line with your phone and telling him the message. |
15,977,707 | I am developing an app that needs to be debugged under a slow connection. My issue is that I only own an iPhone 5 that uses LTE. I can disable LTE in my Settings for a 4G connection but this 4G connection is still to fast for my testing purposes. I would like to know if there is a way to programmatically force the testing iPhone into 3G or EDGE. | 2013/04/12 | [
"https://Stackoverflow.com/questions/15977707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368547/"
] | You'll want to test flaky in addition to just going slow - you can simulate this with apple's network link conditioner and running your iPhone through your mac's internet connection (or run simulator). See [Installing Apple's Network Link Conditioner Tool](https://stackoverflow.com/questions/9659382/installing-apples-network-link-conditioner-tool) .
If you really want some good testing, the best way to do it is look up your cell provider's coverage map and find some crappy locations. Test in those areas while driving in and out of range should weed out any broken network code you have. :) | >
> I can disable LTE in my Settings for a 4G connection but this 4G connection is still to fast for my testing purposes
>
>
>
LTE **is** (a kind of) 4G.
If you disable it, it will fall back to EDGE. Alternatively, you may switch to a Wi-Fi connection and slow it down (if your router has such a feature). |
15,977,707 | I am developing an app that needs to be debugged under a slow connection. My issue is that I only own an iPhone 5 that uses LTE. I can disable LTE in my Settings for a 4G connection but this 4G connection is still to fast for my testing purposes. I would like to know if there is a way to programmatically force the testing iPhone into 3G or EDGE. | 2013/04/12 | [
"https://Stackoverflow.com/questions/15977707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368547/"
] | Network Link Conditioner also exists on the device in recent iOS builds, i'm not positive of when they added it.
But its present in Settings, under the Developer menu. | >
> I can disable LTE in my Settings for a 4G connection but this 4G connection is still to fast for my testing purposes
>
>
>
LTE **is** (a kind of) 4G.
If you disable it, it will fall back to EDGE. Alternatively, you may switch to a Wi-Fi connection and slow it down (if your router has such a feature). |
15,977,707 | I am developing an app that needs to be debugged under a slow connection. My issue is that I only own an iPhone 5 that uses LTE. I can disable LTE in my Settings for a 4G connection but this 4G connection is still to fast for my testing purposes. I would like to know if there is a way to programmatically force the testing iPhone into 3G or EDGE. | 2013/04/12 | [
"https://Stackoverflow.com/questions/15977707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368547/"
] | You'll want to test flaky in addition to just going slow - you can simulate this with apple's network link conditioner and running your iPhone through your mac's internet connection (or run simulator). See [Installing Apple's Network Link Conditioner Tool](https://stackoverflow.com/questions/9659382/installing-apples-network-link-conditioner-tool) .
If you really want some good testing, the best way to do it is look up your cell provider's coverage map and find some crappy locations. Test in those areas while driving in and out of range should weed out any broken network code you have. :) | Network Link Conditioner also exists on the device in recent iOS builds, i'm not positive of when they added it.
But its present in Settings, under the Developer menu. |
65,183,308 | I have dates in my data frame and I want to create a new variables where I uses the date to group them into time periods. The time periods would be
1980-1989
1990-1999
2000-2012
They are of class date
```
date_of_delivery
1984-02-03
1997-08-01
2007-04-25
1999-04-05
```
The new column would look like
```
date_of_delivery dod_group
1984-02-03 1980-1989
1997-08-01 1990-1999
2007-04-25 2000-2012
1999-04-05 1990-1999
```
Thanks | 2020/12/07 | [
"https://Stackoverflow.com/questions/65183308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14705785/"
] | Use `cut`:
```r
cutoffs <- setNames(as.Date(c("1980-01-01", "1990-01-01", "2000-01-01", "2013-01-01")), c("1980-1989", "1990-1999", "2000-2012", "Future"))
cutoffs
# 1980-1989 1990-1999 2000-2012 Future
# "1980-01-01" "1990-01-01" "2000-01-01" "2013-01-01"
cut(dat$date_of_delivery, cutoffs, labels = names(cutoffs)[-length(cutoffs)])
# [1] 1980-1989 1990-1999 2000-2012 1990-1999
# Levels: 1980-1989 1990-1999 2000-2012
```
There are `factor`s. If you want them as strings/`character`, then
```r
as.character(cut(dat$date_of_delivery, cutoffs, labels = names(cutoffs)[-length(cutoffs)]))
# [1] "1980-1989" "1990-1999" "2000-2012" "1990-1999"
``` | You could try the Date method of `cut` from base R.
```
data$dod_group <- cut(as.Date(c("1980-01-01",data$date_of_delivery),
"%Y-%m-%d"),
breaks = "10 years")[-1]
data
# date_of_delivery dod_group
#1 1984-02-03 1980-01-01
#2 1997-08-01 1990-01-01
#3 2007-04-25 2000-01-01
#4 1999-04-05 1990-01-01
```
I added `"1980-01-01"` to get the groups to start at that date, and the `breaks = "10 years"` argument to get the breaks to be decades. Finally, I subsetted the resulting break vector with `[-1]` to get rid of the initial date.
Sample data:
```
data <- structure(list(date_of_delivery = c("1984-02-03", "1997-08-01",
"2007-04-25", "1999-04-05")), class = "data.frame", row.names = c(NA,
-4L))
``` |
35,692,111 | I have the following JSON string which comes from a HTTP request:
```
{ '{firstname:\'Joe\'}': '' } // output of console.log(req.body);
```
I have tried to print the value to console using:
```
console.log(req.body.firstname);
```
but it says the value is undefined. How can I get the value of firstname?
To see what the client is doing this is how it sends the JSON request:
```
//angular2
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post(
'http://192.168.1.45:3000/test',
JSON.stringify({firstname:'Joe'}), //This is the parameter I want
{headers:headers}
)
``` | 2016/02/29 | [
"https://Stackoverflow.com/questions/35692111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2924127/"
] | You missed ' code after **CodeCompiler** so change your query from
```
INSERT INTO futureposts (ID, username, postedby, link, message, picture, name, caption, description, groups, type) VALUES ('','1','CodeCompiler','CodeCompiler,'','','','','','','default','daily')
```
to
```
INSERT INTO futureposts (ID, username, postedby, link, message, picture, name, caption, description, groups, type) VALUES ('','1','CodeCompiler','CodeCompiler','','','','','','default','daily')
```
and also there is one extra column added in query , check it and remove extra column | You missed ' (closing quote) after **CodeCompiler**
....VALUES ('','1','CodeCompiler','**CodeCompiler**,'','....
Also one change that you need to do that is you are giving 12 values to 11 column..I have checked personally in my phpmyadmin by creating same table.
So your final query will be
```
INSERT INTO futureposts (ID, username, postedby, link, message, picture, name, caption, description, groups, type) VALUES ('','1','CodeCompiler','','','','','','','default','daily');
``` |
32,333,740 | know anyone how can I split my seach view in 2 activity? Before the click on search icon you are in one activity and after you click on it you will be in anther activity were you can write what do you want. | 2015/09/01 | [
"https://Stackoverflow.com/questions/32333740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4697187/"
] | As @Eugene Obrezkov pointed out, your issue is related to where you are uploading your images and the grunt task runner. All the assets are copied from that folder (`/assets`) to the `.tmp`, and changes are watched by the grunt task runner, but that doesn't include new image files(If you are to an empty folder in the assets folder, in your case to the image folder). So the solution is quite easy, you must upload directly to the `.tmp` folder, ideally to `.tmp/public/uploads/year/month/`, you can choose your path as you see fit. Now there is a **caveat** with this approach, and it is that there is a **grunt task that clears** the contents of the `.tmp` folder on sails lift, so you will get the opposite effect, now to avoid this is quite easy too, you must edit the `clean.js` task to delete specific folders, to avoid deleting your uploads folder.
Go to to your project folders `tasks/config/clean.js`, and replace what's in there for this code, or modify it as you need.
```
module.exports = function(grunt) {
grunt.config.set('clean', {
dev: [
getFolderPath('fonts/**'),
getFolderPath('images/**'),
getFolderPath('images/**'),
getFolderPath('js/**'),
getFolderPath('styles/**'),
getFolderPath('*.*')
],
build: ['www']
});
grunt.loadNpmTasks('grunt-contrib-clean');
};
function getFolderPath(folderName){
return '.tmp/public/' + folderName;
}
```
Now your uploads will appear immediately to your end-user without restart, and restarts won't delete those uploads. Just make sure the `.tmp/public/uploads/` path exist before trying to upload, or use `mkdir` to create it via code if not found.
There are other solutions, like making sure there is at least a file in the folder you are uploading to when the server starts, or using symlinks, but i think this is a cleaner approach. You can check those options here:
[Image not showing immediately after uploading in sails.js](https://stackoverflow.com/questions/22450795/image-not-showing-immediately-after-uploading-in-sails-js?rq=1) | If you take a look into `tasks` folder, you can find Grunt task that copies all the `assets` folder to `.tmp` folder and make `.tmp` folder as static public folder.
When you are running Sails application, it runs these Grunt tasks, so that if you uploading file direct to `assets` folder it will not be accessible until you re-run server and Grunt tasks.
Solution? There is no solution. Basically, you are doing it wrong. Best practices is to store images\files\whatever on S3 buckets, Google Storage, another hard drive at least, but not `assets` itself. Because it's your source files of your project and in there should be located only files needed for project itself, not user's files, etc... |
32,333,740 | know anyone how can I split my seach view in 2 activity? Before the click on search icon you are in one activity and after you click on it you will be in anther activity were you can write what do you want. | 2015/09/01 | [
"https://Stackoverflow.com/questions/32333740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4697187/"
] | If you take a look into `tasks` folder, you can find Grunt task that copies all the `assets` folder to `.tmp` folder and make `.tmp` folder as static public folder.
When you are running Sails application, it runs these Grunt tasks, so that if you uploading file direct to `assets` folder it will not be accessible until you re-run server and Grunt tasks.
Solution? There is no solution. Basically, you are doing it wrong. Best practices is to store images\files\whatever on S3 buckets, Google Storage, another hard drive at least, but not `assets` itself. Because it's your source files of your project and in there should be located only files needed for project itself, not user's files, etc... | You can achieve without modifing any grunt task. I had the same issue and I have just solved it.
I see you already have an explanation of what's happening in other comments, so I'll go straight to my solution. I uploaded the files to the .tmp folder, and on the callback of the upload, I coppied them to the assets folder using the file system (fs-extra is a great package for that).
So now I can see the images in my UI as soon as it's added (cause I uploaded them to .tmp) and when my server stops, .tmp will be lost, but generated again in the next lift with the files copied to assets.
Hope it helps! |
32,333,740 | know anyone how can I split my seach view in 2 activity? Before the click on search icon you are in one activity and after you click on it you will be in anther activity were you can write what do you want. | 2015/09/01 | [
"https://Stackoverflow.com/questions/32333740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4697187/"
] | If you take a look into `tasks` folder, you can find Grunt task that copies all the `assets` folder to `.tmp` folder and make `.tmp` folder as static public folder.
When you are running Sails application, it runs these Grunt tasks, so that if you uploading file direct to `assets` folder it will not be accessible until you re-run server and Grunt tasks.
Solution? There is no solution. Basically, you are doing it wrong. Best practices is to store images\files\whatever on S3 buckets, Google Storage, another hard drive at least, but not `assets` itself. Because it's your source files of your project and in there should be located only files needed for project itself, not user's files, etc... | This is how I solved this problem. The answer requires several steps. I am assuming you want to place your recently uploaded images in a folder called users.
**Steps:**
1. `npm install express --save` (If you don't have it installed)
2. Create a **Users** folder in your apps root directory.
3. Open the text editor and view the following file `config\express.js`
4. Add or replace with the code
`
var express = require('express');
module.exports.http = {
customMiddleware: function (app) {
app.use('/users', express.static(process.cwd() + '/users'));
}
};
`
5. Make certain the newly uploaded images are placed in the **Users** folder
6. Finish |
32,333,740 | know anyone how can I split my seach view in 2 activity? Before the click on search icon you are in one activity and after you click on it you will be in anther activity were you can write what do you want. | 2015/09/01 | [
"https://Stackoverflow.com/questions/32333740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4697187/"
] | As @Eugene Obrezkov pointed out, your issue is related to where you are uploading your images and the grunt task runner. All the assets are copied from that folder (`/assets`) to the `.tmp`, and changes are watched by the grunt task runner, but that doesn't include new image files(If you are to an empty folder in the assets folder, in your case to the image folder). So the solution is quite easy, you must upload directly to the `.tmp` folder, ideally to `.tmp/public/uploads/year/month/`, you can choose your path as you see fit. Now there is a **caveat** with this approach, and it is that there is a **grunt task that clears** the contents of the `.tmp` folder on sails lift, so you will get the opposite effect, now to avoid this is quite easy too, you must edit the `clean.js` task to delete specific folders, to avoid deleting your uploads folder.
Go to to your project folders `tasks/config/clean.js`, and replace what's in there for this code, or modify it as you need.
```
module.exports = function(grunt) {
grunt.config.set('clean', {
dev: [
getFolderPath('fonts/**'),
getFolderPath('images/**'),
getFolderPath('images/**'),
getFolderPath('js/**'),
getFolderPath('styles/**'),
getFolderPath('*.*')
],
build: ['www']
});
grunt.loadNpmTasks('grunt-contrib-clean');
};
function getFolderPath(folderName){
return '.tmp/public/' + folderName;
}
```
Now your uploads will appear immediately to your end-user without restart, and restarts won't delete those uploads. Just make sure the `.tmp/public/uploads/` path exist before trying to upload, or use `mkdir` to create it via code if not found.
There are other solutions, like making sure there is at least a file in the folder you are uploading to when the server starts, or using symlinks, but i think this is a cleaner approach. You can check those options here:
[Image not showing immediately after uploading in sails.js](https://stackoverflow.com/questions/22450795/image-not-showing-immediately-after-uploading-in-sails-js?rq=1) | You can achieve without modifing any grunt task. I had the same issue and I have just solved it.
I see you already have an explanation of what's happening in other comments, so I'll go straight to my solution. I uploaded the files to the .tmp folder, and on the callback of the upload, I coppied them to the assets folder using the file system (fs-extra is a great package for that).
So now I can see the images in my UI as soon as it's added (cause I uploaded them to .tmp) and when my server stops, .tmp will be lost, but generated again in the next lift with the files copied to assets.
Hope it helps! |
32,333,740 | know anyone how can I split my seach view in 2 activity? Before the click on search icon you are in one activity and after you click on it you will be in anther activity were you can write what do you want. | 2015/09/01 | [
"https://Stackoverflow.com/questions/32333740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4697187/"
] | As @Eugene Obrezkov pointed out, your issue is related to where you are uploading your images and the grunt task runner. All the assets are copied from that folder (`/assets`) to the `.tmp`, and changes are watched by the grunt task runner, but that doesn't include new image files(If you are to an empty folder in the assets folder, in your case to the image folder). So the solution is quite easy, you must upload directly to the `.tmp` folder, ideally to `.tmp/public/uploads/year/month/`, you can choose your path as you see fit. Now there is a **caveat** with this approach, and it is that there is a **grunt task that clears** the contents of the `.tmp` folder on sails lift, so you will get the opposite effect, now to avoid this is quite easy too, you must edit the `clean.js` task to delete specific folders, to avoid deleting your uploads folder.
Go to to your project folders `tasks/config/clean.js`, and replace what's in there for this code, or modify it as you need.
```
module.exports = function(grunt) {
grunt.config.set('clean', {
dev: [
getFolderPath('fonts/**'),
getFolderPath('images/**'),
getFolderPath('images/**'),
getFolderPath('js/**'),
getFolderPath('styles/**'),
getFolderPath('*.*')
],
build: ['www']
});
grunt.loadNpmTasks('grunt-contrib-clean');
};
function getFolderPath(folderName){
return '.tmp/public/' + folderName;
}
```
Now your uploads will appear immediately to your end-user without restart, and restarts won't delete those uploads. Just make sure the `.tmp/public/uploads/` path exist before trying to upload, or use `mkdir` to create it via code if not found.
There are other solutions, like making sure there is at least a file in the folder you are uploading to when the server starts, or using symlinks, but i think this is a cleaner approach. You can check those options here:
[Image not showing immediately after uploading in sails.js](https://stackoverflow.com/questions/22450795/image-not-showing-immediately-after-uploading-in-sails-js?rq=1) | This is how I solved this problem. The answer requires several steps. I am assuming you want to place your recently uploaded images in a folder called users.
**Steps:**
1. `npm install express --save` (If you don't have it installed)
2. Create a **Users** folder in your apps root directory.
3. Open the text editor and view the following file `config\express.js`
4. Add or replace with the code
`
var express = require('express');
module.exports.http = {
customMiddleware: function (app) {
app.use('/users', express.static(process.cwd() + '/users'));
}
};
`
5. Make certain the newly uploaded images are placed in the **Users** folder
6. Finish |
32,333,740 | know anyone how can I split my seach view in 2 activity? Before the click on search icon you are in one activity and after you click on it you will be in anther activity were you can write what do you want. | 2015/09/01 | [
"https://Stackoverflow.com/questions/32333740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4697187/"
] | You can achieve without modifing any grunt task. I had the same issue and I have just solved it.
I see you already have an explanation of what's happening in other comments, so I'll go straight to my solution. I uploaded the files to the .tmp folder, and on the callback of the upload, I coppied them to the assets folder using the file system (fs-extra is a great package for that).
So now I can see the images in my UI as soon as it's added (cause I uploaded them to .tmp) and when my server stops, .tmp will be lost, but generated again in the next lift with the files copied to assets.
Hope it helps! | This is how I solved this problem. The answer requires several steps. I am assuming you want to place your recently uploaded images in a folder called users.
**Steps:**
1. `npm install express --save` (If you don't have it installed)
2. Create a **Users** folder in your apps root directory.
3. Open the text editor and view the following file `config\express.js`
4. Add or replace with the code
`
var express = require('express');
module.exports.http = {
customMiddleware: function (app) {
app.use('/users', express.static(process.cwd() + '/users'));
}
};
`
5. Make certain the newly uploaded images are placed in the **Users** folder
6. Finish |
13,177,426 | I've made use of **modal window** for a wizard implementation which has around 4,5 steps. I need to destroy it completely after the **last step**(onFinish) and **OnCancel step without having a page refresh**. I can of course hide it, but hiding modal windows restores everything as such when i open up it again. Could anyone help me on this issue?
Thanks
Any hints answers are helpful for me. | 2012/11/01 | [
"https://Stackoverflow.com/questions/13177426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242378/"
] | This completely removes the modal from the DOM , is working for the "appended" modals as well .
#pickoptionmodal is the id of my modal window.
==============================================
```
$(document).on('hidden.bs.modal','#pickoptionmodal',function(e){
e.preventDefault();
$("#pickoptionmodal").remove();
});
``` | With ui-router this may be an option for you. It reloads the controller on close so reinitializes the modal contents before it fires next time.
```
$("#myModalId").on('hidden.bs.modal', function () {
$state.reload(); //resets the modal
});
``` |
13,177,426 | I've made use of **modal window** for a wizard implementation which has around 4,5 steps. I need to destroy it completely after the **last step**(onFinish) and **OnCancel step without having a page refresh**. I can of course hide it, but hiding modal windows restores everything as such when i open up it again. Could anyone help me on this issue?
Thanks
Any hints answers are helpful for me. | 2012/11/01 | [
"https://Stackoverflow.com/questions/13177426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242378/"
] | if is bootstrap 3 you can use:
```js
$("#mimodal").on('hidden.bs.modal', function () {
$(this).data('bs.modal', null);
});
``` | I had to use same modal for different link clicks. I just replaced the html content with empty "" of the modal in hidden callback. |
13,177,426 | I've made use of **modal window** for a wizard implementation which has around 4,5 steps. I need to destroy it completely after the **last step**(onFinish) and **OnCancel step without having a page refresh**. I can of course hide it, but hiding modal windows restores everything as such when i open up it again. Could anyone help me on this issue?
Thanks
Any hints answers are helpful for me. | 2012/11/01 | [
"https://Stackoverflow.com/questions/13177426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242378/"
] | *NOTE: This solution works only for Bootstrap before version 3. For a Bootstrap 3 answer, refer to [this one by user2612497](https://stackoverflow.com/a/18169689/177710).*
What you want to do is:
```
$('#modalElement').on('hidden', function(){
$(this).data('modal', null);
});
```
that will cause the modal to initialize itself every time it is shown. So if you are using remote content to load into the div or whatever, it will re-do it everytime it is opened. You are merely destroying the modal instance after each time it is hidden.
Or whenever you want to trigger the destroying of the element (in case it is not actually every time you hide it) you just have to call the middle line:
```
$('#modalElement').data('modal', null);
```
Twitter bootstrap looks for its instance to be located in the data attribute, if an instance exists it just toggles it, if an instance doesn't exist it will create a new one.
Hope that helps. | Single line complete removal on hide ( ES6 )
`$("#myModal").on('hidden.bs.modal', (e)=>e.currentTarget.remove());` |
13,177,426 | I've made use of **modal window** for a wizard implementation which has around 4,5 steps. I need to destroy it completely after the **last step**(onFinish) and **OnCancel step without having a page refresh**. I can of course hide it, but hiding modal windows restores everything as such when i open up it again. Could anyone help me on this issue?
Thanks
Any hints answers are helpful for me. | 2012/11/01 | [
"https://Stackoverflow.com/questions/13177426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242378/"
] | *NOTE: This solution works only for Bootstrap before version 3. For a Bootstrap 3 answer, refer to [this one by user2612497](https://stackoverflow.com/a/18169689/177710).*
What you want to do is:
```
$('#modalElement').on('hidden', function(){
$(this).data('modal', null);
});
```
that will cause the modal to initialize itself every time it is shown. So if you are using remote content to load into the div or whatever, it will re-do it everytime it is opened. You are merely destroying the modal instance after each time it is hidden.
Or whenever you want to trigger the destroying of the element (in case it is not actually every time you hide it) you just have to call the middle line:
```
$('#modalElement').data('modal', null);
```
Twitter bootstrap looks for its instance to be located in the data attribute, if an instance exists it just toggles it, if an instance doesn't exist it will create a new one.
Hope that helps. | From what i understand, you don't wanna remove it, nor hide it ? Because you might wanna reuse it later ..but don't want it to have the old content if ever you open it up again ?
```
<div class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<a href="#" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>
```
If you wanna use it as a dynamic template just do something like
```
$(selector).modal({show: true})
....
$(selector).modal({show: false})
$(".modal-body").empty()
....
$(".modal-body").append("new stuff & text")
$(selector).modal({show: true})
``` |
13,177,426 | I've made use of **modal window** for a wizard implementation which has around 4,5 steps. I need to destroy it completely after the **last step**(onFinish) and **OnCancel step without having a page refresh**. I can of course hide it, but hiding modal windows restores everything as such when i open up it again. Could anyone help me on this issue?
Thanks
Any hints answers are helpful for me. | 2012/11/01 | [
"https://Stackoverflow.com/questions/13177426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242378/"
] | For 3.x version
```
$( '.modal' ).modal( 'hide' ).data( 'bs.modal', null );
```
For 2.x version (risky; read comments below)
When you create bootstrap modal three elements on your page being changed. So if you want to completely rollback all changes, you have to do it manually for each of it.
```
$( '.modal' ).remove();
$( '.modal-backdrop' ).remove();
$( 'body' ).removeClass( "modal-open" );
``` | My approach would be to use the [`clone()`](http://api.jquery.com/clone/) method of jQuery. It creates a copy of your element, and that's what you want : a copy of your first unaltered modal, that you can replace at your wish : [Demo (jsfiddle)](http://jsfiddle.net/Sherbrow/8XCps/)
```js
var myBackup = $('#myModal').clone();
// Delegated events because we make a copy, and the copied button does not exist onDomReady
$('body').on('click','#myReset',function() {
$('#myModal').modal('hide').remove();
var myClone = myBackup.clone();
$('body').append(myClone);
});
```
The markup I used is the most basic, so you just need to bind on the right elements / events, and you should have your wizard reset.
**Be careful** to bind with [delegated events](http://api.jquery.com/on/#direct-and-delegated-events), or rebind at each reset the inner elements of your modal so that each new modal behave the same way. |
13,177,426 | I've made use of **modal window** for a wizard implementation which has around 4,5 steps. I need to destroy it completely after the **last step**(onFinish) and **OnCancel step without having a page refresh**. I can of course hide it, but hiding modal windows restores everything as such when i open up it again. Could anyone help me on this issue?
Thanks
Any hints answers are helpful for me. | 2012/11/01 | [
"https://Stackoverflow.com/questions/13177426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242378/"
] | My approach would be to use the [`clone()`](http://api.jquery.com/clone/) method of jQuery. It creates a copy of your element, and that's what you want : a copy of your first unaltered modal, that you can replace at your wish : [Demo (jsfiddle)](http://jsfiddle.net/Sherbrow/8XCps/)
```js
var myBackup = $('#myModal').clone();
// Delegated events because we make a copy, and the copied button does not exist onDomReady
$('body').on('click','#myReset',function() {
$('#myModal').modal('hide').remove();
var myClone = myBackup.clone();
$('body').append(myClone);
});
```
The markup I used is the most basic, so you just need to bind on the right elements / events, and you should have your wizard reset.
**Be careful** to bind with [delegated events](http://api.jquery.com/on/#direct-and-delegated-events), or rebind at each reset the inner elements of your modal so that each new modal behave the same way. | this worked for me on BS4:
```
let $modal = $(this);
$modal.modal('hide').on("hidden.bs.modal", function (){
$modal.remove();
});
```
we remove the modal after it is completely hidden.
from BS doc:
>
> hidden.bs.modal: This event is fired when the modal has finished being
> hidden from the user (will wait for CSS transitions to complete).
>
>
> |
13,177,426 | I've made use of **modal window** for a wizard implementation which has around 4,5 steps. I need to destroy it completely after the **last step**(onFinish) and **OnCancel step without having a page refresh**. I can of course hide it, but hiding modal windows restores everything as such when i open up it again. Could anyone help me on this issue?
Thanks
Any hints answers are helpful for me. | 2012/11/01 | [
"https://Stackoverflow.com/questions/13177426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242378/"
] | This completely removes the modal from the DOM , is working for the "appended" modals as well .
#pickoptionmodal is the id of my modal window.
==============================================
```
$(document).on('hidden.bs.modal','#pickoptionmodal',function(e){
e.preventDefault();
$("#pickoptionmodal").remove();
});
``` | If modal shadow remains darker and not going for showing more than one modal then this will be helpful
```
$('.modal').live('hide',function(){
if($('.modal-backdrop').length>1){
$('.modal-backdrop')[0].remove();
}
});
``` |
13,177,426 | I've made use of **modal window** for a wizard implementation which has around 4,5 steps. I need to destroy it completely after the **last step**(onFinish) and **OnCancel step without having a page refresh**. I can of course hide it, but hiding modal windows restores everything as such when i open up it again. Could anyone help me on this issue?
Thanks
Any hints answers are helpful for me. | 2012/11/01 | [
"https://Stackoverflow.com/questions/13177426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242378/"
] | bootstrap 3 + jquery 2.0.3:
```
$('#myModal').on('hide.bs.modal', function () {
$('#myModal').removeData();
})
``` | With ui-router this may be an option for you. It reloads the controller on close so reinitializes the modal contents before it fires next time.
```
$("#myModalId").on('hidden.bs.modal', function () {
$state.reload(); //resets the modal
});
``` |
13,177,426 | I've made use of **modal window** for a wizard implementation which has around 4,5 steps. I need to destroy it completely after the **last step**(onFinish) and **OnCancel step without having a page refresh**. I can of course hide it, but hiding modal windows restores everything as such when i open up it again. Could anyone help me on this issue?
Thanks
Any hints answers are helpful for me. | 2012/11/01 | [
"https://Stackoverflow.com/questions/13177426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242378/"
] | I have tried accepted answer but it isn't seems working on my end and I don't know how the accepted answer suppose to work.
```
$('#modalId').on('hidden.bs.modal', function () {
$(this).remove();
})
```
This is working perfectly fine on my side. BS Version > 3 | If modal shadow remains darker and not going for showing more than one modal then this will be helpful
```
$('.modal').live('hide',function(){
if($('.modal-backdrop').length>1){
$('.modal-backdrop')[0].remove();
}
});
``` |
13,177,426 | I've made use of **modal window** for a wizard implementation which has around 4,5 steps. I need to destroy it completely after the **last step**(onFinish) and **OnCancel step without having a page refresh**. I can of course hide it, but hiding modal windows restores everything as such when i open up it again. Could anyone help me on this issue?
Thanks
Any hints answers are helpful for me. | 2012/11/01 | [
"https://Stackoverflow.com/questions/13177426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242378/"
] | My approach would be to use the [`clone()`](http://api.jquery.com/clone/) method of jQuery. It creates a copy of your element, and that's what you want : a copy of your first unaltered modal, that you can replace at your wish : [Demo (jsfiddle)](http://jsfiddle.net/Sherbrow/8XCps/)
```js
var myBackup = $('#myModal').clone();
// Delegated events because we make a copy, and the copied button does not exist onDomReady
$('body').on('click','#myReset',function() {
$('#myModal').modal('hide').remove();
var myClone = myBackup.clone();
$('body').append(myClone);
});
```
The markup I used is the most basic, so you just need to bind on the right elements / events, and you should have your wizard reset.
**Be careful** to bind with [delegated events](http://api.jquery.com/on/#direct-and-delegated-events), or rebind at each reset the inner elements of your modal so that each new modal behave the same way. | Single line complete removal on hide ( ES6 )
`$("#myModal").on('hidden.bs.modal', (e)=>e.currentTarget.remove());` |
1,806,909 | [Tacit or point-free style programming](http://en.wikipedia.org/wiki/Tacit_programming) allows one to create functions without regard to their arguments. Can this be done in F#? | 2009/11/27 | [
"https://Stackoverflow.com/questions/1806909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14139/"
] | Just to go with Chuck's answer & Chris Smiths' comment, you could write
```
let digits = string_of_int >> String.length
digits 9000;; // 4
[1; 10; 100] |> List.map digits;; // [1;2;3]
```
When you combine those composition & pipeline operators with higher-order functions, you can do complicated stuff very succinctly:
```
let prodSqrtAbs = Seq.map (abs>>sqrt) >> Seq.reduce (*)
prodSqrtAbs [| -9.0; 4.0 |];; // 6.0
```
---
**EDIT**: I just read about J and its implicit fork operator. That is very powerful. You can build equivalent higher-order operators in F#, but they won't be applied implicitly. So, for example, first define `lift` (using explicit arguments)
```
let lift op a b x = op (a x) (b x)
```
and then apply it explicitly
```
let avg = lift (/) List.sum List.length
```
to get something resembling [the J example](http://en.wikipedia.org/w/index.php?title=Tacit_programming&oldid=301960149#APL_.28family.29) on the Wikipedia page you linked to. But its not quite "tacit." | Sure. All you need is function composition and currying, and both of these are possible in F#.
```
let compose f1 f2 = fun x -> f1 (f2 x);;
let digits = compose String.length string_of_int;;
digits 9000;; // 4
``` |
48,570,209 | This is my first time on the website. I have a big problem with my hangman.
I have a wordBank:
```
wordBank = ["pizza", "pie", "cookie", "candy", "salad", "chicken", "pork", "burger", "fries"]
```
I have a variable that chooses a random word from the wordBank and makes it into a array:
```
randomChosenWord = wordBank[round(random(wordBank.length - 1))].split('')
```
And I have a array that is gets pushed with a amount of placeholders the same as the length of my randomly chosen word. If I press my button object [I have many from A-Z] , it will replace the placeholder thats in the same index as the letter in the randomly chosen word with the letter on the button:
```
this.click = function() {
if (mouseX > this.x - 10 && mouseX < this.x + 10 && mouseY > this.y - 10 && mouseY < this.y + 10) {
if (randomChosenWord.includes(this.letter)) {
lettersChosen.splice(randomChosenWord.indexOf(this.letter), 1, this.letter)
}
```
An Example:
Pizza is the randomly chosen word
The array that keeps track of the letters i choose is displayed as " - - - - - " (Same length as pizza)
If I press the button that says z, it will replace the index which is the same as the index that has the first z in the randomly chosen word. This will display " - - z - - "
**This works well but I want it to replace all placeholders that are within the indexes that have z, so it can show as " - - z z - "**
How can I find the duplicated elements in a array and replace them? | 2018/02/01 | [
"https://Stackoverflow.com/questions/48570209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8005223/"
] | You can loop through the length of the random word, checking each letter to see if it is the chosen letter. If it is, replace the character at that index.
```
for(var i = 0; i < randomChosenWord.length; i++) {
if(randomChosenWord[i] === this.letter){
lettersChosen.splice(i, 1, this.letter);
}
}
```
This would replace the line
```
lettersChosen.splice(randomChosenWord.indexOf(this.letter), 1, this.letter)
``` | You can change this line: `if (randomChosenWord.includes(this.letter)) {` to a while loop. |
48,570,209 | This is my first time on the website. I have a big problem with my hangman.
I have a wordBank:
```
wordBank = ["pizza", "pie", "cookie", "candy", "salad", "chicken", "pork", "burger", "fries"]
```
I have a variable that chooses a random word from the wordBank and makes it into a array:
```
randomChosenWord = wordBank[round(random(wordBank.length - 1))].split('')
```
And I have a array that is gets pushed with a amount of placeholders the same as the length of my randomly chosen word. If I press my button object [I have many from A-Z] , it will replace the placeholder thats in the same index as the letter in the randomly chosen word with the letter on the button:
```
this.click = function() {
if (mouseX > this.x - 10 && mouseX < this.x + 10 && mouseY > this.y - 10 && mouseY < this.y + 10) {
if (randomChosenWord.includes(this.letter)) {
lettersChosen.splice(randomChosenWord.indexOf(this.letter), 1, this.letter)
}
```
An Example:
Pizza is the randomly chosen word
The array that keeps track of the letters i choose is displayed as " - - - - - " (Same length as pizza)
If I press the button that says z, it will replace the index which is the same as the index that has the first z in the randomly chosen word. This will display " - - z - - "
**This works well but I want it to replace all placeholders that are within the indexes that have z, so it can show as " - - z z - "**
How can I find the duplicated elements in a array and replace them? | 2018/02/01 | [
"https://Stackoverflow.com/questions/48570209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8005223/"
] | Short way of doing it:
```
lettersChosen.split('').map(function (letter, i) {
return randomChosenWord[i] === this.letter ? this.letter : letter;
}).join('')
```
Split the lettersChosen into an array of individual letters, iterate through them using array.map and replace all matching letters, then join into a string again. | You can change this line: `if (randomChosenWord.includes(this.letter)) {` to a while loop. |
48,570,209 | This is my first time on the website. I have a big problem with my hangman.
I have a wordBank:
```
wordBank = ["pizza", "pie", "cookie", "candy", "salad", "chicken", "pork", "burger", "fries"]
```
I have a variable that chooses a random word from the wordBank and makes it into a array:
```
randomChosenWord = wordBank[round(random(wordBank.length - 1))].split('')
```
And I have a array that is gets pushed with a amount of placeholders the same as the length of my randomly chosen word. If I press my button object [I have many from A-Z] , it will replace the placeholder thats in the same index as the letter in the randomly chosen word with the letter on the button:
```
this.click = function() {
if (mouseX > this.x - 10 && mouseX < this.x + 10 && mouseY > this.y - 10 && mouseY < this.y + 10) {
if (randomChosenWord.includes(this.letter)) {
lettersChosen.splice(randomChosenWord.indexOf(this.letter), 1, this.letter)
}
```
An Example:
Pizza is the randomly chosen word
The array that keeps track of the letters i choose is displayed as " - - - - - " (Same length as pizza)
If I press the button that says z, it will replace the index which is the same as the index that has the first z in the randomly chosen word. This will display " - - z - - "
**This works well but I want it to replace all placeholders that are within the indexes that have z, so it can show as " - - z z - "**
How can I find the duplicated elements in a array and replace them? | 2018/02/01 | [
"https://Stackoverflow.com/questions/48570209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8005223/"
] | You can loop through the length of the random word, checking each letter to see if it is the chosen letter. If it is, replace the character at that index.
```
for(var i = 0; i < randomChosenWord.length; i++) {
if(randomChosenWord[i] === this.letter){
lettersChosen.splice(i, 1, this.letter);
}
}
```
This would replace the line
```
lettersChosen.splice(randomChosenWord.indexOf(this.letter), 1, this.letter)
``` | Short way of doing it:
```
lettersChosen.split('').map(function (letter, i) {
return randomChosenWord[i] === this.letter ? this.letter : letter;
}).join('')
```
Split the lettersChosen into an array of individual letters, iterate through them using array.map and replace all matching letters, then join into a string again. |
32,762,046 | I am working on an ionic app and we have a button to Call someone. This doesn't make a whole lot of sense when using a tablet so I would like to not show this button if the person is using a tablet.
Is there an easy way using ionic/cordova that I can detect if the device is a tablet (or I suppose I could also detect if the device has a phone application)? | 2015/09/24 | [
"https://Stackoverflow.com/questions/32762046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143919/"
] | You can see how call feature detection is done in [CordovaCallNumberPlugin](https://github.com/Rohfosho/CordovaCallNumberPlugin).
There are tablets which support calling so I would check for this, but this is of course up to you and depends on your application.
**Android:**
```
private boolean isTelephonyEnabled(){
TelephonyManager tm = (TelephonyManager)cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
}
```
**iOS:**
```
if(![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:number]]) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"NoFeatureCallSupported"];
}
``` | It depends what platforms you are supporting as to how easy this is.
Cordova "out-of-the-box" can't determine if a device is a tablet.
For iOS, a simple bit of Javascript can be used to detect if the device is an iPad by examining the user agent string:
```
var isTablet = !!navigator.userAgent.match(/iPad/i);
```
However, for Android, JS isn't good enough, it requires some native Java:
```
private boolean isTabletDevice(Context applicationContext) {
boolean device_large = ((applicationContext.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) >=
Configuration.SCREENLAYOUT_SIZE_LARGE);
if (device_large) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = this.cordova.getActivity();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
Log.d(LOG_TAG, "Is Tablet Device");
return true;
}
}
Log.d(LOG_TAG, "Is NOT Tablet Device");
return false;
}
```
This plugin wraps up both these approaches in an easy-to-use package for Android and iOS: <https://github.com/dpa99c/phonegap-istablet>. |
32,762,046 | I am working on an ionic app and we have a button to Call someone. This doesn't make a whole lot of sense when using a tablet so I would like to not show this button if the person is using a tablet.
Is there an easy way using ionic/cordova that I can detect if the device is a tablet (or I suppose I could also detect if the device has a phone application)? | 2015/09/24 | [
"https://Stackoverflow.com/questions/32762046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143919/"
] | It depends what platforms you are supporting as to how easy this is.
Cordova "out-of-the-box" can't determine if a device is a tablet.
For iOS, a simple bit of Javascript can be used to detect if the device is an iPad by examining the user agent string:
```
var isTablet = !!navigator.userAgent.match(/iPad/i);
```
However, for Android, JS isn't good enough, it requires some native Java:
```
private boolean isTabletDevice(Context applicationContext) {
boolean device_large = ((applicationContext.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) >=
Configuration.SCREENLAYOUT_SIZE_LARGE);
if (device_large) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = this.cordova.getActivity();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
Log.d(LOG_TAG, "Is Tablet Device");
return true;
}
}
Log.d(LOG_TAG, "Is NOT Tablet Device");
return false;
}
```
This plugin wraps up both these approaches in an easy-to-use package for Android and iOS: <https://github.com/dpa99c/phonegap-istablet>. | You can use ngCordova plugin `$cordovaDevice`: <http://ngcordova.com/docs/plugins/device/>
Just add `$cordovaDevice` as a dependency in your controller and use it to tell what device is being used.
Perhaps you can build an array of models and check if the model is inside of that array, if it is, then disable the button with an `ng-if` or `ng-show` in the HTML.
Example
**JS**
```
app.controller('MyCtrl', [
'$scope',
'$cordovaDevice',
function($scope, $cordovaDevice) {
var model = $cordovaDevice.getModel();
var listOfModels = ['model1', 'model2', 'model3'];
if (listOfModels.indexOf(model) > -1) {
console.log("Model found inside array");
$scope.enablePhoneCall = false;
} else {
console.log("Model NOT found inside array");
$scope.enablePhoneCall = true;
}
}
]);
```
**HTML**
```
<button class="button button-calm" ng-if="enablePhoneCall">Call</button>
```
More info:
* <http://ngcordova.com/docs/plugins/device/>
* <https://github.com/apache/cordova-plugin-device>
List of models: <http://theiphonewiki.com/wiki/index.php?title=Models>
PS: Don't forget to add `ngCordova` as a dependency when you define your ionic app. |
32,762,046 | I am working on an ionic app and we have a button to Call someone. This doesn't make a whole lot of sense when using a tablet so I would like to not show this button if the person is using a tablet.
Is there an easy way using ionic/cordova that I can detect if the device is a tablet (or I suppose I could also detect if the device has a phone application)? | 2015/09/24 | [
"https://Stackoverflow.com/questions/32762046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143919/"
] | It depends what platforms you are supporting as to how easy this is.
Cordova "out-of-the-box" can't determine if a device is a tablet.
For iOS, a simple bit of Javascript can be used to detect if the device is an iPad by examining the user agent string:
```
var isTablet = !!navigator.userAgent.match(/iPad/i);
```
However, for Android, JS isn't good enough, it requires some native Java:
```
private boolean isTabletDevice(Context applicationContext) {
boolean device_large = ((applicationContext.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) >=
Configuration.SCREENLAYOUT_SIZE_LARGE);
if (device_large) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = this.cordova.getActivity();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
Log.d(LOG_TAG, "Is Tablet Device");
return true;
}
}
Log.d(LOG_TAG, "Is NOT Tablet Device");
return false;
}
```
This plugin wraps up both these approaches in an easy-to-use package for Android and iOS: <https://github.com/dpa99c/phonegap-istablet>. | Ionic adds various platform classes to the document body. In iOS you can simply check for the classes `platform-ipad` or `platform-ipod` to check for a non-iPhone. Source: [Ionic Platform Body Classes](https://github.com/delta98/ionic-platform-body-classes/) & [Platform Classes](http://ionicframework.com/docs/platform-customization/platform-classes.html).
On Android this won't be so straight forward and the answer @Ariel gave seems like a good approach to this issue. |
32,762,046 | I am working on an ionic app and we have a button to Call someone. This doesn't make a whole lot of sense when using a tablet so I would like to not show this button if the person is using a tablet.
Is there an easy way using ionic/cordova that I can detect if the device is a tablet (or I suppose I could also detect if the device has a phone application)? | 2015/09/24 | [
"https://Stackoverflow.com/questions/32762046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143919/"
] | It depends what platforms you are supporting as to how easy this is.
Cordova "out-of-the-box" can't determine if a device is a tablet.
For iOS, a simple bit of Javascript can be used to detect if the device is an iPad by examining the user agent string:
```
var isTablet = !!navigator.userAgent.match(/iPad/i);
```
However, for Android, JS isn't good enough, it requires some native Java:
```
private boolean isTabletDevice(Context applicationContext) {
boolean device_large = ((applicationContext.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) >=
Configuration.SCREENLAYOUT_SIZE_LARGE);
if (device_large) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = this.cordova.getActivity();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
Log.d(LOG_TAG, "Is Tablet Device");
return true;
}
}
Log.d(LOG_TAG, "Is NOT Tablet Device");
return false;
}
```
This plugin wraps up both these approaches in an easy-to-use package for Android and iOS: <https://github.com/dpa99c/phonegap-istablet>. | Found an easier way that doesn't need plugins and works for both IOS and Android tablets.
Just add to the `run` function of your app the following piece of code.
```
angular.module('app').run(function ($rootScope, $window) {
// Get the current platform.
var platform = ionic.Platform.platform();
// Initialize isTablet and isApp to false.
$rootScope.isTablet = $rootScope.isApp = false;
if (platform === 'android' || platform === 'ios') {
// Check if the larger size of your window is bigger than 700px.
// The reason I am checking for the max is because the tablet
// might be in landscape mode.
Math.max($window.innerHeight, $window.innerWidth) > 700 ?
$rootScope.isTablet = true : $rootScope.isApp = true;
}
}
```
Now anywhere throughout your app you can use easily know if it is an app or a tablet or desktop.
>
> In Html:
>
>
>
```
<!-- App Logic -->
<div ng-if="isApp">
...
</div>
<!-- Tablet Logic -->
<div ng-if="isTablet">
...
</div>
<!-- Desktop Logic -->
<div ng-if="!isApp && !isTablet">
...
</div>
```
>
> In JS Controllers
>
>
>
```
angular.module('app').controller('myController', function($rootScope) {
if ($rootScope.isApp) {
// App Logic
...
} else if ($rootScope.isTablet) {
// Tablet Logic
...
} else {
// Desktop Logic
...
}
}
```
P.S. Don't forget to change the word `'app'` in my examples to the name of your ionic app, and to inject `$rootScope` in any controller that you will be using it.
P.P.S. if indeed one of the new phones coming out today or tomorrow have a bigger size than 700px on the larger dimension of their screen, I would treat it as a tablet. |
32,762,046 | I am working on an ionic app and we have a button to Call someone. This doesn't make a whole lot of sense when using a tablet so I would like to not show this button if the person is using a tablet.
Is there an easy way using ionic/cordova that I can detect if the device is a tablet (or I suppose I could also detect if the device has a phone application)? | 2015/09/24 | [
"https://Stackoverflow.com/questions/32762046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143919/"
] | You can see how call feature detection is done in [CordovaCallNumberPlugin](https://github.com/Rohfosho/CordovaCallNumberPlugin).
There are tablets which support calling so I would check for this, but this is of course up to you and depends on your application.
**Android:**
```
private boolean isTelephonyEnabled(){
TelephonyManager tm = (TelephonyManager)cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
}
```
**iOS:**
```
if(![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:number]]) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"NoFeatureCallSupported"];
}
``` | You can use ngCordova plugin `$cordovaDevice`: <http://ngcordova.com/docs/plugins/device/>
Just add `$cordovaDevice` as a dependency in your controller and use it to tell what device is being used.
Perhaps you can build an array of models and check if the model is inside of that array, if it is, then disable the button with an `ng-if` or `ng-show` in the HTML.
Example
**JS**
```
app.controller('MyCtrl', [
'$scope',
'$cordovaDevice',
function($scope, $cordovaDevice) {
var model = $cordovaDevice.getModel();
var listOfModels = ['model1', 'model2', 'model3'];
if (listOfModels.indexOf(model) > -1) {
console.log("Model found inside array");
$scope.enablePhoneCall = false;
} else {
console.log("Model NOT found inside array");
$scope.enablePhoneCall = true;
}
}
]);
```
**HTML**
```
<button class="button button-calm" ng-if="enablePhoneCall">Call</button>
```
More info:
* <http://ngcordova.com/docs/plugins/device/>
* <https://github.com/apache/cordova-plugin-device>
List of models: <http://theiphonewiki.com/wiki/index.php?title=Models>
PS: Don't forget to add `ngCordova` as a dependency when you define your ionic app. |
32,762,046 | I am working on an ionic app and we have a button to Call someone. This doesn't make a whole lot of sense when using a tablet so I would like to not show this button if the person is using a tablet.
Is there an easy way using ionic/cordova that I can detect if the device is a tablet (or I suppose I could also detect if the device has a phone application)? | 2015/09/24 | [
"https://Stackoverflow.com/questions/32762046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143919/"
] | You can see how call feature detection is done in [CordovaCallNumberPlugin](https://github.com/Rohfosho/CordovaCallNumberPlugin).
There are tablets which support calling so I would check for this, but this is of course up to you and depends on your application.
**Android:**
```
private boolean isTelephonyEnabled(){
TelephonyManager tm = (TelephonyManager)cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
}
```
**iOS:**
```
if(![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:number]]) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"NoFeatureCallSupported"];
}
``` | Ionic adds various platform classes to the document body. In iOS you can simply check for the classes `platform-ipad` or `platform-ipod` to check for a non-iPhone. Source: [Ionic Platform Body Classes](https://github.com/delta98/ionic-platform-body-classes/) & [Platform Classes](http://ionicframework.com/docs/platform-customization/platform-classes.html).
On Android this won't be so straight forward and the answer @Ariel gave seems like a good approach to this issue. |
32,762,046 | I am working on an ionic app and we have a button to Call someone. This doesn't make a whole lot of sense when using a tablet so I would like to not show this button if the person is using a tablet.
Is there an easy way using ionic/cordova that I can detect if the device is a tablet (or I suppose I could also detect if the device has a phone application)? | 2015/09/24 | [
"https://Stackoverflow.com/questions/32762046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143919/"
] | You can see how call feature detection is done in [CordovaCallNumberPlugin](https://github.com/Rohfosho/CordovaCallNumberPlugin).
There are tablets which support calling so I would check for this, but this is of course up to you and depends on your application.
**Android:**
```
private boolean isTelephonyEnabled(){
TelephonyManager tm = (TelephonyManager)cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
}
```
**iOS:**
```
if(![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:number]]) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"NoFeatureCallSupported"];
}
``` | Found an easier way that doesn't need plugins and works for both IOS and Android tablets.
Just add to the `run` function of your app the following piece of code.
```
angular.module('app').run(function ($rootScope, $window) {
// Get the current platform.
var platform = ionic.Platform.platform();
// Initialize isTablet and isApp to false.
$rootScope.isTablet = $rootScope.isApp = false;
if (platform === 'android' || platform === 'ios') {
// Check if the larger size of your window is bigger than 700px.
// The reason I am checking for the max is because the tablet
// might be in landscape mode.
Math.max($window.innerHeight, $window.innerWidth) > 700 ?
$rootScope.isTablet = true : $rootScope.isApp = true;
}
}
```
Now anywhere throughout your app you can use easily know if it is an app or a tablet or desktop.
>
> In Html:
>
>
>
```
<!-- App Logic -->
<div ng-if="isApp">
...
</div>
<!-- Tablet Logic -->
<div ng-if="isTablet">
...
</div>
<!-- Desktop Logic -->
<div ng-if="!isApp && !isTablet">
...
</div>
```
>
> In JS Controllers
>
>
>
```
angular.module('app').controller('myController', function($rootScope) {
if ($rootScope.isApp) {
// App Logic
...
} else if ($rootScope.isTablet) {
// Tablet Logic
...
} else {
// Desktop Logic
...
}
}
```
P.S. Don't forget to change the word `'app'` in my examples to the name of your ionic app, and to inject `$rootScope` in any controller that you will be using it.
P.P.S. if indeed one of the new phones coming out today or tomorrow have a bigger size than 700px on the larger dimension of their screen, I would treat it as a tablet. |
363,259 | I've been discussing the usage of "in Church Road" over "on Church Road" with my colleagues in a sentence such as "The supermarket is in Church Road". Whilst it is overwhelming clear that "on Church Road" is the favoured option in this discussion, it remains unclear as to whether the use of "in Church Road" is completely uncommon or incorrect in this context.
The case regarding "Church **Street**", we feel, is clearly a simple case of who is speaking, but "Church Road" is presenting us one or two problems.
Any help? | 2016/12/13 | [
"https://english.stackexchange.com/questions/363259",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/210625/"
] | [british-english](/questions/tagged/british-english "show questions tagged 'british-english'")
In British English, *in* is the preferred preposition. It specifies that the location is *within the bounds or extent of the street,* not actually buried in the tarmac.
>
> I live in Church Road.
>
>
>
*On* is becoming more prevalent — probably because of the availability of American television and film — and it would certainly be understood. But it's just not the British way.
It's explicitly cited in OED:
>
> **I.** Of position or location.
>
> **1. a.** Of place or position in space or anything having material extension: Within the limits or bounds of, within (any place or thing).
>
>
> May relate to a space of any size, however large or small: e.g. *in* the universe, *in* the world, *in* heaven, *in* hell, *in* the earth, *in* the sea (otherwise *on* the earth, *on* the sea, *at* sea), *in* a ship, vessel, *in* a field, wood, forest, desert, wilderness (but *on* a heath, moor, or common), *in* (U.S. *on*) a street, *in* a house, carriage, box, drawer, nut-shell, drop of water, etc.
>
>
> | I'm a native English speaker and I am working on my MA in Linguistics.
When referring to buildings, you should always say "on Church Street" or "on Church Road". Using "in" implies that the building is inside the road, which doesn't make a lot of sense. |
363,259 | I've been discussing the usage of "in Church Road" over "on Church Road" with my colleagues in a sentence such as "The supermarket is in Church Road". Whilst it is overwhelming clear that "on Church Road" is the favoured option in this discussion, it remains unclear as to whether the use of "in Church Road" is completely uncommon or incorrect in this context.
The case regarding "Church **Street**", we feel, is clearly a simple case of who is speaking, but "Church Road" is presenting us one or two problems.
Any help? | 2016/12/13 | [
"https://english.stackexchange.com/questions/363259",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/210625/"
] | I'm a native English speaker and I am working on my MA in Linguistics.
When referring to buildings, you should always say "on Church Street" or "on Church Road". Using "in" implies that the building is inside the road, which doesn't make a lot of sense. | Very simple. "In Church Road" is British English; "On Church Road" is American English. |
363,259 | I've been discussing the usage of "in Church Road" over "on Church Road" with my colleagues in a sentence such as "The supermarket is in Church Road". Whilst it is overwhelming clear that "on Church Road" is the favoured option in this discussion, it remains unclear as to whether the use of "in Church Road" is completely uncommon or incorrect in this context.
The case regarding "Church **Street**", we feel, is clearly a simple case of who is speaking, but "Church Road" is presenting us one or two problems.
Any help? | 2016/12/13 | [
"https://english.stackexchange.com/questions/363259",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/210625/"
] | [british-english](/questions/tagged/british-english "show questions tagged 'british-english'")
In British English, *in* is the preferred preposition. It specifies that the location is *within the bounds or extent of the street,* not actually buried in the tarmac.
>
> I live in Church Road.
>
>
>
*On* is becoming more prevalent — probably because of the availability of American television and film — and it would certainly be understood. But it's just not the British way.
It's explicitly cited in OED:
>
> **I.** Of position or location.
>
> **1. a.** Of place or position in space or anything having material extension: Within the limits or bounds of, within (any place or thing).
>
>
> May relate to a space of any size, however large or small: e.g. *in* the universe, *in* the world, *in* heaven, *in* hell, *in* the earth, *in* the sea (otherwise *on* the earth, *on* the sea, *at* sea), *in* a ship, vessel, *in* a field, wood, forest, desert, wilderness (but *on* a heath, moor, or common), *in* (U.S. *on*) a street, *in* a house, carriage, box, drawer, nut-shell, drop of water, etc.
>
>
> | Very simple. "In Church Road" is British English; "On Church Road" is American English. |
6,679 | I was trying to find a chat room associated with an answer to a few different questions, but in all instances I kept getting hit with a 'Page Not Found' presumably because I lacked the 20 rep to participate.
I was under the impression that in order to participate in chat I need 20 rep on the relevant site (in this case RPG SE). Is this assumption erroneous?
If so, do I need rep on Stack Exchange, if so, how do I do that? This might seem like a dumb question, but it appears that their page is a list of questions from a litany of different sub-exchanges such as RPG SE, Mathematica SE, etc.
Specifically this post: <https://rpg.stackexchange.com/a/19679/31402>
and this post: <https://rpg.stackexchange.com/a/38202/31402> | 2017/01/10 | [
"https://rpg.meta.stackexchange.com/questions/6679",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/31402/"
] | You already have enough reputation to participate in chat. That's not what's going on there.
Since forever, chat rooms that aren't active get automatically frozen (read-only), then eventually possibly deleted (inaccessible). [The criteria for deletion](http://chat.stackexchange.com/faq#retention) nearly perfectly matches the typical chat room that is created when comments are moved to chat, but the move-to-chat feature is younger than the delete-disused-rooms feature, and they have never been reconciled by the SE developers.
This results in getting “Page Not Found” when you go look for old chat rooms that were spawned from comments moved to chat, because they've been auto-deleted. These deleted rooms are technically still archived, but no longer publicly accessible. That's also for great reasons that make sense in other cases (a deleted room shouldn't be accessible, right?!), but doesn't quite make sense for moved-comments chat rooms.
There's a feature request on Meta.SO to have it changed so transcripts of such rooms are still readable — because wouldn't it make sense for those logs to be available still? — but it doesn't appear to have much traction: [Make chat room transcripts forever public if the room was auto-deleted](https://meta.stackexchange.com/questions/288612/make-chat-room-transcripts-forever-public-if-the-room-was-auto-deleted)
Is there a workaround?
----------------------
If a room is particularly important to humans despite not meeting the algorithm's sense of importance, it can be resurrected. Most aren't super-interesting, but your second example kind of has the *intention* of being longer-living: the idea was for it to be a place to discuss a certain topic, but as a room it never took off. (The actual activity in that chat room was almost non-existent.)
Most of the time, it *won't* be worth it, but in the rare cases where it is, a mod can resurrect a room by undeleting and unfreezing it; the easiest way being a flag on the associated moved-to-chat comment. If it garners sufficient activity after that, it will avoid auto-deletion again (though not freezing, but those are at least readable still). No promise that such requests will always be fulfilled, but then again, it's neither much work on our part nor much disruption if it was done without good reason, since it'll revert to the deleted state if it's not used. | SevenSidedDie's pretty adequately explained why you can't view those chat rooms, which is the core of the issue.
I want to clarify what's going on with the reputation and access, since you're correct about some things and mistaken about others:
* The Chat counts your network reputation as the sum total of your reputation on each Stack Exchange site you're a member of. You already have at least 2k Stack Exchange rep by the chat's count. (There is otherwise no concept of "Stack Exchange rep".)
* [You are correct that you need 20 rep to participate in chat](https://rpg.stackexchange.com/help/privileges/chat). However once you unlock that privilege you can participate in ***any*** chat room. You do not need to earn 20 rep per site. I can speak in chat rooms for sites I don't even have an account on. (Stack Overflow is different: since it has its own chat servers, it only counts reputation from Stack Overflow.)
* You do need 20 rep to participate in chats, but you *never* need it to view them. Chat rooms are public, even to people who have no account anywhere on the Stack Exchange network — try viewing a room in private browsing mode. If you're having issues finding a room, this would have nothing to do with it. |
70,290,260 | I want the bot to delete a message if the 'no no word' (anything in `nono`) is in it, but it should delete only if ***only*** that word is sent.
Example: the 'no no word' is "Hate", but if I send "I Hate you", it shouldn't delete the message. It should delete only if I send *only* "Hate" (without the "I" and "you" before and after it).
Here is my code:
```py
nono = ['Hate']
@client.event
@commands.has_permissions(manage_messages = False)
async def on_message(message):
if message.author.id == client.user.id:
return
if message.guild is not None:
for word in nono:
if word in message.content:
await message.delete()
await message.author.send('I hate you too')
await client.process_commands(message)
else :
return
``` | 2021/12/09 | [
"https://Stackoverflow.com/questions/70290260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17541665/"
] | Are you sure that you wrote "I Hate you" and not "I hate you" in your message?
I have built a minimal example according to your code and it works fine.
```py
nono = ['Hate']
message = "I hate you"
for word in nono:
m = message.upper()
if word.upper() in m:
print("delete")
else:
print("Nothing")
```
I also recommend you to upper case your strings so that your detection is not case sensitive. | Try using a json file, I've personally made a few automod bots and all of them use json.
Here's an example:
```
@commands.Cog.listener()
async def on_message(self, message):
user = message.author
guild_id = message.guild.id
em = discord.Embed(title="Profanity filter", description="Please refrain from using blacklisted words!", color=magenta)
em.set_footer(text=user.name, icon_url=user.avatar_url)
em.set_author(name=message.guild.name, icon_url=message.guild.icon_url)
with open(f"json/{guild_id}/blacklist.json", 'r') as f:
badwords = json.load(f)
if any(word in message.content.lower() for word in badwords):
await message.delete()
return await message.channel.send(embed=em)
```
It reads the json file that's in the folder with the name corresponding to the discord guild ID. If the word is in that file it deletes it.
This is what the json file would look like:
```
{
"test": {
"test": "test"
},
"test": {
"test2": "test2"
}
}
``` |
70,290,260 | I want the bot to delete a message if the 'no no word' (anything in `nono`) is in it, but it should delete only if ***only*** that word is sent.
Example: the 'no no word' is "Hate", but if I send "I Hate you", it shouldn't delete the message. It should delete only if I send *only* "Hate" (without the "I" and "you" before and after it).
Here is my code:
```py
nono = ['Hate']
@client.event
@commands.has_permissions(manage_messages = False)
async def on_message(message):
if message.author.id == client.user.id:
return
if message.guild is not None:
for word in nono:
if word in message.content:
await message.delete()
await message.author.send('I hate you too')
await client.process_commands(message)
else :
return
``` | 2021/12/09 | [
"https://Stackoverflow.com/questions/70290260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17541665/"
] | Are you sure that you wrote "I Hate you" and not "I hate you" in your message?
I have built a minimal example according to your code and it works fine.
```py
nono = ['Hate']
message = "I hate you"
for word in nono:
m = message.upper()
if word.upper() in m:
print("delete")
else:
print("Nothing")
```
I also recommend you to upper case your strings so that your detection is not case sensitive. | **Update:**
My friend has figured it out. Basically, this is the code from him:
```py
nono ['Hate']
for word in nono:
if message.content.lower().find(word)!=-1:
await message.delete()
await message.author.send("I hate you too dummy!")
```
Kudos to him :D |
70,290,260 | I want the bot to delete a message if the 'no no word' (anything in `nono`) is in it, but it should delete only if ***only*** that word is sent.
Example: the 'no no word' is "Hate", but if I send "I Hate you", it shouldn't delete the message. It should delete only if I send *only* "Hate" (without the "I" and "you" before and after it).
Here is my code:
```py
nono = ['Hate']
@client.event
@commands.has_permissions(manage_messages = False)
async def on_message(message):
if message.author.id == client.user.id:
return
if message.guild is not None:
for word in nono:
if word in message.content:
await message.delete()
await message.author.send('I hate you too')
await client.process_commands(message)
else :
return
``` | 2021/12/09 | [
"https://Stackoverflow.com/questions/70290260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17541665/"
] | Are you sure that you wrote "I Hate you" and not "I hate you" in your message?
I have built a minimal example according to your code and it works fine.
```py
nono = ['Hate']
message = "I hate you"
for word in nono:
m = message.upper()
if word.upper() in m:
print("delete")
else:
print("Nothing")
```
I also recommend you to upper case your strings so that your detection is not case sensitive. | You most probably are looking for [the `==` operator](https://www.w3schools.com/python/trypython.asp?filename=demo_oper_compare1):
```py
nono = ['Hate']
@client.event
@commands.has_permissions(manage_messages = False)
async def on_message(message):
if message.author.id == client.user.id:
return
if message.guild is not None:
for word in nono:
if word == message.content: #If the message's content is EXACTLY and ONLY the word
author = message.author
#Storing the message's 'author' in this variable as 'message.author.send()' probably won't work
#as mentioned in https://stackoverflow.com/questions/70290260/discord-py-delete-message-if-the-no-no-word-is-in-it/70290501#comment124313432_70307898
await message.delete()
await author.send('I hate you too')
await client.process_commands(message)
else :
return
```
You used `in` instead of `==`. `==` checks if the LHS (Left Hand Side) is the same as the RHS (Right Hand Side). `in` in `if word in message.content:` checks if the LHS (`word`) is *somewhere* in the RHS (`message.content`) and *doesn't bother if there's something other than/after/before/with the LHS* unlike `==`. |
70,290,260 | I want the bot to delete a message if the 'no no word' (anything in `nono`) is in it, but it should delete only if ***only*** that word is sent.
Example: the 'no no word' is "Hate", but if I send "I Hate you", it shouldn't delete the message. It should delete only if I send *only* "Hate" (without the "I" and "you" before and after it).
Here is my code:
```py
nono = ['Hate']
@client.event
@commands.has_permissions(manage_messages = False)
async def on_message(message):
if message.author.id == client.user.id:
return
if message.guild is not None:
for word in nono:
if word in message.content:
await message.delete()
await message.author.send('I hate you too')
await client.process_commands(message)
else :
return
``` | 2021/12/09 | [
"https://Stackoverflow.com/questions/70290260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17541665/"
] | Try using a json file, I've personally made a few automod bots and all of them use json.
Here's an example:
```
@commands.Cog.listener()
async def on_message(self, message):
user = message.author
guild_id = message.guild.id
em = discord.Embed(title="Profanity filter", description="Please refrain from using blacklisted words!", color=magenta)
em.set_footer(text=user.name, icon_url=user.avatar_url)
em.set_author(name=message.guild.name, icon_url=message.guild.icon_url)
with open(f"json/{guild_id}/blacklist.json", 'r') as f:
badwords = json.load(f)
if any(word in message.content.lower() for word in badwords):
await message.delete()
return await message.channel.send(embed=em)
```
It reads the json file that's in the folder with the name corresponding to the discord guild ID. If the word is in that file it deletes it.
This is what the json file would look like:
```
{
"test": {
"test": "test"
},
"test": {
"test2": "test2"
}
}
``` | **Update:**
My friend has figured it out. Basically, this is the code from him:
```py
nono ['Hate']
for word in nono:
if message.content.lower().find(word)!=-1:
await message.delete()
await message.author.send("I hate you too dummy!")
```
Kudos to him :D |
70,290,260 | I want the bot to delete a message if the 'no no word' (anything in `nono`) is in it, but it should delete only if ***only*** that word is sent.
Example: the 'no no word' is "Hate", but if I send "I Hate you", it shouldn't delete the message. It should delete only if I send *only* "Hate" (without the "I" and "you" before and after it).
Here is my code:
```py
nono = ['Hate']
@client.event
@commands.has_permissions(manage_messages = False)
async def on_message(message):
if message.author.id == client.user.id:
return
if message.guild is not None:
for word in nono:
if word in message.content:
await message.delete()
await message.author.send('I hate you too')
await client.process_commands(message)
else :
return
``` | 2021/12/09 | [
"https://Stackoverflow.com/questions/70290260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17541665/"
] | Try using a json file, I've personally made a few automod bots and all of them use json.
Here's an example:
```
@commands.Cog.listener()
async def on_message(self, message):
user = message.author
guild_id = message.guild.id
em = discord.Embed(title="Profanity filter", description="Please refrain from using blacklisted words!", color=magenta)
em.set_footer(text=user.name, icon_url=user.avatar_url)
em.set_author(name=message.guild.name, icon_url=message.guild.icon_url)
with open(f"json/{guild_id}/blacklist.json", 'r') as f:
badwords = json.load(f)
if any(word in message.content.lower() for word in badwords):
await message.delete()
return await message.channel.send(embed=em)
```
It reads the json file that's in the folder with the name corresponding to the discord guild ID. If the word is in that file it deletes it.
This is what the json file would look like:
```
{
"test": {
"test": "test"
},
"test": {
"test2": "test2"
}
}
``` | You most probably are looking for [the `==` operator](https://www.w3schools.com/python/trypython.asp?filename=demo_oper_compare1):
```py
nono = ['Hate']
@client.event
@commands.has_permissions(manage_messages = False)
async def on_message(message):
if message.author.id == client.user.id:
return
if message.guild is not None:
for word in nono:
if word == message.content: #If the message's content is EXACTLY and ONLY the word
author = message.author
#Storing the message's 'author' in this variable as 'message.author.send()' probably won't work
#as mentioned in https://stackoverflow.com/questions/70290260/discord-py-delete-message-if-the-no-no-word-is-in-it/70290501#comment124313432_70307898
await message.delete()
await author.send('I hate you too')
await client.process_commands(message)
else :
return
```
You used `in` instead of `==`. `==` checks if the LHS (Left Hand Side) is the same as the RHS (Right Hand Side). `in` in `if word in message.content:` checks if the LHS (`word`) is *somewhere* in the RHS (`message.content`) and *doesn't bother if there's something other than/after/before/with the LHS* unlike `==`. |
12,907,206 | This is coming from a wordpress site I'm working on, but isn't a WP-specific question.
I have an if/else PHP statement that checks whether the user is looking at my site's home page or not. If they are looking at the home page, I want the code to do nothing. If they AREN'T, I want it to display the page title in a config.
The code I currently have is:
```
<div class="page-header">
<h1>
<?php
if ( is_front_page()){
echo ' ';
}
elseif (is_home()) {
if (get_option('page_for_posts', true)) {
echo get_the_title(get_option('page_for_posts', true));
} else {
_e('Latest Posts', 'roots');
}
} elseif (is_archive()) {
$term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
if ($term) {
echo $term->name;
} elseif (is_post_type_archive()) {
echo get_queried_object()->labels->name;
} elseif (is_day()) {
printf(__('Daily Archives: %s', 'roots'), get_the_date());
} elseif (is_month()) {
printf(__('Monthly Archives: %s', 'roots'), get_the_date('F Y'));
} elseif (is_year()) {
printf(__('Yearly Archives: %s', 'roots'), get_the_date('Y'));
} elseif (is_author()) {
global $post;
$author_id = $post->post_author;
printf(__('Author Archives: %s', 'roots'), get_the_author_meta('display_name', $author_id));
} else {
single_cat_title();
}
} elseif (is_search()) {
printf(__('Search Results for %s', 'roots'), get_search_query());
} elseif (is_404()) {
_e('File Not Found', 'roots');
} else {
the_title();
}
?>
</h1>
</div>
```
I know the `echo ' ';` is probably way off, but I'm an absolute php beginner! At present this creates an empty `<div>` and `<h4>` tag, but I'd rather clean it up and create nothing at all on the home page.
How can I best modify the code above to achieve this? | 2012/10/16 | [
"https://Stackoverflow.com/questions/12907206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556006/"
] | You need to move your code around. If you don't want the leading `<div><h1>` be printed on the front page, then move the `if` check before that. Add an `else` where you then print the `<div><h1>`, the big if/else code blob, and the closing `</div>`, etc.
Also read up on [switching in and out of PHPs code and html mode](http://php.net/manual/en/language.basic-syntax.phpmode.php).
Albeit, it's probably best explained by just showing:
```
<?php
if ( is_front_page()){
echo ' ';
}
else {
?>
<div class="page-header">
<h1>
<?php
if (is_home()) {
if (get_option('page_for_posts', true)) {
echo get_the_title(get_option('page_for_posts', true));
/*
...
*/
} else {
the_title();
}
?>
</h1>
</div>
<?php
}
?>
```
The only interesting thing here is that you enclose the html+code blob between the `else`s opening `{` and closing `}` curly brace. | Put your echos into a variable instead of printing them, then after your if statements do
echo ($var =='') ? '' : ''.$var.'';
Html tags between the last 2 sets of single quotes |
643,662 | I'm fairly newbie to these concepts, so please try to give a simply answer.
Electric energy is often compared to gravitational energy. This analogy helps to understand the concept of voltage. With gravitation, there is a *potential difference* between two points (given that they're not in the same height), and this potential difference is the *potential energy difference* per unit of mass. With electricity, the *potential difference* is potential energy difference per one Coulomb of charge.
My question is: With gravitation, the mere arrangement of having 2 points with potential difference between them doesn't mean having a flow of mass between them. We need to bring some mass to the higher point in order to have *potential energy*. But with electricity, it seems that if you only have two points with potential difference between them, meaning that you already have *potential energy*, and all you have to do is to connect this two points with a conductive material.
Another question related to this: The difference in gravitational potential difference is rooted in the difference of the height between the points. What is the root cause of the electrical potential difference between two points? | 2021/06/06 | [
"https://physics.stackexchange.com/questions/643662",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/299695/"
] | You probably realize this is a very general question and a wall of text can be insufficient to answer it thoroughly. Still, one the most concise definitions of waves is that it's an oscillation which propagates in space.
When you ask "what are these waves made of", I suppose you wonder about a physical quantity which oscillates in each particular case. For example, in case of waves on the water surface such quantity would be the vertical displacement of the molecules of water. Generally the answer depends on the nature of waves. In electromagnetic waves, it's the electromagnetic field. In de Broglie's waves, it's the probability amplitude of finding a particle.
Regarding the medium where the waves can propagate, it again differs between different waves. For example, electromagnetic waves can propagate in vacuum while acoustic waves cannot. | Broadly, a wave is simply a quantity that changes in a periodic way over space and/or time.
In the case of a water wave, the changing quantity is the distance through which the surface is displaced- or, if you like, just the height of the surface.
With a wave on a string, the changing quantity is the displacement of the string from its resting position.
With a sound wave, the changing quantity is air pressure.
The frequency of a wave is the number of times per second that the changing quantity oscillates. The wavelength is the distance between successive occurrences of maximum or minimum values of the changing quantity.
With electromagnetic waves, the changing quantity is the strength of the electric and magnetic fields that permeate space. If you are happy with the idea of an electric field, for example, then you can think of the wave as being a periodic fluctuation in the strength of the field at every point.
All particles seem to have a wave-like aspect (the particle wave duality you mentioned). In the case of those waves, the changing quantity, very loosely speaking, is a measure of the probability that the particle will be found at a particular point.
Strictly speaking, the idea of a pure wave with a precise frequency and wavelength everywhere in space is a bit of a fiction. In reality waves tend to be less uniform than that, and their properties can become very difficult to model precisely. |
643,662 | I'm fairly newbie to these concepts, so please try to give a simply answer.
Electric energy is often compared to gravitational energy. This analogy helps to understand the concept of voltage. With gravitation, there is a *potential difference* between two points (given that they're not in the same height), and this potential difference is the *potential energy difference* per unit of mass. With electricity, the *potential difference* is potential energy difference per one Coulomb of charge.
My question is: With gravitation, the mere arrangement of having 2 points with potential difference between them doesn't mean having a flow of mass between them. We need to bring some mass to the higher point in order to have *potential energy*. But with electricity, it seems that if you only have two points with potential difference between them, meaning that you already have *potential energy*, and all you have to do is to connect this two points with a conductive material.
Another question related to this: The difference in gravitational potential difference is rooted in the difference of the height between the points. What is the root cause of the electrical potential difference between two points? | 2021/06/06 | [
"https://physics.stackexchange.com/questions/643662",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/299695/"
] | You probably realize this is a very general question and a wall of text can be insufficient to answer it thoroughly. Still, one the most concise definitions of waves is that it's an oscillation which propagates in space.
When you ask "what are these waves made of", I suppose you wonder about a physical quantity which oscillates in each particular case. For example, in case of waves on the water surface such quantity would be the vertical displacement of the molecules of water. Generally the answer depends on the nature of waves. In electromagnetic waves, it's the electromagnetic field. In de Broglie's waves, it's the probability amplitude of finding a particle.
Regarding the medium where the waves can propagate, it again differs between different waves. For example, electromagnetic waves can propagate in vacuum while acoustic waves cannot. | For the layman: The defining characteristic of a wave is that it takes time for an influence to travel from place to place. E.g. Throw a stone in the water, and the influence (ripples) takes time to travel across the pond.
Physics deals with abstract entities where the medium is not always physical, from water waves (medium = water) to light and radio waves (medium = Electromagnetic field) to probability waves in Quantum Mechanics (where the medium may only exist in an observer's head)
Fun Fact: Newton's original formulation of Gravity had gravity affecting objects instantaneously (no time delay) so was not a wave theory |
643,662 | I'm fairly newbie to these concepts, so please try to give a simply answer.
Electric energy is often compared to gravitational energy. This analogy helps to understand the concept of voltage. With gravitation, there is a *potential difference* between two points (given that they're not in the same height), and this potential difference is the *potential energy difference* per unit of mass. With electricity, the *potential difference* is potential energy difference per one Coulomb of charge.
My question is: With gravitation, the mere arrangement of having 2 points with potential difference between them doesn't mean having a flow of mass between them. We need to bring some mass to the higher point in order to have *potential energy*. But with electricity, it seems that if you only have two points with potential difference between them, meaning that you already have *potential energy*, and all you have to do is to connect this two points with a conductive material.
Another question related to this: The difference in gravitational potential difference is rooted in the difference of the height between the points. What is the root cause of the electrical potential difference between two points? | 2021/06/06 | [
"https://physics.stackexchange.com/questions/643662",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/299695/"
] | Ever since the discovery of calculus mathematics, mathematical functions are used in order to model observations and special axioms are introduced in order to connect the pure numbers of mathematics with observable numbers.
Waves in water, the first waves to be observed are defined by their height and frequency in time and motion in time and space, and can be fitted with the solutions of what is called a ["wave equation"](http://hyperphysics.phy-astr.gsu.edu/hbase/Waves/waveq.html)
>
> The wave equation for a plane wave traveling in the x direction is $$\frac{\partial^2y}{\partial x^2}=\frac1{v^2}\frac{\partial^2y}{\partial t^2}$$ where $v$ is the phase velocity of the wave and $y$ represents the variable which is changing as the wave passes.
>
>
>
The solutions are in terms of sines and cosines which have the frequency of the repetition inherent.
When [Maxwell brilliantly](https://en.wikipedia.org/wiki/Maxwell%27s_equations#Formulation_in_SI_units_convention) united what were disparate laws and equation in the study of electricity and magnetism into one set of interdependent differential equations, to everybody's surprise, a wave equation resulted. The solutions of this fitted light and the rest of electromagnetic phenomena to very great accuracy.
[Here is](https://en.wikipedia.org/wiki/Electromagnetic_radiation#Properties) a polarized electromagnetic wave showing that it depends on Electric and B magnetic fields changing in time.
[](https://i.stack.imgur.com/JB2NP.gif)
>
> Electromagnetic waves can be imagined as a self-propagating transverse oscillating wave of electric and magnetic fields. This 3D animation shows a plane linearly polarized wave propagating from left to right. The electric and magnetic fields in such a wave are in-phase with each other, reaching minima and maxima together.
>
>
>
From infrared radiation to visible light to radioto gamma rays, this model is always validated .
>
> even worse when I read about the double slit experiment and particle wave duality.
>
>
>
The waves in particle wave duality are **probability waves** [as seen here](http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/qm.html). The wave function postulate is in the third page of the link. This means one must accumulate events in order to see the interference patterns predicted by the wave nature of the probability of interaction See this [answer of mine o](https://physics.stackexchange.com/questions/238855/is-it-wrong-to-say-that-an-electron-can-be-a-wave/238866#238866)n this.. | Broadly, a wave is simply a quantity that changes in a periodic way over space and/or time.
In the case of a water wave, the changing quantity is the distance through which the surface is displaced- or, if you like, just the height of the surface.
With a wave on a string, the changing quantity is the displacement of the string from its resting position.
With a sound wave, the changing quantity is air pressure.
The frequency of a wave is the number of times per second that the changing quantity oscillates. The wavelength is the distance between successive occurrences of maximum or minimum values of the changing quantity.
With electromagnetic waves, the changing quantity is the strength of the electric and magnetic fields that permeate space. If you are happy with the idea of an electric field, for example, then you can think of the wave as being a periodic fluctuation in the strength of the field at every point.
All particles seem to have a wave-like aspect (the particle wave duality you mentioned). In the case of those waves, the changing quantity, very loosely speaking, is a measure of the probability that the particle will be found at a particular point.
Strictly speaking, the idea of a pure wave with a precise frequency and wavelength everywhere in space is a bit of a fiction. In reality waves tend to be less uniform than that, and their properties can become very difficult to model precisely. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.