Search is not available for this dataset
qid
int64 1
74.7M
| question
stringlengths 1
70k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 0
115k
| response_k
stringlengths 0
60.5k
|
---|---|---|---|---|---|
25,948,218 | My java project has files which have same name but different cases (Test.java & test.java). I have setup a case sensitive file system on my mac and am able to view/edit them via CLI. However, Intellij Idea does not regard them as different and compilation fails. How can I fix Intellij Idea to honor cases for a file name?
Thanks | 2014/09/20 | [
"https://Stackoverflow.com/questions/25948218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367890/"
] | I filed a support request at JetBrains. Here is the answer:
>
> add "idea.case.sensitive.fs=true" to bin/idea.properties file (<https://intellij-support.jetbrains.com/entries/23395793> ), perform File | Invalidate Caches and restart the IDE.
>
>
>
It solved the issue for me.
update: 2015-02-14 / Idea 14.0.3
It is no longer sufficient to add the property to the idea.properties file. Add `-Didea.case.sensitive.fs=true` to "Settings | ... | Java Compiler | Additional command line parameters". | To update your case sensitive settings you can simply run the folowing in your shell (Path would have to be changed for InteliJ as I use php storm but should work for the jet brains products)
```
echo idea.case.sensitive.fs=true >> /Applications/PhpStorm.app/Contents/bin/idea.properties
``` |
25,948,218 | My java project has files which have same name but different cases (Test.java & test.java). I have setup a case sensitive file system on my mac and am able to view/edit them via CLI. However, Intellij Idea does not regard them as different and compilation fails. How can I fix Intellij Idea to honor cases for a file name?
Thanks | 2014/09/20 | [
"https://Stackoverflow.com/questions/25948218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367890/"
] | I filed a support request at JetBrains. Here is the answer:
>
> add "idea.case.sensitive.fs=true" to bin/idea.properties file (<https://intellij-support.jetbrains.com/entries/23395793> ), perform File | Invalidate Caches and restart the IDE.
>
>
>
It solved the issue for me.
update: 2015-02-14 / Idea 14.0.3
It is no longer sufficient to add the property to the idea.properties file. Add `-Didea.case.sensitive.fs=true` to "Settings | ... | Java Compiler | Additional command line parameters". | It looks like the best option may be to add the idea.properties option to user profile configuration rather than global.
See the first comment here:
<https://confluence.jetbrains.com/display/IDEADEV/Filesystem+Case-Sensitivity+Mismatch>
Also this page mentions where the idea.properties file should go, if you don't have one already.
<https://www.jetbrains.com/help/idea/file-idea-properties.html> |
25,948,218 | My java project has files which have same name but different cases (Test.java & test.java). I have setup a case sensitive file system on my mac and am able to view/edit them via CLI. However, Intellij Idea does not regard them as different and compilation fails. How can I fix Intellij Idea to honor cases for a file name?
Thanks | 2014/09/20 | [
"https://Stackoverflow.com/questions/25948218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367890/"
] | To update your case sensitive settings you can simply run the folowing in your shell (Path would have to be changed for InteliJ as I use php storm but should work for the jet brains products)
```
echo idea.case.sensitive.fs=true >> /Applications/PhpStorm.app/Contents/bin/idea.properties
``` | It looks like the best option may be to add the idea.properties option to user profile configuration rather than global.
See the first comment here:
<https://confluence.jetbrains.com/display/IDEADEV/Filesystem+Case-Sensitivity+Mismatch>
Also this page mentions where the idea.properties file should go, if you don't have one already.
<https://www.jetbrains.com/help/idea/file-idea-properties.html> |
963,370 | I'm trying to install the SSRS data connector for my CRM4 implementation.
I'm using the [Method 2: Modify the Install-config.xml file from this page](http://support.microsoft.com/kb/947060). But keep getting the same error message:
>
> Unable to validate SQL Server Reporting Services Report Server
> installation. Please check that it is correctly installed on the local
> machine.
>
>
>
I've added the following to my XML file.
```
<reportserverurl>http://SSRS-Server/Reportserver$MYORG_MSCRM</reportserverurl>
<instancename>MYORG_MSCRM</instancename>
```
Anyone know what is still wrong?
I tried several instance names but they all don't work either.
I can access my SSRS server by going to `http://SSRS-Server/Reports` and it will give a list of all services running there.
Any help would be much appreciated. | 2009/06/08 | [
"https://Stackoverflow.com/questions/963370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You may need to post more details regarding this issue:
1) The 2nd method described in this link : [here](http://support.microsoft.com/kb/947060) is used when the Reporting Server database is installed using the SQL Server named instance. Are you installing the Reporting Server database in the default instance or named instance ?
2) If you are using default instance, you might not need to use custom XML, you can just run the installer without requiring the input XML file.
3) What is the architecture of your CRM implementation ? is the CRM Application, SQL server and Reporting Server resided in the same server ? or different server ?
Hope this helps. | I realise this is a really old article however I wanted to post the resolution I found to work as I have spent the past 3 days trying to resolve this issue! I created an account just to post this.
I was having the same problem as the original article. I had SSRS 2008 installed on a server, CRM (4.0!!!) on a different server and SQL 2008 on a different server again. When all permission issues were resolved and ports were opened from the SSRS server to the SQL server, I was still having problems getting the SetupSrsDataConnector.exe to see the locally installed instance of SSRS2008 (Not R2).
I found the resolution to the issue in this article:
<https://community.dynamics.com/crm/b/pabloperalta/archive/2011/07/12/unable-to-validate-sql-server-reporting-services-report-server-installation-error-while-installing-srs-data-connector>
Effectively the problem I was having is that my copy of the SRS Connector installation files were old and needed updating, however my server did not have internet connectivity. In the link above, it gives you a download location to get a .mps file which contains the updates for the SRS Connector.
You need to download this .mps file and then run the installation via command prompt with a customised install-config.xml file, which specifies the SSRS ReportServer URL and the SSRS Instance Name in a custom tag (what you named the SSRS instance when you installed it) and another custom tag for <*Patch update="true">C:\Path to the .msp file< /Patch*>
This was my installation command:
"D:\Stage\SRSDataConnector\SetupSrsDataConnector.exe" /CONFIG "D:\Stage\SRSDataConnectorUpdates\install-config.xml" |
3,873,110 | I have a table with two number columns, and a unique constraint over them both. I would like to insert a new pair of values UNLESS the pair already exists. What is the simplest way to do this?
If I do
```
insert into TABLE values (100,200)
```
and the pair already exists I get a ORA-00001 error, so I would like to do something like
```
insert or update into TABLE values (100,200)
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3873110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64082/"
] | You can use [MERGE](http://psoug.org/reference/merge.html) | You can try something like:
```
insert into table
select :a, :b from dual
where not exists (select 1 from table where column1 = :a and column2=:b)
``` |
4,162,930 | Let it be $\alpha=1+\sqrt[3]{5}\,i$ and $f(x)$ the minimal polynomial of $\alpha$ in $\mathbb{Q}$.
Is $\mathbb{Q}(\alpha)$ the splitting field of $\alpha$?
I generally know how to deal with splitting field when the roots are simple but I dont know how to deal with this or in general when minimal polynomial aren't that easy to handle with.
Are there any properties or theorems that help as criterions to determine whether we have a splitting field or not? (if there is anything more general that covers not only this case I would be more than pleased to note them down)
I hope I didn't spell the question wrong and thanks in advance | 2021/06/04 | [
"https://math.stackexchange.com/questions/4162930",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/918258/"
] | For your example, let $\beta=\sqrt[3]5i$, then we have $\beta^6=-25$. Clearly $\beta$ has degree 6 over $\mathbb Q$, and its conjugates are given by $\beta\zeta^k$, $k=0,\dots,5$, where $\zeta=\frac{1+\sqrt3i}2$ is a primitive sixth root of unity. Therefore, the extension $\mathbb Q(\beta)/\mathbb Q$ is not Galois, because $\zeta$ is not contained in $\mathbb Q(\beta)$.
If $\mathbb Q(\alpha)$ is the splitting field, then it must be a Galois extension, but $\mathbb Q(\alpha)=\mathbb Q(\beta)$. In general, the extension of the form $\mathbb Q(\sqrt[n]m)$ can be dealt with in the same way. | Knowing that ℚ(1+∛5i)=ℚ(∛5i) and that ∛5i is root of the polynomial x^6+25, then the splitting field must be ℚ(∛5i\*ω), where ω is a primitive root of x^6-1. Thus, ℚ(α) isn't the splitting field. |
20,981,466 | I'm facing problem with jquery
here is my code
```
<script type='text/javascript' src='jquery-1.10.2.min.js'></script>
<script type="text/javascript">
$(function() {
$(".more2").click(function() {
var element = $(this);
var msg = element.attr("id");
$.ajax({
type: "POST",
url: "insta2.php",
data: "lastmsg="+ encodeURIComponent(msg),
success:function (data) {
$("#morebutton").replaceWith(data);
}
});
return false;
});
});
</script>
<span class="more" id="morebutton">
<a id="1" class="more2" title="Follow" href="#" style="color:#000">
Read More
</a>
</span>
```
and here is insta2.php
```
<?php
if(isset($_POST['lastmsg']))
{
$a= $_POST['lastmsg'];
$a = $a++;
?>
<br>
<span class="more" id="morebutton">
<a id="<?php echo $a;?>" class="more2" title="Follow" href="#" style="color:#000">
<?php echo $a;?> Read More
</a> </span>
<?php }?>
```
my jquery only one 1 set and after that every click not working
is there any way to continue counting ?
like this
Read More
1 Read More
2 Read More
3 Read More
4 Read More
and so on... | 2014/01/07 | [
"https://Stackoverflow.com/questions/20981466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69821/"
] | Looking at the [source](https://github.com/thquinn/DraggableGridView) you provided, the `DraggableGridView` class is already under `src`. So adding the jar that contains the same is redundant and dex will complain about duplicate definitions.
To fix it, just remove the `DraggableGridView.jar` from your project. | Project - build Path - Libraries.
Check if android private libraries contains the same jars listed in the libraries in the first place. If so remove private libraries and leave the jars.
That worked for me. |
20,981,466 | I'm facing problem with jquery
here is my code
```
<script type='text/javascript' src='jquery-1.10.2.min.js'></script>
<script type="text/javascript">
$(function() {
$(".more2").click(function() {
var element = $(this);
var msg = element.attr("id");
$.ajax({
type: "POST",
url: "insta2.php",
data: "lastmsg="+ encodeURIComponent(msg),
success:function (data) {
$("#morebutton").replaceWith(data);
}
});
return false;
});
});
</script>
<span class="more" id="morebutton">
<a id="1" class="more2" title="Follow" href="#" style="color:#000">
Read More
</a>
</span>
```
and here is insta2.php
```
<?php
if(isset($_POST['lastmsg']))
{
$a= $_POST['lastmsg'];
$a = $a++;
?>
<br>
<span class="more" id="morebutton">
<a id="<?php echo $a;?>" class="more2" title="Follow" href="#" style="color:#000">
<?php echo $a;?> Read More
</a> </span>
<?php }?>
```
my jquery only one 1 set and after that every click not working
is there any way to continue counting ?
like this
Read More
1 Read More
2 Read More
3 Read More
4 Read More
and so on... | 2014/01/07 | [
"https://Stackoverflow.com/questions/20981466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69821/"
] | Looking at the [source](https://github.com/thquinn/DraggableGridView) you provided, the `DraggableGridView` class is already under `src`. So adding the jar that contains the same is redundant and dex will complain about duplicate definitions.
To fix it, just remove the `DraggableGridView.jar` from your project. | Add all the jars in the libs folder externally and uncheck the android private libraries this should work |
20,981,466 | I'm facing problem with jquery
here is my code
```
<script type='text/javascript' src='jquery-1.10.2.min.js'></script>
<script type="text/javascript">
$(function() {
$(".more2").click(function() {
var element = $(this);
var msg = element.attr("id");
$.ajax({
type: "POST",
url: "insta2.php",
data: "lastmsg="+ encodeURIComponent(msg),
success:function (data) {
$("#morebutton").replaceWith(data);
}
});
return false;
});
});
</script>
<span class="more" id="morebutton">
<a id="1" class="more2" title="Follow" href="#" style="color:#000">
Read More
</a>
</span>
```
and here is insta2.php
```
<?php
if(isset($_POST['lastmsg']))
{
$a= $_POST['lastmsg'];
$a = $a++;
?>
<br>
<span class="more" id="morebutton">
<a id="<?php echo $a;?>" class="more2" title="Follow" href="#" style="color:#000">
<?php echo $a;?> Read More
</a> </span>
<?php }?>
```
my jquery only one 1 set and after that every click not working
is there any way to continue counting ?
like this
Read More
1 Read More
2 Read More
3 Read More
4 Read More
and so on... | 2014/01/07 | [
"https://Stackoverflow.com/questions/20981466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69821/"
] | Project - build Path - Libraries.
Check if android private libraries contains the same jars listed in the libraries in the first place. If so remove private libraries and leave the jars.
That worked for me. | Add all the jars in the libs folder externally and uncheck the android private libraries this should work |
34,379,584 | I shoul use setText() but how should I use it instead of System.out.println()?
I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question.
```
public class JsonReader extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt");
System.out.println(json.toString());
System.out.println(json.get("display"));
//TextView tv = (TextView) findViewById( R.id.tv );
//tv.setText(json.toString());
//tv.setText(json.get("display"));
}
```
} | 2015/12/20 | [
"https://Stackoverflow.com/questions/34379584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5184742/"
] | You need to use **Logs** to print and debug stuff in android.
Generally there are **five methods**,
```
Log.v() Log.d() Log.i() Log.w() and Log.e()
```
>
> v for Verbose
>
>
> d for Debug
>
>
> i for Info
>
>
> w for Warnings
>
>
> e for Error
>
>
>
**In your case**
```
Log.d("Key", json.toString() + "");
Log.d("Key", json.get("display") + "");
```
And you look for the values in the log cat, using the "Key" | You can use a [`CharArrayWriter`](http://developer.android.com/reference/java/io/CharArrayWriter.html) to collect the output:
```
CharArrayWriter writer = new CharArrayWriter();
// write your stuff
TextView view = ...
view.setText(writer.toString());
```
You'll have to use the methods available to a `Writer` rather than those of a `PrintStream` such as `System.out` (no `println()` methods).
If you want to use basically the same calls to generate the output, you can create a `ByteArrayOutputStream` and wrap it in a `PrintStream`. After writing (and closing the `PrintStream`), retrieve the byte array from the `ByteArrayOutputStream` and convert it to a `String` using one of the `String` constructors. You just have to specify the character encoding you want to use, both when creating the `PrintStream` and when converting the bytes to a `String`.
Another alternative would be to replace printing with simply appending your data to a `StringBuilder`.
A final alternative is simply to append directly to the `TextView`, but that requires converting every piece of output to some sort of `CharSequence`. |
34,379,584 | I shoul use setText() but how should I use it instead of System.out.println()?
I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question.
```
public class JsonReader extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt");
System.out.println(json.toString());
System.out.println(json.get("display"));
//TextView tv = (TextView) findViewById( R.id.tv );
//tv.setText(json.toString());
//tv.setText(json.get("display"));
}
```
} | 2015/12/20 | [
"https://Stackoverflow.com/questions/34379584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5184742/"
] | You will need to print the result in a TextView if you want to view the result on phone instead of LogCat console as suggested by johnrao07.
To print result in a TextView first add a TextView widget in activity\_main.xml layout file.
```
<TextView
android:id="@+id/text_view_id"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
Then JsonReader.java class main function instead of `System.out.println(json.toString());` call `((TextView) findViewById(R.id.text_view_id)).setText(json.toString());` | You need to use **Logs** to print and debug stuff in android.
Generally there are **five methods**,
```
Log.v() Log.d() Log.i() Log.w() and Log.e()
```
>
> v for Verbose
>
>
> d for Debug
>
>
> i for Info
>
>
> w for Warnings
>
>
> e for Error
>
>
>
**In your case**
```
Log.d("Key", json.toString() + "");
Log.d("Key", json.get("display") + "");
```
And you look for the values in the log cat, using the "Key" |
34,379,584 | I shoul use setText() but how should I use it instead of System.out.println()?
I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question.
```
public class JsonReader extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt");
System.out.println(json.toString());
System.out.println(json.get("display"));
//TextView tv = (TextView) findViewById( R.id.tv );
//tv.setText(json.toString());
//tv.setText(json.get("display"));
}
```
} | 2015/12/20 | [
"https://Stackoverflow.com/questions/34379584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5184742/"
] | You need to use **Logs** to print and debug stuff in android.
Generally there are **five methods**,
```
Log.v() Log.d() Log.i() Log.w() and Log.e()
```
>
> v for Verbose
>
>
> d for Debug
>
>
> i for Info
>
>
> w for Warnings
>
>
> e for Error
>
>
>
**In your case**
```
Log.d("Key", json.toString() + "");
Log.d("Key", json.get("display") + "");
```
And you look for the values in the log cat, using the "Key" | ```
public class JsonReader extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable(){
public void run(){
JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt");
System.out.println(json.toString());
System.out.println(json.get("display"));
runOnUiThread(new Runnable(){
public void run(){
TextView tv = (TextView) findViewById( R.id.tv );
tv.setText(json.toString());
tv.setText(json.get("display"));
}
});
}
}).start();
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
//move to onCreate
}
}
``` |
34,379,584 | I shoul use setText() but how should I use it instead of System.out.println()?
I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question.
```
public class JsonReader extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt");
System.out.println(json.toString());
System.out.println(json.get("display"));
//TextView tv = (TextView) findViewById( R.id.tv );
//tv.setText(json.toString());
//tv.setText(json.get("display"));
}
```
} | 2015/12/20 | [
"https://Stackoverflow.com/questions/34379584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5184742/"
] | You will need to print the result in a TextView if you want to view the result on phone instead of LogCat console as suggested by johnrao07.
To print result in a TextView first add a TextView widget in activity\_main.xml layout file.
```
<TextView
android:id="@+id/text_view_id"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
Then JsonReader.java class main function instead of `System.out.println(json.toString());` call `((TextView) findViewById(R.id.text_view_id)).setText(json.toString());` | You can use a [`CharArrayWriter`](http://developer.android.com/reference/java/io/CharArrayWriter.html) to collect the output:
```
CharArrayWriter writer = new CharArrayWriter();
// write your stuff
TextView view = ...
view.setText(writer.toString());
```
You'll have to use the methods available to a `Writer` rather than those of a `PrintStream` such as `System.out` (no `println()` methods).
If you want to use basically the same calls to generate the output, you can create a `ByteArrayOutputStream` and wrap it in a `PrintStream`. After writing (and closing the `PrintStream`), retrieve the byte array from the `ByteArrayOutputStream` and convert it to a `String` using one of the `String` constructors. You just have to specify the character encoding you want to use, both when creating the `PrintStream` and when converting the bytes to a `String`.
Another alternative would be to replace printing with simply appending your data to a `StringBuilder`.
A final alternative is simply to append directly to the `TextView`, but that requires converting every piece of output to some sort of `CharSequence`. |
34,379,584 | I shoul use setText() but how should I use it instead of System.out.println()?
I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question.
```
public class JsonReader extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt");
System.out.println(json.toString());
System.out.println(json.get("display"));
//TextView tv = (TextView) findViewById( R.id.tv );
//tv.setText(json.toString());
//tv.setText(json.get("display"));
}
```
} | 2015/12/20 | [
"https://Stackoverflow.com/questions/34379584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5184742/"
] | You will need to print the result in a TextView if you want to view the result on phone instead of LogCat console as suggested by johnrao07.
To print result in a TextView first add a TextView widget in activity\_main.xml layout file.
```
<TextView
android:id="@+id/text_view_id"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
Then JsonReader.java class main function instead of `System.out.println(json.toString());` call `((TextView) findViewById(R.id.text_view_id)).setText(json.toString());` | ```
public class JsonReader extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable(){
public void run(){
JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt");
System.out.println(json.toString());
System.out.println(json.get("display"));
runOnUiThread(new Runnable(){
public void run(){
TextView tv = (TextView) findViewById( R.id.tv );
tv.setText(json.toString());
tv.setText(json.get("display"));
}
});
}
}).start();
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
//move to onCreate
}
}
``` |
39,041,257 | How optimize an API call in symfony?
I call with Guzzle bundle, but the time in some situations is very long.
In client application call a function from the server.
In server application extract the objects from the database and send back to the client.
In client creat the new object with properties from server respons. | 2016/08/19 | [
"https://Stackoverflow.com/questions/39041257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | One of the ways to improve your API calls is to use caching. In Symfony there are many different ways to achieve this. I can show you one of them (`PhpFileCache` example):
In **services.yml** create cache service:
```
your_app.cache_provider:
class: Doctrine\Common\Cache\PhpFileCache
arguments: ["%kernel.cache_dir%/path_to/your_cache_dir", ".your.cached_file_name.php"]
```
(Remember, you need `Doctrine` extension in your app to work)
Then pass your caching service `your_app.cache_provider` to any service where you need caching:
Again in your **services.yml**:
```
some_service_of_yours:
class: AppBundle\Services\YourService
arguments: ['@your_app.cache_provider']
```
Finally, in your service (where you want to perform API caching):
```
use Doctrine\Common\Cache\CacheProvider;
class YourService
{
private $cache;
public function __construct(CacheProvider $cache)
{
$this->cache = $cache;
}
public function makeApiRequest()
{
$key = 'some_unique_identifier_of_your_cache_record';
if(!$data = $this->cache->fetch($key))
{
$data = $provider->makeActualApiCallHere('http://some_url');
$this->cache->save($key, serialize($data), 10800); //10800 here is amount of seconds to store your data in cache before its invalidated, change it to your needs
}
return $data; // now you can use the data
}
}
```
This is quite GENERIC example, you should change it to your exact needs, but idea is simple. You can cache data and avoid unnecessary API calls to speed things up. Be careful though, because cache has drawback of presenting stale(obsolete) data. Some things can (and should) be cached, but some things don't. | **If you control the server**
You should put a cache reverse proxy like Varnish on top of your PHP server. The PHP app must send HTTP cache headers to tell to the proxy how many time it must cache the request. Alternatively, you can use a library like [FOSHttpCache](http://foshttpcachebundle.readthedocs.io/en/latest/) to setup a cache invalidation strategy (the PHP server will purge the cache from the proxy when an update of the data occurs - it's a more advanced and complex scenario).
The PHP server will not even be called if the requested resource is in the reverse proxy cache.
You should also use a profiler like Blackfire.io or xhprof to find why some parts of your PHP code (or your SQL queries) take so many time to be executed, then optimize.
**If you control the client**
You can use [this HTTP cache middleware for Guzzle](https://github.com/Kevinrob/guzzle-cache-middleware) to cache every API result according to HTTP headers sent by the API. |
86,352 | ```
> CREATE TABLE test(foo FLOAT);
> INSERT INTO test VALUES(1.2899999);
> SELECT * FROM test;
+------+
| foo |
+------+
| 1.29 |
+------+
```
While it's obvious that FLOAT is not a precise data type, it is still rounding this data too arbitrarily. Let's check if it's actually able to store it:
```
> ALTER TABLE test MODIFY foo DOUBLE;
> SELECT * FROM test;
+--------------------+
| foo |
+--------------------+
| 1.2899998426437378 |
+--------------------+
```
Whoops, only the 7th digit got corrupted due format limitations. Is there a way to prevent overzealous rounding in this situation, short of converting the column to DOUBLE? | 2014/12/16 | [
"https://dba.stackexchange.com/questions/86352",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/9479/"
] | I hate precision-based issues. I dealt with one before: [Data Truncated for Column](https://dba.stackexchange.com/questions/4091/data-truncated-for-column/4094#4094)
You may have do the ALTER TABLE manually
```
CREATE TABLE test_new LIKE test;
ALTER TABLE test_new MODIFY foo DOUBLE;
INSERT INTO test_new (foo) SELECT CONVERT(foo,DOUBLE) FROM test;
RENAME TABLE test TO test_old,test_new TO test;
DROP TABLE test_old;
```
or
```
CREATE TABLE test_new LIKE test;
ALTER TABLE test_new MODIFY foo DOUBLE;
INSERT INTO test_new (foo) SELECT CONVERT(foo,DECIMAL(10,7)) FROM test;
RENAME TABLE test TO test_old,test_new TO test;
DROP TABLE test_old;
```
or
```
CREATE TABLE test_new LIKE test;
ALTER TABLE test_new MODIFY foo DOUBLE;
INSERT INTO test_new (foo) SELECT FORMAT(foo,7) FROM test;
RENAME TABLE test TO test_old,test_new TO test;
DROP TABLE test_old;
```
Not sure what will happen, but give it a try and see what happens. | Maybe this post could be somehow useful for your question - as far as I had experience with till now (even in ERP db we serviced for nearly 5 years) type `FLOAT` or `DOUBLE` was almost never used.
Instead of it all the fields storing values like cost prices, purchase prices, stock item characteristics, warehouse, production, accountance data - always had fixed decimal places count by using i.e. `NUMERIC(20,8)` (MSSQL) which of course in MySQL would be `DECIMAL(20,8)`.
Thus, if any rounding were to be performed, it must have been done (mostly) in the application layer. |
34,494 | I have a data-set of genetic variants which I'm trying to use as predictors for a simple phenotype, and for starters I use a binary logistic regression in SPSS. I have around 900 individuals, and for each individual around 50 variations and a phenotype.
However, I get an unreasonably high amount of removed values when I run the analysis (there is some missing variants data all over the entire table), i.e., only around 50% of my measurements are actually used, and I can't find the exclusion-cut-off SPSS uses for this anywhere.
Does anyone know the cut-off that SPSS employs in this? Or does it remove a measurement once it finds a single missing variant? | 2012/08/17 | [
"https://stats.stackexchange.com/questions/34494",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/12259/"
] | SPSS removes cases [list-wise](http://en.wikipedia.org/wiki/Listwise_deletion) by default, and in my experience this is the case for the majority of statistical procedures. So if a case is missing data for any of the variables in the analysis it will be dropped entirely from the model. For generating correlation matrices or linear regression you *can* exclude cases pair-wise if you want (I'm not sure if that is ever really advised), but for logistic and generalized linear model regression procedures this isn't an option. Hence you may want to look at techniques for imputing missing data.
Below are some resources I came up quickly for missing data analysis in SPSS;
* User [ttnphns](https://stats.stackexchange.com/users/3277/ttnphns) has a macro for hot-deck imputation on his [web site](http://rivita.ru/spssmacros_en.shtml). I also see [Andrew Hayes](http://www.afhayes.com/spss-sas-and-mplus-macros-and-code.html) has a macro for hot-deck imputation.
* Raynald Levesque's site has a set of example syntax implementations of various [missing values procedures](http://spsstools.net/SampleSyntax.htm#WorkingWithMissingValues). Including another implementation of hot-deck imputation!
* SPSS has various tools in-built for imputing missing values. See the commands `MVA`, `RMV`, and `MULTIPLE IMPUTATION`. See the [Missing Values Analysis](http://publib.boulder.ibm.com/infocenter/spssstat/v20r0m0/index.jsp?topic=%2Fcom.ibm.spss.statistics.help%2Fidh_miss.htm) section in the HELP documentation.
I'm not quite sure what is available in base and what are available as add-ons. I believe the `MULTIPLE IMPUTATION` command is an add-on, but the others are part of the base package. and the `MVA` commands are add-ons, but the `RMV` procedure is part of the base package.
For more general questions about missing data analysis, peruse the tag [missing-data](/questions/tagged/missing-data "show questions tagged 'missing-data'"). | Ran into this problem too, the only option for missing case deletion in logistic regression is listwise.
It is very weird that its not an option, there are certainly cases where pairwise deletion is appropriate (e.g. ipsative data)
I recommend switching to R
Its a steep learning curve but well worth it for the degree of control, particularly if youre working with large datasets |
74,309,944 | I have a db like this:
```
tibble(Q1 = c("0","A"),
Q2 = c("A","A"),
Q3 = c("0","A"),
C1 = c("A","0")
) -> DB
```
I aim to add a new column which is a count of how many `"0"` are detected in the row when the column starts with `"Q"`.
In this case, this column would be like
```
DB %>%
mutate(S = c(2,0))
``` | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17122831/"
] | ```r
DB %>%
rowwise() %>%
mutate(S = sum(c_across(starts_with("Q")) == "0")) %>%
ungroup()
# # A tibble: 2 x 5
# Q1 Q2 Q3 C1 S
# <chr> <chr> <chr> <chr> <int>
# 1 0 A 0 A 2
# 2 A A A 0 0
``` | One possible solution:
```
DB %>%
mutate(S = rowSums(.[startsWith(names(.), "Q")]=="0"))
# A tibble: 2 x 5
Q1 Q2 Q3 C1 S
<chr> <chr> <chr> <chr> <dbl>
1 0 A 0 A 2
2 A A A 0 0
``` |
20,928,413 | I am getting odd redirection in general. It works in development but not production. Here are the responses for an update. The same things happens on a create.
DEVELOPMENT
```
Redirected to http://localhost:3000/trackers
Completed 302 Found in 43ms (ActiveRecord: 18.7ms)
Started GET "/trackers" for 127.0.0.1 at 2014-01-06 06:41:02 -0600
```
PRODUCTION
```
Redirected to http://example.com/trackers
Completed 302 Found in 218ms (ActiveRecord: 63.9ms)
Started GET "/" for [IP} at 2014-01-05 20:15:33 +0000
```
routes.rb (pertinant)
```
trackers GET /trackers(.:format) trackers#index
POST /trackers(.:format) trackers#create
new_tracker GET /trackers/new(.:format) trackers#new
edit_tracker GET /trackers/:id/edit(.:format) trackers#edit
tracker GET /trackers/:id(.:format) trackers#show
PUT /trackers/:id(.:format) trackers#update
DELETE /trackers/:id(.:format) trackers#destroy
```
Here is my tracker controller
```
class TrackersController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource
def create
@tracker = params[:tracker]
@user = current_user
if @user.trackers.create(@tracker)
redirect_to trackers_path, :notice => "New Tracker Created!"
else
redirect_to trackers_path, :notice => "Tracker Could not be created."
end
end
def update
@tracker = Tracker.find(params[:id])
if @tracker.update_attributes(params[:tracker])
redirect_to trackers_path, :notice => "Tracker Updated!"
else
redirect_to trackers_path(params[:id]), :notice => "Unable to Update Tracker"
end
end
end
```
NGINX
```
upstream unicorn{
server unix:/tmp/unicorn.legalleads.sock fail_timeout=0;}
server {
listen 80;
server_name example.com;
return 301 https://$host;}
server {
listen 443 default;
server_name example.com;
root /home/a/apps/legalleads/public;
try_files $uri/index.html $uri @unicorn;
ssl on;
ssl_certificate /etc/nginx/ssl/com.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}
location @unicorn {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://unicorn;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
}
``` | 2014/01/05 | [
"https://Stackoverflow.com/questions/20928413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1938097/"
] | `$scope.$digest()` is what processes all of the `$watch` events that are on the current and children scope. It essentially manually tells the scope to check if a scope variable has changed. You don't generally want to use this when you are inside of a controller or a directive, because the `$scope.$apply()` function calls the `$digest` anyway and it is called when you mutate a scope variable.
Checkout this [link](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest) for an example. | You don't need a `$rootScope.$digest` here because resolving/rejecting the promise will fire a `$rootScope.$digest` internally, as `$interval`,`$timeout`,and `$http` (after request finished) do that for you. And this `$digest` can throw errors of `$digest` already in progress. |
13,279,390 | Write a program that reads in a series of first names and eliminates duplicates by storing them in a Set. Allow the user to search for a first name.
(Trust me, I am not taking any Java classes. So, not my homework).
My issue is to implement this: **Allow the user to search for a first name.**
Everything else works, just the search feature.
*My Code so far....*
```
package com.Sets;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class DuplicateElimination {
public static void main(String[] args) {
// Write a program thats ask for first names and store it in an array.
String fName;
Scanner input = new Scanner(System.in);
String[] names = new String[10];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter First Name: ");
names[i] = input.nextLine();
}
// Printout that array as a list.
List<String> list = Arrays.asList(names);
// Initial Array Elements
System.out.printf("%s ", list);
System.out.println();
// Calling removeDuplicates method
removeDuplicates(list);
}
// Make a method called removeDuplicates.
private static void removeDuplicates(Collection<String> values) {
// Implement a Hashset in it.
Set<String> set = new HashSet<String>(values);
// Printout a non-duplicate list of elements.
for (String value : set) {
System.out.printf("%s ", value);
}
System.out.println();
}
// Make a method to search for a first name.
public static void searchForName(Collection<String> names) {
String someName;
Set<String> set = new HashSet<String>(names);
Scanner input = new Scanner(System.in);
for (int i = 0; i <= 10; i++) {
System.out.println("Search this name: ");
someName = input.nextLine();
}
if (someName ) {
} else {
}
}
}
```
I don't feel confident about my searchForName method... can someone give an idea on how I could make this work? | 2012/11/07 | [
"https://Stackoverflow.com/questions/13279390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1415064/"
] | Use `language.ShowDialog();`. Per [MSDN](http://msdn.microsoft.com/en-us/library/c7ykbedk.aspx), the code following it is not executed until after the dialog box is closed. | It's a little dangerous to put code before `InitializeComponent` - you'll run into `NullReferenceException`s if you forget to avoid trying to touch controls on your form. Updating member fields is OK, though.
Could the code that loads `FrmMain` load and execute `FrmLanguage` first, perhaps near the place where the INI file is checked? |
13,279,390 | Write a program that reads in a series of first names and eliminates duplicates by storing them in a Set. Allow the user to search for a first name.
(Trust me, I am not taking any Java classes. So, not my homework).
My issue is to implement this: **Allow the user to search for a first name.**
Everything else works, just the search feature.
*My Code so far....*
```
package com.Sets;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class DuplicateElimination {
public static void main(String[] args) {
// Write a program thats ask for first names and store it in an array.
String fName;
Scanner input = new Scanner(System.in);
String[] names = new String[10];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter First Name: ");
names[i] = input.nextLine();
}
// Printout that array as a list.
List<String> list = Arrays.asList(names);
// Initial Array Elements
System.out.printf("%s ", list);
System.out.println();
// Calling removeDuplicates method
removeDuplicates(list);
}
// Make a method called removeDuplicates.
private static void removeDuplicates(Collection<String> values) {
// Implement a Hashset in it.
Set<String> set = new HashSet<String>(values);
// Printout a non-duplicate list of elements.
for (String value : set) {
System.out.printf("%s ", value);
}
System.out.println();
}
// Make a method to search for a first name.
public static void searchForName(Collection<String> names) {
String someName;
Set<String> set = new HashSet<String>(names);
Scanner input = new Scanner(System.in);
for (int i = 0; i <= 10; i++) {
System.out.println("Search this name: ");
someName = input.nextLine();
}
if (someName ) {
} else {
}
}
}
```
I don't feel confident about my searchForName method... can someone give an idea on how I could make this work? | 2012/11/07 | [
"https://Stackoverflow.com/questions/13279390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1415064/"
] | Use `language.ShowDialog();`. Per [MSDN](http://msdn.microsoft.com/en-us/library/c7ykbedk.aspx), the code following it is not executed until after the dialog box is closed. | I'm not sure if this will work, so just let me know if it helps you.
In your Main() method, you could load the first form with:
```
Application.Run(new FrmLanguage());
```
Then from that form gather the language setting, and load the other form like normal. |
1,600,597 | Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution? | 2009/10/21 | [
"https://Stackoverflow.com/questions/1600597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40441/"
] | The second chunk of code is just about the best approach you can get all other things staying the same.
However, it may be possible to create a property on `Something` which takes `Item`. In turn the event code could access this `Item` off the sender of the event or it might be included in the eventargs for the event. Hence eliminating the need for the closure.
Personally I've added "Elimination of Unnecessary Closure" as a worthwhile refactoring since it can be difficult to reason on them. | The problem you are facing here is related to such language construct as **closure**.
Second piece of code fixes the problem. |
1,600,597 | Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution? | 2009/10/21 | [
"https://Stackoverflow.com/questions/1600597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40441/"
] | If ItemCollection is a [(generic) List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) you can use its [ForEach](http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx)-method. It will give you a fresh scope per i:
```
ItemCollection.ForEach(
i =>
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
});
```
Or you can use any other suitable [Linq](http://msdn.microsoft.com/en-us/netframework/aa904594.aspx)-method - like [Select](http://msdn.microsoft.com/en-us/library/bb548891.aspx):
```
var somethings = ItemCollection.Select(
i =>
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
return s;
});
foreach(Something s in somethings)
SomethingCollection.Add(s);
``` | The problem you are facing here is related to such language construct as **closure**.
Second piece of code fixes the problem. |
1,600,597 | Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution? | 2009/10/21 | [
"https://Stackoverflow.com/questions/1600597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40441/"
] | UPDATE: There is extensive analysis and commentary on this issue here:
<http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/>
---
This is an extremely frequently reported issue; usually it is reported as a compiler bug, but in fact the compiler is doing the right thing according to the specification. Anonymous functions close over *variables*, not *values*, and there is only a single foreach loop variable. Therefore each lambda closes over the same variable, and therefore gets the current value of that variable.
This is surprising to almost everyone, and leads to much confusion and many bug reports. We are *considering* changing the specification and implementation for a hypothetical future version of C# so that the loop variable is logically declared inside the looping construct, giving a "fresh" variable every time through the loop.
**This would be a breaking change**, but I suspect the number of people who depend on this strange behaviour is quite low. If you have opinions on this subject, feel free to add comments to the blog posts mentioned up the update above. Thanks! | The problem you are facing here is related to such language construct as **closure**.
Second piece of code fixes the problem. |
1,600,597 | Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution? | 2009/10/21 | [
"https://Stackoverflow.com/questions/1600597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40441/"
] | The second chunk of code is just about the best approach you can get all other things staying the same.
However, it may be possible to create a property on `Something` which takes `Item`. In turn the event code could access this `Item` off the sender of the event or it might be included in the eventargs for the event. Hence eliminating the need for the closure.
Personally I've added "Elimination of Unnecessary Closure" as a worthwhile refactoring since it can be difficult to reason on them. | ```
foreach(Item i on ItemCollection)
{
Something s = new Something(i);
s.EventX += (sender, eventArgs) => { ProcessItem(eventArgs.Item);};
SomethingCollection.Add(s);
}
```
would you not just pass 'i' in into your 'Something' Class and use it in EventX's event args |
1,600,597 | Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution? | 2009/10/21 | [
"https://Stackoverflow.com/questions/1600597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40441/"
] | The second chunk of code is just about the best approach you can get all other things staying the same.
However, it may be possible to create a property on `Something` which takes `Item`. In turn the event code could access this `Item` off the sender of the event or it might be included in the eventargs for the event. Hence eliminating the need for the closure.
Personally I've added "Elimination of Unnecessary Closure" as a worthwhile refactoring since it can be difficult to reason on them. | If ItemCollection is a [(generic) List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) you can use its [ForEach](http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx)-method. It will give you a fresh scope per i:
```
ItemCollection.ForEach(
i =>
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
});
```
Or you can use any other suitable [Linq](http://msdn.microsoft.com/en-us/netframework/aa904594.aspx)-method - like [Select](http://msdn.microsoft.com/en-us/library/bb548891.aspx):
```
var somethings = ItemCollection.Select(
i =>
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
return s;
});
foreach(Something s in somethings)
SomethingCollection.Add(s);
``` |
1,600,597 | Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution? | 2009/10/21 | [
"https://Stackoverflow.com/questions/1600597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40441/"
] | UPDATE: There is extensive analysis and commentary on this issue here:
<http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/>
---
This is an extremely frequently reported issue; usually it is reported as a compiler bug, but in fact the compiler is doing the right thing according to the specification. Anonymous functions close over *variables*, not *values*, and there is only a single foreach loop variable. Therefore each lambda closes over the same variable, and therefore gets the current value of that variable.
This is surprising to almost everyone, and leads to much confusion and many bug reports. We are *considering* changing the specification and implementation for a hypothetical future version of C# so that the loop variable is logically declared inside the looping construct, giving a "fresh" variable every time through the loop.
**This would be a breaking change**, but I suspect the number of people who depend on this strange behaviour is quite low. If you have opinions on this subject, feel free to add comments to the blog posts mentioned up the update above. Thanks! | The second chunk of code is just about the best approach you can get all other things staying the same.
However, it may be possible to create a property on `Something` which takes `Item`. In turn the event code could access this `Item` off the sender of the event or it might be included in the eventargs for the event. Hence eliminating the need for the closure.
Personally I've added "Elimination of Unnecessary Closure" as a worthwhile refactoring since it can be difficult to reason on them. |
1,600,597 | Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution? | 2009/10/21 | [
"https://Stackoverflow.com/questions/1600597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40441/"
] | If ItemCollection is a [(generic) List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) you can use its [ForEach](http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx)-method. It will give you a fresh scope per i:
```
ItemCollection.ForEach(
i =>
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
});
```
Or you can use any other suitable [Linq](http://msdn.microsoft.com/en-us/netframework/aa904594.aspx)-method - like [Select](http://msdn.microsoft.com/en-us/library/bb548891.aspx):
```
var somethings = ItemCollection.Select(
i =>
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
return s;
});
foreach(Something s in somethings)
SomethingCollection.Add(s);
``` | ```
foreach(Item i on ItemCollection)
{
Something s = new Something(i);
s.EventX += (sender, eventArgs) => { ProcessItem(eventArgs.Item);};
SomethingCollection.Add(s);
}
```
would you not just pass 'i' in into your 'Something' Class and use it in EventX's event args |
1,600,597 | Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution? | 2009/10/21 | [
"https://Stackoverflow.com/questions/1600597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40441/"
] | UPDATE: There is extensive analysis and commentary on this issue here:
<http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/>
---
This is an extremely frequently reported issue; usually it is reported as a compiler bug, but in fact the compiler is doing the right thing according to the specification. Anonymous functions close over *variables*, not *values*, and there is only a single foreach loop variable. Therefore each lambda closes over the same variable, and therefore gets the current value of that variable.
This is surprising to almost everyone, and leads to much confusion and many bug reports. We are *considering* changing the specification and implementation for a hypothetical future version of C# so that the loop variable is logically declared inside the looping construct, giving a "fresh" variable every time through the loop.
**This would be a breaking change**, but I suspect the number of people who depend on this strange behaviour is quite low. If you have opinions on this subject, feel free to add comments to the blog posts mentioned up the update above. Thanks! | ```
foreach(Item i on ItemCollection)
{
Something s = new Something(i);
s.EventX += (sender, eventArgs) => { ProcessItem(eventArgs.Item);};
SomethingCollection.Add(s);
}
```
would you not just pass 'i' in into your 'Something' Class and use it in EventX's event args |
1,600,597 | Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution? | 2009/10/21 | [
"https://Stackoverflow.com/questions/1600597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40441/"
] | UPDATE: There is extensive analysis and commentary on this issue here:
<http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/>
---
This is an extremely frequently reported issue; usually it is reported as a compiler bug, but in fact the compiler is doing the right thing according to the specification. Anonymous functions close over *variables*, not *values*, and there is only a single foreach loop variable. Therefore each lambda closes over the same variable, and therefore gets the current value of that variable.
This is surprising to almost everyone, and leads to much confusion and many bug reports. We are *considering* changing the specification and implementation for a hypothetical future version of C# so that the loop variable is logically declared inside the looping construct, giving a "fresh" variable every time through the loop.
**This would be a breaking change**, but I suspect the number of people who depend on this strange behaviour is quite low. If you have opinions on this subject, feel free to add comments to the blog posts mentioned up the update above. Thanks! | If ItemCollection is a [(generic) List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) you can use its [ForEach](http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx)-method. It will give you a fresh scope per i:
```
ItemCollection.ForEach(
i =>
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
});
```
Or you can use any other suitable [Linq](http://msdn.microsoft.com/en-us/netframework/aa904594.aspx)-method - like [Select](http://msdn.microsoft.com/en-us/library/bb548891.aspx):
```
var somethings = ItemCollection.Select(
i =>
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
return s;
});
foreach(Something s in somethings)
SomethingCollection.Add(s);
``` |
471,949 | Let's take the function $f(x)=x^{-1}$. My question is this: Is the sum $$\frac{1}{x-a}+\frac{1}{x+a}$$ as $a\rightarrow 0$ near the point $x=0$ equal 0? And how would I proove this anytime I encounter this kind of limit? How would this work with derivatives or integrals? | 2013/08/20 | [
"https://math.stackexchange.com/questions/471949",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/47567/"
] | The quantity you seem to be asking about is $$\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}$$ "near" $x=0.$ Well, assuming that $x$ is not $0,$ then this is simply $$\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}=\frac1x+\frac1x=\frac2x$$ by continuity. Now, if $x=0,$ then we have $$\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}=\lim\_{a\to 0}-\frac{1}{a}+\frac{1}{a}=\lim\_{a\to 0}0=0.$$
This is a good example of why we can't always interchange limits, since $$\lim\_{a\to 0}\lim\_{x\to 0}\frac{1}{x-a}+\frac{1}{x+a}=0,$$ but $$\lim\_{x\to 0}\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}$$ does not exist. | Well, it depends what limit are you evaluating first.
First, $\lim\_{a\to 0}(\lim\_{x\to 0} (\frac{1}{x-a}+\frac{1}{x+a}))=\lim\_{a\to 0}0=0$, but, on the other hand, you have $\lim\_{x\to 0}(\lim\_{a\to 0} (\frac{1}{x-a}+\frac{1}{x+a}))=\lim\_{x\to 0}\frac{2}{x}$ and this limit does not exist. So, the order of taking these "iterated" limits in a two variable (or generally, $n$-variable) problems is important. |
118,606 | I am a 15-year-old female, and I am currently a high soprano. I can currently sing from a low C4 to a high F above the bar. Is there a way I could get higher and become a coloratura soprano or gain an octave? | 2021/11/18 | [
"https://music.stackexchange.com/questions/118606",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/83089/"
] | You already have a full soprano range: C4 to F6. Coloratura is a vocal quality, not a range. Coloratura voices generally have a light quality to them, as opposed to the more powerful voice of a dramatic soprano. Coloraturas specialize in highly decorative passages with lots of runs, trills, and other ornaments.
So coloratura is a skill to develop if you have a lighter-sounding voice. At 15 your vocal color may still be changing, but you'll have to wait and see.
---
Also of interest...
* [Lyrical Contralto vs Dramatic Mezzo-soprano](https://music.stackexchange.com/q/116076/70803)
* [Will my voice get any higher?](https://music.stackexchange.com/q/58355/70803) | You dont just simply add a octave. Most singers range is between an octave and maybe a 10th. Even then a 10th is extraordinary.
Singing around middle C is hard for soprano and very few ever get to the fabled nessum dorma high B.
Your range will gravitate between the E above middle C to the G a tenth above it. That is fine. You will have to become pretty great before any more is required.
Colatura as a style is not dependant on any particular range for the soprano at least. It is more to do with a style that is rich in ornamentation. This makes it very demanding to the singer and only the really great female singers ever excel at it.
Dame June Sutherland probably being the greatest singer of this type in 20th century. |
18,529,965 | Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18529965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11421/"
] | Dapper does not currently have an instrumentation point here. This is perhaps due, as you note, to the fact that we (as the authors) use mini-profiler to handle this. However, if it helps, the core parts of mini-profiler are actually designed to be architecture neutral, and I know of other people using it with winforms, wpf, wcf, etc - which would give you access to the profiling / tracing connection wrapper.
In theory, it would be perfectly possible to add some blanket capture-point, but I'm concerned about two things:
* (primarily) security: since dapper doesn't have a concept of a context, it would be *really really* easy for malign code to attach quietly to sniff all sql traffic that goes via dapper; I really don't like the sound of that (this isn't an issue with the "decorator" approach, as the caller owns the connection, hence the logging context)
* (secondary) performance: but... in truth, it is hard to say that a simple delegate-check (which would presumably be `null` in most cases) would have much impact
Of course, the other thing you could do is: steal the connection wrapper code from mini-profiler, and replace the profiler-context stuff with just: `Debug.WriteLine` etc. | You should consider using SQL profiler located in the menu of *SQL Management Studio* ***→ Extras → SQL Server Profiler*** (no Dapper extensions needed - may work with other RDBMS when they got a SQL profiler tool too).
Then, start a new session.
You'll get something like this for example (you see all parameters and the complete SQL string):
```
exec sp_executesql N'SELECT * FROM Updates WHERE CAST(Product_ID as VARCHAR(50)) = @appId AND (Blocked IS NULL OR Blocked = 0)
AND (Beta IS NULL OR Beta = 0 OR @includeBeta = 1) AND (LangCode IS NULL OR LangCode IN (SELECT * FROM STRING_SPLIT(@langCode, '','')))',N'@appId nvarchar(4000),@includeBeta bit,@langCode nvarchar(4000)',@appId=N'fea5b0a7-1da6-4394-b8c8-05e7cb979161',@includeBeta=0,@langCode=N'de'
``` |
18,529,965 | Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18529965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11421/"
] | I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget [MiniProfiler.Integrations](https://www.nuget.org/packages/MiniProfiler.Integrations/) I would like to share.
**Update V2**: it supports to work with other database servers, for MySQL it requires to have [MiniProfiler.Integrations.MySql](https://www.nuget.org/packages/MiniProfiler.Integrations.MySql/)
Below are steps to work with SQL Server:
1.Instantiate the connection
```
var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
// your code
}
```
2.After all works done, write all commands to a file if you want
```
File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());
``` | You should consider using SQL profiler located in the menu of *SQL Management Studio* ***→ Extras → SQL Server Profiler*** (no Dapper extensions needed - may work with other RDBMS when they got a SQL profiler tool too).
Then, start a new session.
You'll get something like this for example (you see all parameters and the complete SQL string):
```
exec sp_executesql N'SELECT * FROM Updates WHERE CAST(Product_ID as VARCHAR(50)) = @appId AND (Blocked IS NULL OR Blocked = 0)
AND (Beta IS NULL OR Beta = 0 OR @includeBeta = 1) AND (LangCode IS NULL OR LangCode IN (SELECT * FROM STRING_SPLIT(@langCode, '','')))',N'@appId nvarchar(4000),@includeBeta bit,@langCode nvarchar(4000)',@appId=N'fea5b0a7-1da6-4394-b8c8-05e7cb979161',@includeBeta=0,@langCode=N'de'
``` |
18,529,965 | Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18529965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11421/"
] | Try [Dapper.Logging](https://github.com/hryz/Dapper.Logging/tree/71f4f3de06b95f131e84171698e0d3ed7cb52f83).
-----------------------------------------------------------------------------------------------------------
You can get it from NuGet. The way it works is you pass your code that creates your actual database connection into a factory that creates wrapped connections. Whenever a wrapped connection is opened or closed or you run a query against it, it will be logged. You can configure the logging message templates and other settings like whether SQL parameters are saved. Elapsed time is also saved.
In my opinion, the only downside is that the documentation is sparse, but I think that's just because it's a new project (as of this writing). I had to dig through the repo for a bit to understand it and to get it configured to my liking, but now it's working great.
From the documentation:
>
> The tool consists of simple decorators for the `DbConnection` and
> `DbCommand` which track the execution time and write messages to the
> `ILogger<T>`. The `ILogger<T>` can be handled by any logging framework
> (e.g. Serilog). The result is similar to the default EF Core logging
> behavior.
>
>
> The lib declares a helper method for registering the
> `IDbConnectionFactory` in the IoC container. The connection factory is
> SQL Provider agnostic. That's why you have to specify the real factory
> method:
>
>
>
> ```
> services.AddDbConnectionFactory(prv => new SqlConnection(conStr));
>
> ```
>
> After registration, the `IDbConnectionFactory` can be injected into
> classes that need a SQL connection.
>
>
>
> ```
> private readonly IDbConnectionFactory _connectionFactory;
> public GetProductsHandler(IDbConnectionFactory connectionFactory)
> {
> _connectionFactory = connectionFactory;
> }
>
> ```
>
> The `IDbConnectionFactory.CreateConnection` will return a decorated
> version that logs the activity.
>
>
>
> ```
> using (DbConnection db = _connectionFactory.CreateConnection())
> {
> //...
> }
>
> ```
>
> | This is not exhaustive and is essentially a bit of hack, but if you have your SQL and you want to initialize your parameters, it's useful for basic debugging. Set up this extension method, then call it anywhere as desired.
```
public static class DapperExtensions
{
public static string ArgsAsSql(this DynamicParameters args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
var sb = new StringBuilder();
foreach (var name in args.ParameterNames)
{
var pValue = args.Get<dynamic>(name);
var type = pValue.GetType();
if (type == typeof(DateTime))
sb.AppendFormat("DECLARE @{0} DATETIME ='{1}'\n", name, pValue.ToString("yyyy-MM-dd HH:mm:ss.fff"));
else if (type == typeof(bool))
sb.AppendFormat("DECLARE @{0} BIT = {1}\n", name, (bool)pValue ? 1 : 0);
else if (type == typeof(int))
sb.AppendFormat("DECLARE @{0} INT = {1}\n", name, pValue);
else if (type == typeof(List<int>))
sb.AppendFormat("-- REPLACE @{0} IN SQL: ({1})\n", name, string.Join(",", (List<int>)pValue));
else
sb.AppendFormat("DECLARE @{0} NVARCHAR(MAX) = '{1}'\n", name, pValue.ToString());
}
return sb.ToString();
}
}
```
You can then just use this in the immediate or watch windows to grab the SQL. |
18,529,965 | Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18529965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11421/"
] | You should consider using SQL profiler located in the menu of *SQL Management Studio* ***→ Extras → SQL Server Profiler*** (no Dapper extensions needed - may work with other RDBMS when they got a SQL profiler tool too).
Then, start a new session.
You'll get something like this for example (you see all parameters and the complete SQL string):
```
exec sp_executesql N'SELECT * FROM Updates WHERE CAST(Product_ID as VARCHAR(50)) = @appId AND (Blocked IS NULL OR Blocked = 0)
AND (Beta IS NULL OR Beta = 0 OR @includeBeta = 1) AND (LangCode IS NULL OR LangCode IN (SELECT * FROM STRING_SPLIT(@langCode, '','')))',N'@appId nvarchar(4000),@includeBeta bit,@langCode nvarchar(4000)',@appId=N'fea5b0a7-1da6-4394-b8c8-05e7cb979161',@includeBeta=0,@langCode=N'de'
``` | This is not exhaustive and is essentially a bit of hack, but if you have your SQL and you want to initialize your parameters, it's useful for basic debugging. Set up this extension method, then call it anywhere as desired.
```
public static class DapperExtensions
{
public static string ArgsAsSql(this DynamicParameters args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
var sb = new StringBuilder();
foreach (var name in args.ParameterNames)
{
var pValue = args.Get<dynamic>(name);
var type = pValue.GetType();
if (type == typeof(DateTime))
sb.AppendFormat("DECLARE @{0} DATETIME ='{1}'\n", name, pValue.ToString("yyyy-MM-dd HH:mm:ss.fff"));
else if (type == typeof(bool))
sb.AppendFormat("DECLARE @{0} BIT = {1}\n", name, (bool)pValue ? 1 : 0);
else if (type == typeof(int))
sb.AppendFormat("DECLARE @{0} INT = {1}\n", name, pValue);
else if (type == typeof(List<int>))
sb.AppendFormat("-- REPLACE @{0} IN SQL: ({1})\n", name, string.Join(",", (List<int>)pValue));
else
sb.AppendFormat("DECLARE @{0} NVARCHAR(MAX) = '{1}'\n", name, pValue.ToString());
}
return sb.ToString();
}
}
```
You can then just use this in the immediate or watch windows to grab the SQL. |
18,529,965 | Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18529965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11421/"
] | I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget [MiniProfiler.Integrations](https://www.nuget.org/packages/MiniProfiler.Integrations/) I would like to share.
**Update V2**: it supports to work with other database servers, for MySQL it requires to have [MiniProfiler.Integrations.MySql](https://www.nuget.org/packages/MiniProfiler.Integrations.MySql/)
Below are steps to work with SQL Server:
1.Instantiate the connection
```
var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
// your code
}
```
2.After all works done, write all commands to a file if you want
```
File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());
``` | This is not exhaustive and is essentially a bit of hack, but if you have your SQL and you want to initialize your parameters, it's useful for basic debugging. Set up this extension method, then call it anywhere as desired.
```
public static class DapperExtensions
{
public static string ArgsAsSql(this DynamicParameters args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
var sb = new StringBuilder();
foreach (var name in args.ParameterNames)
{
var pValue = args.Get<dynamic>(name);
var type = pValue.GetType();
if (type == typeof(DateTime))
sb.AppendFormat("DECLARE @{0} DATETIME ='{1}'\n", name, pValue.ToString("yyyy-MM-dd HH:mm:ss.fff"));
else if (type == typeof(bool))
sb.AppendFormat("DECLARE @{0} BIT = {1}\n", name, (bool)pValue ? 1 : 0);
else if (type == typeof(int))
sb.AppendFormat("DECLARE @{0} INT = {1}\n", name, pValue);
else if (type == typeof(List<int>))
sb.AppendFormat("-- REPLACE @{0} IN SQL: ({1})\n", name, string.Join(",", (List<int>)pValue));
else
sb.AppendFormat("DECLARE @{0} NVARCHAR(MAX) = '{1}'\n", name, pValue.ToString());
}
return sb.ToString();
}
}
```
You can then just use this in the immediate or watch windows to grab the SQL. |
18,529,965 | Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18529965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11421/"
] | Dapper does not currently have an instrumentation point here. This is perhaps due, as you note, to the fact that we (as the authors) use mini-profiler to handle this. However, if it helps, the core parts of mini-profiler are actually designed to be architecture neutral, and I know of other people using it with winforms, wpf, wcf, etc - which would give you access to the profiling / tracing connection wrapper.
In theory, it would be perfectly possible to add some blanket capture-point, but I'm concerned about two things:
* (primarily) security: since dapper doesn't have a concept of a context, it would be *really really* easy for malign code to attach quietly to sniff all sql traffic that goes via dapper; I really don't like the sound of that (this isn't an issue with the "decorator" approach, as the caller owns the connection, hence the logging context)
* (secondary) performance: but... in truth, it is hard to say that a simple delegate-check (which would presumably be `null` in most cases) would have much impact
Of course, the other thing you could do is: steal the connection wrapper code from mini-profiler, and replace the profiler-context stuff with just: `Debug.WriteLine` etc. | This is not exhaustive and is essentially a bit of hack, but if you have your SQL and you want to initialize your parameters, it's useful for basic debugging. Set up this extension method, then call it anywhere as desired.
```
public static class DapperExtensions
{
public static string ArgsAsSql(this DynamicParameters args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
var sb = new StringBuilder();
foreach (var name in args.ParameterNames)
{
var pValue = args.Get<dynamic>(name);
var type = pValue.GetType();
if (type == typeof(DateTime))
sb.AppendFormat("DECLARE @{0} DATETIME ='{1}'\n", name, pValue.ToString("yyyy-MM-dd HH:mm:ss.fff"));
else if (type == typeof(bool))
sb.AppendFormat("DECLARE @{0} BIT = {1}\n", name, (bool)pValue ? 1 : 0);
else if (type == typeof(int))
sb.AppendFormat("DECLARE @{0} INT = {1}\n", name, pValue);
else if (type == typeof(List<int>))
sb.AppendFormat("-- REPLACE @{0} IN SQL: ({1})\n", name, string.Join(",", (List<int>)pValue));
else
sb.AppendFormat("DECLARE @{0} NVARCHAR(MAX) = '{1}'\n", name, pValue.ToString());
}
return sb.ToString();
}
}
```
You can then just use this in the immediate or watch windows to grab the SQL. |
18,529,965 | Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18529965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11421/"
] | Dapper does not currently have an instrumentation point here. This is perhaps due, as you note, to the fact that we (as the authors) use mini-profiler to handle this. However, if it helps, the core parts of mini-profiler are actually designed to be architecture neutral, and I know of other people using it with winforms, wpf, wcf, etc - which would give you access to the profiling / tracing connection wrapper.
In theory, it would be perfectly possible to add some blanket capture-point, but I'm concerned about two things:
* (primarily) security: since dapper doesn't have a concept of a context, it would be *really really* easy for malign code to attach quietly to sniff all sql traffic that goes via dapper; I really don't like the sound of that (this isn't an issue with the "decorator" approach, as the caller owns the connection, hence the logging context)
* (secondary) performance: but... in truth, it is hard to say that a simple delegate-check (which would presumably be `null` in most cases) would have much impact
Of course, the other thing you could do is: steal the connection wrapper code from mini-profiler, and replace the profiler-context stuff with just: `Debug.WriteLine` etc. | Just to add an update here since I see this question still get's quite a few hits - these days I use either [Glimpse](http://getglimpse.com/) (seems it's dead now) or [Stackify Prefix](https://stackify.com/prefix/) which both have sql command trace capabilities.
It's not exactly what I was looking for when I asked the original question but solve the same problem. |
18,529,965 | Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18529965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11421/"
] | I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget [MiniProfiler.Integrations](https://www.nuget.org/packages/MiniProfiler.Integrations/) I would like to share.
**Update V2**: it supports to work with other database servers, for MySQL it requires to have [MiniProfiler.Integrations.MySql](https://www.nuget.org/packages/MiniProfiler.Integrations.MySql/)
Below are steps to work with SQL Server:
1.Instantiate the connection
```
var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
// your code
}
```
2.After all works done, write all commands to a file if you want
```
File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());
``` | Try [Dapper.Logging](https://github.com/hryz/Dapper.Logging/tree/71f4f3de06b95f131e84171698e0d3ed7cb52f83).
-----------------------------------------------------------------------------------------------------------
You can get it from NuGet. The way it works is you pass your code that creates your actual database connection into a factory that creates wrapped connections. Whenever a wrapped connection is opened or closed or you run a query against it, it will be logged. You can configure the logging message templates and other settings like whether SQL parameters are saved. Elapsed time is also saved.
In my opinion, the only downside is that the documentation is sparse, but I think that's just because it's a new project (as of this writing). I had to dig through the repo for a bit to understand it and to get it configured to my liking, but now it's working great.
From the documentation:
>
> The tool consists of simple decorators for the `DbConnection` and
> `DbCommand` which track the execution time and write messages to the
> `ILogger<T>`. The `ILogger<T>` can be handled by any logging framework
> (e.g. Serilog). The result is similar to the default EF Core logging
> behavior.
>
>
> The lib declares a helper method for registering the
> `IDbConnectionFactory` in the IoC container. The connection factory is
> SQL Provider agnostic. That's why you have to specify the real factory
> method:
>
>
>
> ```
> services.AddDbConnectionFactory(prv => new SqlConnection(conStr));
>
> ```
>
> After registration, the `IDbConnectionFactory` can be injected into
> classes that need a SQL connection.
>
>
>
> ```
> private readonly IDbConnectionFactory _connectionFactory;
> public GetProductsHandler(IDbConnectionFactory connectionFactory)
> {
> _connectionFactory = connectionFactory;
> }
>
> ```
>
> The `IDbConnectionFactory.CreateConnection` will return a decorated
> version that logs the activity.
>
>
>
> ```
> using (DbConnection db = _connectionFactory.CreateConnection())
> {
> //...
> }
>
> ```
>
> |
18,529,965 | Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18529965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11421/"
] | I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget [MiniProfiler.Integrations](https://www.nuget.org/packages/MiniProfiler.Integrations/) I would like to share.
**Update V2**: it supports to work with other database servers, for MySQL it requires to have [MiniProfiler.Integrations.MySql](https://www.nuget.org/packages/MiniProfiler.Integrations.MySql/)
Below are steps to work with SQL Server:
1.Instantiate the connection
```
var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
// your code
}
```
2.After all works done, write all commands to a file if you want
```
File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());
``` | Dapper does not currently have an instrumentation point here. This is perhaps due, as you note, to the fact that we (as the authors) use mini-profiler to handle this. However, if it helps, the core parts of mini-profiler are actually designed to be architecture neutral, and I know of other people using it with winforms, wpf, wcf, etc - which would give you access to the profiling / tracing connection wrapper.
In theory, it would be perfectly possible to add some blanket capture-point, but I'm concerned about two things:
* (primarily) security: since dapper doesn't have a concept of a context, it would be *really really* easy for malign code to attach quietly to sniff all sql traffic that goes via dapper; I really don't like the sound of that (this isn't an issue with the "decorator" approach, as the caller owns the connection, hence the logging context)
* (secondary) performance: but... in truth, it is hard to say that a simple delegate-check (which would presumably be `null` in most cases) would have much impact
Of course, the other thing you could do is: steal the connection wrapper code from mini-profiler, and replace the profiler-context stuff with just: `Debug.WriteLine` etc. |
18,529,965 | Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18529965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11421/"
] | You should consider using SQL profiler located in the menu of *SQL Management Studio* ***→ Extras → SQL Server Profiler*** (no Dapper extensions needed - may work with other RDBMS when they got a SQL profiler tool too).
Then, start a new session.
You'll get something like this for example (you see all parameters and the complete SQL string):
```
exec sp_executesql N'SELECT * FROM Updates WHERE CAST(Product_ID as VARCHAR(50)) = @appId AND (Blocked IS NULL OR Blocked = 0)
AND (Beta IS NULL OR Beta = 0 OR @includeBeta = 1) AND (LangCode IS NULL OR LangCode IN (SELECT * FROM STRING_SPLIT(@langCode, '','')))',N'@appId nvarchar(4000),@includeBeta bit,@langCode nvarchar(4000)',@appId=N'fea5b0a7-1da6-4394-b8c8-05e7cb979161',@includeBeta=0,@langCode=N'de'
``` | Just to add an update here since I see this question still get's quite a few hits - these days I use either [Glimpse](http://getglimpse.com/) (seems it's dead now) or [Stackify Prefix](https://stackify.com/prefix/) which both have sql command trace capabilities.
It's not exactly what I was looking for when I asked the original question but solve the same problem. |
2,507,595 | I'm using Google Test Framework to set some unit tests. I have got three projects in my solution:
* FN (my project)
* FN\_test (my tests)
* gtest (Google Test Framework)
I set FN\_test to have FN and gtest as references (dependencies), and then I think I'm ready to set up my tests (I've already set everyone to /MTd (not doing this was leading me to linking errors before)).
Particularly, I define a class called Embark in FN I would like to test using FN\_test. So far, so good. Thus I write a classe called EmbarkTest using googletest, declare a member Embark\* and write inside the constructor:
```
EmbarkTest() {
e = new Embark(900,2010);
}
```
Then , F7 pressed, I get the following:
`1>FN_test.obj : error LNK2019: unresolved external symbol "public: __thiscall Embark::Embark(int,int)" (??0Embark@@QAE@HH@Z) referenced in function "protected: __thiscall EmbarkTest::EmbarkTest(void)" (??0EmbarkTest@@IAE@XZ)`
`1>D:\Users\lg\Product\code\FN\Debug\FN_test.exe : fatal error LNK1120: 1 unresolved externals`
Does someone know what have I done wrong and/or what can I do to settle this?
**EDIT**: *Relevant* code from Embark.h
```
class Embark
{
public:
//Constructor for initial state
Embark(int _id, int _year);
//Destructor
~Embark();
/* ... */
}
``` | 2010/03/24 | [
"https://Stackoverflow.com/questions/2507595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241161/"
] | I found the answer to be a rather simple one. After two days of intense headknocking, it's this:
**You have to compile your main project as `.lib` and not `.exe`**
After doing this, all linking went as a bliss. I thought Visual Studio would do this automatically for me, since I declared a dependency to FN from FN\_test: I assumed Visual Studio would create the libs. It didn't.
---
**RANT** (no need to read after this)
Since it's rather rare to link one project that makes an executable to another one which does the same thing, finding references on this kind of issue was somewhat hard. Google searches presented me no useful results. MSDN forums were also unhelpful.
But when you do unit testing on a application, will it be common to have this happening, say, a test project and a application project on the same solution? I have no knowledge about other testing frameworks for C++. I have chosen Google Test Framework for:
1. In Google we trust
2. Great documentation
3. Very simple to use and understand
But, however, it has no much merits on integration. I think other tools would integrate way better to Visual Studio, IDE responsiveness inclusive. But I preferred to suffer now than afterwards. I hope this tool keeps improving, for I liked it. | The linker can't find the definition of the `Embark` constructor.
* Have you defined that constructor somewhere?
* Is your test project actually linking to the FN library? |
2,507,595 | I'm using Google Test Framework to set some unit tests. I have got three projects in my solution:
* FN (my project)
* FN\_test (my tests)
* gtest (Google Test Framework)
I set FN\_test to have FN and gtest as references (dependencies), and then I think I'm ready to set up my tests (I've already set everyone to /MTd (not doing this was leading me to linking errors before)).
Particularly, I define a class called Embark in FN I would like to test using FN\_test. So far, so good. Thus I write a classe called EmbarkTest using googletest, declare a member Embark\* and write inside the constructor:
```
EmbarkTest() {
e = new Embark(900,2010);
}
```
Then , F7 pressed, I get the following:
`1>FN_test.obj : error LNK2019: unresolved external symbol "public: __thiscall Embark::Embark(int,int)" (??0Embark@@QAE@HH@Z) referenced in function "protected: __thiscall EmbarkTest::EmbarkTest(void)" (??0EmbarkTest@@IAE@XZ)`
`1>D:\Users\lg\Product\code\FN\Debug\FN_test.exe : fatal error LNK1120: 1 unresolved externals`
Does someone know what have I done wrong and/or what can I do to settle this?
**EDIT**: *Relevant* code from Embark.h
```
class Embark
{
public:
//Constructor for initial state
Embark(int _id, int _year);
//Destructor
~Embark();
/* ... */
}
``` | 2010/03/24 | [
"https://Stackoverflow.com/questions/2507595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241161/"
] | I found the answer to be a rather simple one. After two days of intense headknocking, it's this:
**You have to compile your main project as `.lib` and not `.exe`**
After doing this, all linking went as a bliss. I thought Visual Studio would do this automatically for me, since I declared a dependency to FN from FN\_test: I assumed Visual Studio would create the libs. It didn't.
---
**RANT** (no need to read after this)
Since it's rather rare to link one project that makes an executable to another one which does the same thing, finding references on this kind of issue was somewhat hard. Google searches presented me no useful results. MSDN forums were also unhelpful.
But when you do unit testing on a application, will it be common to have this happening, say, a test project and a application project on the same solution? I have no knowledge about other testing frameworks for C++. I have chosen Google Test Framework for:
1. In Google we trust
2. Great documentation
3. Very simple to use and understand
But, however, it has no much merits on integration. I think other tools would integrate way better to Visual Studio, IDE responsiveness inclusive. But I preferred to suffer now than afterwards. I hope this tool keeps improving, for I liked it. | The linker can't find `Embark::Embark(int, int)`
Here is what MSDN says about error [LNK2019](http://msdn.microsoft.com/en-us/library/799kze2z(VS.80).aspx). |
23,880,663 | What we take for granted in other languages and almost expect it to work in go, won't work - its almost so natural to do this, so why isn't the compiler happy? Just feeling like bailing out of go sometimes.
The only way to increment the value is to put it in its own separate line?
<http://play.golang.org/p/_UnpZVSN9n>
```
package main
import "fmt"
import "strconv"
func main() {
a := 1
//Evaluate expression and pass into function - won't work
fmt.Println(strconv.Itoa(a++))
//Braces around a++ also won't work
fmt.Println(strconv.Itoa((a++)))
}
``` | 2014/05/27 | [
"https://Stackoverflow.com/questions/23880663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/901460/"
] | `++` and `--` are statements in golang, not expressions | Specifically, `++` and `--` are statements because it can be very difficult to understand the order of evaluation when they're in an expression.
Consider the following:
```
// This is not valid Go!
x := 1
x = x++ + x
y := 1
y = ++y + y
```
What would you expect `x` to be? What would you expect `y` to be? By contrast, the order of evaluation is very clear when this is a statement. |
23,880,663 | What we take for granted in other languages and almost expect it to work in go, won't work - its almost so natural to do this, so why isn't the compiler happy? Just feeling like bailing out of go sometimes.
The only way to increment the value is to put it in its own separate line?
<http://play.golang.org/p/_UnpZVSN9n>
```
package main
import "fmt"
import "strconv"
func main() {
a := 1
//Evaluate expression and pass into function - won't work
fmt.Println(strconv.Itoa(a++))
//Braces around a++ also won't work
fmt.Println(strconv.Itoa((a++)))
}
``` | 2014/05/27 | [
"https://Stackoverflow.com/questions/23880663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/901460/"
] | `++` and `--` are statements in golang, not expressions | Just to help clarify, an expression has a `=`, `:=` or `+=` in them. A statement (such as `++` and `—`) does not. See <https://stackoverflow.com/a/1720029/12817546>.
```
package main
import "fmt"
var x int
func f(x int) {
x = x + 1 //expression
x++ //statement
fmt.Println(x) //2
}
func main() {
f(x) //expression statement
}
```
An "expression" specifies the computation of a value by applying operators and functions to operands. See <https://golang.org/ref/spec#Expressions>.
A "statement" controls execution. See <https://golang.org/ref/spec#Statements>.
An "expression statement" is a function and method call or receive operation that appears in a statement. See <https://golang.org/ref/spec#Expression_statements>. |
23,880,663 | What we take for granted in other languages and almost expect it to work in go, won't work - its almost so natural to do this, so why isn't the compiler happy? Just feeling like bailing out of go sometimes.
The only way to increment the value is to put it in its own separate line?
<http://play.golang.org/p/_UnpZVSN9n>
```
package main
import "fmt"
import "strconv"
func main() {
a := 1
//Evaluate expression and pass into function - won't work
fmt.Println(strconv.Itoa(a++))
//Braces around a++ also won't work
fmt.Println(strconv.Itoa((a++)))
}
``` | 2014/05/27 | [
"https://Stackoverflow.com/questions/23880663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/901460/"
] | Specifically, `++` and `--` are statements because it can be very difficult to understand the order of evaluation when they're in an expression.
Consider the following:
```
// This is not valid Go!
x := 1
x = x++ + x
y := 1
y = ++y + y
```
What would you expect `x` to be? What would you expect `y` to be? By contrast, the order of evaluation is very clear when this is a statement. | Just to help clarify, an expression has a `=`, `:=` or `+=` in them. A statement (such as `++` and `—`) does not. See <https://stackoverflow.com/a/1720029/12817546>.
```
package main
import "fmt"
var x int
func f(x int) {
x = x + 1 //expression
x++ //statement
fmt.Println(x) //2
}
func main() {
f(x) //expression statement
}
```
An "expression" specifies the computation of a value by applying operators and functions to operands. See <https://golang.org/ref/spec#Expressions>.
A "statement" controls execution. See <https://golang.org/ref/spec#Statements>.
An "expression statement" is a function and method call or receive operation that appears in a statement. See <https://golang.org/ref/spec#Expression_statements>. |
1,483,068 | The charset is Unicode. I want to write a string of CString type into a file, and then read it out from the file afterwards.
I write the string into a file with CFile::Write() method:
```
int nLen = strSample.GetLength()*sizeof(TCHAR);
file.Write(strSample.GetBuffer(), nLen);
```
Here is the question: I want to obtain the CString from the file containing the content of strSample. How can I do it?
Thank you very much! | 2009/09/27 | [
"https://Stackoverflow.com/questions/1483068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87955/"
] | ```
UINT nBytes = (UINT)file.GetLength();
int nChars = nBytes / sizeof(TCHAR);
nBytes = file.Read(strSample.GetBuffer(nChars), nBytes);
strSample.ReleaseBuffer(nChars);
``` | I think you forgot to include the '\0' at the end
strSample.GetLength() + 1 |
1,483,068 | The charset is Unicode. I want to write a string of CString type into a file, and then read it out from the file afterwards.
I write the string into a file with CFile::Write() method:
```
int nLen = strSample.GetLength()*sizeof(TCHAR);
file.Write(strSample.GetBuffer(), nLen);
```
Here is the question: I want to obtain the CString from the file containing the content of strSample. How can I do it?
Thank you very much! | 2009/09/27 | [
"https://Stackoverflow.com/questions/1483068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87955/"
] | ```
UINT nBytes = (UINT)file.GetLength();
int nChars = nBytes / sizeof(TCHAR);
nBytes = file.Read(strSample.GetBuffer(nChars), nBytes);
strSample.ReleaseBuffer(nChars);
``` | I would try this, since it can be that the file is larger than what is read (DOS style end line). Read does not set the final \0, but ReleaseBuffer apparently does, if not called with -1.
```
UINT nBytes = (UINT)file.GetLength();
UINT nBytesRead = file.Read(strSample.GetBuffer(nBytes+1), nBytes);
strSample.ReleaseBuffer(nBytesRead);
``` |
551,535 | Yeah, you probably are reading this question and thinking I'm one of those engineers who hasn't learned about the s-plane. I can assure you I'm not! I know that the transfer function of an RC circuit (Vout/Vin) has a REAL pole, with no imaginary component at s= -1/RC + j0. I am curious what happens when we excite an RC circuit at its TRUE pole, which is a decaying exponential with the expression e^(-t/RC).
Of course, the output of an RC Low-pass filter will never blow up to infinity. But what about the ratio of the output to the input, which after all, is the transfer function I originally defined?
Well, let's take this to LTSpice. Below is what I've simulated:
[![enter image description here](https://i.stack.imgur.com/GChDh.png)](https://i.stack.imgur.com/GChDh.png)
I would expect Vout/Vin to be infinity everywhere, however what I see is a ramp. I suspect I'm missing something about how to properly interpret the magnitude response of my transfer function with its true pole as an input. A time-domain view such as what I have should explain something, but I can't understand why it's a ramp.
If anyone has any intuition behind this question, please let me know. | 2021/03/06 | [
"https://electronics.stackexchange.com/questions/551535",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/257550/"
] | Good question, here's my attempt. You still have to convert your input signal from the time domain to s domain, then do the math, then convert the result back to the time domain. That pole just tells you where the resonance is, the behavior of the resonance is usually "growing infinitely forever" - but the exact behavior needs to be found from doing the math.
Using transforms from: <https://en.wikipedia.org/wiki/Laplace_transform>
$$
\frac{1}{1+sRC}V\_i(s)=V\_o(s)\\
V\_i(t) = V\_{i0}e^{-t/(RC)}=V\_{i0}e^{-t/\tau}\\
V\_i(s) = \frac{V\_{i0}}{1/\tau+s}\\
V\_o(s) = \frac{1/\tau}{1/\tau+s}\frac{V\_{i0}}{1/\tau+s}\\
V\_o(s) = \frac{ V\_{i0}/\tau}{(1/\tau+s)^2}\\
V\_o(t) = (V\_{i0}/\tau)\times t e^{-t/\tau}
$$
Which gives us:
$$
V\_o(t)/V\_i(t) = \frac{(V\_{i0}/\tau)\times t e^{-t/\tau}}{V\_{i0}e^{-t/\tau}}\\
V\_o(t)/V\_i(t) = t\times 1/\tau
$$
Predicting that, in the time domain, the ratio of output to input voltage increases linearly with t. In the s-domain, the ratio is infinity.
EDIT: This actually perfectly matches your result, even the correct slope - except there is an offset of 1 unit on the y axis. My guess is that the simulation found the DC point using \$V\_{i}=1 \text{ V}\$ at \$t<0\$, so changes the math. The above assumes \$V\_{i}=0 \text{ V}\$ at \$t<0\$. So it's pretty much the same, just a little difference because of the initial condition.
If the initial condition was V=1, you can use the superposition principle and add the solution we found (for V=0 until t=0, then decaying) to the solution if V=1 when t was negative and V=0 when t is positive
$$
V\_o(t) = (V\_{i0}/\tau)\times t e^{-t/\tau}+V\_{i0}e^{-t/\tau}\\
V\_o(t)/V\_i(t) = \frac{(V\_{i0}/\tau)\times t e^{-t/\tau}+V\_{i0}e^{-t/\tau}}{V\_{i0}e^{-t/\tau}}\\
V\_o(t)/V\_i(t) = t\times 1/\tau+1
$$
Now it exactly matches what you have! So the simulation does use V=1 for when t is negative, and this should clearly show what's happening. Just because something is infinity in the s domain doesn't mean it is in time. | Here is my (very short) answer:
All the calculations in the frequency domain (transfer function, input-and output impedances, pole location,..) do consider STEADY STATE conditions for the circuit under test. Therefore - due to the time dependence of your input - you cannot expect that the circuit will react upon such an input as predicted by the pole analysis.
The observed response of the circuit will be dominated by the time domain behaviour (transient response)...
**Comment** (Edit): In his nice answer KD9PDP has shown that we must switch-over to the time domain - nevertheless, making use of the transfer function - to find the correct result. |
551,535 | Yeah, you probably are reading this question and thinking I'm one of those engineers who hasn't learned about the s-plane. I can assure you I'm not! I know that the transfer function of an RC circuit (Vout/Vin) has a REAL pole, with no imaginary component at s= -1/RC + j0. I am curious what happens when we excite an RC circuit at its TRUE pole, which is a decaying exponential with the expression e^(-t/RC).
Of course, the output of an RC Low-pass filter will never blow up to infinity. But what about the ratio of the output to the input, which after all, is the transfer function I originally defined?
Well, let's take this to LTSpice. Below is what I've simulated:
[![enter image description here](https://i.stack.imgur.com/GChDh.png)](https://i.stack.imgur.com/GChDh.png)
I would expect Vout/Vin to be infinity everywhere, however what I see is a ramp. I suspect I'm missing something about how to properly interpret the magnitude response of my transfer function with its true pole as an input. A time-domain view such as what I have should explain something, but I can't understand why it's a ramp.
If anyone has any intuition behind this question, please let me know. | 2021/03/06 | [
"https://electronics.stackexchange.com/questions/551535",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/257550/"
] | Good question, here's my attempt. You still have to convert your input signal from the time domain to s domain, then do the math, then convert the result back to the time domain. That pole just tells you where the resonance is, the behavior of the resonance is usually "growing infinitely forever" - but the exact behavior needs to be found from doing the math.
Using transforms from: <https://en.wikipedia.org/wiki/Laplace_transform>
$$
\frac{1}{1+sRC}V\_i(s)=V\_o(s)\\
V\_i(t) = V\_{i0}e^{-t/(RC)}=V\_{i0}e^{-t/\tau}\\
V\_i(s) = \frac{V\_{i0}}{1/\tau+s}\\
V\_o(s) = \frac{1/\tau}{1/\tau+s}\frac{V\_{i0}}{1/\tau+s}\\
V\_o(s) = \frac{ V\_{i0}/\tau}{(1/\tau+s)^2}\\
V\_o(t) = (V\_{i0}/\tau)\times t e^{-t/\tau}
$$
Which gives us:
$$
V\_o(t)/V\_i(t) = \frac{(V\_{i0}/\tau)\times t e^{-t/\tau}}{V\_{i0}e^{-t/\tau}}\\
V\_o(t)/V\_i(t) = t\times 1/\tau
$$
Predicting that, in the time domain, the ratio of output to input voltage increases linearly with t. In the s-domain, the ratio is infinity.
EDIT: This actually perfectly matches your result, even the correct slope - except there is an offset of 1 unit on the y axis. My guess is that the simulation found the DC point using \$V\_{i}=1 \text{ V}\$ at \$t<0\$, so changes the math. The above assumes \$V\_{i}=0 \text{ V}\$ at \$t<0\$. So it's pretty much the same, just a little difference because of the initial condition.
If the initial condition was V=1, you can use the superposition principle and add the solution we found (for V=0 until t=0, then decaying) to the solution if V=1 when t was negative and V=0 when t is positive
$$
V\_o(t) = (V\_{i0}/\tau)\times t e^{-t/\tau}+V\_{i0}e^{-t/\tau}\\
V\_o(t)/V\_i(t) = \frac{(V\_{i0}/\tau)\times t e^{-t/\tau}+V\_{i0}e^{-t/\tau}}{V\_{i0}e^{-t/\tau}}\\
V\_o(t)/V\_i(t) = t\times 1/\tau+1
$$
Now it exactly matches what you have! So the simulation does use V=1 for when t is negative, and this should clearly show what's happening. Just because something is infinity in the s domain doesn't mean it is in time. | [KD9PDP's answer](https://electronics.stackexchange.com/a/551541/95619) alreay explains very nice (+1) why the result is as you see it, but there might be an easier way to do it. You already have the impulse response (1) and the input (2):
$$\begin{align}
h(t)&=\dfrac{1}{RC}\mathrm{e}^{-\frac{t}{RC}}\tag{1} \\
s(t)&=\mathrm{e}^{-\frac{t}{RC}}\tag{2}
\end{align}$$
The convolution integral is now simple because \$h(t)\$ and \$s(t)\$ are simplified before applying the integral:
$$\begin{align}
s(t)\star h(t)&=\int\_{\tau}{\dfrac{1}{RC}\mathrm{e}^{-\frac{\tau}{RC}}\cdot\mathrm{e}^{-\frac{t-\tau}{RC}}\mathrm{d}\tau} \\
{}&=\int\_{\tau}{\dfrac{1}{RC}\mathrm{e}^{-\frac{t}{RC}}\mathrm{d}\tau} \\
{}&=\dfrac{1}{RC}\mathrm{e}^{-\frac{t}{RC}}\cdot t\tag{3} \\
\end{align}$$
Since the variable is \$\tau\$, the integrand is a constant, and integrating it means adding \$t\$, which is the only difference between (3) and (1). As noted in the other answer, it's also a matter of initial conditions (\$\mathrm{i.c.}\$), since LTspice assumes those to be given by the value of the behavioural expression at `t=0`, which is `1`. |
551,535 | Yeah, you probably are reading this question and thinking I'm one of those engineers who hasn't learned about the s-plane. I can assure you I'm not! I know that the transfer function of an RC circuit (Vout/Vin) has a REAL pole, with no imaginary component at s= -1/RC + j0. I am curious what happens when we excite an RC circuit at its TRUE pole, which is a decaying exponential with the expression e^(-t/RC).
Of course, the output of an RC Low-pass filter will never blow up to infinity. But what about the ratio of the output to the input, which after all, is the transfer function I originally defined?
Well, let's take this to LTSpice. Below is what I've simulated:
[![enter image description here](https://i.stack.imgur.com/GChDh.png)](https://i.stack.imgur.com/GChDh.png)
I would expect Vout/Vin to be infinity everywhere, however what I see is a ramp. I suspect I'm missing something about how to properly interpret the magnitude response of my transfer function with its true pole as an input. A time-domain view such as what I have should explain something, but I can't understand why it's a ramp.
If anyone has any intuition behind this question, please let me know. | 2021/03/06 | [
"https://electronics.stackexchange.com/questions/551535",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/257550/"
] | Good question, here's my attempt. You still have to convert your input signal from the time domain to s domain, then do the math, then convert the result back to the time domain. That pole just tells you where the resonance is, the behavior of the resonance is usually "growing infinitely forever" - but the exact behavior needs to be found from doing the math.
Using transforms from: <https://en.wikipedia.org/wiki/Laplace_transform>
$$
\frac{1}{1+sRC}V\_i(s)=V\_o(s)\\
V\_i(t) = V\_{i0}e^{-t/(RC)}=V\_{i0}e^{-t/\tau}\\
V\_i(s) = \frac{V\_{i0}}{1/\tau+s}\\
V\_o(s) = \frac{1/\tau}{1/\tau+s}\frac{V\_{i0}}{1/\tau+s}\\
V\_o(s) = \frac{ V\_{i0}/\tau}{(1/\tau+s)^2}\\
V\_o(t) = (V\_{i0}/\tau)\times t e^{-t/\tau}
$$
Which gives us:
$$
V\_o(t)/V\_i(t) = \frac{(V\_{i0}/\tau)\times t e^{-t/\tau}}{V\_{i0}e^{-t/\tau}}\\
V\_o(t)/V\_i(t) = t\times 1/\tau
$$
Predicting that, in the time domain, the ratio of output to input voltage increases linearly with t. In the s-domain, the ratio is infinity.
EDIT: This actually perfectly matches your result, even the correct slope - except there is an offset of 1 unit on the y axis. My guess is that the simulation found the DC point using \$V\_{i}=1 \text{ V}\$ at \$t<0\$, so changes the math. The above assumes \$V\_{i}=0 \text{ V}\$ at \$t<0\$. So it's pretty much the same, just a little difference because of the initial condition.
If the initial condition was V=1, you can use the superposition principle and add the solution we found (for V=0 until t=0, then decaying) to the solution if V=1 when t was negative and V=0 when t is positive
$$
V\_o(t) = (V\_{i0}/\tau)\times t e^{-t/\tau}+V\_{i0}e^{-t/\tau}\\
V\_o(t)/V\_i(t) = \frac{(V\_{i0}/\tau)\times t e^{-t/\tau}+V\_{i0}e^{-t/\tau}}{V\_{i0}e^{-t/\tau}}\\
V\_o(t)/V\_i(t) = t\times 1/\tau+1
$$
Now it exactly matches what you have! So the simulation does use V=1 for when t is negative, and this should clearly show what's happening. Just because something is infinity in the s domain doesn't mean it is in time. | If the system's impulse response is \$h(t)=e^{-at}u(t)\$, \$a>0\$, where \$u(t)\$ is the unit step function, and if its input is \$x(t)=e^{-at}u(t)\$, then its response is given by
$$y(t)=te^{-at}u(t)\tag{1}$$
which is a basic result. The function \$(1)\$ is just the inverse Laplace transform of a double real-valued pole:
$$Y(s)=\frac{1}{(s+a)^2}\tag{2}$$
Clearly, the output \$y(t)\$ decays to zero. However, the ratio \$y(t)/x(t)\$ is a ramp for \$t>0\$.
Please note that the ratio \$y(t)/x(t)\$ is not the system's transfer function. The transfer function is the ratio of the Laplace transforms of the input and output:
$$H(s)=\frac{Y(s)}{X(s)}\tag{3}$$
For a first-order lowpass filter with time constant \$\tau\$, \$H(s)\$ is given by
$$H(s)=\frac{1}{1+s\tau}\tag{4}$$ |
551,535 | Yeah, you probably are reading this question and thinking I'm one of those engineers who hasn't learned about the s-plane. I can assure you I'm not! I know that the transfer function of an RC circuit (Vout/Vin) has a REAL pole, with no imaginary component at s= -1/RC + j0. I am curious what happens when we excite an RC circuit at its TRUE pole, which is a decaying exponential with the expression e^(-t/RC).
Of course, the output of an RC Low-pass filter will never blow up to infinity. But what about the ratio of the output to the input, which after all, is the transfer function I originally defined?
Well, let's take this to LTSpice. Below is what I've simulated:
[![enter image description here](https://i.stack.imgur.com/GChDh.png)](https://i.stack.imgur.com/GChDh.png)
I would expect Vout/Vin to be infinity everywhere, however what I see is a ramp. I suspect I'm missing something about how to properly interpret the magnitude response of my transfer function with its true pole as an input. A time-domain view such as what I have should explain something, but I can't understand why it's a ramp.
If anyone has any intuition behind this question, please let me know. | 2021/03/06 | [
"https://electronics.stackexchange.com/questions/551535",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/257550/"
] | Good question, here's my attempt. You still have to convert your input signal from the time domain to s domain, then do the math, then convert the result back to the time domain. That pole just tells you where the resonance is, the behavior of the resonance is usually "growing infinitely forever" - but the exact behavior needs to be found from doing the math.
Using transforms from: <https://en.wikipedia.org/wiki/Laplace_transform>
$$
\frac{1}{1+sRC}V\_i(s)=V\_o(s)\\
V\_i(t) = V\_{i0}e^{-t/(RC)}=V\_{i0}e^{-t/\tau}\\
V\_i(s) = \frac{V\_{i0}}{1/\tau+s}\\
V\_o(s) = \frac{1/\tau}{1/\tau+s}\frac{V\_{i0}}{1/\tau+s}\\
V\_o(s) = \frac{ V\_{i0}/\tau}{(1/\tau+s)^2}\\
V\_o(t) = (V\_{i0}/\tau)\times t e^{-t/\tau}
$$
Which gives us:
$$
V\_o(t)/V\_i(t) = \frac{(V\_{i0}/\tau)\times t e^{-t/\tau}}{V\_{i0}e^{-t/\tau}}\\
V\_o(t)/V\_i(t) = t\times 1/\tau
$$
Predicting that, in the time domain, the ratio of output to input voltage increases linearly with t. In the s-domain, the ratio is infinity.
EDIT: This actually perfectly matches your result, even the correct slope - except there is an offset of 1 unit on the y axis. My guess is that the simulation found the DC point using \$V\_{i}=1 \text{ V}\$ at \$t<0\$, so changes the math. The above assumes \$V\_{i}=0 \text{ V}\$ at \$t<0\$. So it's pretty much the same, just a little difference because of the initial condition.
If the initial condition was V=1, you can use the superposition principle and add the solution we found (for V=0 until t=0, then decaying) to the solution if V=1 when t was negative and V=0 when t is positive
$$
V\_o(t) = (V\_{i0}/\tau)\times t e^{-t/\tau}+V\_{i0}e^{-t/\tau}\\
V\_o(t)/V\_i(t) = \frac{(V\_{i0}/\tau)\times t e^{-t/\tau}+V\_{i0}e^{-t/\tau}}{V\_{i0}e^{-t/\tau}}\\
V\_o(t)/V\_i(t) = t\times 1/\tau+1
$$
Now it exactly matches what you have! So the simulation does use V=1 for when t is negative, and this should clearly show what's happening. Just because something is infinity in the s domain doesn't mean it is in time. | It *is* ramping to infinity as you expected. The s-domain calculation is a steady-state calculation, and you have an initial transient (your input exponential was effectively a constant '1' for all t < 0). You have to wait for that to decay (i.e. become negligible) -- e.g. a long (infinite) time.
You can see that after 10 time constants, your 'gain' is already 10. |
551,535 | Yeah, you probably are reading this question and thinking I'm one of those engineers who hasn't learned about the s-plane. I can assure you I'm not! I know that the transfer function of an RC circuit (Vout/Vin) has a REAL pole, with no imaginary component at s= -1/RC + j0. I am curious what happens when we excite an RC circuit at its TRUE pole, which is a decaying exponential with the expression e^(-t/RC).
Of course, the output of an RC Low-pass filter will never blow up to infinity. But what about the ratio of the output to the input, which after all, is the transfer function I originally defined?
Well, let's take this to LTSpice. Below is what I've simulated:
[![enter image description here](https://i.stack.imgur.com/GChDh.png)](https://i.stack.imgur.com/GChDh.png)
I would expect Vout/Vin to be infinity everywhere, however what I see is a ramp. I suspect I'm missing something about how to properly interpret the magnitude response of my transfer function with its true pole as an input. A time-domain view such as what I have should explain something, but I can't understand why it's a ramp.
If anyone has any intuition behind this question, please let me know. | 2021/03/06 | [
"https://electronics.stackexchange.com/questions/551535",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/257550/"
] | Here is my (very short) answer:
All the calculations in the frequency domain (transfer function, input-and output impedances, pole location,..) do consider STEADY STATE conditions for the circuit under test. Therefore - due to the time dependence of your input - you cannot expect that the circuit will react upon such an input as predicted by the pole analysis.
The observed response of the circuit will be dominated by the time domain behaviour (transient response)...
**Comment** (Edit): In his nice answer KD9PDP has shown that we must switch-over to the time domain - nevertheless, making use of the transfer function - to find the correct result. | It *is* ramping to infinity as you expected. The s-domain calculation is a steady-state calculation, and you have an initial transient (your input exponential was effectively a constant '1' for all t < 0). You have to wait for that to decay (i.e. become negligible) -- e.g. a long (infinite) time.
You can see that after 10 time constants, your 'gain' is already 10. |
551,535 | Yeah, you probably are reading this question and thinking I'm one of those engineers who hasn't learned about the s-plane. I can assure you I'm not! I know that the transfer function of an RC circuit (Vout/Vin) has a REAL pole, with no imaginary component at s= -1/RC + j0. I am curious what happens when we excite an RC circuit at its TRUE pole, which is a decaying exponential with the expression e^(-t/RC).
Of course, the output of an RC Low-pass filter will never blow up to infinity. But what about the ratio of the output to the input, which after all, is the transfer function I originally defined?
Well, let's take this to LTSpice. Below is what I've simulated:
[![enter image description here](https://i.stack.imgur.com/GChDh.png)](https://i.stack.imgur.com/GChDh.png)
I would expect Vout/Vin to be infinity everywhere, however what I see is a ramp. I suspect I'm missing something about how to properly interpret the magnitude response of my transfer function with its true pole as an input. A time-domain view such as what I have should explain something, but I can't understand why it's a ramp.
If anyone has any intuition behind this question, please let me know. | 2021/03/06 | [
"https://electronics.stackexchange.com/questions/551535",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/257550/"
] | [KD9PDP's answer](https://electronics.stackexchange.com/a/551541/95619) alreay explains very nice (+1) why the result is as you see it, but there might be an easier way to do it. You already have the impulse response (1) and the input (2):
$$\begin{align}
h(t)&=\dfrac{1}{RC}\mathrm{e}^{-\frac{t}{RC}}\tag{1} \\
s(t)&=\mathrm{e}^{-\frac{t}{RC}}\tag{2}
\end{align}$$
The convolution integral is now simple because \$h(t)\$ and \$s(t)\$ are simplified before applying the integral:
$$\begin{align}
s(t)\star h(t)&=\int\_{\tau}{\dfrac{1}{RC}\mathrm{e}^{-\frac{\tau}{RC}}\cdot\mathrm{e}^{-\frac{t-\tau}{RC}}\mathrm{d}\tau} \\
{}&=\int\_{\tau}{\dfrac{1}{RC}\mathrm{e}^{-\frac{t}{RC}}\mathrm{d}\tau} \\
{}&=\dfrac{1}{RC}\mathrm{e}^{-\frac{t}{RC}}\cdot t\tag{3} \\
\end{align}$$
Since the variable is \$\tau\$, the integrand is a constant, and integrating it means adding \$t\$, which is the only difference between (3) and (1). As noted in the other answer, it's also a matter of initial conditions (\$\mathrm{i.c.}\$), since LTspice assumes those to be given by the value of the behavioural expression at `t=0`, which is `1`. | It *is* ramping to infinity as you expected. The s-domain calculation is a steady-state calculation, and you have an initial transient (your input exponential was effectively a constant '1' for all t < 0). You have to wait for that to decay (i.e. become negligible) -- e.g. a long (infinite) time.
You can see that after 10 time constants, your 'gain' is already 10. |
551,535 | Yeah, you probably are reading this question and thinking I'm one of those engineers who hasn't learned about the s-plane. I can assure you I'm not! I know that the transfer function of an RC circuit (Vout/Vin) has a REAL pole, with no imaginary component at s= -1/RC + j0. I am curious what happens when we excite an RC circuit at its TRUE pole, which is a decaying exponential with the expression e^(-t/RC).
Of course, the output of an RC Low-pass filter will never blow up to infinity. But what about the ratio of the output to the input, which after all, is the transfer function I originally defined?
Well, let's take this to LTSpice. Below is what I've simulated:
[![enter image description here](https://i.stack.imgur.com/GChDh.png)](https://i.stack.imgur.com/GChDh.png)
I would expect Vout/Vin to be infinity everywhere, however what I see is a ramp. I suspect I'm missing something about how to properly interpret the magnitude response of my transfer function with its true pole as an input. A time-domain view such as what I have should explain something, but I can't understand why it's a ramp.
If anyone has any intuition behind this question, please let me know. | 2021/03/06 | [
"https://electronics.stackexchange.com/questions/551535",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/257550/"
] | If the system's impulse response is \$h(t)=e^{-at}u(t)\$, \$a>0\$, where \$u(t)\$ is the unit step function, and if its input is \$x(t)=e^{-at}u(t)\$, then its response is given by
$$y(t)=te^{-at}u(t)\tag{1}$$
which is a basic result. The function \$(1)\$ is just the inverse Laplace transform of a double real-valued pole:
$$Y(s)=\frac{1}{(s+a)^2}\tag{2}$$
Clearly, the output \$y(t)\$ decays to zero. However, the ratio \$y(t)/x(t)\$ is a ramp for \$t>0\$.
Please note that the ratio \$y(t)/x(t)\$ is not the system's transfer function. The transfer function is the ratio of the Laplace transforms of the input and output:
$$H(s)=\frac{Y(s)}{X(s)}\tag{3}$$
For a first-order lowpass filter with time constant \$\tau\$, \$H(s)\$ is given by
$$H(s)=\frac{1}{1+s\tau}\tag{4}$$ | It *is* ramping to infinity as you expected. The s-domain calculation is a steady-state calculation, and you have an initial transient (your input exponential was effectively a constant '1' for all t < 0). You have to wait for that to decay (i.e. become negligible) -- e.g. a long (infinite) time.
You can see that after 10 time constants, your 'gain' is already 10. |
7,327,164 | I am developing a node.js app, and I want to use a module I am creating for the node.js server also on the client side.
An example module would be circle.js:
```
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
```
and you do a simple
```
var circle = require('./circle')
```
to use it in node.
How could I use that same file in the web directory for my client side javascript? | 2011/09/06 | [
"https://Stackoverflow.com/questions/7327164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101909/"
] | This seems to be how to make a module something you can use on the client side.
<https://caolan.org/posts/writing_for_node_and_the_browser.html>
mymodule.js:
```
(function(exports){
// your code goes here
exports.test = function(){
return 'hello world'
};
})(typeof exports === 'undefined'? this['mymodule']={}: exports);
```
And then to use the module on the client:
```
<script src="mymodule.js"></script>
<script>
alert(mymodule.test());
</script>
```
This code would work in node:
```
var mymodule = require('./mymodule');
``` | ![Browserify](https://i.stack.imgur.com/5FtLy.png)
[Browserify](https://github.com/substack/node-browserify)
It magically lets you do that. |
7,327,164 | I am developing a node.js app, and I want to use a module I am creating for the node.js server also on the client side.
An example module would be circle.js:
```
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
```
and you do a simple
```
var circle = require('./circle')
```
to use it in node.
How could I use that same file in the web directory for my client side javascript? | 2011/09/06 | [
"https://Stackoverflow.com/questions/7327164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101909/"
] | ![Browserify](https://i.stack.imgur.com/5FtLy.png)
[Browserify](https://github.com/substack/node-browserify)
It magically lets you do that. | [Webmake](https://github.com/medikoo/modules-webmake) was made to port CommonJS/NodeJS modules to browser. Give it a try |
7,327,164 | I am developing a node.js app, and I want to use a module I am creating for the node.js server also on the client side.
An example module would be circle.js:
```
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
```
and you do a simple
```
var circle = require('./circle')
```
to use it in node.
How could I use that same file in the web directory for my client side javascript? | 2011/09/06 | [
"https://Stackoverflow.com/questions/7327164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101909/"
] | This seems to be how to make a module something you can use on the client side.
<https://caolan.org/posts/writing_for_node_and_the_browser.html>
mymodule.js:
```
(function(exports){
// your code goes here
exports.test = function(){
return 'hello world'
};
})(typeof exports === 'undefined'? this['mymodule']={}: exports);
```
And then to use the module on the client:
```
<script src="mymodule.js"></script>
<script>
alert(mymodule.test());
</script>
```
This code would work in node:
```
var mymodule = require('./mymodule');
``` | [Webmake](https://github.com/medikoo/modules-webmake) was made to port CommonJS/NodeJS modules to browser. Give it a try |
31,424,294 | say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs? | 2015/07/15 | [
"https://Stackoverflow.com/questions/31424294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1798362/"
] | In the current version of JavaScript, you can do this by escaping the newlines at the ends of lines, which is a *bit* better but note that leading whitespace will be included in the string, and you still have to use concatenation to swap in your values:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />\
data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />\
data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />\
data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />\
<input type="button" id="subUpdated" value="Save">');
```
In the next version of JavaScript, "ES6", we'll have *template strings* which can be multi-line and which let you easily swap in text using `${...}`:
```
// REQUIRES ES6
var rightPane = $("#right");
// Draw the right pane
rightPane.html(`
<h2>${task.task}<h2> <hr />
data1: <input type="text" id="data1" value="${task.data1}" /> <br />
data2: <input type="text" id="data2" value="${task.data2}" /> <br />
data1: <input type="text" id="data3" value="${task.data3}" /> <br />
<input type="button" id="subUpdated" value="Save">
`);
```
(Again leading whitespace is included in the string.)
To do that before ES6, you can use any of several templating libraries (Handlebars, Mustache, RivetsJS).
For a really simple version, you could use [the function I wrote](https://stackoverflow.com/a/31368057/157247) for another question. | Not currently, other than templates as others have mentioned. What you could do, however, is to include the initial HTML code in your main document, and then set the values with `rightPane.val(task.data1);`, etc. |
31,424,294 | say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs? | 2015/07/15 | [
"https://Stackoverflow.com/questions/31424294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1798362/"
] | In the current version of JavaScript, you can do this by escaping the newlines at the ends of lines, which is a *bit* better but note that leading whitespace will be included in the string, and you still have to use concatenation to swap in your values:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />\
data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />\
data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />\
data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />\
<input type="button" id="subUpdated" value="Save">');
```
In the next version of JavaScript, "ES6", we'll have *template strings* which can be multi-line and which let you easily swap in text using `${...}`:
```
// REQUIRES ES6
var rightPane = $("#right");
// Draw the right pane
rightPane.html(`
<h2>${task.task}<h2> <hr />
data1: <input type="text" id="data1" value="${task.data1}" /> <br />
data2: <input type="text" id="data2" value="${task.data2}" /> <br />
data1: <input type="text" id="data3" value="${task.data3}" /> <br />
<input type="button" id="subUpdated" value="Save">
`);
```
(Again leading whitespace is included in the string.)
To do that before ES6, you can use any of several templating libraries (Handlebars, Mustache, RivetsJS).
For a really simple version, you could use [the function I wrote](https://stackoverflow.com/a/31368057/157247) for another question. | You can try to do something like this: [Format a string using placeholders and an object of substitutions?](https://stackoverflow.com/questions/7975005/format-a-string-using-placeholders-and-an-object-of-substitutions)
but as Hacketo suggests it would be better to learn to use templates. Take for instance look at underscore.js (<http://underscorejs.org/#template>) |
31,424,294 | say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs? | 2015/07/15 | [
"https://Stackoverflow.com/questions/31424294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1798362/"
] | In the current version of JavaScript, you can do this by escaping the newlines at the ends of lines, which is a *bit* better but note that leading whitespace will be included in the string, and you still have to use concatenation to swap in your values:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />\
data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />\
data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />\
data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />\
<input type="button" id="subUpdated" value="Save">');
```
In the next version of JavaScript, "ES6", we'll have *template strings* which can be multi-line and which let you easily swap in text using `${...}`:
```
// REQUIRES ES6
var rightPane = $("#right");
// Draw the right pane
rightPane.html(`
<h2>${task.task}<h2> <hr />
data1: <input type="text" id="data1" value="${task.data1}" /> <br />
data2: <input type="text" id="data2" value="${task.data2}" /> <br />
data1: <input type="text" id="data3" value="${task.data3}" /> <br />
<input type="button" id="subUpdated" value="Save">
`);
```
(Again leading whitespace is included in the string.)
To do that before ES6, you can use any of several templating libraries (Handlebars, Mustache, RivetsJS).
For a really simple version, you could use [the function I wrote](https://stackoverflow.com/a/31368057/157247) for another question. | One alternative way of approaching this would be :
```
var $h2 = $("<h2>", {text : task.task});
var $data1 = $("<input>", {type : 'text', value : task.data1});
var $data2 = $("<input>", {type : 'text', value : task.data2});
var $data3 = $("<input>", {type : 'text', value : task.data3});
var $button = $("<input>", {type : 'button', value : 'Save'});
rightPane.append($h2, $data1, $data2, $data3, $button);
```
This might be a little easier to follow when scanning over the code, rather than shifting through the `.html()` function. |
31,424,294 | say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs? | 2015/07/15 | [
"https://Stackoverflow.com/questions/31424294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1798362/"
] | In the current version of JavaScript, you can do this by escaping the newlines at the ends of lines, which is a *bit* better but note that leading whitespace will be included in the string, and you still have to use concatenation to swap in your values:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />\
data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />\
data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />\
data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />\
<input type="button" id="subUpdated" value="Save">');
```
In the next version of JavaScript, "ES6", we'll have *template strings* which can be multi-line and which let you easily swap in text using `${...}`:
```
// REQUIRES ES6
var rightPane = $("#right");
// Draw the right pane
rightPane.html(`
<h2>${task.task}<h2> <hr />
data1: <input type="text" id="data1" value="${task.data1}" /> <br />
data2: <input type="text" id="data2" value="${task.data2}" /> <br />
data1: <input type="text" id="data3" value="${task.data3}" /> <br />
<input type="button" id="subUpdated" value="Save">
`);
```
(Again leading whitespace is included in the string.)
To do that before ES6, you can use any of several templating libraries (Handlebars, Mustache, RivetsJS).
For a really simple version, you could use [the function I wrote](https://stackoverflow.com/a/31368057/157247) for another question. | You could take a look at a JavaScript templating engine. Such as Handlebars, Mustache etc. You can see some of the popular ones [here](http://www.creativebloq.com/web-design/templating-engines-9134396): You can *kind* of view these as user controls similar to what you get in ASP.NET
This is an example of Handlebars for your code:
```
<h2>{{task}}<h2> <hr />
data1: <input type="text" id="data1" value="{{data1}}" /> <br />
data2: <input type="text" id="data2" value="{{data2}}" /> <br />
data1: <input type="text" id="data3" value="{{data3}}" /> <br />
<input type="button" id="subUpdated" value="Save">
``` |
31,424,294 | say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs? | 2015/07/15 | [
"https://Stackoverflow.com/questions/31424294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1798362/"
] | In the current version of JavaScript, you can do this by escaping the newlines at the ends of lines, which is a *bit* better but note that leading whitespace will be included in the string, and you still have to use concatenation to swap in your values:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />\
data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />\
data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />\
data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />\
<input type="button" id="subUpdated" value="Save">');
```
In the next version of JavaScript, "ES6", we'll have *template strings* which can be multi-line and which let you easily swap in text using `${...}`:
```
// REQUIRES ES6
var rightPane = $("#right");
// Draw the right pane
rightPane.html(`
<h2>${task.task}<h2> <hr />
data1: <input type="text" id="data1" value="${task.data1}" /> <br />
data2: <input type="text" id="data2" value="${task.data2}" /> <br />
data1: <input type="text" id="data3" value="${task.data3}" /> <br />
<input type="button" id="subUpdated" value="Save">
`);
```
(Again leading whitespace is included in the string.)
To do that before ES6, you can use any of several templating libraries (Handlebars, Mustache, RivetsJS).
For a really simple version, you could use [the function I wrote](https://stackoverflow.com/a/31368057/157247) for another question. | You could create your own super-simple 'template engine'.
* Write your template in the markup of your page as you would a usual element.
* Give the template container element an attribute to denote its role as a template, for example a data attribute of `data-template`.
* Clone and detach all `data-template` elements when the DOM is ready.
* On some event, insert your values as you like, then re-insert the compiled template into the page.
For example:
```js
$(document).ready(function() {
var template = $('[data-template]').detach().clone();
var values = { foo: 'bar', yipee: 'yahoo' };
$('button').click(function() {
for(var prop in values) {
template.find('[data-value="' + prop + '"]').html(values[prop]);
$('#container').append(template);
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Insert</button>
<div id="container"></div>
<div data-template>
<div data-value="foo"></div>
<div>
<div data-value="yipee"></div>
</div>
</div>
``` |
31,424,294 | say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs? | 2015/07/15 | [
"https://Stackoverflow.com/questions/31424294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1798362/"
] | You could create your own super-simple 'template engine'.
* Write your template in the markup of your page as you would a usual element.
* Give the template container element an attribute to denote its role as a template, for example a data attribute of `data-template`.
* Clone and detach all `data-template` elements when the DOM is ready.
* On some event, insert your values as you like, then re-insert the compiled template into the page.
For example:
```js
$(document).ready(function() {
var template = $('[data-template]').detach().clone();
var values = { foo: 'bar', yipee: 'yahoo' };
$('button').click(function() {
for(var prop in values) {
template.find('[data-value="' + prop + '"]').html(values[prop]);
$('#container').append(template);
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Insert</button>
<div id="container"></div>
<div data-template>
<div data-value="foo"></div>
<div>
<div data-value="yipee"></div>
</div>
</div>
``` | Not currently, other than templates as others have mentioned. What you could do, however, is to include the initial HTML code in your main document, and then set the values with `rightPane.val(task.data1);`, etc. |
31,424,294 | say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs? | 2015/07/15 | [
"https://Stackoverflow.com/questions/31424294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1798362/"
] | You could create your own super-simple 'template engine'.
* Write your template in the markup of your page as you would a usual element.
* Give the template container element an attribute to denote its role as a template, for example a data attribute of `data-template`.
* Clone and detach all `data-template` elements when the DOM is ready.
* On some event, insert your values as you like, then re-insert the compiled template into the page.
For example:
```js
$(document).ready(function() {
var template = $('[data-template]').detach().clone();
var values = { foo: 'bar', yipee: 'yahoo' };
$('button').click(function() {
for(var prop in values) {
template.find('[data-value="' + prop + '"]').html(values[prop]);
$('#container').append(template);
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Insert</button>
<div id="container"></div>
<div data-template>
<div data-value="foo"></div>
<div>
<div data-value="yipee"></div>
</div>
</div>
``` | You can try to do something like this: [Format a string using placeholders and an object of substitutions?](https://stackoverflow.com/questions/7975005/format-a-string-using-placeholders-and-an-object-of-substitutions)
but as Hacketo suggests it would be better to learn to use templates. Take for instance look at underscore.js (<http://underscorejs.org/#template>) |
31,424,294 | say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs? | 2015/07/15 | [
"https://Stackoverflow.com/questions/31424294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1798362/"
] | You could create your own super-simple 'template engine'.
* Write your template in the markup of your page as you would a usual element.
* Give the template container element an attribute to denote its role as a template, for example a data attribute of `data-template`.
* Clone and detach all `data-template` elements when the DOM is ready.
* On some event, insert your values as you like, then re-insert the compiled template into the page.
For example:
```js
$(document).ready(function() {
var template = $('[data-template]').detach().clone();
var values = { foo: 'bar', yipee: 'yahoo' };
$('button').click(function() {
for(var prop in values) {
template.find('[data-value="' + prop + '"]').html(values[prop]);
$('#container').append(template);
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Insert</button>
<div id="container"></div>
<div data-template>
<div data-value="foo"></div>
<div>
<div data-value="yipee"></div>
</div>
</div>
``` | One alternative way of approaching this would be :
```
var $h2 = $("<h2>", {text : task.task});
var $data1 = $("<input>", {type : 'text', value : task.data1});
var $data2 = $("<input>", {type : 'text', value : task.data2});
var $data3 = $("<input>", {type : 'text', value : task.data3});
var $button = $("<input>", {type : 'button', value : 'Save'});
rightPane.append($h2, $data1, $data2, $data3, $button);
```
This might be a little easier to follow when scanning over the code, rather than shifting through the `.html()` function. |
31,424,294 | say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs? | 2015/07/15 | [
"https://Stackoverflow.com/questions/31424294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1798362/"
] | You could create your own super-simple 'template engine'.
* Write your template in the markup of your page as you would a usual element.
* Give the template container element an attribute to denote its role as a template, for example a data attribute of `data-template`.
* Clone and detach all `data-template` elements when the DOM is ready.
* On some event, insert your values as you like, then re-insert the compiled template into the page.
For example:
```js
$(document).ready(function() {
var template = $('[data-template]').detach().clone();
var values = { foo: 'bar', yipee: 'yahoo' };
$('button').click(function() {
for(var prop in values) {
template.find('[data-value="' + prop + '"]').html(values[prop]);
$('#container').append(template);
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Insert</button>
<div id="container"></div>
<div data-template>
<div data-value="foo"></div>
<div>
<div data-value="yipee"></div>
</div>
</div>
``` | You could take a look at a JavaScript templating engine. Such as Handlebars, Mustache etc. You can see some of the popular ones [here](http://www.creativebloq.com/web-design/templating-engines-9134396): You can *kind* of view these as user controls similar to what you get in ASP.NET
This is an example of Handlebars for your code:
```
<h2>{{task}}<h2> <hr />
data1: <input type="text" id="data1" value="{{data1}}" /> <br />
data2: <input type="text" id="data2" value="{{data2}}" /> <br />
data1: <input type="text" id="data3" value="{{data3}}" /> <br />
<input type="button" id="subUpdated" value="Save">
``` |
27,975,841 | I need to write in a pure JavaScript function which will execute only for 5 seconds and will stop if either one of the following conditions (whichever comes first)
1. 5 seconds has elapsed
2. user inputted a field
I could only do condition 2 but can't figure out how to break the loop after 5 seconds:
```
function beginScanningForItemVer2(){
var userInput= false;
var element;
while (!userInput){
element = document.getElementById("input").value;
if (element != null){
userInput= true;
}
}
}
```
EDIT:
Thanks guys for helping me. Please keep helping me...
It seems I cannot use a while loop for detecting user input because my CPU usage goes up really fast while on the loop. Is there any way to accomplish both of these? Please help me | 2015/01/16 | [
"https://Stackoverflow.com/questions/27975841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4459865/"
] | Javascript tends to be very callback oriented, since by default all the Javascript on a page runs in a single thread, which means that the UI isn't responsive while other code is busy running. So rather than looping in a function and looking for input on each loop, you likely want to register a callback function which will be called when your input element experiences a change -- for example, the `onchange` listener will run your callback whenever the value of the element changes. You could unregister this callback 5 seconds later to stop anything from happening if the user inputs something after the 5 seconds are up.
Sparse example (referencing <http://www.w3schools.com/jsref/event_onchange.asp>):
```
// Set a function to be called when the value of the input element changes.
object.onchange = function() {
valueAfterChange = document.getElementById("input").value;
// Do something with valueAfterChange.
}
// window.setInterval calls a function after a set delay.
window.setInterval(function() {
object.onchange = null;
// Anything else you might want to do after 5 seconds.
}, 5000); // Call this function after 5000 milliseconds == 5 seconds.
``` | **Eddited**
You could combine `setInterval` and `setTimeout` to solve . Your code will look like this.
```
var interval = setInterval(function() {
var userInput= false;
var element;
while (!userInput){
element = document.getElementById("input").value;
if (element != null){
userInput= true;
}
}
}, 1000);
setTimeout(function() {
clearInterval(interval);
}, 5000)
```
You could see more information here. Cheers.
<https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers> |
65,047,655 | I am following [this thread](https://stackoverflow.com/questions/7707074/creating-dynamic-button-with-click-event-in-javascript) which shows how to generate DOM elements dynamically.
Suppose I have this snippet that generate a series of buttons:
```
for(var i = 0; i < result.length;i++){
var menuCatButton = document.createElement("button");
menuCatButton.id = "menu-mgt-button-"+result[i];
menuMgtCategoryButtons.appendChild(menuCatButton);
}
```
How do I apply this set of style to all of the newly created buttons?
```
.new-button {
background-color: #4CAF50;
border: 1px solid;
color: white;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 20px;
cursor: pointer;
width: 120px;
height:50px;
white-space: normal;
}
.new-button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
``` | 2020/11/28 | [
"https://Stackoverflow.com/questions/65047655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10765455/"
] | You can add the class the element using `classList.add()`.
**Demo:**
```js
var result = [1,2];
var menuMgtCategoryButtons = document.getElementById('menuMgtCategoryButtons');
for(var i = 0; i < result.length;i++){
var menuCatButton = document.createElement("button");
menuCatButton.id = "menu-mgt-button-"+result[i];
menuCatButton.textContent = "Button "+result[i]; // add the text to the button
menuCatButton.classList.add('new-button'); // add the class to the button
menuMgtCategoryButtons.appendChild(menuCatButton);
}
```
```css
.new-button {
background-color: #4CAF50;
border: 1px solid;
color: white;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 20px;
cursor: pointer;
width: 120px;
height:50px;
white-space: normal;
}
.new-button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
```
```html
<div id="menuMgtCategoryButtons"></div>
``` | Add this line
```
menuCatButton.className="new-button"
``` |
65,047,655 | I am following [this thread](https://stackoverflow.com/questions/7707074/creating-dynamic-button-with-click-event-in-javascript) which shows how to generate DOM elements dynamically.
Suppose I have this snippet that generate a series of buttons:
```
for(var i = 0; i < result.length;i++){
var menuCatButton = document.createElement("button");
menuCatButton.id = "menu-mgt-button-"+result[i];
menuMgtCategoryButtons.appendChild(menuCatButton);
}
```
How do I apply this set of style to all of the newly created buttons?
```
.new-button {
background-color: #4CAF50;
border: 1px solid;
color: white;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 20px;
cursor: pointer;
width: 120px;
height:50px;
white-space: normal;
}
.new-button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
``` | 2020/11/28 | [
"https://Stackoverflow.com/questions/65047655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10765455/"
] | You can add the class the element using `classList.add()`.
**Demo:**
```js
var result = [1,2];
var menuMgtCategoryButtons = document.getElementById('menuMgtCategoryButtons');
for(var i = 0; i < result.length;i++){
var menuCatButton = document.createElement("button");
menuCatButton.id = "menu-mgt-button-"+result[i];
menuCatButton.textContent = "Button "+result[i]; // add the text to the button
menuCatButton.classList.add('new-button'); // add the class to the button
menuMgtCategoryButtons.appendChild(menuCatButton);
}
```
```css
.new-button {
background-color: #4CAF50;
border: 1px solid;
color: white;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 20px;
cursor: pointer;
width: 120px;
height:50px;
white-space: normal;
}
.new-button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
```
```html
<div id="menuMgtCategoryButtons"></div>
``` | Just add the class to each element in the loop just after you have created the element.
```
menuCatButton.classList.add("new-button");
``` |
1,659,348 | `For example:`
Suppose we have an impulsive force $f(t)$ lasting from $t=t\_0$ until $t=t\_1$ which is applied to a mass $m$. Then by Newtons Second law we have $$\int\_{t=t\_0}^{t=t\_1}f(t)\,\mathrm{d}t=\int\_\color{red}{t=t\_0}^\color{red}{t=t\_1}m\color{blue}{\frac{\mathrm{d}v}{\mathrm{d}t}}\mathrm{d}t=\int\_\color{red}{v=v\_0}^\color{red}{v=v\_1}m\,\mathrm{d}v=m(v\_1-v\_0)\tag{1}$$
What I can't understand is; What substitution was made to allow the limits marked $\color{red}{\mathrm{red}}$ to change from $t$ to $v$.
I thought it might be due to $$\color{blue}{\frac{\mathrm{d}v}{\mathrm{d}t}}=\frac{\mathrm{d}v}{\mathrm{d}x}\cdot \underbrace{\frac{\mathrm{d}x}{\mathrm{d}t}}\_{\Large{\color{#180}{=v}}}=v\frac{\mathrm{d}v}{\mathrm{d}x}$$ by the chain rule.
But it is something much simpler than this, and I believe I am over-thinking it too much. Could someone please tell me what substitution was made to change the limits marked $\color{red}{\mathrm{red}}$ in equation $(1)$?
---
Edit:
-----
Comments below seem to indicate that one can simply change the limits of integration to make the integral dimensionally correct. But I consider this to be a less rigorous approach, and I was taught that integral limits **must** be changed via a substitution. So I still need to know what substitution was made?
Thanks again. | 2016/02/17 | [
"https://math.stackexchange.com/questions/1659348",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/144533/"
] | The fundamental reason to change the limits of integration is that
the *variable* of integration has changed.
Substitution is an obvious case in which this is likely to occur.
For example, substitute $u = x - 2$ in $\int (x - 2) dx$:
$$
\int\_0^2 (x - 2) dx = \int\_{-2}^0 u\; du.
$$
The intuition I follow on this is that the start of the integral occurs
"when $x=0$" and ends "when $x=2$".
But "when" $x=0$, it must also be true that $u=-2$,
and "when" $x=2$, it must also be true that $u=0$.
So *in terms of $u$,* the integral needs to start
"when $u=-2$" and end "when $u=0$".
A more rigorous treatment would take $x - 2$ as a function over
the domain $[0,2]$ and transform it; but transforming the function
also transforms its domain, so $x - 2$ over the domain $[0,2]$
transforms to $u$ over the domain $[-2,0]$.
*Anything* that changes the integration variable of a definite integral
also has to be reflected in the limits of integration,
because just as with any substitution, you're integrating a (possibly)
different function over a (possibly) different domain.
That is, if the integrand changes from $f(t)dt$ to $h(v)dv$
(even if $h(v)$ is a constant function, as it is in the question),
the integral over $v$ needs to start and end at $v$-values that are
correctly matched to the $t$-values at which the integral over $t$
started and ended.
---
Note that in any change of variables, regardless of whether we achieve it
by first writing down an explicit substitution formula (such as $u = x - 2$),
has to account for the derivative of the new variable of integration
with respect to the old one. For a substitution from $t$ to $u$ via the
equation $u = h(t)$, the derivative of the new w.r.t. the old is
$\dfrac{du}{dt} = h'(t)$
and it is accounted for in the rule
$$
\int g(h(t))\, h'(t)\, dt = g(u)\, du.
$$
As far as I know, a change of variables must not break this rule,
so there must somehow be a substitution $u = h(t)$ that can explain it.
In the integral in the question,
$f(t) = m \dfrac{d^2 x}{dt^2}$.
If $\dfrac{dx}{dt} = v = h(t)$
and if $g$ is the constant function with value $m$,
then $\dfrac{d^2 x}{dt^2} = \dfrac{dv}{dt} = h'(t)$ and $g(h(t)) = m$, so
$$
\int m \frac{dv}{dt} \, dt
= \int g(h(t))\, h'(t)\, dt
= \int g(v)\, dv = \int m \, dv.
$$
The definite integral follows the same rule but also has to make the
corresponding change to the interval of integration:
$$
\int\_{t\_0}^{t\_1} g(h(t))\, h'(t)\, dt
= \int\_{h(t\_0)}^{h(t\_1)} g(v)\, dv;
$$
setting $v\_0=h(t\_0)$ and $v\_1=h(t\_1)$,
$$
\int\_{t\_0}^{t\_1} m \frac{dv}{dt} \, dt
= \int\_{h(t\_0)}^{h(t\_1)} m \, dv
= \int\_{v\_0}^{v\_1} m \, dv.
$$ | Apart from your prefactors (like mass), when you integrate $dv/dt$ you integrate the derivative of a function, hence we all know the answer is the function itself. Hence: $$\int\_{t\_0}^{t\_1} v^{\prime}(t)\, dt = v(t\_1) - v(t\_0)$$ |
55,011,833 | Other people who have asked this question had answers about downloading Vim from Vim.org, but that website doesn't respond.
Are there other ways to use Vi on Windows? | 2019/03/05 | [
"https://Stackoverflow.com/questions/55011833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10496528/"
] | Use a mutation observer to watch the list item instead of watching the document as a whole.
```js
// The item we want to watch
var watch = document.querySelector('.active')
// The new observer with a callback to execute upon change
var observer = new MutationObserver((mutationsList) => {
console.log(new Date().toUTCString())
});
// Start observing the element using these settings
observer.observe(watch, { childList: true, subtree: true });
// Some random test function to modify the element
// This will make sure the callback is running correctly
setInterval(() => {
watch.innerHTML = Math.random() * 1000
}, 1000)
```
```html
<ul>
<li class="active"></li>
</ul>
``` | Most jQuery code has a similar counterpart available. The `$('li.active')` can be replaced with `document.querySelectorAll('li.active')`. This gives you all elements matching your selector. The `bind` call would be achieved by iterating over the elements and using `addEventListener('DOMSubtreeModified', function(event) { … })`. |
3,933,744 | When I closed MySql server, how can I understand that mysql server is gone away from my Qt program?
**Edit:**
Here my trial:
When I close MySql, I get these results, and I can't catch that MySql is closed.
My Code Snippet is
```
QSqlQuery query(db);
query.exec("SELECT * From RequestIds");
qDebug()<<query.lastError();
qDebug()<<db.lastError()<<QTime::currentTime();
qDebug()<<db.isOpen();
qDebug()<<db.isValid();
```
and output is:
```
QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away")
QSqlError(-1, "", "") QTime("14:22:58")
true
true
```
I don't understand why db.isOpen() returns true. | 2010/10/14 | [
"https://Stackoverflow.com/questions/3933744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311762/"
] | There is a bug related with QSqlDatabase::isOpen() in Qt.
<https://bugreports.qt.io/browse/QTBUG-223> | Your program has no idea of its surroundings. If something changes, you may be able to have the OS notify your program, or you'll have to test yourself.
If the database connection closes before your program, the status from the connection should return some kind of error code. You **are checking status** from the connection functions?
Write a simple program that opens a window and upon the click of a button, writes to the database. After writing to the database, the program should display the status in the window. Run your program. Press button to get the "controlled" response. Close the database then click on the button again.
You may be able to do this with a debugger, depending on the ability of the debugger & OS to queue up messages. |
3,933,744 | When I closed MySql server, how can I understand that mysql server is gone away from my Qt program?
**Edit:**
Here my trial:
When I close MySql, I get these results, and I can't catch that MySql is closed.
My Code Snippet is
```
QSqlQuery query(db);
query.exec("SELECT * From RequestIds");
qDebug()<<query.lastError();
qDebug()<<db.lastError()<<QTime::currentTime();
qDebug()<<db.isOpen();
qDebug()<<db.isValid();
```
and output is:
```
QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away")
QSqlError(-1, "", "") QTime("14:22:58")
true
true
```
I don't understand why db.isOpen() returns true. | 2010/10/14 | [
"https://Stackoverflow.com/questions/3933744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311762/"
] | There is a bug related with QSqlDatabase::isOpen() in Qt.
<https://bugreports.qt.io/browse/QTBUG-223> | `QSqlQuery::lastError()` should give you an error if your query via `QSqlQuery::exec()` has failed. Also `QSqlDatabase::isOpen()` should report the state of your connection, `QSqlDatabase::lastError()` is also available |
3,933,744 | When I closed MySql server, how can I understand that mysql server is gone away from my Qt program?
**Edit:**
Here my trial:
When I close MySql, I get these results, and I can't catch that MySql is closed.
My Code Snippet is
```
QSqlQuery query(db);
query.exec("SELECT * From RequestIds");
qDebug()<<query.lastError();
qDebug()<<db.lastError()<<QTime::currentTime();
qDebug()<<db.isOpen();
qDebug()<<db.isValid();
```
and output is:
```
QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away")
QSqlError(-1, "", "") QTime("14:22:58")
true
true
```
I don't understand why db.isOpen() returns true. | 2010/10/14 | [
"https://Stackoverflow.com/questions/3933744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311762/"
] | There is a bug related with QSqlDatabase::isOpen() in Qt.
<https://bugreports.qt.io/browse/QTBUG-223> | You can use `isOpenError` to determine whether opening the initial database connection was successfull. I agree that `isOpen` returning `true` is confusing.
To monitor the database connection I repeatedly try to open and close a lightweight MySQL connection (e.g. every 3 seconds):
```
#include <mysql/mysql.h>
mysql_init(&connection);
MYSQL *result = mysql_real_connect(&connection,
host.isNull() ? static_cast<const char *>(0) : host.toLocal8Bit().constData(),
user.isNull() ? static_cast<const char *>(0) : user.toLocal8Bit().constData(),
pass.isNull() ? static_cast<const char *>(0) : pass.toLocal8Bit().constData(),
dbName.isNull() ? static_cast<const char *>(0) : dbName.toLocal8Bit().constData(),
0,
0,
0);
bool currentlyConnected = (result != 0);
```
In the above example, `host`, `user`, `pass`, and `dbName` are `QString` instances containing the connection information. Note that you need the MySQL development headers. |
45,852,012 | So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."
TL;DR
How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)
Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.
```
package filecreator.coolversion;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileCreatorCoolversion {
public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;
public static void main(String[] args) throws IOException {
System.out.println("********************************");
System.out.println("* Welcome to File Creator 2.0! *");
System.out.println("********************************");
System.out.println(" ");
while(!success) {
System.out.println("Would you like to create a file? Y/N?");
String usrans = sc.nextLine();
if(usrans.equalsIgnoreCase("y")) {
System.out.println("Proceeding with file creation...");
break;
} else if(usrans.equalsIgnoreCase("n")) {
System.out.println("Exiting Program...");
System.exit(0);
} else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {
System.out.println("That is not a valid answer! Please try again!");
System.out.println(" ");
}
}
while(!success) {
System.out.println(" ");
System.out.println("Please enter a valid filename:");
filename = sc.nextLine();
if(filename.isEmpty()) {
System.out.println("Please enter a file name!");
break;
} else if(filename.contains("/") || filename.contains(":") ||
filename.contains("*") || filename.contains("?") ||
filename.contains("<") || filename.contains(">") ||
filename.contains("|") || filename.contains("\"") ||
filename.contains("\\")) {
System.out.println("Please do not include / \\ : * ? \" < > |");
} else if(!filename.contains(".")) {
System.out.println("Please add a apropriate file extensions");
} else if (filename.) {
//HERE IS WHERE IM STUCK
} else {
System.out.println(" ");
System.out.println("File name \"" + filename + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Where would you like to have your file saved?");
System.out.println("Please enter a valid directory");
while(!success) {
filedir = sc.nextLine();
if(!filename.contains(":")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else if(!filename.contains("\\")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else {
System.out.println("File directory \"" + filedir + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Creating file...");
}
```
} | 2017/08/24 | [
"https://Stackoverflow.com/questions/45852012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902004/"
] | Any selector-only solution requires you to make assumptions about your markup that may or may not be within your control since the specificity of two contextual selectors is always the same regardless of how close the ancestor is to each descendant that is matched, and any solution that makes use of inheriting the actual properties themselves requires you to apply them to the `.red`, `.yellow` and `.blue` sections, which may not be desired. For example, you'd have to apply `background-color` to the sections in order for `background-color: inherit` to work on the descendants, but you may not want the sections themselves to have any background color, so that won't be an option to you.
Custom properties allow descendants to inherit values from their closest ancestors without polluting other properties in this manner, and without other cascading rules getting in the way (competing rules with equally specific contextual selectors, etc). You'll only be able to do this reliably with custom properties for this reason.
```css
.red {
--color: red;
}
.yellow {
--color: yellow;
}
.blue {
--color: blue;
}
input, article, p {
background-color: var(--color);
}
```
```html
<section class="yellow">
<section class="blue">
<form>
<input type="button" value="This should use the blue theme" />
</form>
</section>
<section class="red">
<article>
<p>This should use the red theme</p>
</article>
</section>
<section class="yellow">
<nav>
<p>This should use the yellow theme</p>
</nav>
</section>
<p>This should be yellow.</p>
</section>
``` | I tried this and it works, regardless of what element is it as long as you define the parent, hope this helps
```
body > :first-child
{
background-color: #ff0000;
}
``` |
45,852,012 | So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."
TL;DR
How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)
Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.
```
package filecreator.coolversion;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileCreatorCoolversion {
public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;
public static void main(String[] args) throws IOException {
System.out.println("********************************");
System.out.println("* Welcome to File Creator 2.0! *");
System.out.println("********************************");
System.out.println(" ");
while(!success) {
System.out.println("Would you like to create a file? Y/N?");
String usrans = sc.nextLine();
if(usrans.equalsIgnoreCase("y")) {
System.out.println("Proceeding with file creation...");
break;
} else if(usrans.equalsIgnoreCase("n")) {
System.out.println("Exiting Program...");
System.exit(0);
} else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {
System.out.println("That is not a valid answer! Please try again!");
System.out.println(" ");
}
}
while(!success) {
System.out.println(" ");
System.out.println("Please enter a valid filename:");
filename = sc.nextLine();
if(filename.isEmpty()) {
System.out.println("Please enter a file name!");
break;
} else if(filename.contains("/") || filename.contains(":") ||
filename.contains("*") || filename.contains("?") ||
filename.contains("<") || filename.contains(">") ||
filename.contains("|") || filename.contains("\"") ||
filename.contains("\\")) {
System.out.println("Please do not include / \\ : * ? \" < > |");
} else if(!filename.contains(".")) {
System.out.println("Please add a apropriate file extensions");
} else if (filename.) {
//HERE IS WHERE IM STUCK
} else {
System.out.println(" ");
System.out.println("File name \"" + filename + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Where would you like to have your file saved?");
System.out.println("Please enter a valid directory");
while(!success) {
filedir = sc.nextLine();
if(!filename.contains(":")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else if(!filename.contains("\\")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else {
System.out.println("File directory \"" + filedir + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Creating file...");
}
```
} | 2017/08/24 | [
"https://Stackoverflow.com/questions/45852012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902004/"
] | This porblem is a little bit difficult if you want to solve it with all elements.
You have to think the other way: NOT "a rule is valid until there is another rule" BUT "the closest rule is valid".
How to achieve this?
First set a rule for all elements that are grandchildren except the form tag (perhaps also the ol, ul, nav, ... tags) that the background-color shell **inherit**. Now all this elements inherit theire background-color from the parent element.
Second set one rule for each theme that defines the background-color of all direct children. Here you have to take a look at the problem with the form tag. the form tag has no inheritage (see above) so the children of the form will not get the rule from the closest theme parent. So you have to setup an extra rule for this case.
All in all:
```
*.color * > *:not(form):not(html):not(body) {
background-color:inherit!important;
}
.red > *:not(form):not(.color), .red > form > *:not(.color) {background-color: red!important}
.yellow > *:not(form):not(.color), .yellow > form > *:not(.color) {background-color: yellow!important}
.blue > *:not(form):not(.color), .blue > form > *:not(.color) {background-color: blue!important}
```
(.color is a css class that all sections have, that also have the css class .red or .yellow or .blue)
**the > - signs are important**
you can mix up all the rules.
---
**EDIT** Now I see that `!important` is not neccessary :)
You can also write
```
*.color * > *:not(form):not(html):not(body) {
background-color:inherit;
}
.blue > *:not(form):not(.color), .blue > form > *:not(.color) {background-color: blue}
.red > *:not(form):not(.color), .red > form > *:not(.color) {background-color: red}
.yellow > *:not(form):not(.color), .yellow > form > *:not(.color) {background-color: yellow}
```
**EDIT2** if you want to style a specific tag in a theme, you have to add the rules in the following way.
1) Add all css attributes that you want to style to the first rule of the set:
```
*.color * > *:not(form):not(html):not(body) {
background-color:inherit;
color:inherit;
}
```
2) replace the asterisk by the tag name
```
.blue > *:not(form):not(.color), .blue > form *:not(.color) {background-color: blue}
.red > *:not(form):not(.color), .red > form *:not(.color) {background-color: red}
.yellow > *:not(form):not(.color), .yellow > form *:not(.color) {background-color: yellow}
.blue > input:not(form):not(.color), .blue > form input:not(.color) { color:white; }
.red > input:not(form):not(.color), .red > form input:not(.color) { color: green; }
.yellow > input:not(form):not(.color), .yellow > form input:not(.color) { color: purple; }
```
3) have a look at the **> - signs**! I removed it at one position to make it work with all tags. | To target only the direct descendant of an element, you can use the direct descendant operator: `>`:
```
.red > input {
background-color: red;
}
```
And to go one step better, you can replace all repetitions like so, instead of having to manually declare each element:
```
.red > * {
background-color: red;
}
.yellow > * {
background-color: yellow;
}
.blue > * {
background-color: blue;
}
``` |
45,852,012 | So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."
TL;DR
How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)
Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.
```
package filecreator.coolversion;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileCreatorCoolversion {
public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;
public static void main(String[] args) throws IOException {
System.out.println("********************************");
System.out.println("* Welcome to File Creator 2.0! *");
System.out.println("********************************");
System.out.println(" ");
while(!success) {
System.out.println("Would you like to create a file? Y/N?");
String usrans = sc.nextLine();
if(usrans.equalsIgnoreCase("y")) {
System.out.println("Proceeding with file creation...");
break;
} else if(usrans.equalsIgnoreCase("n")) {
System.out.println("Exiting Program...");
System.exit(0);
} else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {
System.out.println("That is not a valid answer! Please try again!");
System.out.println(" ");
}
}
while(!success) {
System.out.println(" ");
System.out.println("Please enter a valid filename:");
filename = sc.nextLine();
if(filename.isEmpty()) {
System.out.println("Please enter a file name!");
break;
} else if(filename.contains("/") || filename.contains(":") ||
filename.contains("*") || filename.contains("?") ||
filename.contains("<") || filename.contains(">") ||
filename.contains("|") || filename.contains("\"") ||
filename.contains("\\")) {
System.out.println("Please do not include / \\ : * ? \" < > |");
} else if(!filename.contains(".")) {
System.out.println("Please add a apropriate file extensions");
} else if (filename.) {
//HERE IS WHERE IM STUCK
} else {
System.out.println(" ");
System.out.println("File name \"" + filename + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Where would you like to have your file saved?");
System.out.println("Please enter a valid directory");
while(!success) {
filedir = sc.nextLine();
if(!filename.contains(":")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else if(!filename.contains("\\")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else {
System.out.println("File directory \"" + filedir + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Creating file...");
}
```
} | 2017/08/24 | [
"https://Stackoverflow.com/questions/45852012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902004/"
] | Any selector-only solution requires you to make assumptions about your markup that may or may not be within your control since the specificity of two contextual selectors is always the same regardless of how close the ancestor is to each descendant that is matched, and any solution that makes use of inheriting the actual properties themselves requires you to apply them to the `.red`, `.yellow` and `.blue` sections, which may not be desired. For example, you'd have to apply `background-color` to the sections in order for `background-color: inherit` to work on the descendants, but you may not want the sections themselves to have any background color, so that won't be an option to you.
Custom properties allow descendants to inherit values from their closest ancestors without polluting other properties in this manner, and without other cascading rules getting in the way (competing rules with equally specific contextual selectors, etc). You'll only be able to do this reliably with custom properties for this reason.
```css
.red {
--color: red;
}
.yellow {
--color: yellow;
}
.blue {
--color: blue;
}
input, article, p {
background-color: var(--color);
}
```
```html
<section class="yellow">
<section class="blue">
<form>
<input type="button" value="This should use the blue theme" />
</form>
</section>
<section class="red">
<article>
<p>This should use the red theme</p>
</article>
</section>
<section class="yellow">
<nav>
<p>This should use the yellow theme</p>
</nav>
</section>
<p>This should be yellow.</p>
</section>
``` | **Try This :**
```
.yellow > *:not(form):not(section), .yellow form * {background-color: yellow !important}
.blue > *:not(form):not(section), .blue form * {background-color: blue !important}
.red > *:not(form):not(section), .red form * {background-color: red !important}
```
```css
.yellow > *:not(form):not(section), .yellow form * {background-color: yellow !important}
.blue > *:not(form):not(section), .blue form * {background-color: blue !important}
.red > *:not(form):not(section), .red form * {background-color: red !important}
```
```html
<section class="yellow">
<section class="blue">
<form>
<input type="button" value="This should use the blue theme" />
</form>
</section>
<section class="red">
<article>
<p>This should use the red theme</p>
<!-- This is instead yellow, how do I fix that? -->
</article>
</section>
<section class="yellow">
<nav>
<p>This should use the yellow theme</p>
</nav>
</section>
<p>This should be yellow.</p>
</section>
``` |
45,852,012 | So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."
TL;DR
How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)
Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.
```
package filecreator.coolversion;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileCreatorCoolversion {
public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;
public static void main(String[] args) throws IOException {
System.out.println("********************************");
System.out.println("* Welcome to File Creator 2.0! *");
System.out.println("********************************");
System.out.println(" ");
while(!success) {
System.out.println("Would you like to create a file? Y/N?");
String usrans = sc.nextLine();
if(usrans.equalsIgnoreCase("y")) {
System.out.println("Proceeding with file creation...");
break;
} else if(usrans.equalsIgnoreCase("n")) {
System.out.println("Exiting Program...");
System.exit(0);
} else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {
System.out.println("That is not a valid answer! Please try again!");
System.out.println(" ");
}
}
while(!success) {
System.out.println(" ");
System.out.println("Please enter a valid filename:");
filename = sc.nextLine();
if(filename.isEmpty()) {
System.out.println("Please enter a file name!");
break;
} else if(filename.contains("/") || filename.contains(":") ||
filename.contains("*") || filename.contains("?") ||
filename.contains("<") || filename.contains(">") ||
filename.contains("|") || filename.contains("\"") ||
filename.contains("\\")) {
System.out.println("Please do not include / \\ : * ? \" < > |");
} else if(!filename.contains(".")) {
System.out.println("Please add a apropriate file extensions");
} else if (filename.) {
//HERE IS WHERE IM STUCK
} else {
System.out.println(" ");
System.out.println("File name \"" + filename + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Where would you like to have your file saved?");
System.out.println("Please enter a valid directory");
while(!success) {
filedir = sc.nextLine();
if(!filename.contains(":")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else if(!filename.contains("\\")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else {
System.out.println("File directory \"" + filedir + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Creating file...");
}
```
} | 2017/08/24 | [
"https://Stackoverflow.com/questions/45852012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902004/"
] | **Try This :**
```
.yellow > *:not(form):not(section), .yellow form * {background-color: yellow !important}
.blue > *:not(form):not(section), .blue form * {background-color: blue !important}
.red > *:not(form):not(section), .red form * {background-color: red !important}
```
```css
.yellow > *:not(form):not(section), .yellow form * {background-color: yellow !important}
.blue > *:not(form):not(section), .blue form * {background-color: blue !important}
.red > *:not(form):not(section), .red form * {background-color: red !important}
```
```html
<section class="yellow">
<section class="blue">
<form>
<input type="button" value="This should use the blue theme" />
</form>
</section>
<section class="red">
<article>
<p>This should use the red theme</p>
<!-- This is instead yellow, how do I fix that? -->
</article>
</section>
<section class="yellow">
<nav>
<p>This should use the yellow theme</p>
</nav>
</section>
<p>This should be yellow.</p>
</section>
``` | I tried this and it works, regardless of what element is it as long as you define the parent, hope this helps
```
body > :first-child
{
background-color: #ff0000;
}
``` |
45,852,012 | So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."
TL;DR
How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)
Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.
```
package filecreator.coolversion;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileCreatorCoolversion {
public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;
public static void main(String[] args) throws IOException {
System.out.println("********************************");
System.out.println("* Welcome to File Creator 2.0! *");
System.out.println("********************************");
System.out.println(" ");
while(!success) {
System.out.println("Would you like to create a file? Y/N?");
String usrans = sc.nextLine();
if(usrans.equalsIgnoreCase("y")) {
System.out.println("Proceeding with file creation...");
break;
} else if(usrans.equalsIgnoreCase("n")) {
System.out.println("Exiting Program...");
System.exit(0);
} else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {
System.out.println("That is not a valid answer! Please try again!");
System.out.println(" ");
}
}
while(!success) {
System.out.println(" ");
System.out.println("Please enter a valid filename:");
filename = sc.nextLine();
if(filename.isEmpty()) {
System.out.println("Please enter a file name!");
break;
} else if(filename.contains("/") || filename.contains(":") ||
filename.contains("*") || filename.contains("?") ||
filename.contains("<") || filename.contains(">") ||
filename.contains("|") || filename.contains("\"") ||
filename.contains("\\")) {
System.out.println("Please do not include / \\ : * ? \" < > |");
} else if(!filename.contains(".")) {
System.out.println("Please add a apropriate file extensions");
} else if (filename.) {
//HERE IS WHERE IM STUCK
} else {
System.out.println(" ");
System.out.println("File name \"" + filename + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Where would you like to have your file saved?");
System.out.println("Please enter a valid directory");
while(!success) {
filedir = sc.nextLine();
if(!filename.contains(":")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else if(!filename.contains("\\")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else {
System.out.println("File directory \"" + filedir + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Creating file...");
}
```
} | 2017/08/24 | [
"https://Stackoverflow.com/questions/45852012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902004/"
] | To target only the direct descendant of an element, you can use the direct descendant operator: `>`:
```
.red > input {
background-color: red;
}
```
And to go one step better, you can replace all repetitions like so, instead of having to manually declare each element:
```
.red > * {
background-color: red;
}
.yellow > * {
background-color: yellow;
}
.blue > * {
background-color: blue;
}
``` | I tried this and it works, regardless of what element is it as long as you define the parent, hope this helps
```
body > :first-child
{
background-color: #ff0000;
}
``` |
45,852,012 | So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."
TL;DR
How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)
Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.
```
package filecreator.coolversion;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileCreatorCoolversion {
public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;
public static void main(String[] args) throws IOException {
System.out.println("********************************");
System.out.println("* Welcome to File Creator 2.0! *");
System.out.println("********************************");
System.out.println(" ");
while(!success) {
System.out.println("Would you like to create a file? Y/N?");
String usrans = sc.nextLine();
if(usrans.equalsIgnoreCase("y")) {
System.out.println("Proceeding with file creation...");
break;
} else if(usrans.equalsIgnoreCase("n")) {
System.out.println("Exiting Program...");
System.exit(0);
} else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {
System.out.println("That is not a valid answer! Please try again!");
System.out.println(" ");
}
}
while(!success) {
System.out.println(" ");
System.out.println("Please enter a valid filename:");
filename = sc.nextLine();
if(filename.isEmpty()) {
System.out.println("Please enter a file name!");
break;
} else if(filename.contains("/") || filename.contains(":") ||
filename.contains("*") || filename.contains("?") ||
filename.contains("<") || filename.contains(">") ||
filename.contains("|") || filename.contains("\"") ||
filename.contains("\\")) {
System.out.println("Please do not include / \\ : * ? \" < > |");
} else if(!filename.contains(".")) {
System.out.println("Please add a apropriate file extensions");
} else if (filename.) {
//HERE IS WHERE IM STUCK
} else {
System.out.println(" ");
System.out.println("File name \"" + filename + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Where would you like to have your file saved?");
System.out.println("Please enter a valid directory");
while(!success) {
filedir = sc.nextLine();
if(!filename.contains(":")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else if(!filename.contains("\\")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else {
System.out.println("File directory \"" + filedir + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Creating file...");
}
```
} | 2017/08/24 | [
"https://Stackoverflow.com/questions/45852012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902004/"
] | This porblem is a little bit difficult if you want to solve it with all elements.
You have to think the other way: NOT "a rule is valid until there is another rule" BUT "the closest rule is valid".
How to achieve this?
First set a rule for all elements that are grandchildren except the form tag (perhaps also the ol, ul, nav, ... tags) that the background-color shell **inherit**. Now all this elements inherit theire background-color from the parent element.
Second set one rule for each theme that defines the background-color of all direct children. Here you have to take a look at the problem with the form tag. the form tag has no inheritage (see above) so the children of the form will not get the rule from the closest theme parent. So you have to setup an extra rule for this case.
All in all:
```
*.color * > *:not(form):not(html):not(body) {
background-color:inherit!important;
}
.red > *:not(form):not(.color), .red > form > *:not(.color) {background-color: red!important}
.yellow > *:not(form):not(.color), .yellow > form > *:not(.color) {background-color: yellow!important}
.blue > *:not(form):not(.color), .blue > form > *:not(.color) {background-color: blue!important}
```
(.color is a css class that all sections have, that also have the css class .red or .yellow or .blue)
**the > - signs are important**
you can mix up all the rules.
---
**EDIT** Now I see that `!important` is not neccessary :)
You can also write
```
*.color * > *:not(form):not(html):not(body) {
background-color:inherit;
}
.blue > *:not(form):not(.color), .blue > form > *:not(.color) {background-color: blue}
.red > *:not(form):not(.color), .red > form > *:not(.color) {background-color: red}
.yellow > *:not(form):not(.color), .yellow > form > *:not(.color) {background-color: yellow}
```
**EDIT2** if you want to style a specific tag in a theme, you have to add the rules in the following way.
1) Add all css attributes that you want to style to the first rule of the set:
```
*.color * > *:not(form):not(html):not(body) {
background-color:inherit;
color:inherit;
}
```
2) replace the asterisk by the tag name
```
.blue > *:not(form):not(.color), .blue > form *:not(.color) {background-color: blue}
.red > *:not(form):not(.color), .red > form *:not(.color) {background-color: red}
.yellow > *:not(form):not(.color), .yellow > form *:not(.color) {background-color: yellow}
.blue > input:not(form):not(.color), .blue > form input:not(.color) { color:white; }
.red > input:not(form):not(.color), .red > form input:not(.color) { color: green; }
.yellow > input:not(form):not(.color), .yellow > form input:not(.color) { color: purple; }
```
3) have a look at the **> - signs**! I removed it at one position to make it work with all tags. | Not sure if I understand your question, so just comment if I'm wrong.
Increase the specificity of the style so that will not be overridden that easily.
```
.red > article > p {
background-color: red;
}
```
```css
.red input {
background-color: red;
}
.red article {
background-color: red;
}
.red > article > p {
background-color: red;
}
/*.. other tags.. */
.yellow input {
background-color: yellow;
}
.yellow article {
background-color: yellow;
}
.yellow p {
background-color: yellow;
}
/*.. other tags.. */
.blue input {
background-color: blue;
}
.blue article {
background-color: blue;
}
.blue p {
background-color: blue;
}
/*.. other tags.. */
```
```html
<section class="yellow">
<section class="blue">
<form>
<input type="button" value="This should use the blue theme" />
</form>
</section>
<section class="red">
<article>
<p>This should use the red theme</p>
<!-- This is instead yellow, how do I fix that? -->
</article>
</section>
<section class="yellow">
<nav>
<p>This should use the yellow theme</p>
</nav>
</section>
<p>This should be yellow.</p>
</section>
``` |
45,852,012 | So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."
TL;DR
How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)
Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.
```
package filecreator.coolversion;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileCreatorCoolversion {
public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;
public static void main(String[] args) throws IOException {
System.out.println("********************************");
System.out.println("* Welcome to File Creator 2.0! *");
System.out.println("********************************");
System.out.println(" ");
while(!success) {
System.out.println("Would you like to create a file? Y/N?");
String usrans = sc.nextLine();
if(usrans.equalsIgnoreCase("y")) {
System.out.println("Proceeding with file creation...");
break;
} else if(usrans.equalsIgnoreCase("n")) {
System.out.println("Exiting Program...");
System.exit(0);
} else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {
System.out.println("That is not a valid answer! Please try again!");
System.out.println(" ");
}
}
while(!success) {
System.out.println(" ");
System.out.println("Please enter a valid filename:");
filename = sc.nextLine();
if(filename.isEmpty()) {
System.out.println("Please enter a file name!");
break;
} else if(filename.contains("/") || filename.contains(":") ||
filename.contains("*") || filename.contains("?") ||
filename.contains("<") || filename.contains(">") ||
filename.contains("|") || filename.contains("\"") ||
filename.contains("\\")) {
System.out.println("Please do not include / \\ : * ? \" < > |");
} else if(!filename.contains(".")) {
System.out.println("Please add a apropriate file extensions");
} else if (filename.) {
//HERE IS WHERE IM STUCK
} else {
System.out.println(" ");
System.out.println("File name \"" + filename + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Where would you like to have your file saved?");
System.out.println("Please enter a valid directory");
while(!success) {
filedir = sc.nextLine();
if(!filename.contains(":")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else if(!filename.contains("\\")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else {
System.out.println("File directory \"" + filedir + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Creating file...");
}
```
} | 2017/08/24 | [
"https://Stackoverflow.com/questions/45852012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902004/"
] | Any selector-only solution requires you to make assumptions about your markup that may or may not be within your control since the specificity of two contextual selectors is always the same regardless of how close the ancestor is to each descendant that is matched, and any solution that makes use of inheriting the actual properties themselves requires you to apply them to the `.red`, `.yellow` and `.blue` sections, which may not be desired. For example, you'd have to apply `background-color` to the sections in order for `background-color: inherit` to work on the descendants, but you may not want the sections themselves to have any background color, so that won't be an option to you.
Custom properties allow descendants to inherit values from their closest ancestors without polluting other properties in this manner, and without other cascading rules getting in the way (competing rules with equally specific contextual selectors, etc). You'll only be able to do this reliably with custom properties for this reason.
```css
.red {
--color: red;
}
.yellow {
--color: yellow;
}
.blue {
--color: blue;
}
input, article, p {
background-color: var(--color);
}
```
```html
<section class="yellow">
<section class="blue">
<form>
<input type="button" value="This should use the blue theme" />
</form>
</section>
<section class="red">
<article>
<p>This should use the red theme</p>
</article>
</section>
<section class="yellow">
<nav>
<p>This should use the yellow theme</p>
</nav>
</section>
<p>This should be yellow.</p>
</section>
``` | Not sure if I understand your question, so just comment if I'm wrong.
Increase the specificity of the style so that will not be overridden that easily.
```
.red > article > p {
background-color: red;
}
```
```css
.red input {
background-color: red;
}
.red article {
background-color: red;
}
.red > article > p {
background-color: red;
}
/*.. other tags.. */
.yellow input {
background-color: yellow;
}
.yellow article {
background-color: yellow;
}
.yellow p {
background-color: yellow;
}
/*.. other tags.. */
.blue input {
background-color: blue;
}
.blue article {
background-color: blue;
}
.blue p {
background-color: blue;
}
/*.. other tags.. */
```
```html
<section class="yellow">
<section class="blue">
<form>
<input type="button" value="This should use the blue theme" />
</form>
</section>
<section class="red">
<article>
<p>This should use the red theme</p>
<!-- This is instead yellow, how do I fix that? -->
</article>
</section>
<section class="yellow">
<nav>
<p>This should use the yellow theme</p>
</nav>
</section>
<p>This should be yellow.</p>
</section>
``` |
45,852,012 | So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."
TL;DR
How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)
Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.
```
package filecreator.coolversion;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileCreatorCoolversion {
public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;
public static void main(String[] args) throws IOException {
System.out.println("********************************");
System.out.println("* Welcome to File Creator 2.0! *");
System.out.println("********************************");
System.out.println(" ");
while(!success) {
System.out.println("Would you like to create a file? Y/N?");
String usrans = sc.nextLine();
if(usrans.equalsIgnoreCase("y")) {
System.out.println("Proceeding with file creation...");
break;
} else if(usrans.equalsIgnoreCase("n")) {
System.out.println("Exiting Program...");
System.exit(0);
} else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {
System.out.println("That is not a valid answer! Please try again!");
System.out.println(" ");
}
}
while(!success) {
System.out.println(" ");
System.out.println("Please enter a valid filename:");
filename = sc.nextLine();
if(filename.isEmpty()) {
System.out.println("Please enter a file name!");
break;
} else if(filename.contains("/") || filename.contains(":") ||
filename.contains("*") || filename.contains("?") ||
filename.contains("<") || filename.contains(">") ||
filename.contains("|") || filename.contains("\"") ||
filename.contains("\\")) {
System.out.println("Please do not include / \\ : * ? \" < > |");
} else if(!filename.contains(".")) {
System.out.println("Please add a apropriate file extensions");
} else if (filename.) {
//HERE IS WHERE IM STUCK
} else {
System.out.println(" ");
System.out.println("File name \"" + filename + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Where would you like to have your file saved?");
System.out.println("Please enter a valid directory");
while(!success) {
filedir = sc.nextLine();
if(!filename.contains(":")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else if(!filename.contains("\\")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else {
System.out.println("File directory \"" + filedir + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Creating file...");
}
```
} | 2017/08/24 | [
"https://Stackoverflow.com/questions/45852012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902004/"
] | This porblem is a little bit difficult if you want to solve it with all elements.
You have to think the other way: NOT "a rule is valid until there is another rule" BUT "the closest rule is valid".
How to achieve this?
First set a rule for all elements that are grandchildren except the form tag (perhaps also the ol, ul, nav, ... tags) that the background-color shell **inherit**. Now all this elements inherit theire background-color from the parent element.
Second set one rule for each theme that defines the background-color of all direct children. Here you have to take a look at the problem with the form tag. the form tag has no inheritage (see above) so the children of the form will not get the rule from the closest theme parent. So you have to setup an extra rule for this case.
All in all:
```
*.color * > *:not(form):not(html):not(body) {
background-color:inherit!important;
}
.red > *:not(form):not(.color), .red > form > *:not(.color) {background-color: red!important}
.yellow > *:not(form):not(.color), .yellow > form > *:not(.color) {background-color: yellow!important}
.blue > *:not(form):not(.color), .blue > form > *:not(.color) {background-color: blue!important}
```
(.color is a css class that all sections have, that also have the css class .red or .yellow or .blue)
**the > - signs are important**
you can mix up all the rules.
---
**EDIT** Now I see that `!important` is not neccessary :)
You can also write
```
*.color * > *:not(form):not(html):not(body) {
background-color:inherit;
}
.blue > *:not(form):not(.color), .blue > form > *:not(.color) {background-color: blue}
.red > *:not(form):not(.color), .red > form > *:not(.color) {background-color: red}
.yellow > *:not(form):not(.color), .yellow > form > *:not(.color) {background-color: yellow}
```
**EDIT2** if you want to style a specific tag in a theme, you have to add the rules in the following way.
1) Add all css attributes that you want to style to the first rule of the set:
```
*.color * > *:not(form):not(html):not(body) {
background-color:inherit;
color:inherit;
}
```
2) replace the asterisk by the tag name
```
.blue > *:not(form):not(.color), .blue > form *:not(.color) {background-color: blue}
.red > *:not(form):not(.color), .red > form *:not(.color) {background-color: red}
.yellow > *:not(form):not(.color), .yellow > form *:not(.color) {background-color: yellow}
.blue > input:not(form):not(.color), .blue > form input:not(.color) { color:white; }
.red > input:not(form):not(.color), .red > form input:not(.color) { color: green; }
.yellow > input:not(form):not(.color), .yellow > form input:not(.color) { color: purple; }
```
3) have a look at the **> - signs**! I removed it at one position to make it work with all tags. | I tried this and it works, regardless of what element is it as long as you define the parent, hope this helps
```
body > :first-child
{
background-color: #ff0000;
}
``` |
45,852,012 | So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."
TL;DR
How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)
Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.
```
package filecreator.coolversion;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileCreatorCoolversion {
public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;
public static void main(String[] args) throws IOException {
System.out.println("********************************");
System.out.println("* Welcome to File Creator 2.0! *");
System.out.println("********************************");
System.out.println(" ");
while(!success) {
System.out.println("Would you like to create a file? Y/N?");
String usrans = sc.nextLine();
if(usrans.equalsIgnoreCase("y")) {
System.out.println("Proceeding with file creation...");
break;
} else if(usrans.equalsIgnoreCase("n")) {
System.out.println("Exiting Program...");
System.exit(0);
} else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {
System.out.println("That is not a valid answer! Please try again!");
System.out.println(" ");
}
}
while(!success) {
System.out.println(" ");
System.out.println("Please enter a valid filename:");
filename = sc.nextLine();
if(filename.isEmpty()) {
System.out.println("Please enter a file name!");
break;
} else if(filename.contains("/") || filename.contains(":") ||
filename.contains("*") || filename.contains("?") ||
filename.contains("<") || filename.contains(">") ||
filename.contains("|") || filename.contains("\"") ||
filename.contains("\\")) {
System.out.println("Please do not include / \\ : * ? \" < > |");
} else if(!filename.contains(".")) {
System.out.println("Please add a apropriate file extensions");
} else if (filename.) {
//HERE IS WHERE IM STUCK
} else {
System.out.println(" ");
System.out.println("File name \"" + filename + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Where would you like to have your file saved?");
System.out.println("Please enter a valid directory");
while(!success) {
filedir = sc.nextLine();
if(!filename.contains(":")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else if(!filename.contains("\\")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else {
System.out.println("File directory \"" + filedir + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Creating file...");
}
```
} | 2017/08/24 | [
"https://Stackoverflow.com/questions/45852012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902004/"
] | Not sure if I understand your question, so just comment if I'm wrong.
Increase the specificity of the style so that will not be overridden that easily.
```
.red > article > p {
background-color: red;
}
```
```css
.red input {
background-color: red;
}
.red article {
background-color: red;
}
.red > article > p {
background-color: red;
}
/*.. other tags.. */
.yellow input {
background-color: yellow;
}
.yellow article {
background-color: yellow;
}
.yellow p {
background-color: yellow;
}
/*.. other tags.. */
.blue input {
background-color: blue;
}
.blue article {
background-color: blue;
}
.blue p {
background-color: blue;
}
/*.. other tags.. */
```
```html
<section class="yellow">
<section class="blue">
<form>
<input type="button" value="This should use the blue theme" />
</form>
</section>
<section class="red">
<article>
<p>This should use the red theme</p>
<!-- This is instead yellow, how do I fix that? -->
</article>
</section>
<section class="yellow">
<nav>
<p>This should use the yellow theme</p>
</nav>
</section>
<p>This should be yellow.</p>
</section>
``` | I tried this and it works, regardless of what element is it as long as you define the parent, hope this helps
```
body > :first-child
{
background-color: #ff0000;
}
``` |
45,852,012 | So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."
TL;DR
How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)
Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.
```
package filecreator.coolversion;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileCreatorCoolversion {
public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;
public static void main(String[] args) throws IOException {
System.out.println("********************************");
System.out.println("* Welcome to File Creator 2.0! *");
System.out.println("********************************");
System.out.println(" ");
while(!success) {
System.out.println("Would you like to create a file? Y/N?");
String usrans = sc.nextLine();
if(usrans.equalsIgnoreCase("y")) {
System.out.println("Proceeding with file creation...");
break;
} else if(usrans.equalsIgnoreCase("n")) {
System.out.println("Exiting Program...");
System.exit(0);
} else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {
System.out.println("That is not a valid answer! Please try again!");
System.out.println(" ");
}
}
while(!success) {
System.out.println(" ");
System.out.println("Please enter a valid filename:");
filename = sc.nextLine();
if(filename.isEmpty()) {
System.out.println("Please enter a file name!");
break;
} else if(filename.contains("/") || filename.contains(":") ||
filename.contains("*") || filename.contains("?") ||
filename.contains("<") || filename.contains(">") ||
filename.contains("|") || filename.contains("\"") ||
filename.contains("\\")) {
System.out.println("Please do not include / \\ : * ? \" < > |");
} else if(!filename.contains(".")) {
System.out.println("Please add a apropriate file extensions");
} else if (filename.) {
//HERE IS WHERE IM STUCK
} else {
System.out.println(" ");
System.out.println("File name \"" + filename + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Where would you like to have your file saved?");
System.out.println("Please enter a valid directory");
while(!success) {
filedir = sc.nextLine();
if(!filename.contains(":")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else if(!filename.contains("\\")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else {
System.out.println("File directory \"" + filedir + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Creating file...");
}
```
} | 2017/08/24 | [
"https://Stackoverflow.com/questions/45852012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902004/"
] | Any selector-only solution requires you to make assumptions about your markup that may or may not be within your control since the specificity of two contextual selectors is always the same regardless of how close the ancestor is to each descendant that is matched, and any solution that makes use of inheriting the actual properties themselves requires you to apply them to the `.red`, `.yellow` and `.blue` sections, which may not be desired. For example, you'd have to apply `background-color` to the sections in order for `background-color: inherit` to work on the descendants, but you may not want the sections themselves to have any background color, so that won't be an option to you.
Custom properties allow descendants to inherit values from their closest ancestors without polluting other properties in this manner, and without other cascading rules getting in the way (competing rules with equally specific contextual selectors, etc). You'll only be able to do this reliably with custom properties for this reason.
```css
.red {
--color: red;
}
.yellow {
--color: yellow;
}
.blue {
--color: blue;
}
input, article, p {
background-color: var(--color);
}
```
```html
<section class="yellow">
<section class="blue">
<form>
<input type="button" value="This should use the blue theme" />
</form>
</section>
<section class="red">
<article>
<p>This should use the red theme</p>
</article>
</section>
<section class="yellow">
<nav>
<p>This should use the yellow theme</p>
</nav>
</section>
<p>This should be yellow.</p>
</section>
``` | To target only the direct descendant of an element, you can use the direct descendant operator: `>`:
```
.red > input {
background-color: red;
}
```
And to go one step better, you can replace all repetitions like so, instead of having to manually declare each element:
```
.red > * {
background-color: red;
}
.yellow > * {
background-color: yellow;
}
.blue > * {
background-color: blue;
}
``` |
36,688,254 | My question maybe unheard of or may even be impractical.
But, I believe it is practical and acceptable.
**Problem: PHP request and response in background thread.**
Problem constraints:
1. You know it uses POST method.
2. It has two fields fname and lname as html ids that need to be filled.
3. You get response in the same page i.e. index.php .
Pseudocode to solve the problem:
1. Open the website in background. Something like openURL("xyz(dot)com");
2. Read the data sent in html format.
3. Change the value of the fields fname and lname to required fields "Allen" and "Walker."
4. Now, submit the fields back to the server. ( Page has a submit button.)
**Note:** PHP code has a standard if-else check to check for those values. If the field is properly set, it then says "Success" else "Failed"
5. Again, get the response sent by the server.
6. Check if "Success" was returned.
7. If "success" was returned, UPDATE UI thread for saying "JOB done".
Else, "Job failed."
**Note: I am not talking about using a** *WebView*. **Everything happens via a service or AsyncTask**.
---
Now, this is a simple question, and any ideas or a direction is acceptable.
**So, to recap. You have to open a webpage in background, change its field, submit it back and then get the response.**
---
I know we can open a website and get its content. But, I would also like to know if what I said is possible or not. And, I know it is possible. And, that I only lack the knowledge on Java Web API, could you please guide me on this.
Thank You. And, Have a Good day! | 2016/04/18 | [
"https://Stackoverflow.com/questions/36688254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2298251/"
] | use [this link](http://www.androidhive.info/2012/01/android-json-parsing-tutorial/) for best solution of calling web service without using WebView.
In this example fname and lname sent in namevaluepairs we get responce in json formet and parse json and get data also json parse defined in examples. | What you are trying to achieve is to create a webservice call using a [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html).
Like you have mentioned, you can make a post request within the AsyncTask, passing in the variables required for the request.
You can find a good example as shown: [Sending HTTP Post Request with Android](https://stackoverflow.com/questions/31552242/sending-http-post-request-with-android) |
105,305 | quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :( | 2020/09/30 | [
"https://music.stackexchange.com/questions/105305",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/72239/"
] | The song you quote with the bass line la,fa do,so and the chords Bm G D A can’t be identified as B minor or D major without listening to it.
vi IV I V is one possible solution referring to major (beginning on the 6th degree)
but this progression is ambivalent and it can be interpreted in Bm as i VI III bVII (b stands for the minor 7th degree of aeolian mode).
If we listen to the melody and we have somewhere a home feeling on each of these chords it may help us to decide whether the song is in Bm aeolian or in D major.
without a hint of tonic (see other answers): Yes it can be interpreted in both keys. But surely it makes sense to capital letters to assign Roman numbers of major chords and i, vi, for the minor chords.
If you have no other indications I agree with you that you say the song is in D as it begins with D.
But songs like this don’t need to be analyzed by R.N. It is sufficient that you know i VI ... in minor vi IV ... in major. You can practice this analogy back until to early Baroque music. | The answer to your question is **yes**.
The notation you use is relative to tonic. Establishing which sound is the tonic (and whether it changes) is completely outside of this tool. Consider anything noted as II-V as carrying a standard disclaimer "assuming that X is the tonic".
If you have a song with chords: C F C F C F, it might be a I-IV-I-IV, it might be a V-I-V-I. Depends on the rhythm, melody and even the listener. You can "make" yourself hear different tonics for the same progression in a similar way you can make yourself hear different "1" in a repeated drum loop.
There's some modern research concerning this, the classical theory just assumed that all people have roughly the same musical background and follow the same convention. |
105,305 | quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :( | 2020/09/30 | [
"https://music.stackexchange.com/questions/105305",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/72239/"
] | The scale/chords are good clues to the key of a song, but at least as important is the *tonal center*. That's not as easy to define but generally it's where the song comes back to a place of less musical tension.
IMHO the chord played when the song in question returns to a "rest" state is A major. Which means I would say the song is in A and the progression is ii - bVII - IV - I. That would suggest that the scale is actually A mixolydian (not pure major or minor), which is not unusual for rock.
The point is that the key of a song is not only about the scale. Learning to hear the tonal center is sometimes more important. | The answer to your question is **yes**.
The notation you use is relative to tonic. Establishing which sound is the tonic (and whether it changes) is completely outside of this tool. Consider anything noted as II-V as carrying a standard disclaimer "assuming that X is the tonic".
If you have a song with chords: C F C F C F, it might be a I-IV-I-IV, it might be a V-I-V-I. Depends on the rhythm, melody and even the listener. You can "make" yourself hear different tonics for the same progression in a similar way you can make yourself hear different "1" in a repeated drum loop.
There's some modern research concerning this, the classical theory just assumed that all people have roughly the same musical background and follow the same convention. |
105,305 | quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :( | 2020/09/30 | [
"https://music.stackexchange.com/questions/105305",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/72239/"
] | The answer lies in which chord is used to finish the piece (or section thereof.) If a piece ends with V-I (with I being D major and V being A major for example), one would say that that section (or piece) is in D major. To end a piece in the relative minor (same key signature but that's just for notational convenience and not universally used during the Baroque), one would have V-i with i being a b minor chord and V being F# major. (The V chords could be V7s without changing the analysis.)
Try playing A7-D or A-D then F#7-b or F#-b and listen to the difference. This applies to Common Practice Period harmony (which is still commonly used) where the chord on the dominant is a major (even if needing an accidental) in a cadence. (A almost said accidentally major....) | The answer to your question is **yes**.
The notation you use is relative to tonic. Establishing which sound is the tonic (and whether it changes) is completely outside of this tool. Consider anything noted as II-V as carrying a standard disclaimer "assuming that X is the tonic".
If you have a song with chords: C F C F C F, it might be a I-IV-I-IV, it might be a V-I-V-I. Depends on the rhythm, melody and even the listener. You can "make" yourself hear different tonics for the same progression in a similar way you can make yourself hear different "1" in a repeated drum loop.
There's some modern research concerning this, the classical theory just assumed that all people have roughly the same musical background and follow the same convention. |
105,305 | quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :( | 2020/09/30 | [
"https://music.stackexchange.com/questions/105305",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/72239/"
] | The problem goes away if you consider D and Bm to be two sides of the same key. They have the same key signature. The Roman numeral analysis system - in the form you talk about - assumes that either the major or minor side is clearly more prominent, in order to assign number one to a scale degree. You should make a decision: do you want to subscribe to this idea of two possible "ones", or normalize the situation and have the major side's tonic be number I always, even for tunes that are "in minor". Who cares about the numbers? You know where D and B are, what notes are in the default scale specified by the key signature, and how to play the song, isn't that enough?
The tonal center can sway back and forth in a song, and it's often more or less ambiguous. It can even feel like moving completely outside the original major and minor side tonics, and then we talk about a potential modulation. Insisting on moving the number one around all the time is useless IMO. The whole Roman numeral thing and functional harmony is a simplified model for harmony exercises and theory classes. Just a tool to get a perspective on a static harmonic snapshot. But real music isn't so clear and static, it moves and morphs around. | As others have pointed out, whether a song is in a major key or its relative minor is often a matter of debate or opinion. However, there are some clues that can point in one or other direction.
First, in specifically the *harmonic* minor there is a key difference, the raised leading note: thus here you would expect an A# in B minor but it would be difficult to explain in D major. Assuming that I've got the right song (["Take Me Home" by Avicii](https://www.youtube.com/watch?v=IcrbM1l_BoI)), there is an A# on the last beat of the bar every second time the chord sequence repeats, making a V-i progression back to the tonic. I would analyse the chord sequence (in the guitar at the beginning, which is a bit more revealing) as i - VI - IIIc - VII i7d - i - VI - IIIc - VII V.
Second, in the bass line, dominant to tonic is a very strong sequence to establish a tonal centre, so looking for F# - B or A - D progression at a cadence will also be helpful. Thinking of the *end* of the song now, we have the bassline
B - G - D - A - B - G - D - **F# - B**
For both of these reasons I'd say that the song is unambiguously in B minor. |
105,305 | quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :( | 2020/09/30 | [
"https://music.stackexchange.com/questions/105305",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/72239/"
] | As others have pointed out, whether a song is in a major key or its relative minor is often a matter of debate or opinion. However, there are some clues that can point in one or other direction.
First, in specifically the *harmonic* minor there is a key difference, the raised leading note: thus here you would expect an A# in B minor but it would be difficult to explain in D major. Assuming that I've got the right song (["Take Me Home" by Avicii](https://www.youtube.com/watch?v=IcrbM1l_BoI)), there is an A# on the last beat of the bar every second time the chord sequence repeats, making a V-i progression back to the tonic. I would analyse the chord sequence (in the guitar at the beginning, which is a bit more revealing) as i - VI - IIIc - VII i7d - i - VI - IIIc - VII V.
Second, in the bass line, dominant to tonic is a very strong sequence to establish a tonal centre, so looking for F# - B or A - D progression at a cadence will also be helpful. Thinking of the *end* of the song now, we have the bassline
B - G - D - A - B - G - D - **F# - B**
For both of these reasons I'd say that the song is unambiguously in B minor. | The answer to your question is **yes**.
The notation you use is relative to tonic. Establishing which sound is the tonic (and whether it changes) is completely outside of this tool. Consider anything noted as II-V as carrying a standard disclaimer "assuming that X is the tonic".
If you have a song with chords: C F C F C F, it might be a I-IV-I-IV, it might be a V-I-V-I. Depends on the rhythm, melody and even the listener. You can "make" yourself hear different tonics for the same progression in a similar way you can make yourself hear different "1" in a repeated drum loop.
There's some modern research concerning this, the classical theory just assumed that all people have roughly the same musical background and follow the same convention. |
105,305 | quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :( | 2020/09/30 | [
"https://music.stackexchange.com/questions/105305",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/72239/"
] | A complete song need not be just in one key, and stay in that key throughout. I guess that's one good thing about relative key signatures - they are identical.
There are many songs which may be in relative major for the verse, and move to relative minor for the chorus - or vice versa. There are many songs which move between the two relatives *during* the verse/chorus.
Often a telling clue is the dominant harmony - but not always. In the relative minor, often its dominant will use a 'proper' leading note - let's take key C/Am. In key C there's a G note, whereas in key Am, that often gets changed to G♯ - the leading note of *that* key, but not actually part of the diatonic set of notes making up C major. There again, that may just be a move to modulate for a short time *to* the relative minor, or even just to get to a bar or two where Am fits best.
Most pieces have a **tonal centre**, which feels to most like 'home'. This is usually the clue to the piece's key. Does it feel like it can stop at that bar, and be at rest, finished? In a piece such as you proffer, which sounds most like 'at home'? As mentioned in the previous para., a perfect cadence will usually offer the best clue.
Incidentally, *major* chords are written using capital RN, *minors* use lower case.
And with some pieces, it's (almost!) impossible to say what the key is!
Sweet Home Alabama, Unforgettable and Fly me to the Moon come immediately to mind. Maybe someone can convince everyone which key is accurately the 'correct' one for each! But does it *really* matter?
EDIT: to directly answer what I think is the question - let's take a sequence vi, IV, I, V. That could also be written in relative minor as i, VI, III, VII. In any given key, that sequence will be the same chords - e.g. in key C - Am, F, C, G. | The answer lies in which chord is used to finish the piece (or section thereof.) If a piece ends with V-I (with I being D major and V being A major for example), one would say that that section (or piece) is in D major. To end a piece in the relative minor (same key signature but that's just for notational convenience and not universally used during the Baroque), one would have V-i with i being a b minor chord and V being F# major. (The V chords could be V7s without changing the analysis.)
Try playing A7-D or A-D then F#7-b or F#-b and listen to the difference. This applies to Common Practice Period harmony (which is still commonly used) where the chord on the dominant is a major (even if needing an accidental) in a cadence. (A almost said accidentally major....) |
105,305 | quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :( | 2020/09/30 | [
"https://music.stackexchange.com/questions/105305",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/72239/"
] | The scale/chords are good clues to the key of a song, but at least as important is the *tonal center*. That's not as easy to define but generally it's where the song comes back to a place of less musical tension.
IMHO the chord played when the song in question returns to a "rest" state is A major. Which means I would say the song is in A and the progression is ii - bVII - IV - I. That would suggest that the scale is actually A mixolydian (not pure major or minor), which is not unusual for rock.
The point is that the key of a song is not only about the scale. Learning to hear the tonal center is sometimes more important. | As others have pointed out, whether a song is in a major key or its relative minor is often a matter of debate or opinion. However, there are some clues that can point in one or other direction.
First, in specifically the *harmonic* minor there is a key difference, the raised leading note: thus here you would expect an A# in B minor but it would be difficult to explain in D major. Assuming that I've got the right song (["Take Me Home" by Avicii](https://www.youtube.com/watch?v=IcrbM1l_BoI)), there is an A# on the last beat of the bar every second time the chord sequence repeats, making a V-i progression back to the tonic. I would analyse the chord sequence (in the guitar at the beginning, which is a bit more revealing) as i - VI - IIIc - VII i7d - i - VI - IIIc - VII V.
Second, in the bass line, dominant to tonic is a very strong sequence to establish a tonal centre, so looking for F# - B or A - D progression at a cadence will also be helpful. Thinking of the *end* of the song now, we have the bassline
B - G - D - A - B - G - D - **F# - B**
For both of these reasons I'd say that the song is unambiguously in B minor. |
105,305 | quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :( | 2020/09/30 | [
"https://music.stackexchange.com/questions/105305",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/72239/"
] | The answer lies in which chord is used to finish the piece (or section thereof.) If a piece ends with V-I (with I being D major and V being A major for example), one would say that that section (or piece) is in D major. To end a piece in the relative minor (same key signature but that's just for notational convenience and not universally used during the Baroque), one would have V-i with i being a b minor chord and V being F# major. (The V chords could be V7s without changing the analysis.)
Try playing A7-D or A-D then F#7-b or F#-b and listen to the difference. This applies to Common Practice Period harmony (which is still commonly used) where the chord on the dominant is a major (even if needing an accidental) in a cadence. (A almost said accidentally major....) | As others have pointed out, whether a song is in a major key or its relative minor is often a matter of debate or opinion. However, there are some clues that can point in one or other direction.
First, in specifically the *harmonic* minor there is a key difference, the raised leading note: thus here you would expect an A# in B minor but it would be difficult to explain in D major. Assuming that I've got the right song (["Take Me Home" by Avicii](https://www.youtube.com/watch?v=IcrbM1l_BoI)), there is an A# on the last beat of the bar every second time the chord sequence repeats, making a V-i progression back to the tonic. I would analyse the chord sequence (in the guitar at the beginning, which is a bit more revealing) as i - VI - IIIc - VII i7d - i - VI - IIIc - VII V.
Second, in the bass line, dominant to tonic is a very strong sequence to establish a tonal centre, so looking for F# - B or A - D progression at a cadence will also be helpful. Thinking of the *end* of the song now, we have the bassline
B - G - D - A - B - G - D - **F# - B**
For both of these reasons I'd say that the song is unambiguously in B minor. |
105,305 | quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :( | 2020/09/30 | [
"https://music.stackexchange.com/questions/105305",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/72239/"
] | The scale/chords are good clues to the key of a song, but at least as important is the *tonal center*. That's not as easy to define but generally it's where the song comes back to a place of less musical tension.
IMHO the chord played when the song in question returns to a "rest" state is A major. Which means I would say the song is in A and the progression is ii - bVII - IV - I. That would suggest that the scale is actually A mixolydian (not pure major or minor), which is not unusual for rock.
The point is that the key of a song is not only about the scale. Learning to hear the tonal center is sometimes more important. | The problem goes away if you consider D and Bm to be two sides of the same key. They have the same key signature. The Roman numeral analysis system - in the form you talk about - assumes that either the major or minor side is clearly more prominent, in order to assign number one to a scale degree. You should make a decision: do you want to subscribe to this idea of two possible "ones", or normalize the situation and have the major side's tonic be number I always, even for tunes that are "in minor". Who cares about the numbers? You know where D and B are, what notes are in the default scale specified by the key signature, and how to play the song, isn't that enough?
The tonal center can sway back and forth in a song, and it's often more or less ambiguous. It can even feel like moving completely outside the original major and minor side tonics, and then we talk about a potential modulation. Insisting on moving the number one around all the time is useless IMO. The whole Roman numeral thing and functional harmony is a simplified model for harmony exercises and theory classes. Just a tool to get a perspective on a static harmonic snapshot. But real music isn't so clear and static, it moves and morphs around. |
105,305 | quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :( | 2020/09/30 | [
"https://music.stackexchange.com/questions/105305",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/72239/"
] | A complete song need not be just in one key, and stay in that key throughout. I guess that's one good thing about relative key signatures - they are identical.
There are many songs which may be in relative major for the verse, and move to relative minor for the chorus - or vice versa. There are many songs which move between the two relatives *during* the verse/chorus.
Often a telling clue is the dominant harmony - but not always. In the relative minor, often its dominant will use a 'proper' leading note - let's take key C/Am. In key C there's a G note, whereas in key Am, that often gets changed to G♯ - the leading note of *that* key, but not actually part of the diatonic set of notes making up C major. There again, that may just be a move to modulate for a short time *to* the relative minor, or even just to get to a bar or two where Am fits best.
Most pieces have a **tonal centre**, which feels to most like 'home'. This is usually the clue to the piece's key. Does it feel like it can stop at that bar, and be at rest, finished? In a piece such as you proffer, which sounds most like 'at home'? As mentioned in the previous para., a perfect cadence will usually offer the best clue.
Incidentally, *major* chords are written using capital RN, *minors* use lower case.
And with some pieces, it's (almost!) impossible to say what the key is!
Sweet Home Alabama, Unforgettable and Fly me to the Moon come immediately to mind. Maybe someone can convince everyone which key is accurately the 'correct' one for each! But does it *really* matter?
EDIT: to directly answer what I think is the question - let's take a sequence vi, IV, I, V. That could also be written in relative minor as i, VI, III, VII. In any given key, that sequence will be the same chords - e.g. in key C - Am, F, C, G. | The problem goes away if you consider D and Bm to be two sides of the same key. They have the same key signature. The Roman numeral analysis system - in the form you talk about - assumes that either the major or minor side is clearly more prominent, in order to assign number one to a scale degree. You should make a decision: do you want to subscribe to this idea of two possible "ones", or normalize the situation and have the major side's tonic be number I always, even for tunes that are "in minor". Who cares about the numbers? You know where D and B are, what notes are in the default scale specified by the key signature, and how to play the song, isn't that enough?
The tonal center can sway back and forth in a song, and it's often more or less ambiguous. It can even feel like moving completely outside the original major and minor side tonics, and then we talk about a potential modulation. Insisting on moving the number one around all the time is useless IMO. The whole Roman numeral thing and functional harmony is a simplified model for harmony exercises and theory classes. Just a tool to get a perspective on a static harmonic snapshot. But real music isn't so clear and static, it moves and morphs around. |
239,209 | On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad. | 2008/10/27 | [
"https://Stackoverflow.com/questions/239209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17212/"
] | Windows can be installed on a different harddrive and or in a different folder. Use the %windir% or %systemroot% environment variables to get you to the windows folder and append system32. Or use the %path% variable, it's usually the first entrance and the preferred method of searching for files such as dlls AFAIK. As per comments: don't rely too much on the system32 dir being the first item. I do think it's safe to assume it's in %path% somewhere though. | Just an FYI, but in a Terminal Server environment (ie, Citrix), GetWindowsDirectory() may return a unique path for a remote user.
[link text](http://msdn.microsoft.com/en-us/library/ms724454(VS.85).aspx)
As more and more companies use virtualized desktops, developers need to keep this in mind. |
239,209 | On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad. | 2008/10/27 | [
"https://Stackoverflow.com/questions/239209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17212/"
] | You definitely cannot assume that: Windows could be installed on a different drive letter, or in a different directory. On a previous work PC Windows was installed in D:\WINNT, for example.
The short answer is to use the API call GetSystemDirectory(), which will return the path you are after.
The longer answer is to ask: do you really need to know this? If you're using it to copy files into the Windows directory, I'd suggest you ask if you really want to do this. Copying into the Windows directory is not encouraged, as you can mess up other applications very easily. If you're using the path to find DLLs, why not just rely on the OS to find the appropriate one without giving a path? If you're digging into bits of the OS files, consider: is that going to work in future? In general it's better to not explicitly poke around in the Windows directory if you want your program to work on future Windows versions. | Windows can be installed on a different harddrive and or in a different folder. Use the %windir% or %systemroot% environment variables to get you to the windows folder and append system32. Or use the %path% variable, it's usually the first entrance and the preferred method of searching for files such as dlls AFAIK. As per comments: don't rely too much on the system32 dir being the first item. I do think it's safe to assume it's in %path% somewhere though. |
239,209 | On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad. | 2008/10/27 | [
"https://Stackoverflow.com/questions/239209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17212/"
] | Windows can be installed on a different harddrive and or in a different folder. Use the %windir% or %systemroot% environment variables to get you to the windows folder and append system32. Or use the %path% variable, it's usually the first entrance and the preferred method of searching for files such as dlls AFAIK. As per comments: don't rely too much on the system32 dir being the first item. I do think it's safe to assume it's in %path% somewhere though. | I would use the **GetWindowsDirectory** Win32 API to get the current Windows directory, append **System32** to it an then check if it exists. |