qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
12,866,808 | How do I use regex to convert
```
11111aA$xx1111xxdj$%%`
```
to
```
aA$xx1111xxdj$%%
```
So, in other words, I want to remove (or match) the FIRST grouping of `1`'s. | 2012/10/12 | [
"https://Stackoverflow.com/questions/12866808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140811/"
] | If this is the beginning, you can use this:
```
^[1]*
```
As far as replacing, it depends on the language. In powershell, I would do this:
```
[regex]::Replace("11111aA$xx1111xxdj$%%","^[1]*","")
```
This will return:
```
aA$xx1111xxdj$%%
``` | In Javascript
```
var str = '11111aA$xx1111xxdj$%%';
var patt = /^1+/g;
str = str.replace(patt,"");
``` |
189,588 | I've been led to believe that for single variable assignment in T-SQL, `set` is the best way to go about things, for two reasons:
* it's the ANSI standard for variable assignment
* it's actually faster than doing a SELECT (for a single variable)
So...
```
SELECT @thingy = 'turnip shaped'
```
becomes
```
SET @thingy = 'turnip shaped'
```
But how fast, is *fast*? Am I ever really going to notice the difference? | 2008/10/09 | [
"https://Stackoverflow.com/questions/189588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | I don't speed is an issue, it has to do with more with the assignment feature set. I came across [this](http://vyaskn.tripod.com/differences_between_set_and_select.htm) a while ago and there is something new in SQL Server 2008...I heard, try googling SQL Set vs Select SQL SERVER 2008 | Take a look at the "execution plan", it should tell you the cost of each line of your statement |
189,588 | I've been led to believe that for single variable assignment in T-SQL, `set` is the best way to go about things, for two reasons:
* it's the ANSI standard for variable assignment
* it's actually faster than doing a SELECT (for a single variable)
So...
```
SELECT @thingy = 'turnip shaped'
```
becomes
```
SET @thingy = 'turnip shaped'
```
But how fast, is *fast*? Am I ever really going to notice the difference? | 2008/10/09 | [
"https://Stackoverflow.com/questions/189588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | SET is faster on single runs. You can prove this easily enough. Whether or not it makes a difference is up to you, but I prefer SET, since I don't see the point of SELECT if all the code is doing is an assignment. I prefer to keep SELECT confined to SELECT statements from tables, views, etc.
Here is a sample script, with the number of runs set to 1:
```
SET NOCOUNT ON
DECLARE @runs int
DECLARE @i int, @j int
SET @runs = 1
SET @i = 0
SET @j = 0
DECLARE @dtStartDate datetime, @dtEndDate datetime
WHILE @runs > 0
BEGIN
SET @j = 0
SET @dtStartDate = CURRENT_TIMESTAMP
WHILE @j < 1000000
BEGIN
SET @i = @j
SET @j = @j + 1
END
SELECT @dtEndDate = CURRENT_TIMESTAMP
SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SET_MILLISECONDS
SET @j = 0
SET @dtStartDate = CURRENT_TIMESTAMP
WHILE @j < 1000000
BEGIN
SELECT @i = @j
SET @j = @j + 1
END
SELECT @dtEndDate = CURRENT_TIMESTAMP
SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SELECT_MILLISECONDS
SET @runs = @runs - 1
END
```
RESULTS:
Run #1:
SET\_MILLISECONDS
5093
SELECT\_MILLISECONDS
5186
Run #2:
SET\_MILLISECONDS
4876
SELECT\_MILLISECONDS
5466
Run #3:
SET\_MILLISECONDS
4936
SELECT\_MILLISECONDS
5453
Run #4:
SET\_MILLISECONDS
4920
SELECT\_MILLISECONDS
5250
Run #5:
SET\_MILLISECONDS
4860
SELECT\_MILLISECONDS
5093
**Oddly, if you crank the number of runs up to say, 10, the SET begins to lag behind.**
Here is a 10-run result:
SET\_MILLISECONDS
5140
SELECT\_MILLISECONDS
5266
SET\_MILLISECONDS
5250
SELECT\_MILLISECONDS
5466
SET\_MILLISECONDS
5220
SELECT\_MILLISECONDS
5280
SET\_MILLISECONDS
5376
SELECT\_MILLISECONDS
5280
SET\_MILLISECONDS
5233
SELECT\_MILLISECONDS
5453
SET\_MILLISECONDS
5343
SELECT\_MILLISECONDS
5423
SET\_MILLISECONDS
5360
SELECT\_MILLISECONDS
5156
SET\_MILLISECONDS
5686
SELECT\_MILLISECONDS
5233
SET\_MILLISECONDS
5436
SELECT\_MILLISECONDS
5500
SET\_MILLISECONDS
5610
SELECT\_MILLISECONDS
5266 | Take a look at the "execution plan", it should tell you the cost of each line of your statement |
189,588 | I've been led to believe that for single variable assignment in T-SQL, `set` is the best way to go about things, for two reasons:
* it's the ANSI standard for variable assignment
* it's actually faster than doing a SELECT (for a single variable)
So...
```
SELECT @thingy = 'turnip shaped'
```
becomes
```
SET @thingy = 'turnip shaped'
```
But how fast, is *fast*? Am I ever really going to notice the difference? | 2008/10/09 | [
"https://Stackoverflow.com/questions/189588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | SET is faster on single runs. You can prove this easily enough. Whether or not it makes a difference is up to you, but I prefer SET, since I don't see the point of SELECT if all the code is doing is an assignment. I prefer to keep SELECT confined to SELECT statements from tables, views, etc.
Here is a sample script, with the number of runs set to 1:
```
SET NOCOUNT ON
DECLARE @runs int
DECLARE @i int, @j int
SET @runs = 1
SET @i = 0
SET @j = 0
DECLARE @dtStartDate datetime, @dtEndDate datetime
WHILE @runs > 0
BEGIN
SET @j = 0
SET @dtStartDate = CURRENT_TIMESTAMP
WHILE @j < 1000000
BEGIN
SET @i = @j
SET @j = @j + 1
END
SELECT @dtEndDate = CURRENT_TIMESTAMP
SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SET_MILLISECONDS
SET @j = 0
SET @dtStartDate = CURRENT_TIMESTAMP
WHILE @j < 1000000
BEGIN
SELECT @i = @j
SET @j = @j + 1
END
SELECT @dtEndDate = CURRENT_TIMESTAMP
SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SELECT_MILLISECONDS
SET @runs = @runs - 1
END
```
RESULTS:
Run #1:
SET\_MILLISECONDS
5093
SELECT\_MILLISECONDS
5186
Run #2:
SET\_MILLISECONDS
4876
SELECT\_MILLISECONDS
5466
Run #3:
SET\_MILLISECONDS
4936
SELECT\_MILLISECONDS
5453
Run #4:
SET\_MILLISECONDS
4920
SELECT\_MILLISECONDS
5250
Run #5:
SET\_MILLISECONDS
4860
SELECT\_MILLISECONDS
5093
**Oddly, if you crank the number of runs up to say, 10, the SET begins to lag behind.**
Here is a 10-run result:
SET\_MILLISECONDS
5140
SELECT\_MILLISECONDS
5266
SET\_MILLISECONDS
5250
SELECT\_MILLISECONDS
5466
SET\_MILLISECONDS
5220
SELECT\_MILLISECONDS
5280
SET\_MILLISECONDS
5376
SELECT\_MILLISECONDS
5280
SET\_MILLISECONDS
5233
SELECT\_MILLISECONDS
5453
SET\_MILLISECONDS
5343
SELECT\_MILLISECONDS
5423
SET\_MILLISECONDS
5360
SELECT\_MILLISECONDS
5156
SET\_MILLISECONDS
5686
SELECT\_MILLISECONDS
5233
SET\_MILLISECONDS
5436
SELECT\_MILLISECONDS
5500
SET\_MILLISECONDS
5610
SELECT\_MILLISECONDS
5266 | I don't speed is an issue, it has to do with more with the assignment feature set. I came across [this](http://vyaskn.tripod.com/differences_between_set_and_select.htm) a while ago and there is something new in SQL Server 2008...I heard, try googling SQL Set vs Select SQL SERVER 2008 |
445,436 | A block is suspended from a string; does the gravitational force do any work on it? | 2018/12/06 | [
"https://physics.stackexchange.com/questions/445436",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/215172/"
] | Work is performed when the point of application of a force travels through a distance in the direction of the force.
An object suspended by a string in a gravitational field experiences the force of gravity but if it does not move, then no work is being done on it. | No, if the block is still, there is no work being done on it. There is a force on it, yes, but no work. Work is really a function of a period of time i.e. in 1 second, it did 1 Joule of work. It does not make sense to ask the value of such a quantity for any given moment. |
45,648,411 | I am working on a windows application where I get value of a string called 'strData' from a function which has '\' in it. I want to split that string by '\' but I don't know why 'Split' function is not working.
```
string strData= "0101-0000046C\0\0\0"; //This Value comes from a function
string[] strTemp = strData.Split('\\');
return strTemp[0];
```
The Value of 'strTemp[0]' is still "0101-0000046C\0\0\0". Please Help me | 2017/08/12 | [
"https://Stackoverflow.com/questions/45648411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6529025/"
] | Your data is interpreted as a non-escaped string: this means all your `\0` in your code file get resolved to the ascii-char with the value of 0 (value-zero-char).
In your case you finally have to replace the value-zero-char like this:
`strData = strData.Replace("\0", "0\\");` then it works.
**Explanation:** this replaces the value-zero-char with a number-zero-char and a backslash.
As said you either have to escape the source string to `xxx\\0` or write an `@`-sign in front of the string- declaration like this: `var x = @"xxx";` (only theoretically, second method does not work here because you said you get the value from a function). This does in both cases normally solve your issue. | code is incorrect, *backslash zero* \0 is "zero character"
If You want real backslash, use double \\
```
string strData= "0101-0000046C\\0\\0\\0"; //This Value comes from a function
string[] strTemp = strData.Split('\\');
return strTemp[0];
``` |
45,648,411 | I am working on a windows application where I get value of a string called 'strData' from a function which has '\' in it. I want to split that string by '\' but I don't know why 'Split' function is not working.
```
string strData= "0101-0000046C\0\0\0"; //This Value comes from a function
string[] strTemp = strData.Split('\\');
return strTemp[0];
```
The Value of 'strTemp[0]' is still "0101-0000046C\0\0\0". Please Help me | 2017/08/12 | [
"https://Stackoverflow.com/questions/45648411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6529025/"
] | Your data is interpreted as a non-escaped string: this means all your `\0` in your code file get resolved to the ascii-char with the value of 0 (value-zero-char).
In your case you finally have to replace the value-zero-char like this:
`strData = strData.Replace("\0", "0\\");` then it works.
**Explanation:** this replaces the value-zero-char with a number-zero-char and a backslash.
As said you either have to escape the source string to `xxx\\0` or write an `@`-sign in front of the string- declaration like this: `var x = @"xxx";` (only theoretically, second method does not work here because you said you get the value from a function). This does in both cases normally solve your issue. | use `@` to interpret the string literally
```
string strData= @"0101-0000046C\0\0\0";
```
`\0` is only one character so add `@` before the string so that its interpreted literally |
25,450,780 | I'm having a strange issue with a permanent redirection in PHP.
Here's the code I'm using:
```
if ($_SERVER['HTTP_HOST'] != 'www.mydomain.ca')
{
header("HTTP/1.1 301 Moved Permanently");
$loc = "http://www.mydomain.ca".$_SERVER['SCRIPT_NAME'];
header("Location: ".$loc);
exit;
}
```
So, the home page, referenced either by www.myolddomain.ca or www.myolddomain.ca/index.php both work but every other page on the site fails to redirect. I've spent a couple of hours looking at this from all the angles I know and can't fathom it. Does anyone have any idea what the issue could be?
As a note, I've tried this without the 301 header too and get the same issue. | 2014/08/22 | [
"https://Stackoverflow.com/questions/25450780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2300171/"
] | If you have a ftp-account to the server, you can create a .htaccess file and let it handle the requests. Just create a file named `.htaccess` in the root-folder of your site and post the code, changed to your desired pattern(s)
```
Options +FollowSymLinks
RewriteEngine on
RewriteCond {HTTP_HOST} ^yourdomain.com
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]
```
If you want to do it fix via `PHP`, I would create a `redirect.php` and include it on every site you need it. Hard to tell if this is the best solution, it is a bit depending on your way of layouting and structuring. | Try it by htaccess, create .htaccess file and try something like this
RewriteEngine on
RewriteRule (.\*) <http://www.newdomain.com/>$1 [R=301,L]
\*\* Apache Mod-Rewrite moduled should be enabled |
43,741 | I'm building a piece of software which will have a filtering system that involves multiple flags. The complication is that each flag has three possible states:
1. On
2. Off
3. N/A (i.e. It can't be applied, for whatever reason)
Here's my current plan:

So the "Size" and "Weight" flags are "on", "Height" is off and "Lid Width" is N/A (None of the products actually have a lid). Clicking each box toggles the flag, unless it is N/A.
However this method has it's limitations: One of which is that it relies on colour, preventing use by colour-blind users. I could use checkboxes instead, but they take longer to read and absorb when there are a lot visible at once.
N.B. The software will *only* be used by a small selection of experts for many hours a day. So it is less important for it to be easy to learn, and more important for it to be quick to use and visually clear what's going on at all times. | 2013/08/15 | [
"https://ux.stackexchange.com/questions/43741",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11647/"
] | Suggested solution:

>
> How should I visually represent multiple three-state flags? The
> complication is that each flag has three possible states
>
>
>
Means there are only two states "on/off" for the component, but component itself can be disabled or enabled. So it is enough to have two state switch.

Having that understanding it is possible to throw switch away and use ordinary check-boxes instead (preferred solution).
 | Well, if you (rightly) don't rely on colours, you'll have to add another visual element. And I don't see the problem with using checkboxes (from Amazon.co.uk):

You can gray out non-available options.
Update
======
In respond to other posts, here's a comparison of all the ideas so far:
 |
43,741 | I'm building a piece of software which will have a filtering system that involves multiple flags. The complication is that each flag has three possible states:
1. On
2. Off
3. N/A (i.e. It can't be applied, for whatever reason)
Here's my current plan:

So the "Size" and "Weight" flags are "on", "Height" is off and "Lid Width" is N/A (None of the products actually have a lid). Clicking each box toggles the flag, unless it is N/A.
However this method has it's limitations: One of which is that it relies on colour, preventing use by colour-blind users. I could use checkboxes instead, but they take longer to read and absorb when there are a lot visible at once.
N.B. The software will *only* be used by a small selection of experts for many hours a day. So it is less important for it to be easy to learn, and more important for it to be quick to use and visually clear what's going on at all times. | 2013/08/15 | [
"https://ux.stackexchange.com/questions/43741",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11647/"
] | Good answers here, but they don't mention the common name for this UI element...
These are called **"[tri-state checkboxes](http://en.wikipedia.org/wiki/Checkbox#Tri-state_checkbox)"** (wikipedia), and are often used to show a "mixed" or "other" state in toggle switches.



[**more examples here...**](https://www.google.com/search?q=tri-state%20checkbox&source=lnms&tbm=isch) | Well, if you (rightly) don't rely on colours, you'll have to add another visual element. And I don't see the problem with using checkboxes (from Amazon.co.uk):

You can gray out non-available options.
Update
======
In respond to other posts, here's a comparison of all the ideas so far:
 |
43,741 | I'm building a piece of software which will have a filtering system that involves multiple flags. The complication is that each flag has three possible states:
1. On
2. Off
3. N/A (i.e. It can't be applied, for whatever reason)
Here's my current plan:

So the "Size" and "Weight" flags are "on", "Height" is off and "Lid Width" is N/A (None of the products actually have a lid). Clicking each box toggles the flag, unless it is N/A.
However this method has it's limitations: One of which is that it relies on colour, preventing use by colour-blind users. I could use checkboxes instead, but they take longer to read and absorb when there are a lot visible at once.
N.B. The software will *only* be used by a small selection of experts for many hours a day. So it is less important for it to be easy to learn, and more important for it to be quick to use and visually clear what's going on at all times. | 2013/08/15 | [
"https://ux.stackexchange.com/questions/43741",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11647/"
] | Suggested solution:

>
> How should I visually represent multiple three-state flags? The
> complication is that each flag has three possible states
>
>
>
Means there are only two states "on/off" for the component, but component itself can be disabled or enabled. So it is enough to have two state switch.

Having that understanding it is possible to throw switch away and use ordinary check-boxes instead (preferred solution).
 | Red color is eye-attractive although it is for off state. Besides it could be not pleasant while long observation.
I suggest other styles for the states distinction. Dots allow quick eye-jumps and have some meaning (on-off).
 |
43,741 | I'm building a piece of software which will have a filtering system that involves multiple flags. The complication is that each flag has three possible states:
1. On
2. Off
3. N/A (i.e. It can't be applied, for whatever reason)
Here's my current plan:

So the "Size" and "Weight" flags are "on", "Height" is off and "Lid Width" is N/A (None of the products actually have a lid). Clicking each box toggles the flag, unless it is N/A.
However this method has it's limitations: One of which is that it relies on colour, preventing use by colour-blind users. I could use checkboxes instead, but they take longer to read and absorb when there are a lot visible at once.
N.B. The software will *only* be used by a small selection of experts for many hours a day. So it is less important for it to be easy to learn, and more important for it to be quick to use and visually clear what's going on at all times. | 2013/08/15 | [
"https://ux.stackexchange.com/questions/43741",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11647/"
] | Suggested solution:

>
> How should I visually represent multiple three-state flags? The
> complication is that each flag has three possible states
>
>
>
Means there are only two states "on/off" for the component, but component itself can be disabled or enabled. So it is enough to have two state switch.

Having that understanding it is possible to throw switch away and use ordinary check-boxes instead (preferred solution).
 | Good answers here, but they don't mention the common name for this UI element...
These are called **"[tri-state checkboxes](http://en.wikipedia.org/wiki/Checkbox#Tri-state_checkbox)"** (wikipedia), and are often used to show a "mixed" or "other" state in toggle switches.



[**more examples here...**](https://www.google.com/search?q=tri-state%20checkbox&source=lnms&tbm=isch) |
43,741 | I'm building a piece of software which will have a filtering system that involves multiple flags. The complication is that each flag has three possible states:
1. On
2. Off
3. N/A (i.e. It can't be applied, for whatever reason)
Here's my current plan:

So the "Size" and "Weight" flags are "on", "Height" is off and "Lid Width" is N/A (None of the products actually have a lid). Clicking each box toggles the flag, unless it is N/A.
However this method has it's limitations: One of which is that it relies on colour, preventing use by colour-blind users. I could use checkboxes instead, but they take longer to read and absorb when there are a lot visible at once.
N.B. The software will *only* be used by a small selection of experts for many hours a day. So it is less important for it to be easy to learn, and more important for it to be quick to use and visually clear what's going on at all times. | 2013/08/15 | [
"https://ux.stackexchange.com/questions/43741",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/11647/"
] | Good answers here, but they don't mention the common name for this UI element...
These are called **"[tri-state checkboxes](http://en.wikipedia.org/wiki/Checkbox#Tri-state_checkbox)"** (wikipedia), and are often used to show a "mixed" or "other" state in toggle switches.



[**more examples here...**](https://www.google.com/search?q=tri-state%20checkbox&source=lnms&tbm=isch) | Red color is eye-attractive although it is for off state. Besides it could be not pleasant while long observation.
I suggest other styles for the states distinction. Dots allow quick eye-jumps and have some meaning (on-off).
 |
67,585,943 | I don't know what's wrong here, all I'm trying to do is to open this file, but it says it can't find such a file or directory, however as I have highlighted on the side, the file is right there. I just want to open it. I have opened files before but never encountered this. I must have missed something, I checked online, and seems like my syntax is correct, but I don't know.
I get the same error when I try with "alphabetical\_words" which is just a text file.
[](https://i.stack.imgur.com/qllVh.png) | 2021/05/18 | [
"https://Stackoverflow.com/questions/67585943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15054031/"
] | When [open()](https://docs.python.org/3/library/functions.html#open) function receives a relative path, it looks for that file relative to the current working directory. In other words: relative to the current directory from where the script is run. This can be any arbitrary location.
I guess what you want to do is look for `alphabetical.csv` file relative to the script location. To do that use the following formula:
```py
from pathlib import Path
# Get directory of this script
THIS_DIR = Path(__file__).absolute().parent
# Get path of CSV file relative to the directory of this script
CSV_PATH = THIS_DIR.joinpath("alphabetical.csv")
# Open the CSV file using a with-block
with CSV_PATH.open(encoding="utf-8") as csvfile:
pass # Do stuff with opened file
``` | You need to import csv. Then you can open the file as a csv file. For example,
```py
with open ("alphabetical.csv", "r") as csvfile:
```
Then you can use the file.
Make sure the file is in your cwd. |
112,725 | I've heard much about bitcoin maximalism. As I've googled it, a bitcoin maximalist is a person who believe that the only real cryptocurrency would really be needed in the future is the bitcoin. Is this correct? Can someone explain it in simple language to me and also the root causes of this belief? Why would some people believe that bitcoin is the only cryptocurrency ever man would need?
Thanks in advance. | 2022/03/04 | [
"https://bitcoin.stackexchange.com/questions/112725",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/101040/"
] | I think your question might be opinion-based and therefore off-topic on this site, but I'll still try to give a helpful answer.
Bitcoin maximalists believe that bitcoin is the only cryptocurrency worth holding, studying and/or building upon. That belief comes from any of these and/or related claims (with varying degrees of verifiability):
* Bitcoin is the only cryptocurrency that is truly decentralized. (Its creator is unknown and has not been involved with the project for many years, and there is no central authority saying what the protocol changes should be.)
* Bitcoin is the only cryptocurrency that is distributed fairly. (There was no pre-sale for insiders, no pre-mine, everyone had the opportunity to mine right from the start.)
* Any claimed improvements brought by other cryptocurrencies can be implemented in bitcoin as well if they are shown to be useful.
* Bitcoin has the most proof of work going into it, making it the "most secure" chain. | Bitcoin maximalism became a thing after this blog post by Vitalik:
<https://blog.ethereum.org/2014/11/20/bitcoin-maximalism-currency-platform-network-effects/>
I do not agree with anything shared in the post which was written in 2014. It was a narrative to promote an altcoin.
In 2022, maximalism is a meme on Twitter that some bitcoiners feel proud to be a part of. There is no team that represents bitcoin maximalists and people are free to associate themselves with different things. |
258,812 | I want to plot the waveform of an audiosnippet. Since I am working in matlab I exported my audiofile as csv with two columns (n, in). Of course this produces a huge file of about 40MB for my 1 000 000 datapoints. When I now try to plot this using pgf latex will run into a memory error.
```
TeX capacity exceeded, sorry [main memory size=5000000]. ...=in,col sep=comma] {audio.csv};
```
Here is the code I am using to plot:
```
\begin{tikzpicture}
\begin{axis}[width = 18cm, height=6cm,grid=both,xlabel={$n$},ylabel={$x(n)$},ymin=-1, ymax=1,minor y tick num=1,xmin=0, xmax=1000000]
\addplot[color=niceblue] table[x=n,y=in,col sep=comma] {audio.csv};
\end{axis}
\end{tikzpicture}
```
My first try was to reduce the filesize by only using every 128th datapoint. But this way I lose "interesting" datapoints, like the peaks. This makes my plot look incorrect.
Does anyone have an idea how to get a nice plot for my waveform? | 2015/08/05 | [
"https://tex.stackexchange.com/questions/258812",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/83229/"
] | Perhaps you can reduce the number of points by only plotting the envelope of the waveform. Im not certain if that would suffice for your waveform, but you can use Matlab to extract the envelope from the waveform; <http://mathworks.com/help/signal/ug/envelope-extraction-using-the-analytic-signal.html> | A bit late to the party, but I was looking to plot (quite a lot) of waveforms in my LaTeX document and came across this in the search. Unfortunately, this is not an *exact* answer to your question, but a way to accomplish what you want without using tikz / pgf.
1. Use `PythonTeX` (You'll need Python install - I used Anaconda Python)
2. Create `\begin{pycode}\end{pycode}`environment
3. Within `pycode` environment, import the following:
1. `from scipy.io import wavfile`
2. `from matplotlib import pyplot as plt`
3. `import numpy as np`
4. `samplerate, data = wavfile.read(FILENAME/PATH)`
5. `times = np.arange(len(data))/float(samplerate)`
6. SET UP the plot/figure if desired
7. `plt.plot(times, data, color='k')`
8. `plt.savefig('FILENAME/PATH')`
9. Compile `.tex` document
10. Compile python code via `pythontex.exe "FILENAME.tex"
11. Compile `.tex` document again (to incorporate image into document)
The memory limitation on tikz / pgf plotting waveforms is too limiting for my needs which is why I went the Python route. There are quite a lot of options in `matplotlib.pyplot` related to the plot.
Obviously, this is an alternative method. But hopefully it helps anyone who finds tikz/pgf is just not the right option for plotting waveforms in LaTeX. |
33,311,725 | With the new Codeigniter 3.0 version what authentication libraries do you use?
* [Flexi auth](http://haseydesign.com/flexi-auth/) was very good and robust with great documentation for CI 2.0 but it is old and as I can see it is discontinued. Of course it does not work out of the box with CI 3.0. I have tested it and tried to migrate it to CI 3.0 but as it uses the old `ci_sessions` schema I have seen that it has a lot work to be made to rewrite all the code parts that use sessions. It seems to work with file sessions and some alterations on its code though.
* [Community auth](http://community-auth.com/) has a CI 3.0 version but as I have seen, it has many bugs and it is nowhere near reliable at this time. I have tested it thoroughly and it cannot work properly as it has problems with its token jar system and its cookie management. Users cannot login most of the times and it is being used as a whole third-party library at Codeigniter, which personally I don't like as it has a lot of files/folders that are time consuming to be maintained. I would prefer simple CI libraries with 1-2 models like flexi-auth. Although, I wouldn't mind Community Auth's approach if it worked properly.
* [Tank Auth](https://konyukhov.com/soft/tank_auth/) was a reliable solution in the past but not with Codeigniter 3.0 as it has many incompatibilities too. [Questions about its compatibility](https://github.com/TankAuth/Tank-Auth/issues/74) with CI 3.0 were asked but no airplanes in the horizon so far.
* [DX Auth](https://github.com/eyoosuf/DX-Auth/issues) is an old authentication library and as I can see on its github repository, there are some [attempts to migrate it](https://github.com/iwatllc/DX-Auth) on CI 3.0 but I haven't been able personally to test any of them.
So, has anyone successfully integrated (or migrated) any of the previous mentioned libraries on large CI 3.0 web applications? Did you write your own? Did you stick with CI 2 until further CI 3.0 development for that matter?
Update for the down votes
=========================
[This post about Authentication libraries](https://stackoverflow.com/questions/346980/how-should-i-choose-an-authentication-library-for-codeigniter?rq=1) in codeigniter was very popular and helpful. I believe that posts that help the community in that way should not be closed at least not before some helpful answers. It is not discussed anywhere before and I would really like to see the opinions of more experienced developers for that. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33311725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219806/"
] | don't let the down votes get ya down.
check out Ion Auth
<https://github.com/benedmunds/CodeIgniter-Ion-Auth>
take a look at the read me, you will have to rename two files for codeigniter 3. otherwise you can see that there are recent changes to the lib. the author Ben Edmunds is one of the four developers on the new codeigniter council. <http://www.codeigniter.com/help/about> | For a simple library, I use <https://github.com/trafficinc/CodeIgniter-Authit> (Authit). It is very simple so I can do a lot of customizations to it or just leave it be. |
33,311,725 | With the new Codeigniter 3.0 version what authentication libraries do you use?
* [Flexi auth](http://haseydesign.com/flexi-auth/) was very good and robust with great documentation for CI 2.0 but it is old and as I can see it is discontinued. Of course it does not work out of the box with CI 3.0. I have tested it and tried to migrate it to CI 3.0 but as it uses the old `ci_sessions` schema I have seen that it has a lot work to be made to rewrite all the code parts that use sessions. It seems to work with file sessions and some alterations on its code though.
* [Community auth](http://community-auth.com/) has a CI 3.0 version but as I have seen, it has many bugs and it is nowhere near reliable at this time. I have tested it thoroughly and it cannot work properly as it has problems with its token jar system and its cookie management. Users cannot login most of the times and it is being used as a whole third-party library at Codeigniter, which personally I don't like as it has a lot of files/folders that are time consuming to be maintained. I would prefer simple CI libraries with 1-2 models like flexi-auth. Although, I wouldn't mind Community Auth's approach if it worked properly.
* [Tank Auth](https://konyukhov.com/soft/tank_auth/) was a reliable solution in the past but not with Codeigniter 3.0 as it has many incompatibilities too. [Questions about its compatibility](https://github.com/TankAuth/Tank-Auth/issues/74) with CI 3.0 were asked but no airplanes in the horizon so far.
* [DX Auth](https://github.com/eyoosuf/DX-Auth/issues) is an old authentication library and as I can see on its github repository, there are some [attempts to migrate it](https://github.com/iwatllc/DX-Auth) on CI 3.0 but I haven't been able personally to test any of them.
So, has anyone successfully integrated (or migrated) any of the previous mentioned libraries on large CI 3.0 web applications? Did you write your own? Did you stick with CI 2 until further CI 3.0 development for that matter?
Update for the down votes
=========================
[This post about Authentication libraries](https://stackoverflow.com/questions/346980/how-should-i-choose-an-authentication-library-for-codeigniter?rq=1) in codeigniter was very popular and helpful. I believe that posts that help the community in that way should not be closed at least not before some helpful answers. It is not discussed anywhere before and I would really like to see the opinions of more experienced developers for that. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33311725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219806/"
] | don't let the down votes get ya down.
check out Ion Auth
<https://github.com/benedmunds/CodeIgniter-Ion-Auth>
take a look at the read me, you will have to rename two files for codeigniter 3. otherwise you can see that there are recent changes to the lib. the author Ben Edmunds is one of the four developers on the new codeigniter council. <http://www.codeigniter.com/help/about> | Please check [Dnato System Login](https://github.com/abedputra/CodeIgniter-ion-Auth-Login)
Its Simple, Fast and Lightweight auth codeigniter.
**Feature:**
-Add user
-Delete user
-Ban, Unban user
-Register new user sent to email token
-Forget password
-Role user level
-Edit user profile
-Gravatar user profile
-Recaptcha by Google
-And much more
**Frontend**
With Bootstrap Framework. |
33,311,725 | With the new Codeigniter 3.0 version what authentication libraries do you use?
* [Flexi auth](http://haseydesign.com/flexi-auth/) was very good and robust with great documentation for CI 2.0 but it is old and as I can see it is discontinued. Of course it does not work out of the box with CI 3.0. I have tested it and tried to migrate it to CI 3.0 but as it uses the old `ci_sessions` schema I have seen that it has a lot work to be made to rewrite all the code parts that use sessions. It seems to work with file sessions and some alterations on its code though.
* [Community auth](http://community-auth.com/) has a CI 3.0 version but as I have seen, it has many bugs and it is nowhere near reliable at this time. I have tested it thoroughly and it cannot work properly as it has problems with its token jar system and its cookie management. Users cannot login most of the times and it is being used as a whole third-party library at Codeigniter, which personally I don't like as it has a lot of files/folders that are time consuming to be maintained. I would prefer simple CI libraries with 1-2 models like flexi-auth. Although, I wouldn't mind Community Auth's approach if it worked properly.
* [Tank Auth](https://konyukhov.com/soft/tank_auth/) was a reliable solution in the past but not with Codeigniter 3.0 as it has many incompatibilities too. [Questions about its compatibility](https://github.com/TankAuth/Tank-Auth/issues/74) with CI 3.0 were asked but no airplanes in the horizon so far.
* [DX Auth](https://github.com/eyoosuf/DX-Auth/issues) is an old authentication library and as I can see on its github repository, there are some [attempts to migrate it](https://github.com/iwatllc/DX-Auth) on CI 3.0 but I haven't been able personally to test any of them.
So, has anyone successfully integrated (or migrated) any of the previous mentioned libraries on large CI 3.0 web applications? Did you write your own? Did you stick with CI 2 until further CI 3.0 development for that matter?
Update for the down votes
=========================
[This post about Authentication libraries](https://stackoverflow.com/questions/346980/how-should-i-choose-an-authentication-library-for-codeigniter?rq=1) in codeigniter was very popular and helpful. I believe that posts that help the community in that way should not be closed at least not before some helpful answers. It is not discussed anywhere before and I would really like to see the opinions of more experienced developers for that. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33311725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219806/"
] | don't let the down votes get ya down.
check out Ion Auth
<https://github.com/benedmunds/CodeIgniter-Ion-Auth>
take a look at the read me, you will have to rename two files for codeigniter 3. otherwise you can see that there are recent changes to the lib. the author Ben Edmunds is one of the four developers on the new codeigniter council. <http://www.codeigniter.com/help/about> | check this library.that is so nice.and with many features
* login / logout
* Login DDoS Protection
* register and signup via email. (send verification code to your email)
* users can send private message to other users
* user group
* create permissions and access control
* error in other language
this library for CI2. but if you search about this, you can find lib for CI3
<http://codeigniter-aauth-test.readthedocs.io> |
33,311,725 | With the new Codeigniter 3.0 version what authentication libraries do you use?
* [Flexi auth](http://haseydesign.com/flexi-auth/) was very good and robust with great documentation for CI 2.0 but it is old and as I can see it is discontinued. Of course it does not work out of the box with CI 3.0. I have tested it and tried to migrate it to CI 3.0 but as it uses the old `ci_sessions` schema I have seen that it has a lot work to be made to rewrite all the code parts that use sessions. It seems to work with file sessions and some alterations on its code though.
* [Community auth](http://community-auth.com/) has a CI 3.0 version but as I have seen, it has many bugs and it is nowhere near reliable at this time. I have tested it thoroughly and it cannot work properly as it has problems with its token jar system and its cookie management. Users cannot login most of the times and it is being used as a whole third-party library at Codeigniter, which personally I don't like as it has a lot of files/folders that are time consuming to be maintained. I would prefer simple CI libraries with 1-2 models like flexi-auth. Although, I wouldn't mind Community Auth's approach if it worked properly.
* [Tank Auth](https://konyukhov.com/soft/tank_auth/) was a reliable solution in the past but not with Codeigniter 3.0 as it has many incompatibilities too. [Questions about its compatibility](https://github.com/TankAuth/Tank-Auth/issues/74) with CI 3.0 were asked but no airplanes in the horizon so far.
* [DX Auth](https://github.com/eyoosuf/DX-Auth/issues) is an old authentication library and as I can see on its github repository, there are some [attempts to migrate it](https://github.com/iwatllc/DX-Auth) on CI 3.0 but I haven't been able personally to test any of them.
So, has anyone successfully integrated (or migrated) any of the previous mentioned libraries on large CI 3.0 web applications? Did you write your own? Did you stick with CI 2 until further CI 3.0 development for that matter?
Update for the down votes
=========================
[This post about Authentication libraries](https://stackoverflow.com/questions/346980/how-should-i-choose-an-authentication-library-for-codeigniter?rq=1) in codeigniter was very popular and helpful. I believe that posts that help the community in that way should not be closed at least not before some helpful answers. It is not discussed anywhere before and I would really like to see the opinions of more experienced developers for that. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33311725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219806/"
] | Please check [Dnato System Login](https://github.com/abedputra/CodeIgniter-ion-Auth-Login)
Its Simple, Fast and Lightweight auth codeigniter.
**Feature:**
-Add user
-Delete user
-Ban, Unban user
-Register new user sent to email token
-Forget password
-Role user level
-Edit user profile
-Gravatar user profile
-Recaptcha by Google
-And much more
**Frontend**
With Bootstrap Framework. | For a simple library, I use <https://github.com/trafficinc/CodeIgniter-Authit> (Authit). It is very simple so I can do a lot of customizations to it or just leave it be. |
33,311,725 | With the new Codeigniter 3.0 version what authentication libraries do you use?
* [Flexi auth](http://haseydesign.com/flexi-auth/) was very good and robust with great documentation for CI 2.0 but it is old and as I can see it is discontinued. Of course it does not work out of the box with CI 3.0. I have tested it and tried to migrate it to CI 3.0 but as it uses the old `ci_sessions` schema I have seen that it has a lot work to be made to rewrite all the code parts that use sessions. It seems to work with file sessions and some alterations on its code though.
* [Community auth](http://community-auth.com/) has a CI 3.0 version but as I have seen, it has many bugs and it is nowhere near reliable at this time. I have tested it thoroughly and it cannot work properly as it has problems with its token jar system and its cookie management. Users cannot login most of the times and it is being used as a whole third-party library at Codeigniter, which personally I don't like as it has a lot of files/folders that are time consuming to be maintained. I would prefer simple CI libraries with 1-2 models like flexi-auth. Although, I wouldn't mind Community Auth's approach if it worked properly.
* [Tank Auth](https://konyukhov.com/soft/tank_auth/) was a reliable solution in the past but not with Codeigniter 3.0 as it has many incompatibilities too. [Questions about its compatibility](https://github.com/TankAuth/Tank-Auth/issues/74) with CI 3.0 were asked but no airplanes in the horizon so far.
* [DX Auth](https://github.com/eyoosuf/DX-Auth/issues) is an old authentication library and as I can see on its github repository, there are some [attempts to migrate it](https://github.com/iwatllc/DX-Auth) on CI 3.0 but I haven't been able personally to test any of them.
So, has anyone successfully integrated (or migrated) any of the previous mentioned libraries on large CI 3.0 web applications? Did you write your own? Did you stick with CI 2 until further CI 3.0 development for that matter?
Update for the down votes
=========================
[This post about Authentication libraries](https://stackoverflow.com/questions/346980/how-should-i-choose-an-authentication-library-for-codeigniter?rq=1) in codeigniter was very popular and helpful. I believe that posts that help the community in that way should not be closed at least not before some helpful answers. It is not discussed anywhere before and I would really like to see the opinions of more experienced developers for that. | 2015/10/23 | [
"https://Stackoverflow.com/questions/33311725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219806/"
] | Please check [Dnato System Login](https://github.com/abedputra/CodeIgniter-ion-Auth-Login)
Its Simple, Fast and Lightweight auth codeigniter.
**Feature:**
-Add user
-Delete user
-Ban, Unban user
-Register new user sent to email token
-Forget password
-Role user level
-Edit user profile
-Gravatar user profile
-Recaptcha by Google
-And much more
**Frontend**
With Bootstrap Framework. | check this library.that is so nice.and with many features
* login / logout
* Login DDoS Protection
* register and signup via email. (send verification code to your email)
* users can send private message to other users
* user group
* create permissions and access control
* error in other language
this library for CI2. but if you search about this, you can find lib for CI3
<http://codeigniter-aauth-test.readthedocs.io> |
2,863,587 | Given $x\_0 \ldots x\_k$ and $n$, Define $$f(Q)=\sum\_{\substack{n\_0+\ldots+n\_k=n \\ n\_0,\ldots,n\_k \ >=0 \\n\_1+2\*n\_2+\ldots+k\*n\_k=Q}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}$$. Note that $$\sum\_{Q=0}^{n\*k} f(Q)=(\sum\_{i=0}^{k}x\_i)^n$$ which comes from the multinomial expansion. I was wondering how to calculate $\sum\_{Q=0}^{n\*k} Q\cdot f(Q)$.
I've checked several small cases, and it seems that $\sum\_{Q=0}^{n\*k} Q\cdot f(Q) = n(\sum\_{i=0}^{k}x\_i)^{n-1}(\sum\_{i=0}^{k}ix\_i)$, but I'm not sure how to prove that. | 2018/07/26 | [
"https://math.stackexchange.com/questions/2863587",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/376930/"
] | You can calculate the generating function instead. Define
$$
\begin{aligned}
F(X,Y)&=
\sum\_{n=0}^\infty X^n\sum\_{Q=0}^\infty Y^Q
\sum\_{\substack{n\_0+\ldots+n\_k=n \\ n\_0,\ldots,n\_k \ >=0 \\n\_1+2\*n\_2+\ldots+k\*n\_k=Q}} \frac{1}{n\_0!n\_1!\cdots n\_k!}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}\\
&=\sum\_{n=0}^\infty X^n\sum\_{Q=0}^\infty Y^Q
\sum\_{n\_0, \cdots, n\_k\geq 0} \frac{1}{n\_0!n\_1!\cdots n\_k!}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}
\delta\left(n-\sum\_{j=0}^k n\_j\right)
\delta\left(Q-\sum\_{j=0}^k jn\_j\right)\\
&=
\sum\_{n\_0, \cdots, n\_k\geq 0}
\frac{1}{n\_0!n\_1!\cdots n\_k!}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k} X^{\sum\_j n\_j} Y^{\sum\_j jn\_j}\\
&=\prod\_{m=0}^k \exp(x\_m XY^m)
\end{aligned}
$$
where by $\delta(Z)$ I mean the Kronecker delta equating $Z=0$. What you are looking for the $n!$ times the coefficient of $X^nY^Q$ in the expansion of $F(X,Y)$ (in other words, $(Q!)^{-1}\partial\_X^n \partial\_Y^Q F\mid\_{X=Y=0}$). | Starting from Hamed's answer, we can give a quick proof that $\sum\_{Q\ge 0} Qf(Q)$ equals what you think it is. They proved
$$
\sum\_{n\ge 0}\sum\_{q\ge 0}\frac1{n!}f\_n(Q)X^nY^q = \exp\Big(\sum\_{m=0}^k x\_mXY^m\Big)
$$
Differentiating both sides with respect to $Y$, and then multiplying by $Y$, you get
$$
\sum\_{n\ge 0}\sum\_{q\ge 0}\frac1{n!}Qf\_n(Q)X^nY^q = \big(\sum\_{k=0}^m mx\_m XY^m\big)\exp\Big(\sum\_{m=0}^k x\_mXY^m\Big)
$$
Notice that we now have a $Qf\_n(Q)$. These need to be summed, so set $Y=1$:
$$
\sum\_{n\ge 0}\sum\_{q\ge 0}\frac1{n!}Qf\_n(Q)X^n = \big(\sum\_{k=0}^m mx\_m X\big)\exp\Big(X\sum\_{m=0}^k x\_m\Big)
$$
Finally, extract the coefficient of $X^n$ of both sides. On the left hand side, $X\_n$ has a $\frac1{n!}\sum\_{q\ge 0}QF\_n(Q)$ attached to it. On the right, you get the $X^n$ coefficient by multiplying $\big(\sum\_{k=0}^m mx\_m\big)$ with the $X^{n-1}$ coefficient of $\exp\Big(X\sum\_{m=0}^k x\_m\Big)$. This implies
$$
\frac1{n!}\sum\_{q\ge 0}QF\_n(Q)=\big(\sum\_{k=0}^m mx\_m\big)\cdot \frac1{(n-1)!}\Big(\sum\_{k=0}^m x\_m\Big)^{n-1}
$$
which is what you wanted. |
2,863,587 | Given $x\_0 \ldots x\_k$ and $n$, Define $$f(Q)=\sum\_{\substack{n\_0+\ldots+n\_k=n \\ n\_0,\ldots,n\_k \ >=0 \\n\_1+2\*n\_2+\ldots+k\*n\_k=Q}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}$$. Note that $$\sum\_{Q=0}^{n\*k} f(Q)=(\sum\_{i=0}^{k}x\_i)^n$$ which comes from the multinomial expansion. I was wondering how to calculate $\sum\_{Q=0}^{n\*k} Q\cdot f(Q)$.
I've checked several small cases, and it seems that $\sum\_{Q=0}^{n\*k} Q\cdot f(Q) = n(\sum\_{i=0}^{k}x\_i)^{n-1}(\sum\_{i=0}^{k}ix\_i)$, but I'm not sure how to prove that. | 2018/07/26 | [
"https://math.stackexchange.com/questions/2863587",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/376930/"
] | You can calculate the generating function instead. Define
$$
\begin{aligned}
F(X,Y)&=
\sum\_{n=0}^\infty X^n\sum\_{Q=0}^\infty Y^Q
\sum\_{\substack{n\_0+\ldots+n\_k=n \\ n\_0,\ldots,n\_k \ >=0 \\n\_1+2\*n\_2+\ldots+k\*n\_k=Q}} \frac{1}{n\_0!n\_1!\cdots n\_k!}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}\\
&=\sum\_{n=0}^\infty X^n\sum\_{Q=0}^\infty Y^Q
\sum\_{n\_0, \cdots, n\_k\geq 0} \frac{1}{n\_0!n\_1!\cdots n\_k!}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}
\delta\left(n-\sum\_{j=0}^k n\_j\right)
\delta\left(Q-\sum\_{j=0}^k jn\_j\right)\\
&=
\sum\_{n\_0, \cdots, n\_k\geq 0}
\frac{1}{n\_0!n\_1!\cdots n\_k!}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k} X^{\sum\_j n\_j} Y^{\sum\_j jn\_j}\\
&=\prod\_{m=0}^k \exp(x\_m XY^m)
\end{aligned}
$$
where by $\delta(Z)$ I mean the Kronecker delta equating $Z=0$. What you are looking for the $n!$ times the coefficient of $X^nY^Q$ in the expansion of $F(X,Y)$ (in other words, $(Q!)^{-1}\partial\_X^n \partial\_Y^Q F\mid\_{X=Y=0}$). | I'm going to provide a secondary generating function which is probably more relevant to your updated question. Let's recall your definition,
$$
f(Q):=\sum\_{\substack{\sum\_{i=0}^k n\_i=n \\ n\_0,\ldots,n\_k \ \geq0 \\\sum\_{j=0}^kjn\_j=Q}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}
$$
and let us calculate $
G(X):=\sum\_{Q=0}^{nk} f(Q)X^Q
$. Before, we do that note that for any $p\geq 0$, $$\boxed{\sum\_{Q=0}^{nk} Q^pf(Q)=\left.\left(X\frac{d}{dX}\right)^p G(X)\right|\_{X=1}}$$
First of all, note that under the condition $\sum\_{j=0}^k n\_j = n$ and $n\_0, \cdots, n\_k\geq 0$, one has
$$
nk -\sum\_{j=0}^k jn\_j=
\sum\_{j=0}^k (k-j) n\_j\geq 0
$$
As a result, the equation $z-\sum\_{j=0}^k jn\_j=0$ has exactly one solution for $z$ in the integer range $0\leq z\leq nk$. Using this, we have
$$
\begin{aligned}
G(X)&=\sum\_{Q=0}^{nk} X^{Q}
\sum\_{\substack{\sum\_{i=0}^k n\_i=n \\ n\_0,\ldots,n\_k \ \geq 0}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}
\delta\left(Q-\sum\_{j=0}^kjn\_j\right)
\\
&=
\sum\_{\substack{\sum\_{i=0}^k n\_i=n \\ n\_0,\ldots,n\_k \ \geq 0}} \binom{n}{n\_0,\cdots,n\_k}\prod\_{m=0}^k (x\_mX^m)^{n\_m}=\left(\sum\_{m=0}^k x\_m X^m\right)^{n}
\end{aligned}
$$
So to summarize:
$$
\boxed{
G(X)=\sum\_{Q=0}^{nk} f(Q) X^Q = \left(\sum\_{m=0}^k x\_m X^m\right)^{n}
}
$$
This should make the rest obvious. |
2,863,587 | Given $x\_0 \ldots x\_k$ and $n$, Define $$f(Q)=\sum\_{\substack{n\_0+\ldots+n\_k=n \\ n\_0,\ldots,n\_k \ >=0 \\n\_1+2\*n\_2+\ldots+k\*n\_k=Q}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}$$. Note that $$\sum\_{Q=0}^{n\*k} f(Q)=(\sum\_{i=0}^{k}x\_i)^n$$ which comes from the multinomial expansion. I was wondering how to calculate $\sum\_{Q=0}^{n\*k} Q\cdot f(Q)$.
I've checked several small cases, and it seems that $\sum\_{Q=0}^{n\*k} Q\cdot f(Q) = n(\sum\_{i=0}^{k}x\_i)^{n-1}(\sum\_{i=0}^{k}ix\_i)$, but I'm not sure how to prove that. | 2018/07/26 | [
"https://math.stackexchange.com/questions/2863587",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/376930/"
] | Wikipedia on [Bell polynomials](https://en.wikipedia.org/wiki/Bell_polynomials):
>
> Likewise, the partial ordinary Bell polynomial, in contrast to the usual exponential Bell polynomial defined above, is given by $$\hat{B}\_{n,k}(x\_1,x\_2,\ldots,x\_{n-k+1})=\sum \frac{k!}{j\_1! j\_2! \cdots j\_{n-k+1}!} x\_1{}^{j\_1} x\_2{}^{j\_2} \cdots x\_{n-k+1}{}^{j\_{n-k+1}},$$
> where the sum runs over all sequences $j\_1, j\_2, j\_3, \ldots, j\_{n−k+1}$ of non-negative integers such that $$
> j\_1 + j\_2 + \cdots + j\_{n-k+1} = k, \\
> j\_1 + 2j\_2 + \cdots + (n-k+1)j\_{n-k+1} = n.$$
>
>
>
So your sum $$\sum\_{\substack{n\_0+\ldots+n\_k=n \\ n\_0,\ldots,n\_k \ >=0 \\n\_1+2n\_2+\ldots+kn\_k=Q}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}$$
is
$$\sum\_{n\_0=0}^n \binom{n}{n\_0} x\_{0}^{n\_0} \hat{B}\_{Q,n-n\_0}(x\_1, x\_2, \ldots, x\_k)$$
---
Using $${\hat {B}}\_{n,k}(x\_{1},x\_{2},\ldots ,x\_{n-k+1})={\frac {k!}{n!}}B\_{n,k}(1!\cdot x\_{1},2!\cdot x\_{2},\ldots ,(n-k+1)!\cdot x\_{n-k+1})$$ we have
$$\frac{n!}{Q!}\sum\_{n\_0=0}^n \frac{x\_{0}^{n\_0}}{n\_0!} B\_{Q,n-n\_0}(1!\cdot x\_1, 2!\cdot x\_2, \ldots, k!\cdot x\_k)$$
Then the recurrence relation $$B\_{n,k}=\sum\_{i=1}^{n-k+1} \binom{n-1}{i-1} x\_i B\_{n-i,k-1}$$
gives you an evaluation strategy. | Starting from Hamed's answer, we can give a quick proof that $\sum\_{Q\ge 0} Qf(Q)$ equals what you think it is. They proved
$$
\sum\_{n\ge 0}\sum\_{q\ge 0}\frac1{n!}f\_n(Q)X^nY^q = \exp\Big(\sum\_{m=0}^k x\_mXY^m\Big)
$$
Differentiating both sides with respect to $Y$, and then multiplying by $Y$, you get
$$
\sum\_{n\ge 0}\sum\_{q\ge 0}\frac1{n!}Qf\_n(Q)X^nY^q = \big(\sum\_{k=0}^m mx\_m XY^m\big)\exp\Big(\sum\_{m=0}^k x\_mXY^m\Big)
$$
Notice that we now have a $Qf\_n(Q)$. These need to be summed, so set $Y=1$:
$$
\sum\_{n\ge 0}\sum\_{q\ge 0}\frac1{n!}Qf\_n(Q)X^n = \big(\sum\_{k=0}^m mx\_m X\big)\exp\Big(X\sum\_{m=0}^k x\_m\Big)
$$
Finally, extract the coefficient of $X^n$ of both sides. On the left hand side, $X\_n$ has a $\frac1{n!}\sum\_{q\ge 0}QF\_n(Q)$ attached to it. On the right, you get the $X^n$ coefficient by multiplying $\big(\sum\_{k=0}^m mx\_m\big)$ with the $X^{n-1}$ coefficient of $\exp\Big(X\sum\_{m=0}^k x\_m\Big)$. This implies
$$
\frac1{n!}\sum\_{q\ge 0}QF\_n(Q)=\big(\sum\_{k=0}^m mx\_m\big)\cdot \frac1{(n-1)!}\Big(\sum\_{k=0}^m x\_m\Big)^{n-1}
$$
which is what you wanted. |
2,863,587 | Given $x\_0 \ldots x\_k$ and $n$, Define $$f(Q)=\sum\_{\substack{n\_0+\ldots+n\_k=n \\ n\_0,\ldots,n\_k \ >=0 \\n\_1+2\*n\_2+\ldots+k\*n\_k=Q}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}$$. Note that $$\sum\_{Q=0}^{n\*k} f(Q)=(\sum\_{i=0}^{k}x\_i)^n$$ which comes from the multinomial expansion. I was wondering how to calculate $\sum\_{Q=0}^{n\*k} Q\cdot f(Q)$.
I've checked several small cases, and it seems that $\sum\_{Q=0}^{n\*k} Q\cdot f(Q) = n(\sum\_{i=0}^{k}x\_i)^{n-1}(\sum\_{i=0}^{k}ix\_i)$, but I'm not sure how to prove that. | 2018/07/26 | [
"https://math.stackexchange.com/questions/2863587",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/376930/"
] | Wikipedia on [Bell polynomials](https://en.wikipedia.org/wiki/Bell_polynomials):
>
> Likewise, the partial ordinary Bell polynomial, in contrast to the usual exponential Bell polynomial defined above, is given by $$\hat{B}\_{n,k}(x\_1,x\_2,\ldots,x\_{n-k+1})=\sum \frac{k!}{j\_1! j\_2! \cdots j\_{n-k+1}!} x\_1{}^{j\_1} x\_2{}^{j\_2} \cdots x\_{n-k+1}{}^{j\_{n-k+1}},$$
> where the sum runs over all sequences $j\_1, j\_2, j\_3, \ldots, j\_{n−k+1}$ of non-negative integers such that $$
> j\_1 + j\_2 + \cdots + j\_{n-k+1} = k, \\
> j\_1 + 2j\_2 + \cdots + (n-k+1)j\_{n-k+1} = n.$$
>
>
>
So your sum $$\sum\_{\substack{n\_0+\ldots+n\_k=n \\ n\_0,\ldots,n\_k \ >=0 \\n\_1+2n\_2+\ldots+kn\_k=Q}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}$$
is
$$\sum\_{n\_0=0}^n \binom{n}{n\_0} x\_{0}^{n\_0} \hat{B}\_{Q,n-n\_0}(x\_1, x\_2, \ldots, x\_k)$$
---
Using $${\hat {B}}\_{n,k}(x\_{1},x\_{2},\ldots ,x\_{n-k+1})={\frac {k!}{n!}}B\_{n,k}(1!\cdot x\_{1},2!\cdot x\_{2},\ldots ,(n-k+1)!\cdot x\_{n-k+1})$$ we have
$$\frac{n!}{Q!}\sum\_{n\_0=0}^n \frac{x\_{0}^{n\_0}}{n\_0!} B\_{Q,n-n\_0}(1!\cdot x\_1, 2!\cdot x\_2, \ldots, k!\cdot x\_k)$$
Then the recurrence relation $$B\_{n,k}=\sum\_{i=1}^{n-k+1} \binom{n-1}{i-1} x\_i B\_{n-i,k-1}$$
gives you an evaluation strategy. | I'm going to provide a secondary generating function which is probably more relevant to your updated question. Let's recall your definition,
$$
f(Q):=\sum\_{\substack{\sum\_{i=0}^k n\_i=n \\ n\_0,\ldots,n\_k \ \geq0 \\\sum\_{j=0}^kjn\_j=Q}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}
$$
and let us calculate $
G(X):=\sum\_{Q=0}^{nk} f(Q)X^Q
$. Before, we do that note that for any $p\geq 0$, $$\boxed{\sum\_{Q=0}^{nk} Q^pf(Q)=\left.\left(X\frac{d}{dX}\right)^p G(X)\right|\_{X=1}}$$
First of all, note that under the condition $\sum\_{j=0}^k n\_j = n$ and $n\_0, \cdots, n\_k\geq 0$, one has
$$
nk -\sum\_{j=0}^k jn\_j=
\sum\_{j=0}^k (k-j) n\_j\geq 0
$$
As a result, the equation $z-\sum\_{j=0}^k jn\_j=0$ has exactly one solution for $z$ in the integer range $0\leq z\leq nk$. Using this, we have
$$
\begin{aligned}
G(X)&=\sum\_{Q=0}^{nk} X^{Q}
\sum\_{\substack{\sum\_{i=0}^k n\_i=n \\ n\_0,\ldots,n\_k \ \geq 0}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}
\delta\left(Q-\sum\_{j=0}^kjn\_j\right)
\\
&=
\sum\_{\substack{\sum\_{i=0}^k n\_i=n \\ n\_0,\ldots,n\_k \ \geq 0}} \binom{n}{n\_0,\cdots,n\_k}\prod\_{m=0}^k (x\_mX^m)^{n\_m}=\left(\sum\_{m=0}^k x\_m X^m\right)^{n}
\end{aligned}
$$
So to summarize:
$$
\boxed{
G(X)=\sum\_{Q=0}^{nk} f(Q) X^Q = \left(\sum\_{m=0}^k x\_m X^m\right)^{n}
}
$$
This should make the rest obvious. |
2,863,587 | Given $x\_0 \ldots x\_k$ and $n$, Define $$f(Q)=\sum\_{\substack{n\_0+\ldots+n\_k=n \\ n\_0,\ldots,n\_k \ >=0 \\n\_1+2\*n\_2+\ldots+k\*n\_k=Q}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}$$. Note that $$\sum\_{Q=0}^{n\*k} f(Q)=(\sum\_{i=0}^{k}x\_i)^n$$ which comes from the multinomial expansion. I was wondering how to calculate $\sum\_{Q=0}^{n\*k} Q\cdot f(Q)$.
I've checked several small cases, and it seems that $\sum\_{Q=0}^{n\*k} Q\cdot f(Q) = n(\sum\_{i=0}^{k}x\_i)^{n-1}(\sum\_{i=0}^{k}ix\_i)$, but I'm not sure how to prove that. | 2018/07/26 | [
"https://math.stackexchange.com/questions/2863587",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/376930/"
] | Starting from Hamed's answer, we can give a quick proof that $\sum\_{Q\ge 0} Qf(Q)$ equals what you think it is. They proved
$$
\sum\_{n\ge 0}\sum\_{q\ge 0}\frac1{n!}f\_n(Q)X^nY^q = \exp\Big(\sum\_{m=0}^k x\_mXY^m\Big)
$$
Differentiating both sides with respect to $Y$, and then multiplying by $Y$, you get
$$
\sum\_{n\ge 0}\sum\_{q\ge 0}\frac1{n!}Qf\_n(Q)X^nY^q = \big(\sum\_{k=0}^m mx\_m XY^m\big)\exp\Big(\sum\_{m=0}^k x\_mXY^m\Big)
$$
Notice that we now have a $Qf\_n(Q)$. These need to be summed, so set $Y=1$:
$$
\sum\_{n\ge 0}\sum\_{q\ge 0}\frac1{n!}Qf\_n(Q)X^n = \big(\sum\_{k=0}^m mx\_m X\big)\exp\Big(X\sum\_{m=0}^k x\_m\Big)
$$
Finally, extract the coefficient of $X^n$ of both sides. On the left hand side, $X\_n$ has a $\frac1{n!}\sum\_{q\ge 0}QF\_n(Q)$ attached to it. On the right, you get the $X^n$ coefficient by multiplying $\big(\sum\_{k=0}^m mx\_m\big)$ with the $X^{n-1}$ coefficient of $\exp\Big(X\sum\_{m=0}^k x\_m\Big)$. This implies
$$
\frac1{n!}\sum\_{q\ge 0}QF\_n(Q)=\big(\sum\_{k=0}^m mx\_m\big)\cdot \frac1{(n-1)!}\Big(\sum\_{k=0}^m x\_m\Big)^{n-1}
$$
which is what you wanted. | I'm going to provide a secondary generating function which is probably more relevant to your updated question. Let's recall your definition,
$$
f(Q):=\sum\_{\substack{\sum\_{i=0}^k n\_i=n \\ n\_0,\ldots,n\_k \ \geq0 \\\sum\_{j=0}^kjn\_j=Q}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}
$$
and let us calculate $
G(X):=\sum\_{Q=0}^{nk} f(Q)X^Q
$. Before, we do that note that for any $p\geq 0$, $$\boxed{\sum\_{Q=0}^{nk} Q^pf(Q)=\left.\left(X\frac{d}{dX}\right)^p G(X)\right|\_{X=1}}$$
First of all, note that under the condition $\sum\_{j=0}^k n\_j = n$ and $n\_0, \cdots, n\_k\geq 0$, one has
$$
nk -\sum\_{j=0}^k jn\_j=
\sum\_{j=0}^k (k-j) n\_j\geq 0
$$
As a result, the equation $z-\sum\_{j=0}^k jn\_j=0$ has exactly one solution for $z$ in the integer range $0\leq z\leq nk$. Using this, we have
$$
\begin{aligned}
G(X)&=\sum\_{Q=0}^{nk} X^{Q}
\sum\_{\substack{\sum\_{i=0}^k n\_i=n \\ n\_0,\ldots,n\_k \ \geq 0}} \binom{n}{n\_0,\cdots,n\_k}x\_{0}^{n\_0}\ldots x\_{k}^{n\_k}
\delta\left(Q-\sum\_{j=0}^kjn\_j\right)
\\
&=
\sum\_{\substack{\sum\_{i=0}^k n\_i=n \\ n\_0,\ldots,n\_k \ \geq 0}} \binom{n}{n\_0,\cdots,n\_k}\prod\_{m=0}^k (x\_mX^m)^{n\_m}=\left(\sum\_{m=0}^k x\_m X^m\right)^{n}
\end{aligned}
$$
So to summarize:
$$
\boxed{
G(X)=\sum\_{Q=0}^{nk} f(Q) X^Q = \left(\sum\_{m=0}^k x\_m X^m\right)^{n}
}
$$
This should make the rest obvious. |
53,022,575 | I'm trying to write a regex in php to split the string to array.
The string is
```
#000000 | Black #ffffff | White #ff0000 | Red
```
there can or cannot be space between the character and
```
|
```
so the regex needs to work with
```
#000000|Black #ffffff|White #ff0000|Red
```
For the second type of string this works.
```
$str = preg_split('/[\s]+/', $str);
```
How can I modify it to work with the first and second both strings?
Edit: Final output needs to be
```
Array ( [0] => Array ( [0] => #000000 [1] => Black ) [1] => Array ( [0] => #ffffff [1] => White ) [2] => Array ( [0] => #ff0000 [1] => Red) )
``` | 2018/10/27 | [
"https://Stackoverflow.com/questions/53022575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10519464/"
] | From <https://firebase.google.com/docs/android/setup> it looks like 16.0.4 is latest version
```
com.google.firebase:firebase-core:16.0.4
``` | @Johns solution did not work for us as we ran into another known issue with that version (see <https://developers.google.com/android/guides/releases>)
What worked for us is to use the alias of firebase-core:
change `com.google.firebase:firebase-core:16.0.4` to
```
com.google.firebase:firebase-analytics:16.0.5
``` |
67,122,003 | >
> **Task:** According to the Taylor Series of sin(x) calculate with using a double function named **mysin** pass it to a double variable. Take a x value from user and use the mysin function to calculate sin(x).
>
>
> [](https://i.stack.imgur.com/elqSV.png)
>
>
>
Problem is program gives me wrong value of sin(x). I have been trying to solve that issue about 4 hours but couldn't find it. Is it because of sin(x) function or have I missed something in my code?
**My Code:**
```
#include <stdio.h>
double mysin(double x)
{
double value = x;
double sum = x;
int neg_pos = 1;
int fac = 1;
int counter = 0;
while(1)
{
neg_pos *= -1;
fac += 2;
value = value/(fac*(fac-1));
value = value*x*x*neg_pos;
sum += value;
//printf("Hello");
counter++;
if (counter == 100) break;
}
return sum;
}
int main()
{
double number;
scanf("%lf",&number);
printf("%g",mysin(number));
//printf("%g",number);
}
``` | 2021/04/16 | [
"https://Stackoverflow.com/questions/67122003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14886767/"
] | The problem is that you're multiplying by `neg_pos` each step, which toggles between +1 and -1. That means the terms change sign only half the time, whereas they should change sign each time.
The fix is to just multiply by -1 each time rather than `neg_pos`.
Here's a working, slightly-simplified form of your program that calculates sin for a range of numbers from 0 to 3, showing the stdlib calculation to compare.
```
#include <math.h>
#include <stdio.h>
double mysin(double x) {
double value = x;
double sum = x;
int fac = 1;
for (int counter = 0; counter < 100; counter++) {
fac += 2;
value = -value*x*x/fac/(fac-1);
sum += value;
}
return sum;
}
int main() {
for (double x = 0.0; x < 3.0; x += 0.1) {
printf("%g: %g %g\n", x, mysin(x), sin(x));
}
}
```
You can also avoid the separate `fac` and `counter` variables, perhaps like this:
```
double mysin(double x) {
double term=x, sum=x;
for (int f = 0; f < 100; f++) {
term = -term*x*x/(2*f+2)/(2*f+3);
sum += term;
}
return sum;
}
``` | From what I'm understanding you are not calculating the power correctly
Firtsly use this:
```
#include <math.h>
```
Then create a factorial function:
```
int factorial(int x){
int result = 1;
for(int i = 1; i < x; i++){
result += result * i;
}
return result;
}
```
And finally:
```
while(1)
{
neg_pos *= -1;
fac += 2;
power = pow(x,fac);
fac = factorial(fac);
sum += power/fac;
//printf("Hello");
counter++;
if (counter == 100) break;
}
``` |
1,399,204 | Please help in Solving the Trigonometric Equation:
$$\cos^2x - \sin^2x = \cos3x$$ | 2015/08/16 | [
"https://math.stackexchange.com/questions/1399204",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/262417/"
] | $$\begin{align\*}
\cos^2x-\sin^2x &= \cos3x\\
\cos2x &= \cos3x\\
2x &= 2\pi n\pm 3x\\
x &= 2\pi n \text{ or } x=\frac{2\pi n}{5}
\end{align\*}$$
where $n\in\mathbb Z$.
@ThomasAndrews: The second case includes the first case. $2\pi n=\frac{2\pi(5n)}5$. | **Hint:** Use the trigonometry identity for the $\cos 2\theta$. |
1,399,204 | Please help in Solving the Trigonometric Equation:
$$\cos^2x - \sin^2x = \cos3x$$ | 2015/08/16 | [
"https://math.stackexchange.com/questions/1399204",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/262417/"
] | $$
\cos 3x=\cos x \cos x - \sin x \sin x= \cos 2x,
$$
which is equivalent to
$$
3x\pm 2x = 2k\pi
$$
for some integer $k$. | **Hint:** Use the trigonometry identity for the $\cos 2\theta$. |
1,399,204 | Please help in Solving the Trigonometric Equation:
$$\cos^2x - \sin^2x = \cos3x$$ | 2015/08/16 | [
"https://math.stackexchange.com/questions/1399204",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/262417/"
] | $$\begin{align\*}
\cos^2x-\sin^2x &= \cos3x\\
\cos2x &= \cos3x\\
2x &= 2\pi n\pm 3x\\
x &= 2\pi n \text{ or } x=\frac{2\pi n}{5}
\end{align\*}$$
where $n\in\mathbb Z$.
@ThomasAndrews: The second case includes the first case. $2\pi n=\frac{2\pi(5n)}5$. | $$\cos^2 x-\sin^2 x = \cos 3x$$
Now Using the formula $\cos2x = \cos^2 x-\sin^2 x$
So $$\cos 2x = \cos 3x\Rightarrow \cos3x = \cos 2x\Rightarrow 3x = 2n\pi\pm 2x$$
Where $n\in \mathbb{Z}\;,$ above we have used the formula $$\cos x = \cos \alpha \;,$$ Then $x=2n\pi\pm \alpha\;,$ Where $n\in \mathbb{Z}$
So Solutions are $3x = 2n\pi+2x$ or $3x = 2n\pi-2x$$
So we get $x=2n\pi$ or $\displaystyle x = \frac{2n\pi}{5}\;,$ Where $n\in \mathbb{Z}$
So Final Solution is $\displaystyle x= \frac{2n\pi}{5}\;,$ |
1,399,204 | Please help in Solving the Trigonometric Equation:
$$\cos^2x - \sin^2x = \cos3x$$ | 2015/08/16 | [
"https://math.stackexchange.com/questions/1399204",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/262417/"
] | $$\begin{align\*}
\cos^2x-\sin^2x &= \cos3x\\
\cos2x &= \cos3x\\
2x &= 2\pi n\pm 3x\\
x &= 2\pi n \text{ or } x=\frac{2\pi n}{5}
\end{align\*}$$
where $n\in\mathbb Z$.
@ThomasAndrews: The second case includes the first case. $2\pi n=\frac{2\pi(5n)}5$. | $$
\cos 3x=\cos x \cos x - \sin x \sin x= \cos 2x,
$$
which is equivalent to
$$
3x\pm 2x = 2k\pi
$$
for some integer $k$. |
1,399,204 | Please help in Solving the Trigonometric Equation:
$$\cos^2x - \sin^2x = \cos3x$$ | 2015/08/16 | [
"https://math.stackexchange.com/questions/1399204",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/262417/"
] | $$\begin{align\*}
\cos^2x-\sin^2x &= \cos3x\\
\cos2x &= \cos3x\\
2x &= 2\pi n\pm 3x\\
x &= 2\pi n \text{ or } x=\frac{2\pi n}{5}
\end{align\*}$$
where $n\in\mathbb Z$.
@ThomasAndrews: The second case includes the first case. $2\pi n=\frac{2\pi(5n)}5$. | As others have mentioned you should be after the roots of $\cos(3x)-\cos(2x)=0$. To continue from here you may use the identity $\cos \theta-\cos \alpha=-2\sin\frac{\theta-\alpha}{2}\sin\frac{\theta+\alpha}{2}$, i.e.
$$\cos(3x)-\cos(2x)=-2\sin\frac{5x}{2}\sin\frac{x}{2}$$ |
1,399,204 | Please help in Solving the Trigonometric Equation:
$$\cos^2x - \sin^2x = \cos3x$$ | 2015/08/16 | [
"https://math.stackexchange.com/questions/1399204",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/262417/"
] | $$
\cos 3x=\cos x \cos x - \sin x \sin x= \cos 2x,
$$
which is equivalent to
$$
3x\pm 2x = 2k\pi
$$
for some integer $k$. | $$\cos^2 x-\sin^2 x = \cos 3x$$
Now Using the formula $\cos2x = \cos^2 x-\sin^2 x$
So $$\cos 2x = \cos 3x\Rightarrow \cos3x = \cos 2x\Rightarrow 3x = 2n\pi\pm 2x$$
Where $n\in \mathbb{Z}\;,$ above we have used the formula $$\cos x = \cos \alpha \;,$$ Then $x=2n\pi\pm \alpha\;,$ Where $n\in \mathbb{Z}$
So Solutions are $3x = 2n\pi+2x$ or $3x = 2n\pi-2x$$
So we get $x=2n\pi$ or $\displaystyle x = \frac{2n\pi}{5}\;,$ Where $n\in \mathbb{Z}$
So Final Solution is $\displaystyle x= \frac{2n\pi}{5}\;,$ |
1,399,204 | Please help in Solving the Trigonometric Equation:
$$\cos^2x - \sin^2x = \cos3x$$ | 2015/08/16 | [
"https://math.stackexchange.com/questions/1399204",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/262417/"
] | $$
\cos 3x=\cos x \cos x - \sin x \sin x= \cos 2x,
$$
which is equivalent to
$$
3x\pm 2x = 2k\pi
$$
for some integer $k$. | As others have mentioned you should be after the roots of $\cos(3x)-\cos(2x)=0$. To continue from here you may use the identity $\cos \theta-\cos \alpha=-2\sin\frac{\theta-\alpha}{2}\sin\frac{\theta+\alpha}{2}$, i.e.
$$\cos(3x)-\cos(2x)=-2\sin\frac{5x}{2}\sin\frac{x}{2}$$ |
4,642,372 | Working over the real line, I am interested in the integral of the form
$$
I := \int\_a^b dx \int\_a^x dy f(y) \delta'(y),
$$
where $a < 0 < b < \infty$, $f$ is some smooth test function with compact support such that $(a,b) \subset supp(f)$, and $\delta$ is the usual Dirac delta "function".
At first, when attempting to evaluate this integral, I naively used that $\delta'(f) = -\delta(f')=-f'(0)$ so that the above integral would evaluate to $(a-b) f'(0)$.
However, looking at it more closely, the result $\delta'(f) = -\delta(f')$ which can be attributed to "integration by parts", is really only working if the integration is actually over the support of $f$. This is not the case for the first integral.
Instead, I modified the relation such that
$$
I = \int\_a^b dx \left( [f(y) \delta(y)]\_a^x - \int\_a^x dyf'(y) \delta(y) \right)= \int\_a^b dx \left(f(x) \delta(x) - f'(0) \right) = f(0) + (a-b) f'(0).
$$
Is this the correct way to do this? I simply generalised the "integration by parts" rule. Is there a rigourous explanation why this is the correct answer? | 2023/02/19 | [
"https://math.stackexchange.com/questions/4642372",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/604598/"
] | To expand a first-order theory to a second-order theory conservatively (i.e. without adding new first-order definable sets) you have to add a sort for every "definition-scheme". I.e. a sort for every partitioned formula $\varphi(x;y)$.
The canonical expansion of a first-order structure $M$ has, beside the domain of the home sort $M$, a domain for each sort $\varphi(x;y)$ that contains (as elements) the sets $\varphi(U;b)$ where $U$ is a large saturated extension of $M$ and $b∈ M^y$.
In the language of of $M$ is expanded with the membership relations.
---
You find the construction above, with all the gory details, in the Section 13.2 (*The eq-expansion*) of [these notes](https://github.com/domenicozambella/creche/raw/master/PDF/creche.pdf).
In the notes a second-order expansion is used to construct (a version of) Shelah's $T^{\rm eq}$.
If I understand it well, this comes close to the expansion you are proposing, only much tamer form the model-theoretic point of view. | **Attempt** (*community wiki*):
Note that for 2. I've been sloppy in declaring that $\mathfrak{F} \subseteq \mathcal{P}(\mathfrak{M})$ because the Tarskian semantics for multi-sorted logic don't require that. In general $\mathfrak{F}$ could be any set.
However, my understanding is that one can assume without loss of generality that $\mathfrak{F} \subseteq \mathcal{P}(\mathcal{M})$, in the following way.
Let's say we have some structure $\tilde{\mathfrak{F}}$ for the collections (that may or may not consist of subsets of $\mathfrak{M}$). Then we can define a (possibly new) structure $\mathfrak{F} \subseteq \mathcal{P}(\mathfrak{M})$ via the map $\tilde{\mathfrak{F}} \to \mathfrak{F}$ with rule of assignment
$$ \tilde{f} \mapsto \{ m \in \mathfrak{M}: \tilde{E}(m, \tilde{f}) \} ,$$
where $\tilde{E}$ is the interpretation of $\tilde{\in}$ in $\tilde{\mathfrak{F}}$. (I guess I also left it implicit in the question that the interpretation of $\tilde{\in}$ in any $\mathfrak{F} \subseteq \mathcal{P}(\mathfrak{M})$ would be the restriction of $\in$ of the ambient set theory.)
Anyway, regarding 1., I am not sure at all how one would prove it via proof-theoretic means, although presumably there is a way. My understanding though is that if one can prove that the answer to 2. is correct, then the combination of the soundness and completeness theorem would mean that the model-theoretic result also implicitly proves the proof-theoretic result 1.
Specifically, I am asserting that if it is true that all models of $\tilde{T}$ have as their first-order part a model of $T$, and that for every model of $T$ there is at least one corresponding model of $\tilde{T}$ with that as its first-order part, then by the Godel completeness theorem this means that the only things $\tilde{T}$ can prove about statements restricted to $\mathcal{L}$ are those that can be proved by $T$, i.e. $\tilde{T}$ is conservative over $T$. I'm not really certain whether that's correct or precise enough.
So for proving 2., the general idea would be that presumably the only new atomic formulas that are introduced by augmenting $\mathcal{L}$ to $\tilde{\mathcal{L}}$ are of the form $o \tilde{\in} c$. But (1) I'm not sure whether it's *really* true that those are the only new atomic formulas, or whether others are "sneaking in" that I'm not noticing, and (2) if they are the only ones, how to prove that that's the case.
If it's true, then basically the proof strategy would be to try to show that all such atomic formulas $o \tilde{\in} c$ can be "eliminated", or replaced with statements entirely in $\mathcal{L}$ which are proven by $T$.
This seems to divide into three cases: (1) $c$ corresponds to a (explicitly defined) wff. $\psi$ via the axiom schema, (2a) $c$ does not correspond to a wff. but does correspond to an implicitly defined formula, (2b) $c$ does not correspond to any sort of formula.
This is where I start to have a lot of confusion, which seems to be related to that expressed [in this other related question](https://math.stackexchange.com/questions/539105/second-order-logic-and-quantification-over-formulas). Specifically regarding (2b), which I can only think of how to potentially address model-theoretically. Because even though our *intended* models for the collections sort $C$ is always $\mathsf{Def}\_{\mathcal{L}}(\mathfrak{M})$, that doesn't mean we can't have models for $C$ that are strict supersets of $\mathsf{Def}\_{\mathcal{L}}(\mathfrak{M})$ (i.e. even when using the trick to force the interpretation of $C$ to be a subset of $\mathcal{P}(\mathfrak{M})$). And for those possible valuations of $C$-sort variables $c$ corresponding to elements $\mathfrak{F} \setminus \mathsf{Def}\_{\mathcal{L}}(\mathfrak{M})$, I am very unsure how, if at all one could reason about them proof-theoretically.
For case (1), the proof seems to be easy, i.e. we basically have a definitorial expansion, because we can replacement the statement $o \in c\_{\psi,\bar{\omega}}$ with the $\mathcal{L}$-sentence $\forall^O \bar{\omega} \psi(o, \bar{\omega})$ (basically the axiom schema was rigged to accomplish this).
For case (2a), apparently the [Beth definability theorem](https://encyclopediaofmath.org/wiki/Beth_definability_theorem) says that in fact it is the same as case (1), i.e. "no new / nonstandard formulas sneak in the back door". (But I seriously doubt I actually understand the statement of the Beth definability theorem, much less whether I am applying it correctly. I certainly don't understand its generalization, the Craig interpolation theorem.)
So again that would seem to only leave (2b) which I can only think to handle model theoretically. But basically because in that case the variable $c$ doesn't even implicitly define a predicate, that seems to mean it would "correspond to a parameter present in the "second-order part" $\mathfrak{F}$ part of some models of $\tilde{T}$ but not present in other models of $\tilde{T}$". (I know that statement doesn't actually make sense.) So then basically we would conclude by the Godel completeness theorem that $\tilde{T}$ can not prove anything about statements involving it, in particular the one we care about $o \tilde{\in} c$? And because apparently $\tilde{T}$ can't prove anything about $o \tilde{\in} c$ in that case, it would follow that $\tilde{T}$ can't use it to prove anything over the sublanguage $\mathcal{L} \subseteq \tilde{\mathcal{L}}$. So in this case too the collection of true sentences over $\mathcal{L}$ is not expanded by $\tilde{T}$?
So assuming the argument for (2b) is actually correct, we would get a proof that no additional statements in the language $\mathcal{L}$ are proved by $\tilde{T}$, and thus that $\tilde{T}$ is conservative over $T$? |
47,486 | I have a friction damping system which is exited by a harmonic force FE (depicted on the left side).
Is there a way to convert the friction damper to a linear or nonlinear damper, such that the damping at a given excitement frequency is equal?
I am only considering sliding friction.
A reasonable approximation would be sufficient as well.
Any papers or articles on the topic would also be highly appreciated.
[](https://i.stack.imgur.com/YkzOK.png) | 2021/09/29 | [
"https://engineering.stackexchange.com/questions/47486",
"https://engineering.stackexchange.com",
"https://engineering.stackexchange.com/users/25247/"
] | The problem when trying to replace coulomb damping (friction) with viscous damping is that it produces a relatively constant force ($- \mu \cdot N$). (the sign is opposite to the sign of the velocity).
Viscous damping on the other hand is proportional to the velocity. $c\cdot \dot{x}$.
Therefore, its not always possible to substitute the one for the other.
---
A way to represent the equation of motion is
$$m \ddot {x} + kx = -\mu \cdot m\cdot g \frac{|\dot{x}|}{\dot{x}}$$
The presence of the absolute value makes this DE difficult to solve analytically, so the most common solution is numerical.
---
Regarding references:
* S. Graham Kelly - Mechanical Vibrations: Theory and Applications SI edition, has a section (3.7) devoted in coulomb damping. It discusses the formulation and also the solution.
Inman (Engineering Vibration) and Rao (mechanical vibrations) also have sections with coulomb damping. | I think a hydraulic device could approximate it.
General concept: For each direction: a spring-loaded check valve (ie with a cracking pressure) in series with a small-diameter-tube would realize a roughly constant pressure difference, as long as there is some very small flow (i.e. cylinder movement). This could then operate a pilot valve, opening the larger main valve, allowing much more flow once the pre-set amount of pressure (i.e. force on the cylinder) is reached.
[](https://i.stack.imgur.com/nYqdX.jpg)
(it wouldn't be this neat in a real implementation) |
47,486 | I have a friction damping system which is exited by a harmonic force FE (depicted on the left side).
Is there a way to convert the friction damper to a linear or nonlinear damper, such that the damping at a given excitement frequency is equal?
I am only considering sliding friction.
A reasonable approximation would be sufficient as well.
Any papers or articles on the topic would also be highly appreciated.
[](https://i.stack.imgur.com/YkzOK.png) | 2021/09/29 | [
"https://engineering.stackexchange.com/questions/47486",
"https://engineering.stackexchange.com",
"https://engineering.stackexchange.com/users/25247/"
] | In general this is impossible, because for a given value of $F\_e$, the friction damper dissipates a fixed amount of energy per cycle of vibration *independent of the vibration frequency.*
This is (nonlinear) *hysteretic* damping, not (nonlinear) *viscous* damping.
The only way to approximate this with a viscous damper would be to make $C$ a function of both the $F\_e$ and the frequency $\omega$, which won't produce a useful equation of motion except in the special case where the machine only operates at one fixed frequency $\omega$.
Aside from that issue, a general way to make the approximation is to model one cycle of the stick-slip motion of the friction damper and find the energy dissipated during the cycle. Then choose $C$ to dissipate the same amount of energy.
For a simple slip-stick damper you can do this from first principles, though the details are messy, and you need the complete equation of motion of the system - you haven't specified how the mass and/or stiffness are connected to the damper.
A more general approach is to use the so-called Harmonic Balance Method to produce a numerical approximation. There are many variations on the basic idea (and many research papers describing them!) but one implementation is the NLVib function in Matlab. | The problem when trying to replace coulomb damping (friction) with viscous damping is that it produces a relatively constant force ($- \mu \cdot N$). (the sign is opposite to the sign of the velocity).
Viscous damping on the other hand is proportional to the velocity. $c\cdot \dot{x}$.
Therefore, its not always possible to substitute the one for the other.
---
A way to represent the equation of motion is
$$m \ddot {x} + kx = -\mu \cdot m\cdot g \frac{|\dot{x}|}{\dot{x}}$$
The presence of the absolute value makes this DE difficult to solve analytically, so the most common solution is numerical.
---
Regarding references:
* S. Graham Kelly - Mechanical Vibrations: Theory and Applications SI edition, has a section (3.7) devoted in coulomb damping. It discusses the formulation and also the solution.
Inman (Engineering Vibration) and Rao (mechanical vibrations) also have sections with coulomb damping. |
47,486 | I have a friction damping system which is exited by a harmonic force FE (depicted on the left side).
Is there a way to convert the friction damper to a linear or nonlinear damper, such that the damping at a given excitement frequency is equal?
I am only considering sliding friction.
A reasonable approximation would be sufficient as well.
Any papers or articles on the topic would also be highly appreciated.
[](https://i.stack.imgur.com/YkzOK.png) | 2021/09/29 | [
"https://engineering.stackexchange.com/questions/47486",
"https://engineering.stackexchange.com",
"https://engineering.stackexchange.com/users/25247/"
] | In general this is impossible, because for a given value of $F\_e$, the friction damper dissipates a fixed amount of energy per cycle of vibration *independent of the vibration frequency.*
This is (nonlinear) *hysteretic* damping, not (nonlinear) *viscous* damping.
The only way to approximate this with a viscous damper would be to make $C$ a function of both the $F\_e$ and the frequency $\omega$, which won't produce a useful equation of motion except in the special case where the machine only operates at one fixed frequency $\omega$.
Aside from that issue, a general way to make the approximation is to model one cycle of the stick-slip motion of the friction damper and find the energy dissipated during the cycle. Then choose $C$ to dissipate the same amount of energy.
For a simple slip-stick damper you can do this from first principles, though the details are messy, and you need the complete equation of motion of the system - you haven't specified how the mass and/or stiffness are connected to the damper.
A more general approach is to use the so-called Harmonic Balance Method to produce a numerical approximation. There are many variations on the basic idea (and many research papers describing them!) but one implementation is the NLVib function in Matlab. | I think a hydraulic device could approximate it.
General concept: For each direction: a spring-loaded check valve (ie with a cracking pressure) in series with a small-diameter-tube would realize a roughly constant pressure difference, as long as there is some very small flow (i.e. cylinder movement). This could then operate a pilot valve, opening the larger main valve, allowing much more flow once the pre-set amount of pressure (i.e. force on the cylinder) is reached.
[](https://i.stack.imgur.com/nYqdX.jpg)
(it wouldn't be this neat in a real implementation) |
43,621,532 | I'm trying to release a Xamarin.Forms application, but when I change to release in the configuration for the Android project and build I get the following error:
```
Java.Interop.Tools.Diagnostics.XamarinAndroidException: error XA2006: Could not resolve reference to 'System.Int32 Xamarin.Forms.Platform.Resource/String::ApplicationName' (defined in assembly 'Syncfusion.SfChart.XForms.Android, Version=13.2451.0.29, Culture=neutral, PublicKeyToken=null') with scope 'Xamarin.Forms.Platform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. When the scope is different from the defining assembly, it usually means that the type is forwarded. ---> Mono.Cecil.ResolutionException: Failed to resolve System.Int32 Xamarin.Forms.Platform.Resource/String::ApplicationName
at Mono.Linker.Steps.MarkStep.MarkField(FieldReference reference)
at Mono.Linker.Steps.MarkStep.MarkInstruction(Instruction instruction)
at Mono.Linker.Steps.MarkStep.MarkMethodBody(MethodBody body)
at Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method)
at Mono.Linker.Steps.MarkStep.ProcessQueue()
at Mono.Linker.Steps.MarkStep.Process()
at Mono.Linker.Steps.MarkStep.Process(LinkContext context)
at MonoDroid.Tuner.MonoDroidMarkStep.Process(LinkContext context)
at Mono.Linker.Pipeline.Process(LinkContext context)
at MonoDroid.Tuner.Linker.Process(LinkerOptions options, LinkContext& context)
at Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res)
--- End of inner exception stack trace ---
at Java.Interop.Tools.Diagnostics.Diagnostic.Error(Int32 code, Exception innerException, String message, Object[] args)
at Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res)
at Xamarin.Android.Tasks.LinkAssemblies.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() XamarinCRM.Android
``` | 2017/04/25 | [
"https://Stackoverflow.com/questions/43621532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The same error message occurred with me. I was able to solve it like this:
Right-click the **Android Project > Properties > Android Options > Linker**, and then choose the "None" option in the **Linking** property. | We suspect that there are some version conflicts between **Syncfusion/Xamarin.Forms assemblies** and we kindly request you to follow the below steps.
1. Update your **Essential Studio for Xamarin** to latest version **(15.1.0.41)** which can be downloaded from the following location.
**Link:** <https://www.syncfusion.com/downloads/version-history/15_1_0_41>
2. Update your Xamarin.Forms version to 2.3.3.180.
Please get back to us if you are still facing any issues. |
7,581,534 | The following linq
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
throws an exception since some `row["EXM_MARKS"]` has non numeric values like `AB` etc.
How can I get the sum of only numeric ones out of them? | 2011/09/28 | [
"https://Stackoverflow.com/questions/7581534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769091/"
] | For linq to sql queries you can use built-in `SqlFunctions.IsNumeric`
Source: [SqlFunctions.IsNumeric](https://learn.microsoft.com/en-us/dotnet/api/system.data.objects.sqlclient.sqlfunctions.isnumeric?view=netframework-4.7.2) | You can make some extensions utility class like this for elegant solution:
```
public static class TypeExtensions
{
public static bool IsValidDecimal(this string s)
{
decimal result;
return Decimal.TryParse(s, out result);
}
}
```
and use it in this way:
```
var subjectMarks = (from DataRow row in objDatatable.Rows
where row["EXM_MARKS"].IsValidDecimal()
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
Hope this helps. |
7,581,534 | The following linq
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
throws an exception since some `row["EXM_MARKS"]` has non numeric values like `AB` etc.
How can I get the sum of only numeric ones out of them? | 2011/09/28 | [
"https://Stackoverflow.com/questions/7581534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769091/"
] | Add `where` clause that filters out the records that cannot be parsed as decimals. Try:
```
decimal dummy;
var subjectMarks = (from DataRow row in objDatatable.Rows
where decimal.TryParse(row["EXM_MARKS"], out dummy)
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
``` | ```
var subjectMarks = objDatatable.Rows.Where(row => row["EXM_MARKS"].ToString().All(char.isDigit))
```
part of solution is getted in: [here](https://stackoverflow.com/questions/4524957/how-to-check-if-my-string-only-numeric) |
7,581,534 | The following linq
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
throws an exception since some `row["EXM_MARKS"]` has non numeric values like `AB` etc.
How can I get the sum of only numeric ones out of them? | 2011/09/28 | [
"https://Stackoverflow.com/questions/7581534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769091/"
] | You can make some extensions utility class like this for elegant solution:
```
public static class TypeExtensions
{
public static bool IsValidDecimal(this string s)
{
decimal result;
return Decimal.TryParse(s, out result);
}
}
```
and use it in this way:
```
var subjectMarks = (from DataRow row in objDatatable.Rows
where row["EXM_MARKS"].IsValidDecimal()
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
Hope this helps. | ```
var subjectMarks = objDatatable.Rows.Where(row => row["EXM_MARKS"].ToString().All(char.isDigit))
```
part of solution is getted in: [here](https://stackoverflow.com/questions/4524957/how-to-check-if-my-string-only-numeric) |
7,581,534 | The following linq
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
throws an exception since some `row["EXM_MARKS"]` has non numeric values like `AB` etc.
How can I get the sum of only numeric ones out of them? | 2011/09/28 | [
"https://Stackoverflow.com/questions/7581534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769091/"
] | Add `where` clause that filters out the records that cannot be parsed as decimals. Try:
```
decimal dummy;
var subjectMarks = (from DataRow row in objDatatable.Rows
where decimal.TryParse(row["EXM_MARKS"], out dummy)
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
``` | For LINQ to SQL queries with Entity Framework Core, [`ISNUMERIC`](https://learn.microsoft.com/en-us/sql/t-sql/functions/isnumeric-transact-sql?view=sql-server-ver16) function is part of EF Core 6.0 under [EF.Functions](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.sqlserverdbfunctionsextensions.isnumeric?view=efcore-6.0#microsoft-entityframeworkcore-sqlserverdbfunctionsextensions-isnumeric(microsoft-entityframeworkcore-dbfunctions-system-string))
Before version 6.0, you can create a user-defined function mapping !
[`User-defined function mapping`](https://learn.microsoft.com/en-us/ef/core/querying/user-defined-function-mapping) : Apart from mappings provided by EF Core providers, users can also define custom mapping. A user-defined mapping extends the query translation according to the user needs. This functionality is useful when there are user-defined functions in the database, which the user wants to invoke from their LINQ query for example.
```
await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();
_ = await ctx.Blogs.Where(b => ctx.IsNumeric(b.Name)).ToListAsync();
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
static ILoggerFactory ContextLoggerFactory
=> LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
.EnableSensitiveDataLogging()
.UseLoggerFactory(ContextLoggerFactory);
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDbFunction(IsNumericMethodInfo)
.HasName("ISNUMERIC")
.IsBuiltIn();
}
private static readonly MethodInfo IsNumericMethodInfo = typeof(BlogContext)
.GetRuntimeMethod(nameof(IsNumeric), new[] { typeof(string) });
public bool IsNumeric(string s) => throw new NotSupportedException();
}
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
}
``` |
7,581,534 | The following linq
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
throws an exception since some `row["EXM_MARKS"]` has non numeric values like `AB` etc.
How can I get the sum of only numeric ones out of them? | 2011/09/28 | [
"https://Stackoverflow.com/questions/7581534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769091/"
] | use
```
Decimal Z;
var subjectMarks = (from DataRow row in objDatatable.Rows
where Decimal.TryParse (row["EXM_MARKS"], out Z)
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
``` | For LINQ to SQL queries with Entity Framework Core, [`ISNUMERIC`](https://learn.microsoft.com/en-us/sql/t-sql/functions/isnumeric-transact-sql?view=sql-server-ver16) function is part of EF Core 6.0 under [EF.Functions](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.sqlserverdbfunctionsextensions.isnumeric?view=efcore-6.0#microsoft-entityframeworkcore-sqlserverdbfunctionsextensions-isnumeric(microsoft-entityframeworkcore-dbfunctions-system-string))
Before version 6.0, you can create a user-defined function mapping !
[`User-defined function mapping`](https://learn.microsoft.com/en-us/ef/core/querying/user-defined-function-mapping) : Apart from mappings provided by EF Core providers, users can also define custom mapping. A user-defined mapping extends the query translation according to the user needs. This functionality is useful when there are user-defined functions in the database, which the user wants to invoke from their LINQ query for example.
```
await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();
_ = await ctx.Blogs.Where(b => ctx.IsNumeric(b.Name)).ToListAsync();
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
static ILoggerFactory ContextLoggerFactory
=> LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
.EnableSensitiveDataLogging()
.UseLoggerFactory(ContextLoggerFactory);
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDbFunction(IsNumericMethodInfo)
.HasName("ISNUMERIC")
.IsBuiltIn();
}
private static readonly MethodInfo IsNumericMethodInfo = typeof(BlogContext)
.GetRuntimeMethod(nameof(IsNumeric), new[] { typeof(string) });
public bool IsNumeric(string s) => throw new NotSupportedException();
}
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
}
``` |
7,581,534 | The following linq
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
throws an exception since some `row["EXM_MARKS"]` has non numeric values like `AB` etc.
How can I get the sum of only numeric ones out of them? | 2011/09/28 | [
"https://Stackoverflow.com/questions/7581534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769091/"
] | For linq to sql queries you can use built-in `SqlFunctions.IsNumeric`
Source: [SqlFunctions.IsNumeric](https://learn.microsoft.com/en-us/dotnet/api/system.data.objects.sqlclient.sqlfunctions.isnumeric?view=netframework-4.7.2) | use
```
Decimal Z;
var subjectMarks = (from DataRow row in objDatatable.Rows
where Decimal.TryParse (row["EXM_MARKS"], out Z)
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
``` |
7,581,534 | The following linq
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
throws an exception since some `row["EXM_MARKS"]` has non numeric values like `AB` etc.
How can I get the sum of only numeric ones out of them? | 2011/09/28 | [
"https://Stackoverflow.com/questions/7581534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769091/"
] | You could create an extension method `SafeConvertToDecimal` and use this in your LINQ query:
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select row["EXM_MARKS"].SafeConvertToDecimal()).Sum();
```
This extension method would look like this:
```
public static decimal SafeConvertToDecimal(this object obj)
{
decimal result;
if(!decimal.TryParse(obj.ToString(), out result))
result = 0;
return result;
}
```
This approach has the advantage that it looks clean and you aren't converting each object twice as do all other answers. | ```
var subjectMarks = objDatatable.Rows.Where(row => row["EXM_MARKS"].ToString().All(char.isDigit))
```
part of solution is getted in: [here](https://stackoverflow.com/questions/4524957/how-to-check-if-my-string-only-numeric) |
7,581,534 | The following linq
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
throws an exception since some `row["EXM_MARKS"]` has non numeric values like `AB` etc.
How can I get the sum of only numeric ones out of them? | 2011/09/28 | [
"https://Stackoverflow.com/questions/7581534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769091/"
] | Add `where` clause that filters out the records that cannot be parsed as decimals. Try:
```
decimal dummy;
var subjectMarks = (from DataRow row in objDatatable.Rows
where decimal.TryParse(row["EXM_MARKS"], out dummy)
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
``` | You could create an extension method `SafeConvertToDecimal` and use this in your LINQ query:
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select row["EXM_MARKS"].SafeConvertToDecimal()).Sum();
```
This extension method would look like this:
```
public static decimal SafeConvertToDecimal(this object obj)
{
decimal result;
if(!decimal.TryParse(obj.ToString(), out result))
result = 0;
return result;
}
```
This approach has the advantage that it looks clean and you aren't converting each object twice as do all other answers. |
7,581,534 | The following linq
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
throws an exception since some `row["EXM_MARKS"]` has non numeric values like `AB` etc.
How can I get the sum of only numeric ones out of them? | 2011/09/28 | [
"https://Stackoverflow.com/questions/7581534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769091/"
] | You could create an extension method `SafeConvertToDecimal` and use this in your LINQ query:
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select row["EXM_MARKS"].SafeConvertToDecimal()).Sum();
```
This extension method would look like this:
```
public static decimal SafeConvertToDecimal(this object obj)
{
decimal result;
if(!decimal.TryParse(obj.ToString(), out result))
result = 0;
return result;
}
```
This approach has the advantage that it looks clean and you aren't converting each object twice as do all other answers. | You can make some extensions utility class like this for elegant solution:
```
public static class TypeExtensions
{
public static bool IsValidDecimal(this string s)
{
decimal result;
return Decimal.TryParse(s, out result);
}
}
```
and use it in this way:
```
var subjectMarks = (from DataRow row in objDatatable.Rows
where row["EXM_MARKS"].IsValidDecimal()
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
Hope this helps. |
7,581,534 | The following linq
```
var subjectMarks = (from DataRow row in objDatatable.Rows
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
```
throws an exception since some `row["EXM_MARKS"]` has non numeric values like `AB` etc.
How can I get the sum of only numeric ones out of them? | 2011/09/28 | [
"https://Stackoverflow.com/questions/7581534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769091/"
] | For linq to sql queries you can use built-in `SqlFunctions.IsNumeric`
Source: [SqlFunctions.IsNumeric](https://learn.microsoft.com/en-us/dotnet/api/system.data.objects.sqlclient.sqlfunctions.isnumeric?view=netframework-4.7.2) | For LINQ to SQL queries with Entity Framework Core, [`ISNUMERIC`](https://learn.microsoft.com/en-us/sql/t-sql/functions/isnumeric-transact-sql?view=sql-server-ver16) function is part of EF Core 6.0 under [EF.Functions](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.sqlserverdbfunctionsextensions.isnumeric?view=efcore-6.0#microsoft-entityframeworkcore-sqlserverdbfunctionsextensions-isnumeric(microsoft-entityframeworkcore-dbfunctions-system-string))
Before version 6.0, you can create a user-defined function mapping !
[`User-defined function mapping`](https://learn.microsoft.com/en-us/ef/core/querying/user-defined-function-mapping) : Apart from mappings provided by EF Core providers, users can also define custom mapping. A user-defined mapping extends the query translation according to the user needs. This functionality is useful when there are user-defined functions in the database, which the user wants to invoke from their LINQ query for example.
```
await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();
_ = await ctx.Blogs.Where(b => ctx.IsNumeric(b.Name)).ToListAsync();
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
static ILoggerFactory ContextLoggerFactory
=> LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
.EnableSensitiveDataLogging()
.UseLoggerFactory(ContextLoggerFactory);
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDbFunction(IsNumericMethodInfo)
.HasName("ISNUMERIC")
.IsBuiltIn();
}
private static readonly MethodInfo IsNumericMethodInfo = typeof(BlogContext)
.GetRuntimeMethod(nameof(IsNumeric), new[] { typeof(string) });
public bool IsNumeric(string s) => throw new NotSupportedException();
}
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
}
``` |
53,124 | What I understand of these two terms is that:
Paratope is a portion of antibody that recognises and binds to specific antigen.
Idiotype is an antigenic determinant of antibody formed of CDRs that have specificity for a particular epitope. Some authors call the antibodies recognising a particular epitope an idiotype.
Well the CDRs, they actually form the paratope so is it right to say the CDR that acts as an paratope also forms the idiotypic determinant/ idiotype ? | 2016/11/04 | [
"https://biology.stackexchange.com/questions/53124",
"https://biology.stackexchange.com",
"https://biology.stackexchange.com/users/16460/"
] | I have read that the unique amino acid sequence of the VH and VL domains of a given antibody can function not only as an antigen-binding site but also as a set of antigenic determinants. the idiotypic determinants are generated by the confomation of the heavy- and light-chain variable region. Each individual antigenic determinant of the variable region is referred to as an idiotope. In some cases an idiotope may be the actual antigen-binding site (The paratope), and in some cases an idiotope may comprise variable region sequences OUTSIDE of the antigen-binding site. Therefore, each antibody will present multiple idiotopes, and the sum of the individual idiotopes is called the IDIOTYPE of the antibody.
I hope that had been helpful | The following was a reply by an expert from assignmentexpert.com :
>
> Paratope is only the part of Ab that binds to the epitope of an antigen. But this does not mean that every amino acid in the CDR should bind to epitope – it is possible that only 1-2 AAs per CDR bind directly to epitope.
> Therefore, paratope is the part of the idiotype that binds to the epitope.
>
>
> |
20,129,762 | In Java 8 we have the class [Stream<T>](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), which curiously have a method
```
Iterator<T> iterator()
```
So you would expect it to implement interface [Iterable<T>](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html), which requires exactly this method, but that's not the case.
When I want to iterate over a Stream using a foreach loop, I have to do something like
```
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
```
Am I missing something here? | 2013/11/21 | [
"https://Stackoverflow.com/questions/20129762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938782/"
] | To convert a `Stream` to an `Iterable`, you can do
```
Stream<X> stream = null;
Iterable<X> iterable = stream::iterator
```
To pass a `Stream` to a method that expects `Iterable`,
```
void foo(Iterable<X> iterable)
```
simply
```
foo(stream::iterator)
```
however it probably looks funny; it might be better to be a little bit more explicit
```
foo( (Iterable<X>)stream::iterator );
``` | You can use a Stream in a `for` loop as follows:
```
Stream<T> stream = ...;
for (T x : (Iterable<T>) stream::iterator) {
...
}
```
(Run [this snippet here](http://ideone.com/45QSHu))
(This uses a Java 8 functional interface cast.)
(This is covered in some of the comments above (e.g. [Aleksandr Dubinsky](https://stackoverflow.com/questions/20129762/why-does-streamt-not-implement-iterablet#comment30152645_20130475)), but I wanted to pull it out into an answer to make it more visible.) |
20,129,762 | In Java 8 we have the class [Stream<T>](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), which curiously have a method
```
Iterator<T> iterator()
```
So you would expect it to implement interface [Iterable<T>](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html), which requires exactly this method, but that's not the case.
When I want to iterate over a Stream using a foreach loop, I have to do something like
```
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
```
Am I missing something here? | 2013/11/21 | [
"https://Stackoverflow.com/questions/20129762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938782/"
] | To convert a `Stream` to an `Iterable`, you can do
```
Stream<X> stream = null;
Iterable<X> iterable = stream::iterator
```
To pass a `Stream` to a method that expects `Iterable`,
```
void foo(Iterable<X> iterable)
```
simply
```
foo(stream::iterator)
```
however it probably looks funny; it might be better to be a little bit more explicit
```
foo( (Iterable<X>)stream::iterator );
``` | `Stream` does not implement `Iterable`. The general understanding of `Iterable` is anything that can be iterated upon, often again and again. `Stream` may not be replayable.
The only workaround that I can think of, where an iterable based on a stream is replayable too, is to re-create the stream. I am using a `Supplier` below to create a new instance of stream, everytime a new iterator is created.
```
Supplier<Stream<Integer>> streamSupplier = () -> Stream.of(10);
Iterable<Integer> iterable = () -> streamSupplier.get().iterator();
for(int i : iterable) {
System.out.println(i);
}
// Can iterate again
for(int i : iterable) {
System.out.println(i);
}
``` |
20,129,762 | In Java 8 we have the class [Stream<T>](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), which curiously have a method
```
Iterator<T> iterator()
```
So you would expect it to implement interface [Iterable<T>](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html), which requires exactly this method, but that's not the case.
When I want to iterate over a Stream using a foreach loop, I have to do something like
```
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
```
Am I missing something here? | 2013/11/21 | [
"https://Stackoverflow.com/questions/20129762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938782/"
] | [kennytm described](https://stackoverflow.com/a/20130131/1188377) why it's unsafe to treat a `Stream` as an `Iterable`, and [Zhong Yu offered a workaround](https://stackoverflow.com/a/20130475/1188377) that permits using a `Stream` as in `Iterable`, albeit in an unsafe manner. It's possible to get the best of both worlds: a reusable `Iterable` from a `Stream` that meets all the guarantees made by the `Iterable` specification.
**Note: `SomeType` is not a type parameter here--you need to replace it with a proper type (e.g., `String`) or resort to reflection**
```
Stream<SomeType> stream = ...;
Iterable<SomeType> iterable = stream.collect(toList()):
```
There is one major disadvantage:
The benefits of lazy iteration will be lost. If you planned to immediately iterate over all values in the current thread, any overhead will be negligible. However, if you planned to iterate only partially or in a different thread, this immediate and complete iteration could have unintended consequences.
The big advantage, of course, is that you can reuse the `Iterable`, whereas `(Iterable<SomeType>) stream::iterator` would only permit a single use. If the receiving code will be iterating over the collection multiple times, this is not only necessary, but likely beneficial to performance. | `Stream` does not implement `Iterable`. The general understanding of `Iterable` is anything that can be iterated upon, often again and again. `Stream` may not be replayable.
The only workaround that I can think of, where an iterable based on a stream is replayable too, is to re-create the stream. I am using a `Supplier` below to create a new instance of stream, everytime a new iterator is created.
```
Supplier<Stream<Integer>> streamSupplier = () -> Stream.of(10);
Iterable<Integer> iterable = () -> streamSupplier.get().iterator();
for(int i : iterable) {
System.out.println(i);
}
// Can iterate again
for(int i : iterable) {
System.out.println(i);
}
``` |
20,129,762 | In Java 8 we have the class [Stream<T>](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), which curiously have a method
```
Iterator<T> iterator()
```
So you would expect it to implement interface [Iterable<T>](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html), which requires exactly this method, but that's not the case.
When I want to iterate over a Stream using a foreach loop, I have to do something like
```
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
```
Am I missing something here? | 2013/11/21 | [
"https://Stackoverflow.com/questions/20129762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938782/"
] | Not perfect, but will work:
```
iterable = stream.collect(Collectors.toList());
```
Not perfect because it will fetch all items from the stream and put them into that `List`, which is not exactly what `Iterable` and `Stream` are about. They are supposed to be [lazy](https://en.wikipedia.org/wiki/Lazy_loading). | You can iterate over all files in a folder using `Stream<Path>` like this:
```
Path path = Paths.get("...");
Stream<Path> files = Files.list(path);
for (Iterator<Path> it = files.iterator(); it.hasNext(); )
{
Object file = it.next();
// ...
}
``` |
20,129,762 | In Java 8 we have the class [Stream<T>](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), which curiously have a method
```
Iterator<T> iterator()
```
So you would expect it to implement interface [Iterable<T>](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html), which requires exactly this method, but that's not the case.
When I want to iterate over a Stream using a foreach loop, I have to do something like
```
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
```
Am I missing something here? | 2013/11/21 | [
"https://Stackoverflow.com/questions/20129762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938782/"
] | You can use a Stream in a `for` loop as follows:
```
Stream<T> stream = ...;
for (T x : (Iterable<T>) stream::iterator) {
...
}
```
(Run [this snippet here](http://ideone.com/45QSHu))
(This uses a Java 8 functional interface cast.)
(This is covered in some of the comments above (e.g. [Aleksandr Dubinsky](https://stackoverflow.com/questions/20129762/why-does-streamt-not-implement-iterablet#comment30152645_20130475)), but I wanted to pull it out into an answer to make it more visible.) | If you don't mind using third party libraries [cyclops-react](https://github.com/aol/cyclops-react) defines a Stream that implements both Stream and Iterable and is replayable too (solving the problem [kennytm described](https://stackoverflow.com/a/20130131/1188377)).
```
Stream<String> stream = ReactiveSeq.of("hello","world")
.map(s->"prefix-"+s);
```
or :-
```
Iterable<String> stream = ReactiveSeq.of("hello","world")
.map(s->"prefix-"+s);
stream.forEach(System.out::println);
stream.forEach(System.out::println);
```
[Disclosure I am the lead developer of cyclops-react] |
20,129,762 | In Java 8 we have the class [Stream<T>](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), which curiously have a method
```
Iterator<T> iterator()
```
So you would expect it to implement interface [Iterable<T>](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html), which requires exactly this method, but that's not the case.
When I want to iterate over a Stream using a foreach loop, I have to do something like
```
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
```
Am I missing something here? | 2013/11/21 | [
"https://Stackoverflow.com/questions/20129762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938782/"
] | People have already asked the same [on the mailing list](http://mail.openjdk.java.net/pipermail/lambda-dev/2013-March/008876.html) ☺. The main reason is Iterable also has a re-iterable semantic, while Stream is not.
>
> I think the main reason is that `Iterable` implies reusability, whereas `Stream` is something that can only be used once — more like an `Iterator`.
>
>
> If `Stream` extended `Iterable` then existing code might be surprised when it receives an `Iterable` that throws an `Exception` the
> second time they do `for (element : iterable)`.
>
>
> | You can iterate over all files in a folder using `Stream<Path>` like this:
```
Path path = Paths.get("...");
Stream<Path> files = Files.list(path);
for (Iterator<Path> it = files.iterator(); it.hasNext(); )
{
Object file = it.next();
// ...
}
``` |
20,129,762 | In Java 8 we have the class [Stream<T>](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), which curiously have a method
```
Iterator<T> iterator()
```
So you would expect it to implement interface [Iterable<T>](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html), which requires exactly this method, but that's not the case.
When I want to iterate over a Stream using a foreach loop, I have to do something like
```
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
```
Am I missing something here? | 2013/11/21 | [
"https://Stackoverflow.com/questions/20129762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938782/"
] | To convert a `Stream` to an `Iterable`, you can do
```
Stream<X> stream = null;
Iterable<X> iterable = stream::iterator
```
To pass a `Stream` to a method that expects `Iterable`,
```
void foo(Iterable<X> iterable)
```
simply
```
foo(stream::iterator)
```
however it probably looks funny; it might be better to be a little bit more explicit
```
foo( (Iterable<X>)stream::iterator );
``` | If you don't mind using third party libraries [cyclops-react](https://github.com/aol/cyclops-react) defines a Stream that implements both Stream and Iterable and is replayable too (solving the problem [kennytm described](https://stackoverflow.com/a/20130131/1188377)).
```
Stream<String> stream = ReactiveSeq.of("hello","world")
.map(s->"prefix-"+s);
```
or :-
```
Iterable<String> stream = ReactiveSeq.of("hello","world")
.map(s->"prefix-"+s);
stream.forEach(System.out::println);
stream.forEach(System.out::println);
```
[Disclosure I am the lead developer of cyclops-react] |
20,129,762 | In Java 8 we have the class [Stream<T>](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), which curiously have a method
```
Iterator<T> iterator()
```
So you would expect it to implement interface [Iterable<T>](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html), which requires exactly this method, but that's not the case.
When I want to iterate over a Stream using a foreach loop, I have to do something like
```
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
```
Am I missing something here? | 2013/11/21 | [
"https://Stackoverflow.com/questions/20129762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938782/"
] | `Stream` does not implement `Iterable`. The general understanding of `Iterable` is anything that can be iterated upon, often again and again. `Stream` may not be replayable.
The only workaround that I can think of, where an iterable based on a stream is replayable too, is to re-create the stream. I am using a `Supplier` below to create a new instance of stream, everytime a new iterator is created.
```
Supplier<Stream<Integer>> streamSupplier = () -> Stream.of(10);
Iterable<Integer> iterable = () -> streamSupplier.get().iterator();
for(int i : iterable) {
System.out.println(i);
}
// Can iterate again
for(int i : iterable) {
System.out.println(i);
}
``` | You can iterate over all files in a folder using `Stream<Path>` like this:
```
Path path = Paths.get("...");
Stream<Path> files = Files.list(path);
for (Iterator<Path> it = files.iterator(); it.hasNext(); )
{
Object file = it.next();
// ...
}
``` |
20,129,762 | In Java 8 we have the class [Stream<T>](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), which curiously have a method
```
Iterator<T> iterator()
```
So you would expect it to implement interface [Iterable<T>](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html), which requires exactly this method, but that's not the case.
When I want to iterate over a Stream using a foreach loop, I have to do something like
```
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
```
Am I missing something here? | 2013/11/21 | [
"https://Stackoverflow.com/questions/20129762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938782/"
] | People have already asked the same [on the mailing list](http://mail.openjdk.java.net/pipermail/lambda-dev/2013-March/008876.html) ☺. The main reason is Iterable also has a re-iterable semantic, while Stream is not.
>
> I think the main reason is that `Iterable` implies reusability, whereas `Stream` is something that can only be used once — more like an `Iterator`.
>
>
> If `Stream` extended `Iterable` then existing code might be surprised when it receives an `Iterable` that throws an `Exception` the
> second time they do `for (element : iterable)`.
>
>
> | If you don't mind using third party libraries [cyclops-react](https://github.com/aol/cyclops-react) defines a Stream that implements both Stream and Iterable and is replayable too (solving the problem [kennytm described](https://stackoverflow.com/a/20130131/1188377)).
```
Stream<String> stream = ReactiveSeq.of("hello","world")
.map(s->"prefix-"+s);
```
or :-
```
Iterable<String> stream = ReactiveSeq.of("hello","world")
.map(s->"prefix-"+s);
stream.forEach(System.out::println);
stream.forEach(System.out::println);
```
[Disclosure I am the lead developer of cyclops-react] |
20,129,762 | In Java 8 we have the class [Stream<T>](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), which curiously have a method
```
Iterator<T> iterator()
```
So you would expect it to implement interface [Iterable<T>](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html), which requires exactly this method, but that's not the case.
When I want to iterate over a Stream using a foreach loop, I have to do something like
```
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
```
Am I missing something here? | 2013/11/21 | [
"https://Stackoverflow.com/questions/20129762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938782/"
] | People have already asked the same [on the mailing list](http://mail.openjdk.java.net/pipermail/lambda-dev/2013-March/008876.html) ☺. The main reason is Iterable also has a re-iterable semantic, while Stream is not.
>
> I think the main reason is that `Iterable` implies reusability, whereas `Stream` is something that can only be used once — more like an `Iterator`.
>
>
> If `Stream` extended `Iterable` then existing code might be surprised when it receives an `Iterable` that throws an `Exception` the
> second time they do `for (element : iterable)`.
>
>
> | `Stream` does not implement `Iterable`. The general understanding of `Iterable` is anything that can be iterated upon, often again and again. `Stream` may not be replayable.
The only workaround that I can think of, where an iterable based on a stream is replayable too, is to re-create the stream. I am using a `Supplier` below to create a new instance of stream, everytime a new iterator is created.
```
Supplier<Stream<Integer>> streamSupplier = () -> Stream.of(10);
Iterable<Integer> iterable = () -> streamSupplier.get().iterator();
for(int i : iterable) {
System.out.println(i);
}
// Can iterate again
for(int i : iterable) {
System.out.println(i);
}
``` |
15,470,452 | I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?
I have search about background task & background thread ,IOS only support music in background (Not video)
<http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html>
here is some discussion about play video in background
1) <https://discussions.apple.com/thread/2799090?start=0&tstart=0>
2) <http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html>
But there are many apps in AppStore, that play video in Background like
Swift Player : <https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2>
SpeedUpTV : <https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8> | 2013/03/18 | [
"https://Stackoverflow.com/questions/15470452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647942/"
] | This method supports all the possibilities:
* Screen locked by the user;
* List item
* Home button pressed;
As long as you have an instance of AVPlayer running iOS prevents auto lock of the device.
First you need to configure the application to support audio background from the Info.plist file adding in the UIBackgroundModes array the audio element.
Then put in your AppDelegate.m into
**- (BOOL)application:(UIApplication \*)application didFinishLaunchingWithOptions:(NSDictionary \*)launchOptions:**
these methods
```
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
```
and **#import < AVFoundation/AVFoundation.h >**
Then in your view controller that controls AVPlayer
```
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
```
and
```
- (void)viewWillDisappear:(BOOL)animated
{
[mPlayer pause];
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
```
then respond to the
```
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
switch (event.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
if([mPlayer rate] == 0){
[mPlayer play];
} else {
[mPlayer pause];
}
break;
case UIEventSubtypeRemoteControlPlay:
[mPlayer play];
break;
case UIEventSubtypeRemoteControlPause:
[mPlayer pause];
break;
default:
break;
}
}
```
Another trick is needed to resume the reproduction if the user presses the home button (in which case the reproduction is suspended with a fade out).
When you control the reproduction of the video (I have play methods) set
```
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
```
and the corresponding method to be invoked that will launch a timer and resume the reproduction.
```
- (void)applicationDidEnterBackground:(NSNotification *)notification
{
[mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01];
}
```
Its works for me to play video in Backgorund.
Thanks to all. | If you are Playing video using WebView you can handle using javascript to play video on background.
```
strVideoHTML = @"<html><head><style>body.........</style></head> <body><div id=\"overlay\"><div id=\"youtubelogo1\"></div></div><div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } function changeBG(url){ document.getElementById('overlay').style.backgroundImage=url;} function manualPlay() { player.playVideo(); } function manualPause() { player.pauseVideo(); } </script></body> </html>";
NSString *html = [NSString stringWithFormat:strVideoHTML,url, width, height,videoid;
webvideoView.delegate = self;
[webvideoView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.your-url.com"]];
```
On view diappear call
```
strscript = @"manualPlay();
[webvideoView stringByEvaluatingJavaScriptFromString:strscript];
``` |
15,470,452 | I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?
I have search about background task & background thread ,IOS only support music in background (Not video)
<http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html>
here is some discussion about play video in background
1) <https://discussions.apple.com/thread/2799090?start=0&tstart=0>
2) <http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html>
But there are many apps in AppStore, that play video in Background like
Swift Player : <https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2>
SpeedUpTV : <https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8> | 2013/03/18 | [
"https://Stackoverflow.com/questions/15470452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647942/"
] | It is not possible to play background music/video using Avplayer. But it is possible using
MPMoviePlayerViewController. I have done this in one of my app using this player & this app
is run successfully to appstore. | In addition to fattomhk's response, here's what you can do to achieve video forwarding to the time it should be after your application comes in foreground:
* Get `currentPlaybackTime` of playing video when go to background and store it in `lastPlayBackTime`
* Store the time when application goes to background (in `userDefault` probably)
* Again get the time when application comes in foreground
* Calculate the `duration` between background and foreground time
* Set current playback time of video to `lastPlayBackTime` + `duration` |
15,470,452 | I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?
I have search about background task & background thread ,IOS only support music in background (Not video)
<http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html>
here is some discussion about play video in background
1) <https://discussions.apple.com/thread/2799090?start=0&tstart=0>
2) <http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html>
But there are many apps in AppStore, that play video in Background like
Swift Player : <https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2>
SpeedUpTV : <https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8> | 2013/03/18 | [
"https://Stackoverflow.com/questions/15470452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647942/"
] | Swift version for the accepted answer.
In the delegate:
```
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
```
In the view controller that controls AVPlayer
```
override func viewDidAppear(animated: Bool) {
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
self.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
mPlayer.pause()
UIApplication.sharedApplication().endReceivingRemoteControlEvents()
self.resignFirstResponder()
}
```
Don't forget to "import AVFoundation" | If you are Playing video using WebView you can handle using javascript to play video on background.
```
strVideoHTML = @"<html><head><style>body.........</style></head> <body><div id=\"overlay\"><div id=\"youtubelogo1\"></div></div><div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } function changeBG(url){ document.getElementById('overlay').style.backgroundImage=url;} function manualPlay() { player.playVideo(); } function manualPause() { player.pauseVideo(); } </script></body> </html>";
NSString *html = [NSString stringWithFormat:strVideoHTML,url, width, height,videoid;
webvideoView.delegate = self;
[webvideoView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.your-url.com"]];
```
On view diappear call
```
strscript = @"manualPlay();
[webvideoView stringByEvaluatingJavaScriptFromString:strscript];
``` |
15,470,452 | I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?
I have search about background task & background thread ,IOS only support music in background (Not video)
<http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html>
here is some discussion about play video in background
1) <https://discussions.apple.com/thread/2799090?start=0&tstart=0>
2) <http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html>
But there are many apps in AppStore, that play video in Background like
Swift Player : <https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2>
SpeedUpTV : <https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8> | 2013/03/18 | [
"https://Stackoverflow.com/questions/15470452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647942/"
] | If you try to change the background mode:
Sorry, App store wont approve it.[MPMoviePlayerViewController playback video after going to background for youtube](https://stackoverflow.com/questions/15389989/mpmovieplayerviewcontroller-playback-video-after-going-to-background-for-youtube)
In my research, someone would take the sound track out to play in te background when it goes into background as the video would be pause and get the playbacktime for resume playing when go into foreground | If you are Playing video using WebView you can handle using javascript to play video on background.
```
strVideoHTML = @"<html><head><style>body.........</style></head> <body><div id=\"overlay\"><div id=\"youtubelogo1\"></div></div><div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } function changeBG(url){ document.getElementById('overlay').style.backgroundImage=url;} function manualPlay() { player.playVideo(); } function manualPause() { player.pauseVideo(); } </script></body> </html>";
NSString *html = [NSString stringWithFormat:strVideoHTML,url, width, height,videoid;
webvideoView.delegate = self;
[webvideoView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.your-url.com"]];
```
On view diappear call
```
strscript = @"manualPlay();
[webvideoView stringByEvaluatingJavaScriptFromString:strscript];
``` |
15,470,452 | I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?
I have search about background task & background thread ,IOS only support music in background (Not video)
<http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html>
here is some discussion about play video in background
1) <https://discussions.apple.com/thread/2799090?start=0&tstart=0>
2) <http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html>
But there are many apps in AppStore, that play video in Background like
Swift Player : <https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2>
SpeedUpTV : <https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8> | 2013/03/18 | [
"https://Stackoverflow.com/questions/15470452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647942/"
] | Swift version for the accepted answer.
In the delegate:
```
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
```
In the view controller that controls AVPlayer
```
override func viewDidAppear(animated: Bool) {
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
self.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
mPlayer.pause()
UIApplication.sharedApplication().endReceivingRemoteControlEvents()
self.resignFirstResponder()
}
```
Don't forget to "import AVFoundation" | I'd like to add something that for some reason ended up being the culprit for me. I had used AVPlayer and background play for a long time without problems, but this one time I just couldn't get it to work.
I found out that when you go background, the `rate` property of the `AVPlayer` sometimes seems to dip to 0.0 (i.e. paused), and for that reason we simply need to KVO check the rate property at all times, or at least when we go to background. If the rate dips below 0.0 and we can assume that the user wants to play (i.e. the user did not deliberately tap pause in remote controls, the movie ended, etc) we need to call `.play()` on the AVPlayer again.
AFAIK there is no other toggle on the AVPlayer to keep it from pausing itself when app goes to background. |
15,470,452 | I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?
I have search about background task & background thread ,IOS only support music in background (Not video)
<http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html>
here is some discussion about play video in background
1) <https://discussions.apple.com/thread/2799090?start=0&tstart=0>
2) <http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html>
But there are many apps in AppStore, that play video in Background like
Swift Player : <https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2>
SpeedUpTV : <https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8> | 2013/03/18 | [
"https://Stackoverflow.com/questions/15470452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647942/"
] | This method supports all the possibilities:
* Screen locked by the user;
* List item
* Home button pressed;
As long as you have an instance of AVPlayer running iOS prevents auto lock of the device.
First you need to configure the application to support audio background from the Info.plist file adding in the UIBackgroundModes array the audio element.
Then put in your AppDelegate.m into
**- (BOOL)application:(UIApplication \*)application didFinishLaunchingWithOptions:(NSDictionary \*)launchOptions:**
these methods
```
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
```
and **#import < AVFoundation/AVFoundation.h >**
Then in your view controller that controls AVPlayer
```
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
```
and
```
- (void)viewWillDisappear:(BOOL)animated
{
[mPlayer pause];
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
```
then respond to the
```
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
switch (event.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
if([mPlayer rate] == 0){
[mPlayer play];
} else {
[mPlayer pause];
}
break;
case UIEventSubtypeRemoteControlPlay:
[mPlayer play];
break;
case UIEventSubtypeRemoteControlPause:
[mPlayer pause];
break;
default:
break;
}
}
```
Another trick is needed to resume the reproduction if the user presses the home button (in which case the reproduction is suspended with a fade out).
When you control the reproduction of the video (I have play methods) set
```
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
```
and the corresponding method to be invoked that will launch a timer and resume the reproduction.
```
- (void)applicationDidEnterBackground:(NSNotification *)notification
{
[mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01];
}
```
Its works for me to play video in Backgorund.
Thanks to all. | It is not possible to play background music/video using Avplayer. But it is possible using
MPMoviePlayerViewController. I have done this in one of my app using this player & this app
is run successfully to appstore. |
15,470,452 | I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?
I have search about background task & background thread ,IOS only support music in background (Not video)
<http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html>
here is some discussion about play video in background
1) <https://discussions.apple.com/thread/2799090?start=0&tstart=0>
2) <http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html>
But there are many apps in AppStore, that play video in Background like
Swift Player : <https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2>
SpeedUpTV : <https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8> | 2013/03/18 | [
"https://Stackoverflow.com/questions/15470452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647942/"
] | In addition to fattomhk's response, here's what you can do to achieve video forwarding to the time it should be after your application comes in foreground:
* Get `currentPlaybackTime` of playing video when go to background and store it in `lastPlayBackTime`
* Store the time when application goes to background (in `userDefault` probably)
* Again get the time when application comes in foreground
* Calculate the `duration` between background and foreground time
* Set current playback time of video to `lastPlayBackTime` + `duration` | If you are Playing video using WebView you can handle using javascript to play video on background.
```
strVideoHTML = @"<html><head><style>body.........</style></head> <body><div id=\"overlay\"><div id=\"youtubelogo1\"></div></div><div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } function changeBG(url){ document.getElementById('overlay').style.backgroundImage=url;} function manualPlay() { player.playVideo(); } function manualPause() { player.pauseVideo(); } </script></body> </html>";
NSString *html = [NSString stringWithFormat:strVideoHTML,url, width, height,videoid;
webvideoView.delegate = self;
[webvideoView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.your-url.com"]];
```
On view diappear call
```
strscript = @"manualPlay();
[webvideoView stringByEvaluatingJavaScriptFromString:strscript];
``` |
15,470,452 | I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?
I have search about background task & background thread ,IOS only support music in background (Not video)
<http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html>
here is some discussion about play video in background
1) <https://discussions.apple.com/thread/2799090?start=0&tstart=0>
2) <http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html>
But there are many apps in AppStore, that play video in Background like
Swift Player : <https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2>
SpeedUpTV : <https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8> | 2013/03/18 | [
"https://Stackoverflow.com/questions/15470452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647942/"
] | Try with this snippet, I've already integrated this with my app & it's being useful for me..hope this will work for you!!
Follow the steps given below:
* Add UIBackgroundModes in the APPNAME-Info.plist, with the selection
App plays audio
* Then add the AudioToolBox framework to the folder frameworks.
* In the APPNAMEAppDelegate.h add:
-- `#import < AVFoundation/AVFoundation.h>`
-- `#import < AudioToolbox/AudioToolbox.h>`
* In the APPNAMEAppDelegate.m add the following:
// Set AudioSession
```
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
```
* /\* Pick any one of them \*/
* // 1. Overriding the output audio route
>
> //UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute\_Speaker;
> //AudioSessionSetProperty(kAudioSessionProperty\_OverrideAudioRoute,
> sizeof(audioRouteOverride), &audioRouteOverride);
>
>
>
========================================================================
// 2. Changing the default output audio route
```
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
```
into the
```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
```
* but before the two lines:
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
Enjoy Programming!! | I'd like to add something that for some reason ended up being the culprit for me. I had used AVPlayer and background play for a long time without problems, but this one time I just couldn't get it to work.
I found out that when you go background, the `rate` property of the `AVPlayer` sometimes seems to dip to 0.0 (i.e. paused), and for that reason we simply need to KVO check the rate property at all times, or at least when we go to background. If the rate dips below 0.0 and we can assume that the user wants to play (i.e. the user did not deliberately tap pause in remote controls, the movie ended, etc) we need to call `.play()` on the AVPlayer again.
AFAIK there is no other toggle on the AVPlayer to keep it from pausing itself when app goes to background. |
15,470,452 | I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?
I have search about background task & background thread ,IOS only support music in background (Not video)
<http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html>
here is some discussion about play video in background
1) <https://discussions.apple.com/thread/2799090?start=0&tstart=0>
2) <http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html>
But there are many apps in AppStore, that play video in Background like
Swift Player : <https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2>
SpeedUpTV : <https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8> | 2013/03/18 | [
"https://Stackoverflow.com/questions/15470452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647942/"
] | It is not possible to play background music/video using Avplayer. But it is possible using
MPMoviePlayerViewController. I have done this in one of my app using this player & this app
is run successfully to appstore. | If you are Playing video using WebView you can handle using javascript to play video on background.
```
strVideoHTML = @"<html><head><style>body.........</style></head> <body><div id=\"overlay\"><div id=\"youtubelogo1\"></div></div><div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } function changeBG(url){ document.getElementById('overlay').style.backgroundImage=url;} function manualPlay() { player.playVideo(); } function manualPause() { player.pauseVideo(); } </script></body> </html>";
NSString *html = [NSString stringWithFormat:strVideoHTML,url, width, height,videoid;
webvideoView.delegate = self;
[webvideoView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.your-url.com"]];
```
On view diappear call
```
strscript = @"manualPlay();
[webvideoView stringByEvaluatingJavaScriptFromString:strscript];
``` |
15,470,452 | I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?
I have search about background task & background thread ,IOS only support music in background (Not video)
<http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html>
here is some discussion about play video in background
1) <https://discussions.apple.com/thread/2799090?start=0&tstart=0>
2) <http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html>
But there are many apps in AppStore, that play video in Background like
Swift Player : <https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2>
SpeedUpTV : <https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8> | 2013/03/18 | [
"https://Stackoverflow.com/questions/15470452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647942/"
] | If you try to change the background mode:
Sorry, App store wont approve it.[MPMoviePlayerViewController playback video after going to background for youtube](https://stackoverflow.com/questions/15389989/mpmovieplayerviewcontroller-playback-video-after-going-to-background-for-youtube)
In my research, someone would take the sound track out to play in te background when it goes into background as the video would be pause and get the playbacktime for resume playing when go into foreground | In addition to fattomhk's response, here's what you can do to achieve video forwarding to the time it should be after your application comes in foreground:
* Get `currentPlaybackTime` of playing video when go to background and store it in `lastPlayBackTime`
* Store the time when application goes to background (in `userDefault` probably)
* Again get the time when application comes in foreground
* Calculate the `duration` between background and foreground time
* Set current playback time of video to `lastPlayBackTime` + `duration` |
48,421,109 | I am having problem installing a custom plugin in Cordova.
```
plugman -d install --platform android --project platforms\android --plugin plugins\PrintName
```
error:
```
Cannot read property 'fail' of undefined TypeError: Cannot read property 'fail' of undefined
at C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\cordova-lib\src\plugman\fetch.js:168:18
at _fulfilled (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:787:54)
at self.promiseDispatch.done (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:816:30)
at Promise.promise.promiseDispatch (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:749:13)
at C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:509:49
at flush (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:108:17)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
at Function.Module.runMain (module.js:686:11)
at startup (bootstrap_node.js:187:16)
``` | 2018/01/24 | [
"https://Stackoverflow.com/questions/48421109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1268945/"
] | What I ended up having to do is uninstall plugman 2.0
```
npm remove -g plugman
```
Then I install plugman version 1.5.1
```
npm install -g [email protected]
```
Then I could finally add plugins to the project. | Just add the full path for customized Cordova plugin |
48,421,109 | I am having problem installing a custom plugin in Cordova.
```
plugman -d install --platform android --project platforms\android --plugin plugins\PrintName
```
error:
```
Cannot read property 'fail' of undefined TypeError: Cannot read property 'fail' of undefined
at C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\cordova-lib\src\plugman\fetch.js:168:18
at _fulfilled (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:787:54)
at self.promiseDispatch.done (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:816:30)
at Promise.promise.promiseDispatch (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:749:13)
at C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:509:49
at flush (C:\...\AppData\Roaming\npm\node_modules\plugman\node_modules\q\q.js:108:17)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
at Function.Module.runMain (module.js:686:11)
at startup (bootstrap_node.js:187:16)
``` | 2018/01/24 | [
"https://Stackoverflow.com/questions/48421109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1268945/"
] | You need to specify the full plugin path, not a relative path. e.g.:
```
plugman -d install --platform android --project platforms\android --plugin "\full_path\of_your\plugins\PrintName"
``` | Just add the full path for customized Cordova plugin |
546,205 | I read various stats/biostats textbooks, including Casella and Lehmann's book chapter on regression. Most of time, the textbook will report a *p*-value for significance of the parameters after regressing against some model. Then there is a model selection procedure followed afterwards.
However, those books will never touch upon cross validation (CV) or talk about using a test/training split. I learned CV and [Monte Carlo cross-validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics)#Repeated_random_sub-sampling_validation) (MCCV) from machine learning books and rarely have I seen stat books covering CV.
Why were we not taught cross validation in stats? Or is it not practiced by statisticians in general? Or somehow that model selection procedure becomes superior to using testing data for model selection? Does a biostatistician/practicing statistician use CV in model selection in general? | 2021/09/27 | [
"https://stats.stackexchange.com/questions/546205",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/79469/"
] | I can't say with 100% certainty, but I can give you my two cents.
Let's start with the difference in philosophy between statistics (as practised in the books mentioned) and machine learning. The former is (usually, but not always) concerned with some sort of inference. There is usually a latent parameter, like the sample mean or the effect of a novel drug, which requires estimation as well as a statement on the precision of the estimate. The latter (usually, but not always) eschews estimating anything except the conditional mean (be it a regression or a probability in the case of some classification models).
Thus "model selection" in each context means something slightly different by virtue of having different goals. Cross validation is a means of selecting models by means of estimating their generalization error. It is, therefore, primarily a tool for predictive modelling. But statistics (again usually, but always) is not concerned with generalization error as much as it is concerned with parsimony (for example), hence statistics don't use CV to select models.
Prediction from a statisticians point of view is not absent of cross validation. Indeed, Frank Harrell's *Regression Modelling Strategies* mentions the technique, but that book is primarily concerned with the development of predictions models for use in the clinic. | ### Probability
If you consider a really strict delineation of **probability** and statistics, the former is about mathematically describing how likely it is for an event to occur, or a proposition to be true. You can have a textbook or a course that is about probability, without entering the field of statistics at all.
Classical examples include drawing different colored balls out of an urn, combinations in a lottery, or drawing cards from a deck.
### Statistics
**Statistics**, then, is about describing either probability distributions, populations or samples drawn from a population. Parameters that can be used to describe those are, for example, *mean* and *standard deviation*. In this sense, statistics is about describing the results of observations of random variables, or any sample or population that is not necessarily random.
A textbook that takes this view of statistics would include the definitions for those terms, and then various estimators that can be used to get at the parameters that might have produced a certain sample (given a probability distribution, or a random process), and how to judge the correctness of those estimates.
Now, it is entirely plausible that a textbook would stay entirely within this definition of statistics: Describing populations or samples, and using probability distributions to make inference on how like it is that we saw a certain sample -- without entering the world of **statistical modeling**, where cross validation belongs.
### Why not cross validation?
Some textbooks, even holding the view described above, might still include linear regression: its parameters can still be considered estimates that can be calculated from a sample. It can be, of course, used as a predictive model, and thus subjected to [cross validation](https://stats.stackexchange.com/q/122476/107191) -- but once you start using cross validation to make judgements about what terms to include in your model, you step away from the strict definition of the parameters of the linear model being estimates of the population, calculated from a sample drawn from it.
Thus you could say that cross validation is already venturing in to the field of **applied statistics**. |
546,205 | I read various stats/biostats textbooks, including Casella and Lehmann's book chapter on regression. Most of time, the textbook will report a *p*-value for significance of the parameters after regressing against some model. Then there is a model selection procedure followed afterwards.
However, those books will never touch upon cross validation (CV) or talk about using a test/training split. I learned CV and [Monte Carlo cross-validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics)#Repeated_random_sub-sampling_validation) (MCCV) from machine learning books and rarely have I seen stat books covering CV.
Why were we not taught cross validation in stats? Or is it not practiced by statisticians in general? Or somehow that model selection procedure becomes superior to using testing data for model selection? Does a biostatistician/practicing statistician use CV in model selection in general? | 2021/09/27 | [
"https://stats.stackexchange.com/questions/546205",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/79469/"
] | I can't say with 100% certainty, but I can give you my two cents.
Let's start with the difference in philosophy between statistics (as practised in the books mentioned) and machine learning. The former is (usually, but not always) concerned with some sort of inference. There is usually a latent parameter, like the sample mean or the effect of a novel drug, which requires estimation as well as a statement on the precision of the estimate. The latter (usually, but not always) eschews estimating anything except the conditional mean (be it a regression or a probability in the case of some classification models).
Thus "model selection" in each context means something slightly different by virtue of having different goals. Cross validation is a means of selecting models by means of estimating their generalization error. It is, therefore, primarily a tool for predictive modelling. But statistics (again usually, but always) is not concerned with generalization error as much as it is concerned with parsimony (for example), hence statistics don't use CV to select models.
Prediction from a statisticians point of view is not absent of cross validation. Indeed, Frank Harrell's *Regression Modelling Strategies* mentions the technique, but that book is primarily concerned with the development of predictions models for use in the clinic. | **Descriptive vs. predictive**
In, say biology textbooks, the focus is on *describing* the relevant data; the sample mean was…, the p-value for this result is… etc.
In machine learning texts, the focus is on producing models that can *generalize* beyond their training set; thus techniques like cross-validation are required in order to get a handle on that feature.
This oversimplifies a bit, but I think captures the essence of the difference in approach that some works take relative to others. These differences are a reflection of the different priorities and goals for these different domains that apply statistics.
Consider the [*Theory of Point Estimation* by Lehmann and Casella 1998](https://www.ctanujit.org/uploads/2/5/3/9/25393293/_theory_of_point_estimation.pdf). They start chapter 1 with the statement "Statistics is concerned with the collection of data and with their analysis and interpretation.", which reads to me that these authors have chosen to focus more on applying statistics for analysis and interpretation rather than on applying statistics in a manner that can be reliably generalized to other cases. Similarly, they describe the result of "classical inference and decision theory" as " Such a statement about [the estimated values of the model parameters] can be viewed as a summary of the information provided by the data and may be used as a guide to action." -- again the focus is more about how to describe the data (any maybe as a basis, with some interpretation, on how to guide actions), and less about the nature of the problems involved in ML.
Finally, let me emphasize: this is a matter of what particular authors, problem domains etc. have chosen to focus on in different areas. |
546,205 | I read various stats/biostats textbooks, including Casella and Lehmann's book chapter on regression. Most of time, the textbook will report a *p*-value for significance of the parameters after regressing against some model. Then there is a model selection procedure followed afterwards.
However, those books will never touch upon cross validation (CV) or talk about using a test/training split. I learned CV and [Monte Carlo cross-validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics)#Repeated_random_sub-sampling_validation) (MCCV) from machine learning books and rarely have I seen stat books covering CV.
Why were we not taught cross validation in stats? Or is it not practiced by statisticians in general? Or somehow that model selection procedure becomes superior to using testing data for model selection? Does a biostatistician/practicing statistician use CV in model selection in general? | 2021/09/27 | [
"https://stats.stackexchange.com/questions/546205",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/79469/"
] | I can't say with 100% certainty, but I can give you my two cents.
Let's start with the difference in philosophy between statistics (as practised in the books mentioned) and machine learning. The former is (usually, but not always) concerned with some sort of inference. There is usually a latent parameter, like the sample mean or the effect of a novel drug, which requires estimation as well as a statement on the precision of the estimate. The latter (usually, but not always) eschews estimating anything except the conditional mean (be it a regression or a probability in the case of some classification models).
Thus "model selection" in each context means something slightly different by virtue of having different goals. Cross validation is a means of selecting models by means of estimating their generalization error. It is, therefore, primarily a tool for predictive modelling. But statistics (again usually, but always) is not concerned with generalization error as much as it is concerned with parsimony (for example), hence statistics don't use CV to select models.
Prediction from a statisticians point of view is not absent of cross validation. Indeed, Frank Harrell's *Regression Modelling Strategies* mentions the technique, but that book is primarily concerned with the development of predictions models for use in the clinic. | The main reason is that almost all book authors are in [inference statistics](https://en.wikipedia.org/wiki/Statistical_inference). In particular, bio statistics is heavy on this aspect. A lot of stats used in regulated industries, such as banking is guilty of this too. Question like "what caused this? Did this cause that?" are usually asked from the inference point of view.
Cross-validation is of interest to forecasters. If you run into a book written by people who are in predictive field, then you should see the discussion of cross-validation. A good example is Hyndman's book, see [here](https://otexts.com/fpp3/tscv.html). I personally look at p-values mostly when asked to, in our industry we have governance folks who love this type of nonsense and request us to show a ton of pointless metrics. |
546,205 | I read various stats/biostats textbooks, including Casella and Lehmann's book chapter on regression. Most of time, the textbook will report a *p*-value for significance of the parameters after regressing against some model. Then there is a model selection procedure followed afterwards.
However, those books will never touch upon cross validation (CV) or talk about using a test/training split. I learned CV and [Monte Carlo cross-validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics)#Repeated_random_sub-sampling_validation) (MCCV) from machine learning books and rarely have I seen stat books covering CV.
Why were we not taught cross validation in stats? Or is it not practiced by statisticians in general? Or somehow that model selection procedure becomes superior to using testing data for model selection? Does a biostatistician/practicing statistician use CV in model selection in general? | 2021/09/27 | [
"https://stats.stackexchange.com/questions/546205",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/79469/"
] | ### Probability
If you consider a really strict delineation of **probability** and statistics, the former is about mathematically describing how likely it is for an event to occur, or a proposition to be true. You can have a textbook or a course that is about probability, without entering the field of statistics at all.
Classical examples include drawing different colored balls out of an urn, combinations in a lottery, or drawing cards from a deck.
### Statistics
**Statistics**, then, is about describing either probability distributions, populations or samples drawn from a population. Parameters that can be used to describe those are, for example, *mean* and *standard deviation*. In this sense, statistics is about describing the results of observations of random variables, or any sample or population that is not necessarily random.
A textbook that takes this view of statistics would include the definitions for those terms, and then various estimators that can be used to get at the parameters that might have produced a certain sample (given a probability distribution, or a random process), and how to judge the correctness of those estimates.
Now, it is entirely plausible that a textbook would stay entirely within this definition of statistics: Describing populations or samples, and using probability distributions to make inference on how like it is that we saw a certain sample -- without entering the world of **statistical modeling**, where cross validation belongs.
### Why not cross validation?
Some textbooks, even holding the view described above, might still include linear regression: its parameters can still be considered estimates that can be calculated from a sample. It can be, of course, used as a predictive model, and thus subjected to [cross validation](https://stats.stackexchange.com/q/122476/107191) -- but once you start using cross validation to make judgements about what terms to include in your model, you step away from the strict definition of the parameters of the linear model being estimates of the population, calculated from a sample drawn from it.
Thus you could say that cross validation is already venturing in to the field of **applied statistics**. | **Descriptive vs. predictive**
In, say biology textbooks, the focus is on *describing* the relevant data; the sample mean was…, the p-value for this result is… etc.
In machine learning texts, the focus is on producing models that can *generalize* beyond their training set; thus techniques like cross-validation are required in order to get a handle on that feature.
This oversimplifies a bit, but I think captures the essence of the difference in approach that some works take relative to others. These differences are a reflection of the different priorities and goals for these different domains that apply statistics.
Consider the [*Theory of Point Estimation* by Lehmann and Casella 1998](https://www.ctanujit.org/uploads/2/5/3/9/25393293/_theory_of_point_estimation.pdf). They start chapter 1 with the statement "Statistics is concerned with the collection of data and with their analysis and interpretation.", which reads to me that these authors have chosen to focus more on applying statistics for analysis and interpretation rather than on applying statistics in a manner that can be reliably generalized to other cases. Similarly, they describe the result of "classical inference and decision theory" as " Such a statement about [the estimated values of the model parameters] can be viewed as a summary of the information provided by the data and may be used as a guide to action." -- again the focus is more about how to describe the data (any maybe as a basis, with some interpretation, on how to guide actions), and less about the nature of the problems involved in ML.
Finally, let me emphasize: this is a matter of what particular authors, problem domains etc. have chosen to focus on in different areas. |
546,205 | I read various stats/biostats textbooks, including Casella and Lehmann's book chapter on regression. Most of time, the textbook will report a *p*-value for significance of the parameters after regressing against some model. Then there is a model selection procedure followed afterwards.
However, those books will never touch upon cross validation (CV) or talk about using a test/training split. I learned CV and [Monte Carlo cross-validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics)#Repeated_random_sub-sampling_validation) (MCCV) from machine learning books and rarely have I seen stat books covering CV.
Why were we not taught cross validation in stats? Or is it not practiced by statisticians in general? Or somehow that model selection procedure becomes superior to using testing data for model selection? Does a biostatistician/practicing statistician use CV in model selection in general? | 2021/09/27 | [
"https://stats.stackexchange.com/questions/546205",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/79469/"
] | The main reason is that almost all book authors are in [inference statistics](https://en.wikipedia.org/wiki/Statistical_inference). In particular, bio statistics is heavy on this aspect. A lot of stats used in regulated industries, such as banking is guilty of this too. Question like "what caused this? Did this cause that?" are usually asked from the inference point of view.
Cross-validation is of interest to forecasters. If you run into a book written by people who are in predictive field, then you should see the discussion of cross-validation. A good example is Hyndman's book, see [here](https://otexts.com/fpp3/tscv.html). I personally look at p-values mostly when asked to, in our industry we have governance folks who love this type of nonsense and request us to show a ton of pointless metrics. | ### Probability
If you consider a really strict delineation of **probability** and statistics, the former is about mathematically describing how likely it is for an event to occur, or a proposition to be true. You can have a textbook or a course that is about probability, without entering the field of statistics at all.
Classical examples include drawing different colored balls out of an urn, combinations in a lottery, or drawing cards from a deck.
### Statistics
**Statistics**, then, is about describing either probability distributions, populations or samples drawn from a population. Parameters that can be used to describe those are, for example, *mean* and *standard deviation*. In this sense, statistics is about describing the results of observations of random variables, or any sample or population that is not necessarily random.
A textbook that takes this view of statistics would include the definitions for those terms, and then various estimators that can be used to get at the parameters that might have produced a certain sample (given a probability distribution, or a random process), and how to judge the correctness of those estimates.
Now, it is entirely plausible that a textbook would stay entirely within this definition of statistics: Describing populations or samples, and using probability distributions to make inference on how like it is that we saw a certain sample -- without entering the world of **statistical modeling**, where cross validation belongs.
### Why not cross validation?
Some textbooks, even holding the view described above, might still include linear regression: its parameters can still be considered estimates that can be calculated from a sample. It can be, of course, used as a predictive model, and thus subjected to [cross validation](https://stats.stackexchange.com/q/122476/107191) -- but once you start using cross validation to make judgements about what terms to include in your model, you step away from the strict definition of the parameters of the linear model being estimates of the population, calculated from a sample drawn from it.
Thus you could say that cross validation is already venturing in to the field of **applied statistics**. |
546,205 | I read various stats/biostats textbooks, including Casella and Lehmann's book chapter on regression. Most of time, the textbook will report a *p*-value for significance of the parameters after regressing against some model. Then there is a model selection procedure followed afterwards.
However, those books will never touch upon cross validation (CV) or talk about using a test/training split. I learned CV and [Monte Carlo cross-validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics)#Repeated_random_sub-sampling_validation) (MCCV) from machine learning books and rarely have I seen stat books covering CV.
Why were we not taught cross validation in stats? Or is it not practiced by statisticians in general? Or somehow that model selection procedure becomes superior to using testing data for model selection? Does a biostatistician/practicing statistician use CV in model selection in general? | 2021/09/27 | [
"https://stats.stackexchange.com/questions/546205",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/79469/"
] | The main reason is that almost all book authors are in [inference statistics](https://en.wikipedia.org/wiki/Statistical_inference). In particular, bio statistics is heavy on this aspect. A lot of stats used in regulated industries, such as banking is guilty of this too. Question like "what caused this? Did this cause that?" are usually asked from the inference point of view.
Cross-validation is of interest to forecasters. If you run into a book written by people who are in predictive field, then you should see the discussion of cross-validation. A good example is Hyndman's book, see [here](https://otexts.com/fpp3/tscv.html). I personally look at p-values mostly when asked to, in our industry we have governance folks who love this type of nonsense and request us to show a ton of pointless metrics. | **Descriptive vs. predictive**
In, say biology textbooks, the focus is on *describing* the relevant data; the sample mean was…, the p-value for this result is… etc.
In machine learning texts, the focus is on producing models that can *generalize* beyond their training set; thus techniques like cross-validation are required in order to get a handle on that feature.
This oversimplifies a bit, but I think captures the essence of the difference in approach that some works take relative to others. These differences are a reflection of the different priorities and goals for these different domains that apply statistics.
Consider the [*Theory of Point Estimation* by Lehmann and Casella 1998](https://www.ctanujit.org/uploads/2/5/3/9/25393293/_theory_of_point_estimation.pdf). They start chapter 1 with the statement "Statistics is concerned with the collection of data and with their analysis and interpretation.", which reads to me that these authors have chosen to focus more on applying statistics for analysis and interpretation rather than on applying statistics in a manner that can be reliably generalized to other cases. Similarly, they describe the result of "classical inference and decision theory" as " Such a statement about [the estimated values of the model parameters] can be viewed as a summary of the information provided by the data and may be used as a guide to action." -- again the focus is more about how to describe the data (any maybe as a basis, with some interpretation, on how to guide actions), and less about the nature of the problems involved in ML.
Finally, let me emphasize: this is a matter of what particular authors, problem domains etc. have chosen to focus on in different areas. |
22,119,487 | I need to implement a 1024bit math operations in C .I Implemented a simple BigInteger library where the integer is stored as an array "typedef INT UINT1024[400]" where each element represent one digit. It turned up to be so slow so i decided to implement the BigInteger using a 1024bit array of UINT64: "typedef UINT64 UINT1024[16]"
so for example the number : 1000 is represented as {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1000},
18446744073709551615 as {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0xFFFFFFFFFFFFFFFF} and 18446744073709551616 as {0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0}.
I started wih writing the function to convert a char array number to an UINT1024 and an UINT1024 to a char array, it worked with numbers <= 0xFFFFFFFFFFFFFFFF.
Here's what i did:
```
void UINT1024_FROMSTRING(UIN1024 Integer,const char szInteger[],UINT Length) {
int c = 15;
UINT64 Result = 0,Operation,Carry = 0;
UINT64 Temp = 1;
while(Length--)
{
Operation = (szInteger[Length] - '0') * Temp;
Result += Operation + Carry;
/*Overflow ?*/
if (Result < Operation || Temp == 1000000000000000000)
{
Carry = Result - Operation;
Result = 0;
Integer[c--] = 0;
Temp = 1;
}
else Carry = 0;
Temp *= 10;
}
if (Result || Carry)
{
/* I DONT KNOW WHAT TO DO HERE ! */
}
while(c--) Integer[c] = 0;}
```
So please how can i implement it and is it possible to implement it using UINT64 for speed or just to stick with each array element is a digit of the number which is very slow for 1024bit operations.
PS: I can't use any existing library !
Thanks in advance !
---
**Update**
Still can't figure out how to do the multiplication. I am using this function:
```
void _uint128_mul(UINT64 u,UINT64 v,UINT64 * ui64Hi,UINT64 * ui64Lo)
{
UINT64 ulo, uhi, vlo, vhi, k, t;
UINT64 wlo, whi, wt;
uhi = u >> 32;
ulo = u & 0xFFFFFFFF;
vhi = v >> 32;
vlo = v & 0xFFFFFFFF;
t = ulo*vlo; wlo = t & 0xFFFFFFFF;
k = t >> 32;
t = uhi*vlo + k;
whi = t & 0xFFFFFFFF;
wt = t >> 32;
t = ulo*vhi + whi;
k = t >> 32;
*ui64Lo = (t << 32) + wlo;
*ui64Hi = uhi*vhi + wt + k;
}
```
Then
```
void multiply(uint1024_t dUInteger,uint1024_t UInteger)
{
int i = 16;
UINT64 lo,hi,Carry = 0;
while(i--)
{
_uint128_mul(dUInteger[i],UInteger[15],&hi,&lo);
dUInteger[i] = lo + Carry;
Carry = hi;
}
}
```
I really need some help in this and Thanks in advance ! | 2014/03/01 | [
"https://Stackoverflow.com/questions/22119487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2627770/"
] | You need to implement two functions for your UINT1024 class, multiply by integer and add integer. Then for each digit you convert, multiply the previous value by 10 and add the value of the digit. | Writing, debugging, defining test cases, and checking they do work right is a *huge* undertaking. Just get one of the packaged multiprecission arithmetic libraries, like [GMP](https://gmplib.org), perhaps though [NTL](http://www.shoup.net/ntl) or [CLN](http://www.ginac.de/CLN) for C++. There are other alternatives, trawl the web. Jôrg Arndt's [Matters Computational](http://www.jjj.de/fxt/fxtbook.pdf) gives source code for C++. |
22,119,487 | I need to implement a 1024bit math operations in C .I Implemented a simple BigInteger library where the integer is stored as an array "typedef INT UINT1024[400]" where each element represent one digit. It turned up to be so slow so i decided to implement the BigInteger using a 1024bit array of UINT64: "typedef UINT64 UINT1024[16]"
so for example the number : 1000 is represented as {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1000},
18446744073709551615 as {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0xFFFFFFFFFFFFFFFF} and 18446744073709551616 as {0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0}.
I started wih writing the function to convert a char array number to an UINT1024 and an UINT1024 to a char array, it worked with numbers <= 0xFFFFFFFFFFFFFFFF.
Here's what i did:
```
void UINT1024_FROMSTRING(UIN1024 Integer,const char szInteger[],UINT Length) {
int c = 15;
UINT64 Result = 0,Operation,Carry = 0;
UINT64 Temp = 1;
while(Length--)
{
Operation = (szInteger[Length] - '0') * Temp;
Result += Operation + Carry;
/*Overflow ?*/
if (Result < Operation || Temp == 1000000000000000000)
{
Carry = Result - Operation;
Result = 0;
Integer[c--] = 0;
Temp = 1;
}
else Carry = 0;
Temp *= 10;
}
if (Result || Carry)
{
/* I DONT KNOW WHAT TO DO HERE ! */
}
while(c--) Integer[c] = 0;}
```
So please how can i implement it and is it possible to implement it using UINT64 for speed or just to stick with each array element is a digit of the number which is very slow for 1024bit operations.
PS: I can't use any existing library !
Thanks in advance !
---
**Update**
Still can't figure out how to do the multiplication. I am using this function:
```
void _uint128_mul(UINT64 u,UINT64 v,UINT64 * ui64Hi,UINT64 * ui64Lo)
{
UINT64 ulo, uhi, vlo, vhi, k, t;
UINT64 wlo, whi, wt;
uhi = u >> 32;
ulo = u & 0xFFFFFFFF;
vhi = v >> 32;
vlo = v & 0xFFFFFFFF;
t = ulo*vlo; wlo = t & 0xFFFFFFFF;
k = t >> 32;
t = uhi*vlo + k;
whi = t & 0xFFFFFFFF;
wt = t >> 32;
t = ulo*vhi + whi;
k = t >> 32;
*ui64Lo = (t << 32) + wlo;
*ui64Hi = uhi*vhi + wt + k;
}
```
Then
```
void multiply(uint1024_t dUInteger,uint1024_t UInteger)
{
int i = 16;
UINT64 lo,hi,Carry = 0;
while(i--)
{
_uint128_mul(dUInteger[i],UInteger[15],&hi,&lo);
dUInteger[i] = lo + Carry;
Carry = hi;
}
}
```
I really need some help in this and Thanks in advance ! | 2014/03/01 | [
"https://Stackoverflow.com/questions/22119487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2627770/"
] | You need to implement two functions for your UINT1024 class, multiply by integer and add integer. Then for each digit you convert, multiply the previous value by 10 and add the value of the digit. | If you are doing this for your education, you should take the middle road between your two previous approaches. Put more than 1 bit into a leaf or digit, but do not use the full bit range of the integer type.
The reason is that this may significantly simplify the multiplication operation if you can at first just accumulate the products a[i]\*b[j] in c[i+j]. And then normalize the result to the fixed digit range. c has length 2N-1, and this should fit into 1024 bit, so a and b are restricted to 512 bit.
If the arrays a and b hold N digits with maximum value B-1, B=2^b, then the largest of the c[k] is c[N-1] with bound N\*(B-1)^2. Thus the design constraints are
```
(2N)*b>=1024
ld(N)+(2b)<=64
b N 2N*b ld(N)+2b
32 16 1024 68
24 22 1056 53
28 19 1064 61
```
So one possibility is to set b=28, B=1<
---
Even more suited for educational purposes would be to set B=10^d, e.g. with d=9, so that conversion from and to string is relatively trivial. |
4,259,334 | Will XCode installer automatically update my old version or do I need to uninstall old one first?
Sorry, sort of newbie to Mac development. Going fine with Xcode 3.2.4, but new version is out as of today. | 2010/11/23 | [
"https://Stackoverflow.com/questions/4259334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483163/"
] | The new Xcode installer will normally overwrite the older version for you automatically | You don't need to uninstall the old XCode, it will update automatically. |
4,259,334 | Will XCode installer automatically update my old version or do I need to uninstall old one first?
Sorry, sort of newbie to Mac development. Going fine with Xcode 3.2.4, but new version is out as of today. | 2010/11/23 | [
"https://Stackoverflow.com/questions/4259334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483163/"
] | You don't need to uninstall the old XCode, it will update automatically. | Considering that Xcode now supports installing versions side-by-side, I would suggest installing Xcode 3.2.5 in a folder called Dev325 or something and try it out first just to make sure. It's unlikely you will experience a problem, but it has been known to happen. Then, once you have used 3.2.5 for awhile and are comfortable that it is working correctly, uninstall 3.2.4 - *About Xcode.pdf* will tell you how to uninstall properly. |
4,259,334 | Will XCode installer automatically update my old version or do I need to uninstall old one first?
Sorry, sort of newbie to Mac development. Going fine with Xcode 3.2.4, but new version is out as of today. | 2010/11/23 | [
"https://Stackoverflow.com/questions/4259334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483163/"
] | You don't need to uninstall the old XCode, it will update automatically. | I would suggest to install side by side, however, to retain the ability to run 3.2.4 should anything happen. I just upgraded to 3.2.5 and my application does not run in the simulator anymore, giving out an error as follows:
>
> Detected an attempt to call a symbol
> in system libraries that is not
> present on the iPhone:
> nanosleep$UNIX2003 called from
> function
> \_ZN3irr16CIrrDeviceIPhone5yieldEv in image pw2009test\_dbg. If you are
> encountering this problem running a
> simulator binary within gdb, **make
> sure you 'set start-with-shell off'
> first**.
>
>
>
This is the same issue as reported [App crashes with 4.2 iPhone simulator 'set start-with-shell off'](https://stackoverflow.com/questions/4271480/app-crashes-with-4-2-iphone-simulator-set-start-with-shell-off). This issue specifically started after 3.2.5 upgrade. |
4,259,334 | Will XCode installer automatically update my old version or do I need to uninstall old one first?
Sorry, sort of newbie to Mac development. Going fine with Xcode 3.2.4, but new version is out as of today. | 2010/11/23 | [
"https://Stackoverflow.com/questions/4259334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483163/"
] | The new Xcode installer will normally overwrite the older version for you automatically | Considering that Xcode now supports installing versions side-by-side, I would suggest installing Xcode 3.2.5 in a folder called Dev325 or something and try it out first just to make sure. It's unlikely you will experience a problem, but it has been known to happen. Then, once you have used 3.2.5 for awhile and are comfortable that it is working correctly, uninstall 3.2.4 - *About Xcode.pdf* will tell you how to uninstall properly. |
4,259,334 | Will XCode installer automatically update my old version or do I need to uninstall old one first?
Sorry, sort of newbie to Mac development. Going fine with Xcode 3.2.4, but new version is out as of today. | 2010/11/23 | [
"https://Stackoverflow.com/questions/4259334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483163/"
] | The new Xcode installer will normally overwrite the older version for you automatically | I would suggest to install side by side, however, to retain the ability to run 3.2.4 should anything happen. I just upgraded to 3.2.5 and my application does not run in the simulator anymore, giving out an error as follows:
>
> Detected an attempt to call a symbol
> in system libraries that is not
> present on the iPhone:
> nanosleep$UNIX2003 called from
> function
> \_ZN3irr16CIrrDeviceIPhone5yieldEv in image pw2009test\_dbg. If you are
> encountering this problem running a
> simulator binary within gdb, **make
> sure you 'set start-with-shell off'
> first**.
>
>
>
This is the same issue as reported [App crashes with 4.2 iPhone simulator 'set start-with-shell off'](https://stackoverflow.com/questions/4271480/app-crashes-with-4-2-iphone-simulator-set-start-with-shell-off). This issue specifically started after 3.2.5 upgrade. |
3,321,511 | Prove that the area bounded by the curve $y=\tanh x$ and the straight line $y=1$, between $x=0$ and $x=\infty$ is $\ln 2$
$\int^\infty \_0 (1-\tanh x) \mathrm{dx}= \biggr[x-\ln (\cosh x)\biggr]^\infty\_0\\\infty - \ln(\cosh \infty)+1$
How do I get $\ln 2$ because the line and curve intersect at infinity? | 2019/08/12 | [
"https://math.stackexchange.com/questions/3321511",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/455866/"
] | You need to evaluate the limit
$$\lim\_{x\rightarrow \infty} (x - \ln(\cosh(x)))$$
Note that
$$e^{\ln(\cosh(x)) -x} = e^{-x} \cosh(x) = \frac{1}{2}(1 + e^{-2x})\rightarrow \frac{1}{2}$$
Therefore
$$\lim\_{x\rightarrow \infty} (x - \ln(\cosh(x))) = -\ln(1/2) = \ln(2)$$
Hence
$$\int\_0^\infty (1-\tanh(x))dx = \lim\_{y\rightarrow \infty} [x - \ln(\cosh(x))]\_{x=0}^{x=y} = \ln(2) $$ | Well, when you get the antiderivative, you can put in the limits and get
$ \begin{array}{l}
\lim\limits \_{x\rightarrow \infty }[ x-ln( cosh( x))] =\lim\limits \_{x\rightarrow \infty }\left[\frac{( x+ln( cosh( x)))( x-ln( cosh( x)))}{( x+ln( cosh( x)))}\right] =\lim\limits \_{x\rightarrow \infty }\left[\frac{x^{2} -ln^{2}( cosh( x))}{x+ln( cosh( x))}\right]\\
=\lim\limits \_{x\rightarrow \infty }\left[\frac{x^{2}}{x+ln( cosh( x))} -\frac{ln^{2}( cosh( x))}{x+ln( cosh( x))}\right] =\lim\limits \_{x\rightarrow \infty }\left[\frac{2x}{1+tanh( x)} -\frac{2tanh( x) ln( cosh( x))}{1+tanh( x)}\right]\\
\\
\lim\limits \_{x\rightarrow \infty }[ x-ln( cosh( x))] =\lim\limits \_{x\rightarrow \infty }\left[ 2\frac{x-tanh( x) ln( cosh( x))}{1+tanh( x)}\right]\\
This\ means\ it\ equals\ itself,\ because\ tanh( \infty ) =1
\end{array}$
After that, I was stuck... But maybe this will help you; or someone else to answer your problem.
But I do know that
\lim\limits \_{x\rightarrow \infty }[ x-ln( cosh( x))] =ln( 2)
I just don't know how. |
6,454,460 | I am using Oracle and I have modified code on some triggers and a package.
When I run the script file which modifies the code and try to do an update on a table (which fires the trigger) I am getting Existing State of Package discarded
I am getting a bunch of error
```
ORA-04068:
ORA-04061:
ORA-04065:
ORA-06512:--Trigger error -- line 50
ORA-04088:
```
This error is happening only the first time. Any inputs to avoid this would be greatly appreciated. Thank you! | 2011/06/23 | [
"https://Stackoverflow.com/questions/6454460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/529866/"
] | serially\_reusable only makes sense for constant package variables.
There is only one way to avoid this error and maintain performance (reset\_package is really not a good option). Avoid any package level variables in your PL/SQL packages. Your Oracle's server memory is not the right place to store state.
If something really does not change, is expensive to compute and a return value from a function can be reused over and over without recomputation, then DETERMINISTIC helps in that regard
example: DON'T DO THIS:
varchar2(100) cached\_result;
```
function foo return varchar2 is
begin
if cached_result is null then
cached_result:= ... --expensive calc here
end if;
return cached_result;
end foo;
```
DO THIS INSTEAD
```
function foo return varchar2 DETERMINISTIC is
begin
result:=... --expensive calc here
return result;
end foo;
```
Deterministic tells Oracle that for a given input, the result does not change, so it can cache the result and avoid calling the function.
If this is not your use case and you need to share a variable across sessions, use a table, and query it. Your table will end up in the buffer cache memory if it is used with any frequency, so you get the in memory storage you desire without the problems of session variables | Your script is more than likely caching out-dated code. So, from Michael Pakhanstovs link you can run
```
DBMS_SESSION.RESET_PACKAGE
```
at the beginning of your script or use
```
PRAGMA SERIALLY_REUSABLE;
```
in your script.
Note however the implications of both:
<http://download.oracle.com/docs/cd/B13789_01/appdev.101/b10807/13_elems046.htm>
<http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_sessio.htm#i1010767>
[http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11\_QUESTION\_ID:2298325131459](http://asktom.oracle.com/pls/asktom/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:2298325131459)
AskTom on DBMS\_SESSION.RESET\_PACKAGE:
>
> dbms\_session.reset\_package, while MUCH
> faster then logging in and out, has
> some performance implications (not as
> fast as not doing it obviously!).
> That and it'll rip down the entire
> session state, eg: any opened cursors
> you have (prepared statements) as
> well.
>
>
>
AskTom on PRAGMA SERIALLY\_REUSABLE:
>
> Its basically saying 'if you use a
> package and you don't save a state in
> that package and would like avoid
> having the persistance of the package
> in your session -- less memory -- use
> this'
>
>
> |
6,454,460 | I am using Oracle and I have modified code on some triggers and a package.
When I run the script file which modifies the code and try to do an update on a table (which fires the trigger) I am getting Existing State of Package discarded
I am getting a bunch of error
```
ORA-04068:
ORA-04061:
ORA-04065:
ORA-06512:--Trigger error -- line 50
ORA-04088:
```
This error is happening only the first time. Any inputs to avoid this would be greatly appreciated. Thank you! | 2011/06/23 | [
"https://Stackoverflow.com/questions/6454460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/529866/"
] | Your script is more than likely caching out-dated code. So, from Michael Pakhanstovs link you can run
```
DBMS_SESSION.RESET_PACKAGE
```
at the beginning of your script or use
```
PRAGMA SERIALLY_REUSABLE;
```
in your script.
Note however the implications of both:
<http://download.oracle.com/docs/cd/B13789_01/appdev.101/b10807/13_elems046.htm>
<http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_sessio.htm#i1010767>
[http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11\_QUESTION\_ID:2298325131459](http://asktom.oracle.com/pls/asktom/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:2298325131459)
AskTom on DBMS\_SESSION.RESET\_PACKAGE:
>
> dbms\_session.reset\_package, while MUCH
> faster then logging in and out, has
> some performance implications (not as
> fast as not doing it obviously!).
> That and it'll rip down the entire
> session state, eg: any opened cursors
> you have (prepared statements) as
> well.
>
>
>
AskTom on PRAGMA SERIALLY\_REUSABLE:
>
> Its basically saying 'if you use a
> package and you don't save a state in
> that package and would like avoid
> having the persistance of the package
> in your session -- less memory -- use
> this'
>
>
> | I had the same problem.
My situation was that I wrote a dynamic creation script for a package, then in the next script line call the procedure from the package. I think you're in the same situation.
The problem I detected was that the timestamp for the package generation was identical to the timestamp of the procedure call. Nowadays, with faster and faster servers ... it happens.
So in the generation script I have introduced `dbms_lock.wait(2)` after the package creation line.
This got rid of the problem! |
6,454,460 | I am using Oracle and I have modified code on some triggers and a package.
When I run the script file which modifies the code and try to do an update on a table (which fires the trigger) I am getting Existing State of Package discarded
I am getting a bunch of error
```
ORA-04068:
ORA-04061:
ORA-04065:
ORA-06512:--Trigger error -- line 50
ORA-04088:
```
This error is happening only the first time. Any inputs to avoid this would be greatly appreciated. Thank you! | 2011/06/23 | [
"https://Stackoverflow.com/questions/6454460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/529866/"
] | serially\_reusable only makes sense for constant package variables.
There is only one way to avoid this error and maintain performance (reset\_package is really not a good option). Avoid any package level variables in your PL/SQL packages. Your Oracle's server memory is not the right place to store state.
If something really does not change, is expensive to compute and a return value from a function can be reused over and over without recomputation, then DETERMINISTIC helps in that regard
example: DON'T DO THIS:
varchar2(100) cached\_result;
```
function foo return varchar2 is
begin
if cached_result is null then
cached_result:= ... --expensive calc here
end if;
return cached_result;
end foo;
```
DO THIS INSTEAD
```
function foo return varchar2 DETERMINISTIC is
begin
result:=... --expensive calc here
return result;
end foo;
```
Deterministic tells Oracle that for a given input, the result does not change, so it can cache the result and avoid calling the function.
If this is not your use case and you need to share a variable across sessions, use a table, and query it. Your table will end up in the buffer cache memory if it is used with any frequency, so you get the in memory storage you desire without the problems of session variables | I had the same problem.
My situation was that I wrote a dynamic creation script for a package, then in the next script line call the procedure from the package. I think you're in the same situation.
The problem I detected was that the timestamp for the package generation was identical to the timestamp of the procedure call. Nowadays, with faster and faster servers ... it happens.
So in the generation script I have introduced `dbms_lock.wait(2)` after the package creation line.
This got rid of the problem! |
38,664,135 | I need to make a function which will add to the beginning date 3 days and if it's 3 then it shows alert.
```
$beginDate = 2016-07-29 17:14:43 (this one is from sql table format)
$dateNow = date now
if $beginDate + 3 days (72h) is >= $dateNow then echo "It's been three days from..."
```
It seems to be simple but I have hard time to make it work with strtotime() and date() functions. How to code this in PHP? | 2016/07/29 | [
"https://Stackoverflow.com/questions/38664135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4591630/"
] | you can try Smaf.tv, the free cross-platform JS SDK and command line tool, with which you can build and package TV apps with one code base for LG WebOS, Samsung Smart TV (Orsay) & Tizen, Android TV and Amazon Fire TV.
Disclaimer: I am part of the Smaf.tv team, but honestly I believe it fits your objective | If you already have an Android app, then it technically should already work with Android TV. There are a few [TV-specific things](https://developer.android.com/training/tv/start/start.html) you can do:
* Declare a Leanback Launcher intent. Add this to your main activity in the manifest:
```
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
```
* Add a banner to your app's application tag:
```
<application
android:banner="@drawable/banner" >
```
* Test it out to make sure any user interaction you have works with a DPAD / remote control.
You can build and run on a device or in an emulator if you want to double-check. There's plenty more in the docs linked above if you want to learn more. |
66,986,409 | In my `df` below, I want to :
1. identify and flag the outliers in `col_E` using z-scores
2. separately explain how to identify and flag the outliers using z-scores in two or more columns, for example `col_D` & `col_E`
See below for the dataset
```
import pandas as pd
from scipy import stats
# intialise data of lists
df = {
'col_A':['P0', 'P1', 'P2', 'P4', 'P5'],
'col_B':[1,1,1,1,1],
'col_C':[1,2,3,5,9],
'col_D':[120.05, 181.90, 10.34, 153.10, 311.17],
'col_E':[110.21, 191.12, 190.21, 12.00, 245.09 ],
'col_F':[100.22,199.10, 191.13,199.99, 255.19],
'col_G':[140.29, 291.07, 390.22, 245.09, 4122.62],
}
# Create DataFrame
df = pd.DataFrame(df)
# Print the output.
df
```
Desired: flag all outliers in `col_D` first and then `col_D` and `col_E` secondly (Note: In my image below `10.34` and `12.00` were randomly highlighted)
Q1
[](https://i.stack.imgur.com/vVnsZ.png)
Attempt:
```
#Q1
exclude_cols = ['col_A','col_B','col_C','col_D','col_F','col_G']
include_cols = ['col_E'] # desired column
def flag_outliers(s, exclude_cols):
if s.name in exclude_cols:
print(s.name)
return ''
else:
s=df[(np.abs(stats.zscore(df['col_E'])) > 3)] # not sure of this part of the code
return ['background-color: yellow' if v else '' for v in indexes]
df.style.apply(lambda s: flag_outliers(s, exclude_cols), axis=1, subset=include_cols)
#Q2
exclude_cols = ['col_A','col_B','col_C','col_F','col_G']
include_cols = ['col_D','col_E'] # desired columns
def flag_outliers(s, exclude_cols):
if s.name in exclude_cols:
print(s.name)
return ''
else:
s=df[(np.abs(stats.zscore(df['col_E'])) > 3)] # not sure of this part of the code
return ['background-color: yellow' if v else '' for v in indexes]
df.style.apply(lambda s: flag_outliers(s, exclude_cols), axis=1, subset=include_cols)
```
Thanks! | 2021/04/07 | [
"https://Stackoverflow.com/questions/66986409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14488413/"
] | I assume the following meanings to demonstrate a broader range of usage.
* Q1 stands for calculating a single column
* Q2 stands for calculating over multiple columns pooled together.
If Q2 is meant to calculated on multiple columns separately, then you can simply loop your Q1 solution over multiple columns, which should be trivial so I will omit such situation here.
Keys
====
* Q1 is quite straightforward as one can return a list of values by list comprehension.
* Q2 is a little bit complicated because the z-score would be applied over a DataFrame subset (i.e. `axis=None` must be used). According to the [official docs](https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html#Building-styles), when applying style over a DataFrame, the returning object must also be a DataFrame with the same index and columns as the subset. This is what caused the reshaping and DataFrame construction artifacts.
Single Column (Q1)
==================
Note that `z=3` is lowered to `1.5` for demonstration purpose.
# desired column
include\_cols = ['col\_E']
```
# additional control
outlier_threshold = 1.5 # 3 won't work!
ddof = 0 # degree of freedom correction. Sample = 1 and population = 0.
def flag_outliers(s: pd.Series):
outlier_mask = np.abs(stats.zscore(s, ddof=ddof)) > outlier_threshold
# replace boolean values with corresponding strings
return ['background-color: yellow' if val else '' for val in outlier_mask]
df.style.apply(flag_outliers, subset=include_cols)
```
**Result**
[](https://i.stack.imgur.com/cE5Vo.png)
Multiple Column Pooled (Q2, Assumed)
====================================
Q2
==
```
include_cols = ['col_D', 'col_E'] # desired columns
outlier_threshold = 1.5
ddof = 0
def flag_outliers(s: pd.DataFrame) -> pd.DataFrame:
outlier_mask = np.abs(stats.zscore(s.values.reshape(-1), axis=None, ddof=ddof)) > outlier_threshold
# prepare the array of string to be returned
arr = np.array(['background-color: yellow' if val else '' for val in outlier_mask], dtype=object).reshape(s.shape)
# cast the array into dataframe
return pd.DataFrame(arr, columns=s.columns, index=s.index)
df.style.apply(flag_outliers, axis=None, subset=include_cols)
```
**Result**
[](https://i.stack.imgur.com/yDFMK.png) | Based on this [answer](https://stackoverflow.com/questions/52528568/using-dataframes-style-apply-for-highlighting-based-on-comparative-values), just pass the condition of the score to a dict storing the background color of each column index.
```
include_cols = ['col_D', 'col_E']
def color_outliers_yellow(row, include, color='yellow', z_score = 1):
styles = {col: '' for col in row.index}
if row.name in include:
scores = stats.zscore(list(row))
scores = [(f'background-color: {color}' if score > z_score else '') for score in scores]
return {k:v for k, v in zip(styles.keys(), scores)}
else:
return styles
df.style.apply(lambda x: color_outliers_yellow(x, include=include_cols), axis=0)
```
Results in:
[](https://i.stack.imgur.com/7Yv0j.png) |
41,590,518 | I'd like to return the rows which qualify to a certain condition. I can do this for a single row, but I need this for multiple rows combined. For example 'light green' qualifies to 'XYZ' being positive and 'total' > 10, where 'Red' does not. When I combine a neighbouring row or rows, it does => 'dark green'. Can I achieve this going over all the rows and not return duplicate rows?
```
N = 1000
np.random.seed(0)
df = pd.DataFrame(
{'X':np.random.uniform(-3,10,N),
'Y':np.random.uniform(-3,10,N),
'Z':np.random.uniform(-3,10,N),
})
df['total'] = df.X + df.Y + df.Z
df.head(10)
```
[](https://i.stack.imgur.com/9kL6Z.png)
EDIT;
Desired output is 'XYZ'> 0 and 'total' > 10 | 2017/01/11 | [
"https://Stackoverflow.com/questions/41590518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7168104/"
] | Here's a try. You would maybe want to use `rolling` or `expanding` (for speed and elegance) instead of explicitly looping with `range`, but I did it that way so as to be able to print out the rows being used to calculate each boolean.
```
df = df[['X','Y','Z']] # remove the "total" column in order
# to make the syntax a little cleaner
df = df.head(4) # keep the example more manageable
for i in range(len(df)):
for k in range( i+1, len(df)+1 ):
df_sum = df[i:k].sum()
print( "rows", i, "to", k, (df_sum>0).all() & (df_sum.sum()>10) )
rows 0 to 1 True
rows 0 to 2 True
rows 0 to 3 True
rows 0 to 4 True
rows 1 to 2 False
rows 1 to 3 True
rows 1 to 4 True
rows 2 to 3 True
rows 2 to 4 True
rows 3 to 4 True
``` | I am not too sure if I understood your question correctly, but if you are looking to put multiple conditions within a dataframe, you can consider this approach:
`new_df = df[(df["X"] > 0) & (df["Y"] < 0)]`
The `&` condition is for AND, while replacing that with `|` is for OR condition. Do remember to put the different conditions in `()`.
Lastly, if you want to remove duplicates, you can use this
`new_df.drop_duplicates()`
You can find more information about this function at here: <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html>
Hope my answer is useful to you. |
14,898,987 | I have an MySQL statement that performs an inner `SELECT` and returns the result as a pseudo column. I’d like to use the result of this pseudo column in my `WHERE` clause. My current SQL statement looks like this:
```
SELECT
product.product_id,
product.range_id,
product.title,
product.image,
product.image_text,
product.friendly_url,
attribute.comfort_grade_id,
category.category_id,
category.category AS category_name,
category.friendly_url AS category_friendly_url,
(SELECT price_now FROM product_bedding_sizes AS size
WHERE size.product_id = product.product_id
ORDER BY size.price_now ASC LIMIT 1) AS price
FROM
products AS product
LEFT JOIN
categories AS category ON product.category_id = category.category_id
LEFT JOIN
product_bedding_attributes AS attribute
ON product.product_id = attribute.product_id
$where
$order
LIMIT
?,?
```
However, I get the following error message when running the query:
>
> #1054 - Unknown column 'price' in 'where clause'
>
>
>
How can I get around this and actually use the value of `price` in my `WHERE` clause? | 2013/02/15 | [
"https://Stackoverflow.com/questions/14898987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/102205/"
] | The `WHERE` clause is evaluated before the `SELECT` clause, so it doesn't say the alias name. You have to do the filter by the `WHERE` clause in an outer query like this:
```
SELECT *
FROM
(
SELECT
product.product_id,
product.range_id,
product.title,
product.image,
product.image_text,
product.friendly_url,
attribute.comfort_grade_id,
category.category_id,
category.category AS category_name,
category.friendly_url AS category_friendly_url,
(SELECT price_now
FROM product_bedding_sizes AS size
WHERE size.product_id = product.product_id
ORDER BY size.price_now ASC
LIMIT 1) AS price
FROM
...
) AS sub
WHERE price = ... <--- here it can see the price alias.
```
See this for more details:
* [**My SQL Query Order of Operations**](http://www.bennadel.com/blog/70-SQL-Query-Order-of-Operations.htm).
---
**Or:** You can join that table, instead of a correlated subquery like this:
```
SELECT
product.product_id,
product.range_id,
product.title,
product.image,
product.image_text,
product.friendly_url,
attribute.comfort_grade_id,
category.category_id,
category.category AS category_name,
category.friendly_url AS category_friendly_url,
size.price_now
FROM
products AS product
LEFT JOIN
(
SELECT product_id, MIN(price_now) AS price
FROM product_bedding_sizes
GROUP BY product_id
) AS size ON size.product_id = product.product_id
LEFT JOIN
categories AS category ON product.category_id = category.category_id
LEFT JOIN
product_bedding_attributes AS attribute ON product.product_id = attribute.product_id
$where price = ----;
``` | Try using a variable:
```
@price:= (SELECT price_now
FROM product_bedding_sizes AS size
WHERE size.product_id = product.product_id
ORDER BY size.price_now ASC LIMIT 1) AS price;
```
Then reference it as
```
WHERE @price > 9000;
``` |
14,898,987 | I have an MySQL statement that performs an inner `SELECT` and returns the result as a pseudo column. I’d like to use the result of this pseudo column in my `WHERE` clause. My current SQL statement looks like this:
```
SELECT
product.product_id,
product.range_id,
product.title,
product.image,
product.image_text,
product.friendly_url,
attribute.comfort_grade_id,
category.category_id,
category.category AS category_name,
category.friendly_url AS category_friendly_url,
(SELECT price_now FROM product_bedding_sizes AS size
WHERE size.product_id = product.product_id
ORDER BY size.price_now ASC LIMIT 1) AS price
FROM
products AS product
LEFT JOIN
categories AS category ON product.category_id = category.category_id
LEFT JOIN
product_bedding_attributes AS attribute
ON product.product_id = attribute.product_id
$where
$order
LIMIT
?,?
```
However, I get the following error message when running the query:
>
> #1054 - Unknown column 'price' in 'where clause'
>
>
>
How can I get around this and actually use the value of `price` in my `WHERE` clause? | 2013/02/15 | [
"https://Stackoverflow.com/questions/14898987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/102205/"
] | The `WHERE` clause is evaluated before the `SELECT` clause, so it doesn't say the alias name. You have to do the filter by the `WHERE` clause in an outer query like this:
```
SELECT *
FROM
(
SELECT
product.product_id,
product.range_id,
product.title,
product.image,
product.image_text,
product.friendly_url,
attribute.comfort_grade_id,
category.category_id,
category.category AS category_name,
category.friendly_url AS category_friendly_url,
(SELECT price_now
FROM product_bedding_sizes AS size
WHERE size.product_id = product.product_id
ORDER BY size.price_now ASC
LIMIT 1) AS price
FROM
...
) AS sub
WHERE price = ... <--- here it can see the price alias.
```
See this for more details:
* [**My SQL Query Order of Operations**](http://www.bennadel.com/blog/70-SQL-Query-Order-of-Operations.htm).
---
**Or:** You can join that table, instead of a correlated subquery like this:
```
SELECT
product.product_id,
product.range_id,
product.title,
product.image,
product.image_text,
product.friendly_url,
attribute.comfort_grade_id,
category.category_id,
category.category AS category_name,
category.friendly_url AS category_friendly_url,
size.price_now
FROM
products AS product
LEFT JOIN
(
SELECT product_id, MIN(price_now) AS price
FROM product_bedding_sizes
GROUP BY product_id
) AS size ON size.product_id = product.product_id
LEFT JOIN
categories AS category ON product.category_id = category.category_id
LEFT JOIN
product_bedding_attributes AS attribute ON product.product_id = attribute.product_id
$where price = ----;
``` | if you have
```
WHERE price > 0 AND price` <= 199`
```
in your where clause
then try do this with HAVING clause
like that
```
$HAVING
//-- where $having = HAVING price > 0 AND price <= 199
``` |
52,989,218 | I have a one dimensional array of objects and each object has an id and an id of its parent. In the initial array I have each element can have at most one child. So if the array looks like this:
```
{id: 3, parent: 5},
{id: 5, parent: null},
{id: 6, parent: 3},
{id: 1, parent: null},
{id: 4, parent: 7},
{id: 2, parent: 1},
{id: 7, parent: 2}
```
I need it to look similar to this:
```
{id: 5, parent: null, children: [
{id: 3, parent: 5},
{id: 6, parent: 3}
]},
{id: 1, parent: null, children: [
{id: 2, parent: 1},
{id: 7, parent: 2},
{id: 4, parent: 7},
]}
```
I think the way I did it uses too much loops. Is there a better way?
```js
let items = [
{id: 3, parent: 5},
{id: 5, parent: null},
{id: 6, parent: 3},
{id: 1, parent: null},
{id: 4, parent: 7},
{id: 2, parent: 1},
{id: 7, parent: 2}
];
let itemsNew = [];
items = items.map(function(x){
return {id: x.id, parent: x.parent, children: []};
});
// new array with parents only
for(let i=items.length-1; i>=0; i--){
if(items[i].parent == null){
itemsNew.push(items[i]);
items.splice(i, 1);
}
}
for(let i=0; i<itemsNew.length; i++){
let childIndexes = findChildAll(itemsNew[i].id);
// sort the indexes so splicing the array wont misplace them
childIndexes.sort(function(a,b){
return b-a;
});
for(let j=0; j<childIndexes.length; j++){
itemsNew[i].children.push(items[childIndexes[j]]);
items.splice(childIndexes[j], 1);
}
}
// returns an array of indexes of all the element's children and their children
function findChildAll(parentId){
for(let i=0; i<items.length; i++){
if(items[i].parent == parentId){
let resultArray = findChildAll(items[i].id);
// is the result as an array add it to the index
if(resultArray) return [i].concat(resultArray);
// otherwise return just this index
return [i];
}
}
}
console.log(itemsNew);
``` | 2018/10/25 | [
"https://Stackoverflow.com/questions/52989218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3007853/"
] | For me, I ended up just editing the snippet itself. I'm sure I will need to do this every time there is an update and I'm not sure of a better permanent fix outside of creating a user-defined snippet.
My quick and dirty fix was to edit the file...
>
> %USERPROFILE%.vscode\extensions\ms-dotnettools.csharp-1.23.8\snippets\csharp.json
>
>
>
Then look for the following section (found mine around line 53)...
```
"Console.WriteLine": {
"prefix": "cw",
"body": [
"System.Console.WriteLine($0);"
],
"description": "Console.WriteLine"
},
```
Then just change...
```
"System.Console.WriteLine($0);"
```
To...
```
"Console.WriteLine($0);"
```
Save, then restart VSCode and test the `cw` snippet. | You can tell the snippet if the using statement for system is not already on the page to add it. Include the following **after** the open tag `<snippet>` and **before** opening `<declarations>` tag.
```
<Imports>
<Import>
<Namespace>System</Namespace>
</Import>
</Imports>
```
For Reference to add more (in this case it isn't needed but you may in the future) imports you will need to make separate tag pairs (as below).
```
<Import>
<Namespace></Namespace>
</Import>
``` |
8,531,269 | How to Create a `View` with all days in year. `view` should fill with dates from JAN-01 to Dec-31. How can I do this in Oracle ?
If current year have 365 days,`view` should have 365 rows with dates. if current year have 366 days,`view` should have 366 rows with dates. I want the `view` to have a single column of type `DATE`. | 2011/12/16 | [
"https://Stackoverflow.com/questions/8531269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029088/"
] | This simple view will do it:
```
create or replace view year_days as
select trunc(sysdate, 'YYYY') + (level-1) as the_day
from dual
connect by level <= to_number(to_char(last_day(add_months(trunc(sysdate, 'YYYY'),11)), 'DDD'))
/
```
Like this:
```
SQL> select * from year_days;
THE_DAY
---------
01-JAN-11
02-JAN-11
03-JAN-11
04-JAN-11
05-JAN-11
06-JAN-11
07-JAN-11
08-JAN-11
09-JAN-11
10-JAN-11
11-JAN-11
...
20-DEC-11
21-DEC-11
22-DEC-11
23-DEC-11
24-DEC-11
25-DEC-11
26-DEC-11
27-DEC-11
28-DEC-11
29-DEC-11
30-DEC-11
31-DEC-11
365 rows selected.
SQL>
```
The date is generated by applying several Oracle date functions:
* `trunc(sysdate, 'yyyy')` gives us the first of January for the current year
* `add_months(x, 11)` gives us the first of December
* `last_day(x)` gives us the thirty-first of December
* `to_char(x, 'DDD')` gives us the number of the thirty-first of December, 365 this year and 366 next.
* This last figure provides the upper bound for the row generator `CONNECT BY LEVEL <= X` | you can use piplined table, it should be something like this:
```
create or replace type year_date_typ as object (v_day date);
create or replace type year_date_tab as table of year_date_typ;
CREATE OR REPLACE FUNCTION get_dates(year IN VARCHAR2) RETURN year_date_tab PIPELINED IS
v_start_date date := to_date('0101' || year, 'ddmmyyyy');
res year_date_typ := year_date_typ(null);
v_days_in_year integer := 365;
BEGIN
if to_char(last_day(to_date('0102'||year, 'ddmmyyyy')), 'dd') = '29' then
v_days_in_year := 366;
end if;
FOR i in 0 .. v_days_in_year integer-1 LOOP
res.v_day := v_start_date + i;
pipe row(res);
END LOOP;
return;
END get_dates;
```
and you can use it:
```
select * from table(get_dates('2011'));
``` |
8,531,269 | How to Create a `View` with all days in year. `view` should fill with dates from JAN-01 to Dec-31. How can I do this in Oracle ?
If current year have 365 days,`view` should have 365 rows with dates. if current year have 366 days,`view` should have 366 rows with dates. I want the `view` to have a single column of type `DATE`. | 2011/12/16 | [
"https://Stackoverflow.com/questions/8531269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029088/"
] | This simple view will do it:
```
create or replace view year_days as
select trunc(sysdate, 'YYYY') + (level-1) as the_day
from dual
connect by level <= to_number(to_char(last_day(add_months(trunc(sysdate, 'YYYY'),11)), 'DDD'))
/
```
Like this:
```
SQL> select * from year_days;
THE_DAY
---------
01-JAN-11
02-JAN-11
03-JAN-11
04-JAN-11
05-JAN-11
06-JAN-11
07-JAN-11
08-JAN-11
09-JAN-11
10-JAN-11
11-JAN-11
...
20-DEC-11
21-DEC-11
22-DEC-11
23-DEC-11
24-DEC-11
25-DEC-11
26-DEC-11
27-DEC-11
28-DEC-11
29-DEC-11
30-DEC-11
31-DEC-11
365 rows selected.
SQL>
```
The date is generated by applying several Oracle date functions:
* `trunc(sysdate, 'yyyy')` gives us the first of January for the current year
* `add_months(x, 11)` gives us the first of December
* `last_day(x)` gives us the thirty-first of December
* `to_char(x, 'DDD')` gives us the number of the thirty-first of December, 365 this year and 366 next.
* This last figure provides the upper bound for the row generator `CONNECT BY LEVEL <= X` | This works well in MS SQL
```
SELECT TOP (DATEDIFF(day, DATEADD(yy, DATEDIFF(yy,0,getdate()), 0), DATEADD(yy, DATEDIFF(yy,0,getdate()) + 1, -1))) n = ROW_NUMBER() OVER (ORDER BY [object_id]),
dateadd(day, ROW_NUMBER() OVER (ORDER BY [object_id]) - 1, DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)) AS AsOfDate FROM sys.all_objects
``` |
218,076 | Is an infinite topological direct sum of amenable Banach algebras amenable again?
Can you give me a good reference about this notion?
Thanks | 2015/09/11 | [
"https://mathoverflow.net/questions/218076",
"https://mathoverflow.net",
"https://mathoverflow.net/users/27066/"
] | The OP has now clarified that he or she is asking about $c\_0$-direct sums. To answer the question we need the notion of the amenability constant of a Banach algebra. Everything that follows is probably "folklore", in the sense that
(i) Johnson knew how to do it in 1972 but, due to the different culture at the time of mathematical publication, did not bother formally writing it down in his 1972 monograph *Cohomology in Banach Algebras* or his Amer J. Math article of the same year;
(ii) successive generations of researchers, who take seriously the study of amenability of Banach algebras, will *almost surely* have worked these results out for themselves during their own studies.
Actually, this result might also be somewhere in Runde's book, but I haven't checked. (**UPDATE 2015-11-10:** Tomasz Kania has pointed out that this is Corollary 2.3.19 in Runde's *Lectures on Amenability*.)
**Definition.** Given an amenable Banach algebra $B$, the amenability constant of $B$ is defined to be
$${\rm AM}(B):=\inf \{ \Vert M \Vert\_{(B\widehat\otimes B)^{\*\*}}\;\; \colon \;\;\hbox{$M$ is a virtual diagonal for $B$}\}. $$
(By weak-star compactness, the infimum is actually attained.) We adopt the convention that if $B$ is a non-amenable Banach algebra, ${\rm AM}(B)=+\infty$.
*Remark 1.*
It is an easy exercise to show that if $q:A\to B$ is a surjective homomorphism of Banach algebras then ${\rm AM}(B)\leq \Vert q\Vert^2{\rm AM}(A)$.
**Lemma 2.** Suppose $A$ is a Banach algebra and $(B\_i)\_{i\in \Lambda}$ is a family of closed subalgebras such that $\bigcup\_{i\in\Lambda} B\_i$ is dense in $A$. Then ${\rm AM}(A)\leq \sup\_{i\in\Lambda} {\rm AM}(B\_i)$.
Note that since closed subalgebras of ${\bf M}\_2({\mathbb C})$ can be non-amenable, the inequality in this lemma is usually not an equality.
*Outline of the proof of Lemma 2.* We may assume the RHS of the inequality is finite, bounded above by $C$ say; otherwise there is nothing to prove. Consider $(M\_i)\_{i\in\Lambda}$ where $M\_i$ is a virtual diagonal for $B\_i$ such that ${\rm AM}(B\_i)=\Vert M\_i \Vert$. Then $(M\_i)$ is a net in $(A\widehat{\otimes} A)^{\*\*}$, bounded by $C$; take any weak-star cluster point $M$. Then $\Vert M\Vert\leq C$ and one can check $M$ is indeed a virtual diagonal for $A$. **QED.**
**Lemma 3.**
Let $A\_1$ and $A\_2$ be Banach algebras, and let $B=A\_1\oplus\_\infty A\_2$ i.e. with the norm $\Vert (a\_1,a\_2)\Vert := \max (\Vert a\_1\Vert, \Vert a\_2\Vert)$.
Then ${\rm AM}(B)= \max \{{\rm AM}(A\_1), {\rm AM}(A\_2)\}$.
*Proof of lemma 3.* Since there are contractive, surjective algebra homomorphisms $q\_j:B\to A\_j$ ($j=1,2$) we have ${\rm AM}(B)\geq \max \{{\rm AM}(A\_1), {\rm AM}(A\_2)\}$ by Remark 1. Conversely, using the contractive embedding
$$ (A\_1\widehat\otimes A\_1) \oplus\_\infty (A\_2\widehat\otimes A\_2) \to (A\_1\oplus\_\infty A\_2)\widehat\otimes(A\_1\oplus\_\infty A\_2) $$
and the corresponding embedding at the level of biduals, we can combine a virtual diagonal $M\_1$ for $A\_1$ and a virtual diagonal $M\_2$ for $A\_2$ to get a virtual diagonal $M$ for $A$, which satisfies $\vert M \Vert \leq \max( \Vert M\_1\Vert, \Vert M\_2\Vert)$. **QED.**
**Proposition.** Let $(A\_n)\_{n=1}^\infty$ be a sequence of Banach algebras, and let $A=c\_0{\rm-}\bigoplus\_{n=1}^\infty A\_n$. Then
${\rm AM}(A) = \sup\_n {\rm AM}(A\_n) <\infty$.
*Proof that LHS ≥ RHS.* This is like the proof of Lemma 2, using the contractive surjective homomorphisms $A\to A\_n$ for $1\leq n\leq\infty$, and I omit the details.
*Proof that LHS ≤ RHS.* Let $C=\sup\_n {\rm AM}(A\_n)$; we may assume $C<\infty$, otherwise there is nothing to prove. Now let $B\_n = A\_1 \oplus \dots \oplus A\_n$. By Lemma 3 and induction we know that ${\rm AM}(B\_n)\leq C$, for each $n$. Since $\bigcup\_{n\geq 1} B\_n$ is dense in $A$, applying Lemma 2 completes the proof. **QED.**
---
**OLD answer, before the question was clarified**
Tomek Kania has already pointed out the key "counterexample" (assuming that by infinite topological direct sum you mean what I would call the $\ell^\infty$-direct sum).
I should also point out that there are commutative counterexamples. Indeed, let $A={\ell^\infty}{\rm-}\bigoplus \ell^1({\bf T}\_d)$ where ${\bf T}\_d$ denotes the unit circle equipped with the discrete topology, and the multiplication on $\ell^1({\bf T}\_d)$ is given by convolution. Then, as observed in e.g. Proposition 5.8 of <http://arxiv.org/abs/0708.4195> $A$ quotients onto $M(G\_0)$ where $G\_0$ is the Bohr compactificaton of ${\bf T}\_d$.
If $A$ were weakly amenable, then $M(G\_0)$ would be weakly amenable; but by results of Brown and Moran $M(G\_0)$ has non-zero point derivations, hence is not weakly amenable. Therefore $A$ is not weakly amenable, and in particular cannot be amenable. | **No.** $\left(\bigoplus\_{n=1}^\infty M\_n(\mathbb{C}\right)\_{\ell\_\infty}$ is not amenable.
Of course, for $\ell\_p$-sums with $p\in [1,\infty)$ it is even worse. Here already $\ell\_p$ regarded as an infinite sum of one-dimensional algebras is not amenable. |
46,179,420 | I need, to clear my chartViewers from a layout, but when I do, I can't delete the last widget.
when I test the length of my layout, I get 0 but the widget is still here after update of the layout, as in the picture :
[](https://i.stack.imgur.com/dG8xb.png)
here my code when I delete, the widgets and the graphs
```
print("proceding to delete chart ", chartName, " at : ", indexGraph)
currentGraph = self.charts[indexGraph]
currentWidget = self.chartVs[indexGraph]
self.chartLayout.removeWidget(currentWidget)
self.chartVs.remove(currentWidget)
currentGraph.clearData()
self.charts.remove(currentGraph)
self.chartLayout.update()
#currentWidget.resetCachedContent()
listGraphs.remove(chartName)
self.refreshListWithOpt(self.chartTree, listGraphs, 1, optGraphs)
```
and here is the code where I create the graphs and add it to the layout:
```
self.charts.append(chartClass(patientStr, exp))
print("\nNew Plot chart ", self.charts[lastIndex].name, " length : ", lastIndex )
listGraphs.append(self.charts[lastIndex].name)
print("list Graphs : ", listGraphs)
self.charts[lastIndex].plotJSON(myData.plot(patientStr, exp))
self.chartVs.append(QChartView(self.charts[lastIndex]))
self.chartVs[lastIndex].setRenderHint(QPainter.Antialiasing)
self.chartLayout.insertWidget(0, self.chartVs[lastIndex])
```
Any suggestion? | 2017/09/12 | [
"https://Stackoverflow.com/questions/46179420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8264778/"
] | Here is a [link](http://blogs.adatis.co.uk/jonathoneveoconnor/post/Continuous-Integration-With-TeamCity-Automating-SSIS-Build-and-Deployment) that describes the auto-deployment of packages post check-in into SSISDB catalog. If you have SSIS 2012+ then that would be a way to go. Even if not you would need to modify the target to msdb/SSIS file system.
Coming to your second ask, deploy to SQL Agent. You would need to write another build step to do that step of automation. Make use of [T-SQL code](https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-add-jobstep-transact-sql) and add the package name as a parameter and have it deployed. The thing to remember about this is that SQL Agent job can have numerous job steps doing various tasks.
Say if you are deploying 10 packages of project and your requirement demands that all ten to be part of one SQL Server Agent Job, then design your T-SQL Code accordingly. If you need 10 seperate jobs for these packages then your code needs to do that in that manner.
I would strongly advice doing this as a one-time job. If you have the auto-deployment to create Agent when the package gets changed thereby needing to re-create the job, then you would be losing job history. | Generally, In TFS there isn't a way to do that.
Although we can use the [Checkin command](https://www.visualstudio.com/en-us/docs/tfvc/checkin-command) to check in the changes, but have to identify the changes first. The system will identify the changes and display in **Pending Changes** page. Then we can check in the changes manually by click the **Check in** button or with check in command
So, **Check in** is the required and the first step. You can set [Continuous integration (CI)](https://www.visualstudio.com/en-us/docs/build/define/triggers#continuous-integration-ci) for your build definition which with the "`Deploy to SQL Agent`" steps set, thus the build/deploy will be triggered automatically once any changes be checked in.
Reference below articles:
* [Deployment to several databases using SQL Server Data Tools and Team
foundation Server](https://www.sqlshack.com/continuous-integration-sql-server-data-tools-team-foundation-server/)
* [Build and Deploy SSIS packages using VSTS](http://abelsquidhead.com/index.php/2016/10/06/build-and-deploy-ssis-packages-using-vsts/) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.