qid
int64
1
74.7M
question
stringlengths
1
70k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
0
60.5k
473,683
I am looking for a word or phrase which can be used in the sentence: > > It is a rather old, but \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ technology. > > > The word or phrase should address a technology that is totally investigated, researched in detail, and thoroughly optimised, so there is nothing more to find out or improve.
2018/11/19
[ "https://english.stackexchange.com/questions/473683", "https://english.stackexchange.com", "https://english.stackexchange.com/users/324928/" ]
The word that first came to mind for me was ***robust***, which a previous poster had used in describing the meaning of the word they were suggesting ("foolproof"). > > [**robust**](https://www.merriam-webster.com/dictionary/robust) > > > 1d : capable of performing without failure under a wide range of > conditions > > > * *robust software* > > >
The phrase that comes to mind immediately for me is a **well oiled machine**. Macmillan dictionary [notes](https://www.macmillandictionary.com/dictionary/british/well-oiled) that the adjective phrase describes something that "operates without problems;" Merriam-Webster [uses](https://www.merriam-webster.com/dictionary/well-oiled) the defining phrase "smoothly functioning." > > The word or the phrase should address a technology, which is totally investigated, researched into detail, thoroughly optimised so there is nothing more to find out or improve. > > > "Well-oiled" indicates that everything is running optimally with no clear room for improvement and no implied efforts toward further investigation or research, but rather continuing with the great status quo. Also, with more and more machines going digital, use of this phrase would cause a mental association with older technology, but technology that is still functioning well.
54,322,336
I have installed my PWA from Chrome and Firefox on Android, and from Safari on iOS. When I update my code on the website, I see quite different behaviour in the PWAs in terms of using older cached versions vs the newest one - Firefox-created PWA seems to require about 2-3 kill and restarts of the PWA, Chrome takes 5-6, and I couldn't get Safari-based PWA to start showing the newest version without deleting the PWA and re-adding to Home Screen from browser. Is there a spec that defines the conditions under which a newer, non-cached version is fetched? After much reading, I disabled the registering of my service worker, which should have made the PWAs network-only (no service-worker cache) but I continue to get old versions of the site served up in the PWAs. A normal browser window also seems to require multiple deep refreshes to get the new version, so I assume there is something besides the service worker that determines this?
2019/01/23
[ "https://Stackoverflow.com/questions/54322336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1275803/" ]
Some actions like `.Add()` are producing output. To prevent this, pipe the output into the `[void]` by adding `| Out-Null` at the end of the line or `[void]` directly infront of the variable that is used, like: ``` $foo.SomethingThatGeneratesOutput() | Out-Null ``` or ``` [void]$foo = SomethingThatGeneratesOutput ```
As T-Me has stated, to prevent output being generated when executing methods as you are use [Void]. ``` [Void]$Form1.Controls.Add([ObjectType]) ``` If your code is still returning unwanted data, open the script in PowerShell ISE, and execute the script line by line (select the line and press F8). This will help you determine which line of code is generating output still.
395,882
Let $A$ be a ring. Prove that the following conditions are equivalent: $i)$ All ideals $I \subsetneq A$ are prime. $ii)$ The set of all ideals of $A$ is totally ordered by inclusion and all ideals of $A$ are idempotent. Please give me a hint. I dont see the relation between these two statemens.
2013/05/18
[ "https://math.stackexchange.com/questions/395882", "https://math.stackexchange.com", "https://math.stackexchange.com/users/70628/" ]
First suppose the ideals are linearly ordered and they are all idempotent. We will show that a proper ideal $C\lhd R$ is prime: Let $A,B$ be two other ideals such that $AB\subseteq C$. By way of contradiction, suppose that neither $A$ nor $B$ are contained in $C$. By the linear order, the three form a chain with $C$ at the bottom, so, without loss of generality, we suppose $C\subseteq B\subseteq A$. But then $C\supseteq AB\supseteq BB=B$. This contradicts the statement that $B$ is not contained in $C$. Thus, $C$ is prime. --- The other direction is easy of course! Suppose all proper ideals of $R$ are prime. Firstly, for any ideal $A$, $A^2$ is prime. But then by primeness $A\subseteq A^2$, so that $A=A^2$. Secondly, given two ideals $A,B$, the product $AB$ is a prime ideal. But by primeness, either $A\subseteq AB$ or $B \subseteq AB$. In the first case, $A\subseteq AB\subseteq B$ and in the second, $B\subseteq AB\subseteq A$. --- Considering the classic commutative theory result (A commutative ring in which all proper ideals are prime is a field."), this exercise shows that the direct noncommutative analogue ("All ideals prime implies division ring???") is not going to hold." Of course, any full square matrix ring $M\_n(F)$ over a field ($n>1$) has only one proper ideal, which is prime, and this shows that such a ring does not have to be a division ring. But with a suitable definition of a prime right ideal the result can be saved! In Lam and Reyes's excellent paper [*A one-sided prime ideal principle for noncommutative rings*](http://arxiv.org/pdf/0903.5295v4.pdf) such a definition of "prime right ideal" is given, and it's an elementary result shown there that a ring whose right ideals are all prime in this way is a division ring. (Actually the paper is full of much more interesting results, and I just can't resist plugging it here.)
Assume (i). Let $\mathfrak a,\mathfrak b\subsetneq A$ be two ideals and assume $\mathfrak a$ is not contained in $\mathfrak b$, i.e. there exists $a\in\mathfrak a\setminus \mathfrak b$. Then for $b\in\mathfrak b$, we have $aAb\subseteq\mathfrak a\cap \mathfrak b$. As the latter is a prime ideal and $a\notin\mathfrak a\cap \mathfrak b$, we conclude $b\in\mathfrak a\cap \mathfrak b\subseteq \mathfrak a$, in other words $\mathfrak b\subseteq \mathfrak a$. Similarly, if $a\in \mathfrak a$, then $aAa\in\mathfrak a^2$ implies $a\in\mathfrak a^2$, i.e. $\mathfrak a=\mathfrak a^2$.
61,799,543
I have been trying to figure out how to plot this data but can't figure out my mistake: ``` Month Year Sales January 2020 43 feburary 2020 23 March 2020 13 April 2020 11 May 2020 7 June 2020 2 July 2020 1 August 2020 2 September 2020 22 October 2020 11 November 2020 6 December 2020 3 January 2019 3 feburary 2019 11 March 2019 65 April 2019 22 May 2019 33 June 2019 88 July 2019 44 August 2019 12 September 2019 32 October 2019 54 November 2019 76 December 2019 23 January 2018 12 feburary 2018 32 March 2018 234 April 2018 2432 May 2018 432 June 2018 324 July 2018 12 August 2018 324 September 2018 89 October 2018 6 November 2018 46 December 2018 765 ``` I tried the following ``` y = df["sales"] x = df["Month"] plt.plot(x,y) plt.show() ``` Which gives the following plot(The exact values are different as my data values posted here is changed): [![enter image description here](https://i.stack.imgur.com/TfIQ0.png)](https://i.stack.imgur.com/TfIQ0.png) How do I correct it so that my plot breaks off each time at december and plots a new line for a separate year?
2020/05/14
[ "https://Stackoverflow.com/questions/61799543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8499442/" ]
If you have a pandas DataFrame that looks like: ``` year month sales 0 2020 January 43.0 1 2020 feburary 23.0 2 2020 March 13.0 3 2020 April 11.0 4 2020 May 7.0 5 2020 June 2.0 6 2020 July 1.0 7 2020 August 2.0 8 2020 September 22.0 9 2020 October 11.0 10 2020 November 6.0 11 2020 December 3.0 12 2019 January 3.0 13 2019 feburary 11.0 14 2019 March 65.0 15 2019 April 22.0 16 2019 May 33.0 17 2019 June 88.0 18 2019 July 44.0 19 2019 August 12.0 20 2019 September 32.0 21 2019 October 54.0 22 2019 November 76.0 23 2019 December 23.0 24 2018 January 12.0 25 2018 feburary 32.0 26 2018 March 234.0 27 2018 April 2432.0 28 2018 May 432.0 29 2018 June 324.0 30 2018 July 12.0 31 2018 August 324.0 32 2018 September 89.0 33 2018 October 6.0 34 2018 November 46.0 35 2018 December 765.0 ``` We can use `df.groupby('year')` to generate the kind of parsing that you're looking for: ``` fig, ax = plt.subplots() ax.set_xticklabels(df['month'].unique(), rotation=90) for name, group in df.groupby('year'): ax.plot(group['month'], group['sales'], label=name) ax.legend() plt.tight_layout() plt.show() ``` [![enter image description here](https://i.stack.imgur.com/AsLbG.png)](https://i.stack.imgur.com/AsLbG.png)
Try converting your columns to DataTime datatypes: ``` >>> df = pd.DataFrame({'year': [2015, 2016], 'month': [2, 3], 'day': [4, 5]}) >>> pd.to_datetime(df) 0 2015-02-04 1 2016-03-05 ``` You should now be able to plot against your dates.
61,799,543
I have been trying to figure out how to plot this data but can't figure out my mistake: ``` Month Year Sales January 2020 43 feburary 2020 23 March 2020 13 April 2020 11 May 2020 7 June 2020 2 July 2020 1 August 2020 2 September 2020 22 October 2020 11 November 2020 6 December 2020 3 January 2019 3 feburary 2019 11 March 2019 65 April 2019 22 May 2019 33 June 2019 88 July 2019 44 August 2019 12 September 2019 32 October 2019 54 November 2019 76 December 2019 23 January 2018 12 feburary 2018 32 March 2018 234 April 2018 2432 May 2018 432 June 2018 324 July 2018 12 August 2018 324 September 2018 89 October 2018 6 November 2018 46 December 2018 765 ``` I tried the following ``` y = df["sales"] x = df["Month"] plt.plot(x,y) plt.show() ``` Which gives the following plot(The exact values are different as my data values posted here is changed): [![enter image description here](https://i.stack.imgur.com/TfIQ0.png)](https://i.stack.imgur.com/TfIQ0.png) How do I correct it so that my plot breaks off each time at december and plots a new line for a separate year?
2020/05/14
[ "https://Stackoverflow.com/questions/61799543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8499442/" ]
Just add plots to the same graph as: ``` from matplotlib import pyplot as plt import pandas as pd data = pd.read_csv('year_data.csv') for year in data['Year'].unique(): plt.plot(data[data['Year']==year]['Month'], data[data['Year']==year]['Sales']) plt.xticks(rotation=90) plt.show() ``` The above code gives something like: [![graph with multiple plots](https://i.stack.imgur.com/9XQw2.png)](https://i.stack.imgur.com/9XQw2.png)
Try converting your columns to DataTime datatypes: ``` >>> df = pd.DataFrame({'year': [2015, 2016], 'month': [2, 3], 'day': [4, 5]}) >>> pd.to_datetime(df) 0 2015-02-04 1 2016-03-05 ``` You should now be able to plot against your dates.
61,799,543
I have been trying to figure out how to plot this data but can't figure out my mistake: ``` Month Year Sales January 2020 43 feburary 2020 23 March 2020 13 April 2020 11 May 2020 7 June 2020 2 July 2020 1 August 2020 2 September 2020 22 October 2020 11 November 2020 6 December 2020 3 January 2019 3 feburary 2019 11 March 2019 65 April 2019 22 May 2019 33 June 2019 88 July 2019 44 August 2019 12 September 2019 32 October 2019 54 November 2019 76 December 2019 23 January 2018 12 feburary 2018 32 March 2018 234 April 2018 2432 May 2018 432 June 2018 324 July 2018 12 August 2018 324 September 2018 89 October 2018 6 November 2018 46 December 2018 765 ``` I tried the following ``` y = df["sales"] x = df["Month"] plt.plot(x,y) plt.show() ``` Which gives the following plot(The exact values are different as my data values posted here is changed): [![enter image description here](https://i.stack.imgur.com/TfIQ0.png)](https://i.stack.imgur.com/TfIQ0.png) How do I correct it so that my plot breaks off each time at december and plots a new line for a separate year?
2020/05/14
[ "https://Stackoverflow.com/questions/61799543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8499442/" ]
If you have a pandas DataFrame that looks like: ``` year month sales 0 2020 January 43.0 1 2020 feburary 23.0 2 2020 March 13.0 3 2020 April 11.0 4 2020 May 7.0 5 2020 June 2.0 6 2020 July 1.0 7 2020 August 2.0 8 2020 September 22.0 9 2020 October 11.0 10 2020 November 6.0 11 2020 December 3.0 12 2019 January 3.0 13 2019 feburary 11.0 14 2019 March 65.0 15 2019 April 22.0 16 2019 May 33.0 17 2019 June 88.0 18 2019 July 44.0 19 2019 August 12.0 20 2019 September 32.0 21 2019 October 54.0 22 2019 November 76.0 23 2019 December 23.0 24 2018 January 12.0 25 2018 feburary 32.0 26 2018 March 234.0 27 2018 April 2432.0 28 2018 May 432.0 29 2018 June 324.0 30 2018 July 12.0 31 2018 August 324.0 32 2018 September 89.0 33 2018 October 6.0 34 2018 November 46.0 35 2018 December 765.0 ``` We can use `df.groupby('year')` to generate the kind of parsing that you're looking for: ``` fig, ax = plt.subplots() ax.set_xticklabels(df['month'].unique(), rotation=90) for name, group in df.groupby('year'): ax.plot(group['month'], group['sales'], label=name) ax.legend() plt.tight_layout() plt.show() ``` [![enter image description here](https://i.stack.imgur.com/AsLbG.png)](https://i.stack.imgur.com/AsLbG.png)
Your plotting at the moment is aggregating all the years in the same graph, so it actually "loop around" when you reach the end of the year. You could split the dataframe in 12-month periods and actually plot on the same matplotlib subplot as different lines: ``` import pandas as pd import matplotlib.pyplot as plt ###################### ## DATA PREPARATION ## ###################### sales20 = df.loc[df['Year'] == 2020, 'Sales'] sales19 = df.loc[df['Year'] == 2019, 'Sales'] ############## ## PLOTTING ## ############## # Create a new figure fig = plt.figure() # Add a subplot to the figure ax = fig.add_subplot() # Add to the subplot two line plots labeled accordingly ax.plot(df["Month"], sales20, label='2020') ax.plot(df["Month"], sales19, label='2019') # Add handy legend ax.legend(loc='best') # Finger crossed and show the graph plt.show() ``` It's a bit of a quick and dirty solution I must admit... A more elegant one would be to convert the dataframe to being indexed with a `datetime` index, look at the [Pandas docs on the matter](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html)
61,799,543
I have been trying to figure out how to plot this data but can't figure out my mistake: ``` Month Year Sales January 2020 43 feburary 2020 23 March 2020 13 April 2020 11 May 2020 7 June 2020 2 July 2020 1 August 2020 2 September 2020 22 October 2020 11 November 2020 6 December 2020 3 January 2019 3 feburary 2019 11 March 2019 65 April 2019 22 May 2019 33 June 2019 88 July 2019 44 August 2019 12 September 2019 32 October 2019 54 November 2019 76 December 2019 23 January 2018 12 feburary 2018 32 March 2018 234 April 2018 2432 May 2018 432 June 2018 324 July 2018 12 August 2018 324 September 2018 89 October 2018 6 November 2018 46 December 2018 765 ``` I tried the following ``` y = df["sales"] x = df["Month"] plt.plot(x,y) plt.show() ``` Which gives the following plot(The exact values are different as my data values posted here is changed): [![enter image description here](https://i.stack.imgur.com/TfIQ0.png)](https://i.stack.imgur.com/TfIQ0.png) How do I correct it so that my plot breaks off each time at december and plots a new line for a separate year?
2020/05/14
[ "https://Stackoverflow.com/questions/61799543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8499442/" ]
Just add plots to the same graph as: ``` from matplotlib import pyplot as plt import pandas as pd data = pd.read_csv('year_data.csv') for year in data['Year'].unique(): plt.plot(data[data['Year']==year]['Month'], data[data['Year']==year]['Sales']) plt.xticks(rotation=90) plt.show() ``` The above code gives something like: [![graph with multiple plots](https://i.stack.imgur.com/9XQw2.png)](https://i.stack.imgur.com/9XQw2.png)
Your plotting at the moment is aggregating all the years in the same graph, so it actually "loop around" when you reach the end of the year. You could split the dataframe in 12-month periods and actually plot on the same matplotlib subplot as different lines: ``` import pandas as pd import matplotlib.pyplot as plt ###################### ## DATA PREPARATION ## ###################### sales20 = df.loc[df['Year'] == 2020, 'Sales'] sales19 = df.loc[df['Year'] == 2019, 'Sales'] ############## ## PLOTTING ## ############## # Create a new figure fig = plt.figure() # Add a subplot to the figure ax = fig.add_subplot() # Add to the subplot two line plots labeled accordingly ax.plot(df["Month"], sales20, label='2020') ax.plot(df["Month"], sales19, label='2019') # Add handy legend ax.legend(loc='best') # Finger crossed and show the graph plt.show() ``` It's a bit of a quick and dirty solution I must admit... A more elegant one would be to convert the dataframe to being indexed with a `datetime` index, look at the [Pandas docs on the matter](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html)
61,799,543
I have been trying to figure out how to plot this data but can't figure out my mistake: ``` Month Year Sales January 2020 43 feburary 2020 23 March 2020 13 April 2020 11 May 2020 7 June 2020 2 July 2020 1 August 2020 2 September 2020 22 October 2020 11 November 2020 6 December 2020 3 January 2019 3 feburary 2019 11 March 2019 65 April 2019 22 May 2019 33 June 2019 88 July 2019 44 August 2019 12 September 2019 32 October 2019 54 November 2019 76 December 2019 23 January 2018 12 feburary 2018 32 March 2018 234 April 2018 2432 May 2018 432 June 2018 324 July 2018 12 August 2018 324 September 2018 89 October 2018 6 November 2018 46 December 2018 765 ``` I tried the following ``` y = df["sales"] x = df["Month"] plt.plot(x,y) plt.show() ``` Which gives the following plot(The exact values are different as my data values posted here is changed): [![enter image description here](https://i.stack.imgur.com/TfIQ0.png)](https://i.stack.imgur.com/TfIQ0.png) How do I correct it so that my plot breaks off each time at december and plots a new line for a separate year?
2020/05/14
[ "https://Stackoverflow.com/questions/61799543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8499442/" ]
If you have a pandas DataFrame that looks like: ``` year month sales 0 2020 January 43.0 1 2020 feburary 23.0 2 2020 March 13.0 3 2020 April 11.0 4 2020 May 7.0 5 2020 June 2.0 6 2020 July 1.0 7 2020 August 2.0 8 2020 September 22.0 9 2020 October 11.0 10 2020 November 6.0 11 2020 December 3.0 12 2019 January 3.0 13 2019 feburary 11.0 14 2019 March 65.0 15 2019 April 22.0 16 2019 May 33.0 17 2019 June 88.0 18 2019 July 44.0 19 2019 August 12.0 20 2019 September 32.0 21 2019 October 54.0 22 2019 November 76.0 23 2019 December 23.0 24 2018 January 12.0 25 2018 feburary 32.0 26 2018 March 234.0 27 2018 April 2432.0 28 2018 May 432.0 29 2018 June 324.0 30 2018 July 12.0 31 2018 August 324.0 32 2018 September 89.0 33 2018 October 6.0 34 2018 November 46.0 35 2018 December 765.0 ``` We can use `df.groupby('year')` to generate the kind of parsing that you're looking for: ``` fig, ax = plt.subplots() ax.set_xticklabels(df['month'].unique(), rotation=90) for name, group in df.groupby('year'): ax.plot(group['month'], group['sales'], label=name) ax.legend() plt.tight_layout() plt.show() ``` [![enter image description here](https://i.stack.imgur.com/AsLbG.png)](https://i.stack.imgur.com/AsLbG.png)
Just add plots to the same graph as: ``` from matplotlib import pyplot as plt import pandas as pd data = pd.read_csv('year_data.csv') for year in data['Year'].unique(): plt.plot(data[data['Year']==year]['Month'], data[data['Year']==year]['Sales']) plt.xticks(rotation=90) plt.show() ``` The above code gives something like: [![graph with multiple plots](https://i.stack.imgur.com/9XQw2.png)](https://i.stack.imgur.com/9XQw2.png)
6,098,446
What git command will display a list of all committed modifications, one modified file per line, with the file's path?
2011/05/23
[ "https://Stackoverflow.com/questions/6098446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
I think ``` git log --stat ``` is what you're after.
This is how you get a full list without trimming: ``` git log --stat=200 --stat-name-width=150 ``` `200` stands for a total width of the output, and `150` for the width of a file name column. If name-width is bigger than total width it will be truncated.
4,247,113
I have to process spatial data which are nodes in a graph.What data type /variable type /data structure allows me to access the values of i-th node's x value and i-th node's y value.
2010/11/22
[ "https://Stackoverflow.com/questions/4247113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509505/" ]
I may be missing something here, but after looking at the Wikipedia entry on the golden section search it seems like it doesn't solve the same problem as a binary search at all. Whereas a binary search is useful for finding a value in a sorted list, a golden section search is used to find a minimum or maximum value of a function over a range of values.
"works faster" is vague; but binary search should have the lowest worst case bound for number of accesses.
4,247,113
I have to process spatial data which are nodes in a graph.What data type /variable type /data structure allows me to access the values of i-th node's x value and i-th node's y value.
2010/11/22
[ "https://Stackoverflow.com/questions/4247113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509505/" ]
There are two algorithms called "Fibonacci search". [The article you linked](http://en.wikipedia.org/wiki/Golden_section_search) is about a numerical algorithm for finding the maximum or minimum of certain functions. It is the optimal algorithm for this problem. This problem is just different enough from the binary search problem that it should be obvious for any given case which is appropriate. [The other kind of Fibonacci search](http://en.wikipedia.org/wiki/Fibonacci_search) does attack the same problem as binary search. Binary search is essentially always better. Knuth writes that Fibonacci search "is preferable on some computers, because it involves only addition and subtraction, not division by 2." But almost all computers use binary arithmetic, in which division by 2 is *simpler* than addition and subtraction. (The Wikipedia article currently claims that Fibonacci search could have better locality of reference, a claim Knuth does *not* make. It *could*, perhaps, but this is misleading. The tests done by a Fibonacci search are closer together precisely to the extent that they are less helpful in narrowing down the range; on average this would result in more reads from more parts of the table, not fewer. If the records are actually stored on tape, so that seek times dominate, then Fibonacci search might beat binary search—but in that case both algorithms are far from optimal.)
"works faster" is vague; but binary search should have the lowest worst case bound for number of accesses.
4,247,113
I have to process spatial data which are nodes in a graph.What data type /variable type /data structure allows me to access the values of i-th node's x value and i-th node's y value.
2010/11/22
[ "https://Stackoverflow.com/questions/4247113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509505/" ]
There are two algorithms called "Fibonacci search". [The article you linked](http://en.wikipedia.org/wiki/Golden_section_search) is about a numerical algorithm for finding the maximum or minimum of certain functions. It is the optimal algorithm for this problem. This problem is just different enough from the binary search problem that it should be obvious for any given case which is appropriate. [The other kind of Fibonacci search](http://en.wikipedia.org/wiki/Fibonacci_search) does attack the same problem as binary search. Binary search is essentially always better. Knuth writes that Fibonacci search "is preferable on some computers, because it involves only addition and subtraction, not division by 2." But almost all computers use binary arithmetic, in which division by 2 is *simpler* than addition and subtraction. (The Wikipedia article currently claims that Fibonacci search could have better locality of reference, a claim Knuth does *not* make. It *could*, perhaps, but this is misleading. The tests done by a Fibonacci search are closer together precisely to the extent that they are less helpful in narrowing down the range; on average this would result in more reads from more parts of the table, not fewer. If the records are actually stored on tape, so that seek times dominate, then Fibonacci search might beat binary search—but in that case both algorithms are far from optimal.)
I may be missing something here, but after looking at the Wikipedia entry on the golden section search it seems like it doesn't solve the same problem as a binary search at all. Whereas a binary search is useful for finding a value in a sorted list, a golden section search is used to find a minimum or maximum value of a function over a range of values.
21,000,107
In the course of tracking down some memory leaks in the project I'm working on, I've also been working on updating the various hardware API libraries. A couple of these are unmanaged 32bit libraries, which forces our application to compile to x86; this is not a problem in and of itself. I'm working on upgrading these libraries to 64 bit versions so that our application doesn't have to run in 32 bit, but it led me to wonder about memory leaks and the addressable memory space. Given memory leaks, when running in a 64 bit process, will an application theoretically be able to run for a longer period of time before hitting an `OutOfMemoryException`? There are at least two cases for this * **Memory Fragmentation** - There is not a contiguous memory block to allocate a large object, so this exception could be thrown even though there appears to be enough free memory * **Low Physical Memory** - There simply isn't enough memory available, contiguous or not, to allocate a new object
2014/01/08
[ "https://Stackoverflow.com/questions/21000107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3116365/" ]
If you are running out of address space in a 32-bit process, then moving to a 64-bit process will allow you to run much longer. The system may run out of page table resources before you exhaust address space. If you are running out of room in your pagefile, then your process will have the same amount of memory available regardless of whether it's 32- or 64-bit. In this case, since 64-bit processes require more memory for the same thing (8-byte pointers), it will actually run out of memory *sooner* than a 32-bit version of the same process.
Of course it will. On x86 systems, you only have about 2GB of memory that is usable to your app. When you leak it all, you're done, no matter how much of physical or otherwise RAM you have. On x64, it can run for a long long time, exhausting swap file first, and then bringing system to a complete halt.
21,000,107
In the course of tracking down some memory leaks in the project I'm working on, I've also been working on updating the various hardware API libraries. A couple of these are unmanaged 32bit libraries, which forces our application to compile to x86; this is not a problem in and of itself. I'm working on upgrading these libraries to 64 bit versions so that our application doesn't have to run in 32 bit, but it led me to wonder about memory leaks and the addressable memory space. Given memory leaks, when running in a 64 bit process, will an application theoretically be able to run for a longer period of time before hitting an `OutOfMemoryException`? There are at least two cases for this * **Memory Fragmentation** - There is not a contiguous memory block to allocate a large object, so this exception could be thrown even though there appears to be enough free memory * **Low Physical Memory** - There simply isn't enough memory available, contiguous or not, to allocate a new object
2014/01/08
[ "https://Stackoverflow.com/questions/21000107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3116365/" ]
Absolutely it will take longer... However, depending on your machine and the leaking process, HOW MUCH longer can vary... While x64 can allow for **8TB** of memory, your machine most likely won't allow for that. So lets say you have **4GB** of ram and a **12GB** pagefile, then you will probably have **~14GB** of memory available for you to allocate. (The system has some overhead preventing the full **16GB**) Check out this [post](https://stackoverflow.com/questions/2052019/net-why-cant-i-get-more-than-11gb-of-allocated-memory-in-a-x64-process) for more information.
Of course it will. On x86 systems, you only have about 2GB of memory that is usable to your app. When you leak it all, you're done, no matter how much of physical or otherwise RAM you have. On x64, it can run for a long long time, exhausting swap file first, and then bringing system to a complete halt.
21,000,107
In the course of tracking down some memory leaks in the project I'm working on, I've also been working on updating the various hardware API libraries. A couple of these are unmanaged 32bit libraries, which forces our application to compile to x86; this is not a problem in and of itself. I'm working on upgrading these libraries to 64 bit versions so that our application doesn't have to run in 32 bit, but it led me to wonder about memory leaks and the addressable memory space. Given memory leaks, when running in a 64 bit process, will an application theoretically be able to run for a longer period of time before hitting an `OutOfMemoryException`? There are at least two cases for this * **Memory Fragmentation** - There is not a contiguous memory block to allocate a large object, so this exception could be thrown even though there appears to be enough free memory * **Low Physical Memory** - There simply isn't enough memory available, contiguous or not, to allocate a new object
2014/01/08
[ "https://Stackoverflow.com/questions/21000107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3116365/" ]
Absolutely it will take longer... However, depending on your machine and the leaking process, HOW MUCH longer can vary... While x64 can allow for **8TB** of memory, your machine most likely won't allow for that. So lets say you have **4GB** of ram and a **12GB** pagefile, then you will probably have **~14GB** of memory available for you to allocate. (The system has some overhead preventing the full **16GB**) Check out this [post](https://stackoverflow.com/questions/2052019/net-why-cant-i-get-more-than-11gb-of-allocated-memory-in-a-x64-process) for more information.
If you are running out of address space in a 32-bit process, then moving to a 64-bit process will allow you to run much longer. The system may run out of page table resources before you exhaust address space. If you are running out of room in your pagefile, then your process will have the same amount of memory available regardless of whether it's 32- or 64-bit. In this case, since 64-bit processes require more memory for the same thing (8-byte pointers), it will actually run out of memory *sooner* than a 32-bit version of the same process.
14,726,415
I understand the whole business around reference counting and "owning an object" and that if you allocate an object in Objective-c, it's your responsibility to release it However when exactly would you need to call alloc on a newly created object? Would it only be to retain the reference after the end of the scope or is there some other reason
2013/02/06
[ "https://Stackoverflow.com/questions/14726415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2046374/" ]
You need to call alloc in order to allocate the memory for the object. The typical setup of an object is something like: ``` Object *obj = [[Object alloc] init]; ``` The alloc call allocates memory for the object, and the init call initialises it (gives it sensible default values for all attributes/properties). Some object types come with factory methods, eg ``` NSArray *arr = [NSArray array]; ``` In this case, the object is initialised and allocated by the single array call. None of this has anything (directly) to do with reference counting, except that different ownership rules normally apply to the two methods.
I'm not exactly a objective-c guy, but I don't think you call `alloc` on any object, you call it on a class to allocate the object and call `init` on the newly allocated object. You may want to `retain` to retain the reference after the `release` is performed by autorelease pool, if this is your setup. That often happens to the object created using `[NSThing thingWithStuff:stuff]` or some such.
14,726,415
I understand the whole business around reference counting and "owning an object" and that if you allocate an object in Objective-c, it's your responsibility to release it However when exactly would you need to call alloc on a newly created object? Would it only be to retain the reference after the end of the scope or is there some other reason
2013/02/06
[ "https://Stackoverflow.com/questions/14726415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2046374/" ]
You need to call alloc in order to allocate the memory for the object. The typical setup of an object is something like: ``` Object *obj = [[Object alloc] init]; ``` The alloc call allocates memory for the object, and the init call initialises it (gives it sensible default values for all attributes/properties). Some object types come with factory methods, eg ``` NSArray *arr = [NSArray array]; ``` In this case, the object is initialised and allocated by the single array call. None of this has anything (directly) to do with reference counting, except that different ownership rules normally apply to the two methods.
I think you are misunderstanding a basic concept. sending alloc to a class will result in creating a new object of that class (not initialized yet) which you own (retain count will be 1). from your question "when exactly would you need to call alloc on a newly created object?" - if the object is newly created it means that someone already allocated it.. if you meant: when do you need to call retain on a newly created object? the answer is if you want to hold it yourself and not rely on whomever allocated it, and might release it sometime.. remember that alloc/new syntax raises the retain count by one, where as other creating methods (like [NSArray array]) return autorelease objects.. in general i would recommend using ARC and not be bothered by these issues..
14,726,415
I understand the whole business around reference counting and "owning an object" and that if you allocate an object in Objective-c, it's your responsibility to release it However when exactly would you need to call alloc on a newly created object? Would it only be to retain the reference after the end of the scope or is there some other reason
2013/02/06
[ "https://Stackoverflow.com/questions/14726415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2046374/" ]
I think you are misunderstanding a basic concept. sending alloc to a class will result in creating a new object of that class (not initialized yet) which you own (retain count will be 1). from your question "when exactly would you need to call alloc on a newly created object?" - if the object is newly created it means that someone already allocated it.. if you meant: when do you need to call retain on a newly created object? the answer is if you want to hold it yourself and not rely on whomever allocated it, and might release it sometime.. remember that alloc/new syntax raises the retain count by one, where as other creating methods (like [NSArray array]) return autorelease objects.. in general i would recommend using ARC and not be bothered by these issues..
I'm not exactly a objective-c guy, but I don't think you call `alloc` on any object, you call it on a class to allocate the object and call `init` on the newly allocated object. You may want to `retain` to retain the reference after the `release` is performed by autorelease pool, if this is your setup. That often happens to the object created using `[NSThing thingWithStuff:stuff]` or some such.
251,726
The book I have gives the following derivation: Let the temperature of the atmosphere be $-\theta$ and the temperature of the water be $0$. Consider unit cross sectional are of ice, if layer of thickness $dx$ forms in time $dt$ with $x$ thickness of ice above it, heat released due to its formation is $dx\rho L$ where $L$ is latent heat. If this quantity of heat is conducted upwards in time $dt$, $$dx\rho L=K\frac{\theta}{x}dt$$ Therefore, the time taken $$t=\frac{\rho L}{2K\theta}(x\_{2}^2-x\_{1}^2)$$ What I don't understand is why the same amount of time should be taken for the heat to be conducted and for a new layer of ice to be formed. In other words, why is it that the next layer of ice forms only after the heat is released into the atmosphere?
2016/04/24
[ "https://physics.stackexchange.com/questions/251726", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/98561/" ]
The heat is continually being released to the atmosphere, and the layer is continually getting thicker. The heat has to be conducted from the water-ice interface to the ice-atmosphere interface through the layer of ice. And, as the ice gets thicker, the rate of heat being conducted slows down. And the rate of ice formation slows down. So the amount of time taken for the heat to be conducted and for a new incremental layer of ice to be formed is **not the same** for each incremental layer. Those are $x^2$'s in the equation, not x's.
You assume that the temperature difference between the air at $-\theta^\circ C$ and the water directly under the ice $0^\circ C$ is constant. So looking at the thermal conduction equation $\dot Q = K A \frac {\theta}{x}$ if you increase the thickness of the ice $x$ by a factor of two you reduce the rate of heat flow $\dot Q$ by a factor of two. This is because $K, A$ and $\theta$ are constant. So it will take twice as long to freeze a thickness of water $\Delta x$ when the thickness of ice is $2x$ than to freeze the same thickness of water when the thickness of ice is $x$. Your analysis does not not include the additional but smaller factor of having to reduce the temperature of the water near the ice to $0^\circ C$. If water behaved as most liquids it would not start to freeze until the temperature of all the water was $0^\circ C$ the heat being transported through the water by convection to achieve such cooling. Since water is anomalous in that it has a maximum density at $+4 ^\circ C$, the water under the layer of ice has to be cooled to $0^\circ C$ by conduction of heat through the water and then the ice.
251,726
The book I have gives the following derivation: Let the temperature of the atmosphere be $-\theta$ and the temperature of the water be $0$. Consider unit cross sectional are of ice, if layer of thickness $dx$ forms in time $dt$ with $x$ thickness of ice above it, heat released due to its formation is $dx\rho L$ where $L$ is latent heat. If this quantity of heat is conducted upwards in time $dt$, $$dx\rho L=K\frac{\theta}{x}dt$$ Therefore, the time taken $$t=\frac{\rho L}{2K\theta}(x\_{2}^2-x\_{1}^2)$$ What I don't understand is why the same amount of time should be taken for the heat to be conducted and for a new layer of ice to be formed. In other words, why is it that the next layer of ice forms only after the heat is released into the atmosphere?
2016/04/24
[ "https://physics.stackexchange.com/questions/251726", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/98561/" ]
A bit late maybe. A few google searches reveal that the speed at which heat propagates is infinite in the thermodynamics I am studying. So, the heat is transferred instantaneously and the time taken for a layer to form is equal to the time in which this heat is transferred. I had thought that the heat is transferred at a finite speed as a layer is formed. So I had thought that the time taken for the heat to be transferred to the top as a layer is formed would be different from the time the layer took to form and if we take $dt$ as the time taken for the a small layer to form, there would be some delay for the heat to be conducted out of the ice and this time would obviously be greater than the the time it took for the ice to form itself. I don't know if thats what the answers are trying to say but I decided to make an answer anyway.
You assume that the temperature difference between the air at $-\theta^\circ C$ and the water directly under the ice $0^\circ C$ is constant. So looking at the thermal conduction equation $\dot Q = K A \frac {\theta}{x}$ if you increase the thickness of the ice $x$ by a factor of two you reduce the rate of heat flow $\dot Q$ by a factor of two. This is because $K, A$ and $\theta$ are constant. So it will take twice as long to freeze a thickness of water $\Delta x$ when the thickness of ice is $2x$ than to freeze the same thickness of water when the thickness of ice is $x$. Your analysis does not not include the additional but smaller factor of having to reduce the temperature of the water near the ice to $0^\circ C$. If water behaved as most liquids it would not start to freeze until the temperature of all the water was $0^\circ C$ the heat being transported through the water by convection to achieve such cooling. Since water is anomalous in that it has a maximum density at $+4 ^\circ C$, the water under the layer of ice has to be cooled to $0^\circ C$ by conduction of heat through the water and then the ice.
35,737,202
Is left to right a higher precedence then the object String? For my print statement as below I got this. Please explain. ``` class triangle{ public static void main(String[]args){ System.out.println(1+2+"hello"); System.out.println("hello"+1+2); } } ``` Also why do I need to put a cast to a floating x=1.2F; and not double x=1.2;?
2016/03/02
[ "https://Stackoverflow.com/questions/35737202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5911874/" ]
This happens because the module `FscHelper` defines a constructor called `Target` ([see source](https://github.com/fsharp/FAKE/blob/c544eb7a4a567a91ff0c9f05dab1b2d00458b54e/src/app/FakeLib/FscHelper.fs#L244)), and that constructor conflicts with the `Target` function from the `TargetHelper` module. There is an [issue filed about it](https://github.com/fsharp/FAKE/issues/1155). Until the issue is fixed, there are three ways to work around this ambiguity: 1. Don't open `FscHelper`, just use all its innards in a qualified manner (e.g. `FscHelper.Compile` etc.) 2. Re-alias the `TargetHelper.Target` function in the local scope: ``` open Fake open Fake.FscHelper let Target = TargetHelper.Target Target "Default" (fun _ -> trace "Hello World from FAKE" ) ``` 3. Reorder the `open` statements: ``` open Fake.FscHelper open Fake ``` And since you're using this helper, note that the [documentation](http://fsharp.github.io/FAKE/fsc.html) for it is [outdated](https://github.com/fsharp/FAKE/issues/1156). In particular, the `Fsc` task is deprecated in favor of the `Compile` task ([see source](https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/FscHelper.fs#L520)).
Change the order of the open statements ``` #r @"packages/FAKE/tools/FakeLib.dll" open Fake.FscHelper open Fake Target "a" (fun _ -> ["a.fs"] |> Compile [] ``` The order of your open statements determines the precedence of the name resolution with the later opened modules and namespaces taking precedent.
4,246,388
Q: Find the range and domain of the function $$f(x) = \sqrt{1-e^{x+2}}?$$ I've found the domain, which is $x \le -2$ by solving the inequality $1-e^{x+2} \ge 0$. I've tried to find the range by taking the inverse of $f$, which gives me $f^{-1} = \ln(1-x^2)-2$. Then, since for $\ln(1-x^2)$ to be defined, $1-x^2>0$, so solving this inequality gives the interval $x \in (-1,1)$, which I thought is the range of $f$. However, graphing it out on desmos shows that the range is only $[0,1)$. What am I doing wrong?
2021/09/10
[ "https://math.stackexchange.com/questions/4246388", "https://math.stackexchange.com", "https://math.stackexchange.com/users/742592/" ]
Yes, the way your proof would be formalized is by saying $1 - \sum\_{k = 1}^{n}9 \cdot 10^{-k} = 10^{-n}$, and then showing $\lim\_{n \to \infty}10^{-n} = 0$. The "$\infty$" can be formalized by the fact that $\frac{1}{10^n} \to 0$ if and only if $10^n \to \infty$.
We have that the difference between $1$ and $0.999\ldots 9$ is $\frac{1}{10^n}$. Since as $n$ gets larger, we have $\lim\_{n\to\infty} \frac{1}{10^n}=0$, we have that the sequence converges to $1$.
4,246,388
Q: Find the range and domain of the function $$f(x) = \sqrt{1-e^{x+2}}?$$ I've found the domain, which is $x \le -2$ by solving the inequality $1-e^{x+2} \ge 0$. I've tried to find the range by taking the inverse of $f$, which gives me $f^{-1} = \ln(1-x^2)-2$. Then, since for $\ln(1-x^2)$ to be defined, $1-x^2>0$, so solving this inequality gives the interval $x \in (-1,1)$, which I thought is the range of $f$. However, graphing it out on desmos shows that the range is only $[0,1)$. What am I doing wrong?
2021/09/10
[ "https://math.stackexchange.com/questions/4246388", "https://math.stackexchange.com", "https://math.stackexchange.com/users/742592/" ]
Yes, the way your proof would be formalized is by saying $1 - \sum\_{k = 1}^{n}9 \cdot 10^{-k} = 10^{-n}$, and then showing $\lim\_{n \to \infty}10^{-n} = 0$. The "$\infty$" can be formalized by the fact that $\frac{1}{10^n} \to 0$ if and only if $10^n \to \infty$.
There are number systems where this type of argument can be made rigorously, but in these number systems, it is no longer true that $0.\bar{9} = 1$. For instance, in the [hyperreal numbers](https://en.wikipedia.org/wiki/Hyperreal_number) $^\*\Bbb{R}$, the expressions $$0.99999... \text{ and } 1.00000...$$ represent legitimately different numbers, their difference *really is* an [infinitesimal](https://en.wikipedia.org/wiki/Infinitesimal), and this infinitesimal *really is* the reciprocal of an infinite number. However, after taking [standard parts](https://en.wikipedia.org/wiki/Standard_part_function), we learn that $0.\bar{9}$ and $1$ "round off" to the same standard real number, namely $1$, and so this still amounts to a proof that $0.\bar{9} = 1$ considered as elements of $\Bbb{R}$.
11,836,422
My `ajax` looks like ``` // send the data to the server using .ajax() or .post() $.ajax({ type: 'POST', url: 'addVideo', data: { video_title: title, playlist_name: playlist, url: id // csrfmiddlewaretoken: '{{ csrf_token }}', }, done: notify('success', 'video saved successfully'), fail: notify('error', 'There were some errors while saving the video. Please try in a while') }); ``` `notify` looks like ``` function notify(notify_type, msg) { var alerts = $('#alerts'); alerts.addClass('alert'); alerts.append('<a class="close" data-dismiss="alert" href="#">×</a>'); if (notify_type == 'success') { alerts.addClass('alerts-success').append(msg).fadeIn('fast'); } if (notify_type == 'failure') { alerts.addClass('alerts-error').append(msg).fadeIn('fast'); } } ``` * When I save click on button I get success message as > > video saved successfully x(cross mark) > > > * I click cross and notification is gone now * When I AGAIN save click on button, nothing happens, I see firebug complaining `No elements were found with the selector: "#alerts"` * My guess is clicking on cross mark removes the `div="alerts"` tag entirely from DOM. is it correct? **Question** - How can I get the correct behavior. clicking on cross mark removes notification div, clicking on button to create creates the notification div again
2012/08/06
[ "https://Stackoverflow.com/questions/11836422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/379235/" ]
Try doing this. In Mountain Lion, go to Preferences -> General and for `Show scroll bars` choose `Always` like so : ![enter image description here](https://i.stack.imgur.com/FEtw2.png) That should prevent the scroll bar from covering the last option and allow you to click it. Does this help ? **Update** I just checked that this indeed works. In fact for me it's only the `When Scrolling` option that creates a problem. With either of the remaining settings, things are peachy : Unfortunately, I can't post a screen shot since the cmd + click popup disappears as soon as I press the shortcut key for taking a screenshot (Cmd + Shift + 4). **Update 2** I just made this quick screen cast to show the relation between the Mountain Lion Preferences and how it effects eclipse. Take a look at it **[here](http://youtu.be/qV7EmzozI0o)**.
If you press F3 while the cursor is on a variable or method then Eclipse will 'open declaration'. Fix the problem by removing the mouse-based workflow?
55,082,650
I have a model called Resource configured with: ``` class Resource < ActiveRecord::Base has_many_attached :assets end ``` I created an action in my resources\_controller.rb as follows: ``` def delete_asset_attachment @asset = ActiveStorage::Attachment.find_by(params[:id]) logger.debug "The value of @asset is #{@asset}" @asset.purge redirect_to @resource end ``` I have a form that shows the resource and loops through the attached assets. Below is the snippet of code doing the loop through the assets: ``` <% @resource.assets.each do |asset| %> <%= link_to 'Remove Attachment', delete_asset_attachment_resource_url(@resource, asset.id), method: :delete, data: { confirm: 'Are you sure?' } %> <% end %> ``` The /resources page properly shows the resource along with the attached assets. However, when I try to click the link to delete one of the assets, I receive an error: "undefined method `purge' for nil:NilClass". However, in console I see the attachment exists. Here is the output from the server console: ``` Started DELETE "/resources/10/delete_asset_attachment.18" for ::1 at 2019-03-09 17:27:28 -0500 Processing by ResourcesController#delete_asset_attachment as Parameters: {"authenticity_token"=>"EFZO5V9Bii3dId0I6hn5DajFR5WJYZBc8qPAAi5ppQOFW3cws5I4FjyVP9IlvA+2a2kKUJhobnqd8atG4L3k+g==", "id"=>"10"} Resource Load (0.1ms) SELECT "resources".* FROM "resources" WHERE "resources"."id" = ? LIMIT ? [["id", 10], ["LIMIT", 1]] User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]] ActiveStorage::Attachment Load (0.1ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE (10) LIMIT ? [["LIMIT", 1]] The value of @asset is #<ActiveStorage::Attachment:0x00007f8d7bd4df68> ActiveStorage::Blob Load (0.2ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = ? LIMIT ? [["id", 27], ["LIMIT", 1]] Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.6ms) NoMethodError - undefined method `purge' for nil:NilClass: ::1 - - [09/Mar/2019:17:27:28 EST] "POST /resources/10/delete_asset_attachment.18 HTTP/1.1" 500 76939 http://localhost:3000/resources/10/edit -> /resources/10/delete_asset_attachment.18 Started POST "/__better_errors/70da0e976a425fce/variables" for ::1 at 2019-03-09 17:27:28 -0500 ActiveStorage::Blob Load (0.2ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = ? LIMIT ? [["id", 27], ["LIMIT", 11]] ::1 - - [09/Mar/2019:17:27:28 EST] "POST /__better_errors/70da0e976a425fce/variables HTTP/1.1" 200 36499 http://localhost:3000/resources/10/delete_asset_attachment.18 -> /__better_errors/70da0e976a425fce/variables ``` I've searched for solutions everywhere. The couple that exist on stackoverflow didn't address my issue. There is an incredible lack of specific details and examples in the Rails guide or anywhere else on the web for specifically handling deleting attachments. Would appreciate any help. UPDATE: Here are my routes.rb: resources :resources do get 'listing', :on => :collection put :sort, on: :collection member do delete :delete\_asset\_attachment end end UPDATE 2: rails routes output ``` resources GET /resources(.:format) resources#index POST /resources(.:format) resources#create new_resource GET /resources/new(.:format) resources#new edit_resource GET /resources/:id/edit(.:format) resources#edit resource GET /resources/:id(.:format) resources#show PATCH /resources/:id(.:format) resources#update PUT /resources/:id(.:format) resources#update DELETE /resources/:id(.:format) resources#destroy ```
2019/03/09
[ "https://Stackoverflow.com/questions/55082650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/964018/" ]
I've been able to make this work. Ahhhh. The rush, after hours of frustration. Piecing things together after reading this article [Deleting ActiveStorage Attachments From the Controller, 3 Ways](https://nicholasshirley.com/several-strategies-to-delete-activestorage-attachments/) I changed my controller code to be this: ``` def delete_asset_attachment @resource.assets.find_by(params[:attachment_id]).purge redirect_to @resource end ``` and my form to be this: ``` <% @resource.assets.each do |asset| %> <%= asset.filename %> <%= link_to 'Remove Attachment', delete_asset_attachment_resource_url(@resource, asset.id), method: :delete, data: { confirm: 'Are you sure?' } %> <% end %> ``` I believe the issue was that the line in my old code: ``` @asset = ActiveStorage::Attachment.find_by(params[:id]) ``` ...was only passing the @resource id and the attachment was not being found. The key was changing this line: ``` @resource.assets.find_by(params[:attachment_id]).purge ``` ...which more properly points to the correct resource and then the specific asset (attachment) to be purged.
Fix the syntax of `find_by` and use safe ampersand, instead ```rb @asset = ActiveStorage::Attachment.find_by(params[:id]) @asset.purge ``` try: ```rb @asset = ActiveStorage::Attachment.find_by(id: params[:id]) @asset&.purge ```
38,559,006
I have sample string as : 1. `'&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89&color=ff0000|00ffff'` 2. `'&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89'` My objective is to select the text from '`tooltext=`' till the first occurrence of '`&`' which is not preceded by `\\`. I'm using the following regex : ``` /(tooltext=)(.*)([^\\])(&)/ ``` and the `.match()` function. It is working fine for the second string but for the first string it is selecting upto the last occurrence of '`&`' not preceded by `\\`. ``` var a = '&label=20:01:27&tooltext=abc\&|\|cba&value=6|59|58|89&color=ff0000|00ffff', b = a.match(/(tooltext=)(.*)([^\\])(&)(.*[^\\]&)?/i) ``` result, ``` b = ["tooltext=abc\&|\|cba&value=40|84|40|62&", "tooltext=", "abc\&|\|cba&value=40|84|40|6", "2", "&"] ``` But what i need is: ``` b = ["tooltext=abc&||cba&", "tooltext=", "abc&||cb", "a", "&"] ```
2016/07/25
[ "https://Stackoverflow.com/questions/38559006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5117872/" ]
I think you can use a regex like this: ``` /tooltext=(.*?\\&)*.*?&/ ``` **[[`Regex Demo`]](https://regex101.com/r/qQ3nH7/1)** and to always found a non-escaped `&`: ``` /tooltext=(.*?\\&)*.*?[^\\]&/ ```
It looks like your regex is matching all the way to the *last* `&` instead of the first one without a backslash in front of it. Try adding the `?` operator to make it match as small as possible like so: `/(tooltext=)(.*?)([^\\])(&)/` And if you just want the text between `tooltext=` and `&`, try this to make it return the important part as the matched group: `/tooltext=(.*?[^\\])&/`
437,218
On [Wikipedia](https://en.wikipedia.org/wiki/Imre_Simon), it is claimed without a source that Imre Simon founded tropical mathematics. The first work of his I was able to find on the subject is [Limited subsets of a free monoid](https://ieeexplore.ieee.org/document/4567973) which uses the semiring $\mathbb N \cup \{\infty\}$ (together with the operations $\min$ and $+$) in the context of automata theory and formal languages and which dates back to 1978. My questions is: Is this the first paper in which a tropical semiring is used? EDIT: To clarify, I am not asking for the origin of the word tropical itself. That has already been answered on this website. I am asking for the origin of tropical mathematics: that is, the study of the tropical semiring, be it in tropical geometry, algebra or analysis, and whether it was in an applied or theoretical context. In other words, what is the first work that studies the tropical semiring? EDIT: I have a follow-up question on the history of the subject [here](https://mathoverflow.net/questions/437235/history-of-tropical-mathematics)
2022/12/25
[ "https://mathoverflow.net/questions/437218", "https://mathoverflow.net", "https://mathoverflow.net/users/496888/" ]
This answer is due to Benjamin Steinberg: > > Simon's paper is likely the first at least to make serious use of [the > tropical semiring] and it was in theoretical computer science to study > star height and limitedness. > > >
I asked Christian Choffrut and Dominique Perrin this question today. They essentially told me the following: certainly, the name *tropical* comes in honour of the Brazilian mathematician [Imre Simon](https://en.wikipedia.org/wiki/Imre_Simon); and to a Frenchman, Brazil is quite tropical (this is the full depth of the naming).\* As for the mathematical origins, there were many. They mentioned two. 1. The first is the following problem: let $R \subseteq A^\ast$ be a regular language. Does there exist some $n \geq 0$ such that $R^n = R^\ast$? This is an interesting problem, and tropical mathematics can be used to deal with problems of this sort. The details are unclear to me, but probably rather accessible. 2. The second comes from the [Floyd-Warshall](https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm) algorithm for finding minimal paths in graphs. This problem and algorithm can be interpreted in terms of min-plus automata, and this insight was part of the drive to create a larger framework of tropical mathematics. I don't know too many of the details of these two problems, or the tropical insights that help; but I hope this was useful in answering the question somewhat! It can undoubtedly be fleshed out significantly. ${}$ ${}$ \*Regarding this naming, Dominique told me that [M-P. Schützenberger](https://en.wikipedia.org/wiki/Marcel-Paul_Sch%C3%BCtzenberger), the PhD supervisor of both Christian and Dominique, was very fond of such *plaisanteries*, which probably contributed to its becoming an established term.
437,218
On [Wikipedia](https://en.wikipedia.org/wiki/Imre_Simon), it is claimed without a source that Imre Simon founded tropical mathematics. The first work of his I was able to find on the subject is [Limited subsets of a free monoid](https://ieeexplore.ieee.org/document/4567973) which uses the semiring $\mathbb N \cup \{\infty\}$ (together with the operations $\min$ and $+$) in the context of automata theory and formal languages and which dates back to 1978. My questions is: Is this the first paper in which a tropical semiring is used? EDIT: To clarify, I am not asking for the origin of the word tropical itself. That has already been answered on this website. I am asking for the origin of tropical mathematics: that is, the study of the tropical semiring, be it in tropical geometry, algebra or analysis, and whether it was in an applied or theoretical context. In other words, what is the first work that studies the tropical semiring? EDIT: I have a follow-up question on the history of the subject [here](https://mathoverflow.net/questions/437235/history-of-tropical-mathematics)
2022/12/25
[ "https://mathoverflow.net/questions/437218", "https://mathoverflow.net", "https://mathoverflow.net/users/496888/" ]
This answer is due to Benjamin Steinberg: > > Simon's paper is likely the first at least to make serious use of [the > tropical semiring] and it was in theoretical computer science to study > star height and limitedness. > > >
The paper "Limited subsets of a free monoid" was published in 1978. However, another paper A. Mandel, I. Simon, [On finite semigroups of matrices](https://www.sciencedirect.com/science/article/pii/0304397577900019), *Theoret. Comput. Sci.* **5** (1977/78), no. 2, 101--111 was published sligthly earlier and also makes use of tropical semirings. In the bibliography of this paper, there is an earlier reference [9] to a report of the university of São-Paulo, with the following quote: > > Finally, we mention a related problem. Let $M$ be the semiring with > support $\mathbb{N} \cup \{\infty\}$, where $a \oplus b = \min\{a,b\}$ and $a \odot b = a + b$. In [9], a characterization of torsion elements of $M\_n(M)$ is given (...) > > > [9] I. Simon, On limited events IME-USP (1974). Thus this report is likely to be the first work on tropical semirings.
437,218
On [Wikipedia](https://en.wikipedia.org/wiki/Imre_Simon), it is claimed without a source that Imre Simon founded tropical mathematics. The first work of his I was able to find on the subject is [Limited subsets of a free monoid](https://ieeexplore.ieee.org/document/4567973) which uses the semiring $\mathbb N \cup \{\infty\}$ (together with the operations $\min$ and $+$) in the context of automata theory and formal languages and which dates back to 1978. My questions is: Is this the first paper in which a tropical semiring is used? EDIT: To clarify, I am not asking for the origin of the word tropical itself. That has already been answered on this website. I am asking for the origin of tropical mathematics: that is, the study of the tropical semiring, be it in tropical geometry, algebra or analysis, and whether it was in an applied or theoretical context. In other words, what is the first work that studies the tropical semiring? EDIT: I have a follow-up question on the history of the subject [here](https://mathoverflow.net/questions/437235/history-of-tropical-mathematics)
2022/12/25
[ "https://mathoverflow.net/questions/437218", "https://mathoverflow.net", "https://mathoverflow.net/users/496888/" ]
This answer is due to Benjamin Steinberg: > > Simon's paper is likely the first at least to make serious use of [the > tropical semiring] and it was in theoretical computer science to study > star height and limitedness. > > >
What is nowadays called "tropical semiring" was very explicitly defined and used by Bernard Carré in his 1971 paper [An algebra for network routing problems](https://mathscinet.ams.org/mathscinet-getitem?mr=292583). Its abstract: > > Problems involving the determination of routes on networks arise in many different contexts. For example network flow problems in operations research, such as transportation and assignment problems, involve the determination of a succession of shortest or least-cost paths between commodity sources and sinks. Again, critical path analysis > and certain scheduling problems involve the determination of longest paths on activity networks. Pathfinding problems of different kinds also arise in the design of logic networks, and in routing messages through congested communication networks. This paper presents an algebraic structure for the formulation and solution of such problems. After defining the algebraic structure and giving concrete examples applicable to > different kinds of routing problems, we use it in a general analysis of a class of directed > networks, in which each arc has an associated measure (representing for instance a > transportation cost, an activity duration, the state (open or closed) of a switch, or the > probability of a communication link being available). It is then shown that all the routing > problems mentioned above can be expressed in the same algebraic form, and that they can > all be solved by variants of classical methods of linear algebra, differing from these only in > the significance of the additive and multiplicative operations. > > >
437,218
On [Wikipedia](https://en.wikipedia.org/wiki/Imre_Simon), it is claimed without a source that Imre Simon founded tropical mathematics. The first work of his I was able to find on the subject is [Limited subsets of a free monoid](https://ieeexplore.ieee.org/document/4567973) which uses the semiring $\mathbb N \cup \{\infty\}$ (together with the operations $\min$ and $+$) in the context of automata theory and formal languages and which dates back to 1978. My questions is: Is this the first paper in which a tropical semiring is used? EDIT: To clarify, I am not asking for the origin of the word tropical itself. That has already been answered on this website. I am asking for the origin of tropical mathematics: that is, the study of the tropical semiring, be it in tropical geometry, algebra or analysis, and whether it was in an applied or theoretical context. In other words, what is the first work that studies the tropical semiring? EDIT: I have a follow-up question on the history of the subject [here](https://mathoverflow.net/questions/437235/history-of-tropical-mathematics)
2022/12/25
[ "https://mathoverflow.net/questions/437218", "https://mathoverflow.net", "https://mathoverflow.net/users/496888/" ]
I asked Christian Choffrut and Dominique Perrin this question today. They essentially told me the following: certainly, the name *tropical* comes in honour of the Brazilian mathematician [Imre Simon](https://en.wikipedia.org/wiki/Imre_Simon); and to a Frenchman, Brazil is quite tropical (this is the full depth of the naming).\* As for the mathematical origins, there were many. They mentioned two. 1. The first is the following problem: let $R \subseteq A^\ast$ be a regular language. Does there exist some $n \geq 0$ such that $R^n = R^\ast$? This is an interesting problem, and tropical mathematics can be used to deal with problems of this sort. The details are unclear to me, but probably rather accessible. 2. The second comes from the [Floyd-Warshall](https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm) algorithm for finding minimal paths in graphs. This problem and algorithm can be interpreted in terms of min-plus automata, and this insight was part of the drive to create a larger framework of tropical mathematics. I don't know too many of the details of these two problems, or the tropical insights that help; but I hope this was useful in answering the question somewhat! It can undoubtedly be fleshed out significantly. ${}$ ${}$ \*Regarding this naming, Dominique told me that [M-P. Schützenberger](https://en.wikipedia.org/wiki/Marcel-Paul_Sch%C3%BCtzenberger), the PhD supervisor of both Christian and Dominique, was very fond of such *plaisanteries*, which probably contributed to its becoming an established term.
What is nowadays called "tropical semiring" was very explicitly defined and used by Bernard Carré in his 1971 paper [An algebra for network routing problems](https://mathscinet.ams.org/mathscinet-getitem?mr=292583). Its abstract: > > Problems involving the determination of routes on networks arise in many different contexts. For example network flow problems in operations research, such as transportation and assignment problems, involve the determination of a succession of shortest or least-cost paths between commodity sources and sinks. Again, critical path analysis > and certain scheduling problems involve the determination of longest paths on activity networks. Pathfinding problems of different kinds also arise in the design of logic networks, and in routing messages through congested communication networks. This paper presents an algebraic structure for the formulation and solution of such problems. After defining the algebraic structure and giving concrete examples applicable to > different kinds of routing problems, we use it in a general analysis of a class of directed > networks, in which each arc has an associated measure (representing for instance a > transportation cost, an activity duration, the state (open or closed) of a switch, or the > probability of a communication link being available). It is then shown that all the routing > problems mentioned above can be expressed in the same algebraic form, and that they can > all be solved by variants of classical methods of linear algebra, differing from these only in > the significance of the additive and multiplicative operations. > > >
437,218
On [Wikipedia](https://en.wikipedia.org/wiki/Imre_Simon), it is claimed without a source that Imre Simon founded tropical mathematics. The first work of his I was able to find on the subject is [Limited subsets of a free monoid](https://ieeexplore.ieee.org/document/4567973) which uses the semiring $\mathbb N \cup \{\infty\}$ (together with the operations $\min$ and $+$) in the context of automata theory and formal languages and which dates back to 1978. My questions is: Is this the first paper in which a tropical semiring is used? EDIT: To clarify, I am not asking for the origin of the word tropical itself. That has already been answered on this website. I am asking for the origin of tropical mathematics: that is, the study of the tropical semiring, be it in tropical geometry, algebra or analysis, and whether it was in an applied or theoretical context. In other words, what is the first work that studies the tropical semiring? EDIT: I have a follow-up question on the history of the subject [here](https://mathoverflow.net/questions/437235/history-of-tropical-mathematics)
2022/12/25
[ "https://mathoverflow.net/questions/437218", "https://mathoverflow.net", "https://mathoverflow.net/users/496888/" ]
The paper "Limited subsets of a free monoid" was published in 1978. However, another paper A. Mandel, I. Simon, [On finite semigroups of matrices](https://www.sciencedirect.com/science/article/pii/0304397577900019), *Theoret. Comput. Sci.* **5** (1977/78), no. 2, 101--111 was published sligthly earlier and also makes use of tropical semirings. In the bibliography of this paper, there is an earlier reference [9] to a report of the university of São-Paulo, with the following quote: > > Finally, we mention a related problem. Let $M$ be the semiring with > support $\mathbb{N} \cup \{\infty\}$, where $a \oplus b = \min\{a,b\}$ and $a \odot b = a + b$. In [9], a characterization of torsion elements of $M\_n(M)$ is given (...) > > > [9] I. Simon, On limited events IME-USP (1974). Thus this report is likely to be the first work on tropical semirings.
What is nowadays called "tropical semiring" was very explicitly defined and used by Bernard Carré in his 1971 paper [An algebra for network routing problems](https://mathscinet.ams.org/mathscinet-getitem?mr=292583). Its abstract: > > Problems involving the determination of routes on networks arise in many different contexts. For example network flow problems in operations research, such as transportation and assignment problems, involve the determination of a succession of shortest or least-cost paths between commodity sources and sinks. Again, critical path analysis > and certain scheduling problems involve the determination of longest paths on activity networks. Pathfinding problems of different kinds also arise in the design of logic networks, and in routing messages through congested communication networks. This paper presents an algebraic structure for the formulation and solution of such problems. After defining the algebraic structure and giving concrete examples applicable to > different kinds of routing problems, we use it in a general analysis of a class of directed > networks, in which each arc has an associated measure (representing for instance a > transportation cost, an activity duration, the state (open or closed) of a switch, or the > probability of a communication link being available). It is then shown that all the routing > problems mentioned above can be expressed in the same algebraic form, and that they can > all be solved by variants of classical methods of linear algebra, differing from these only in > the significance of the additive and multiplicative operations. > > >
75,353
My 10.8.2 MacBook Air is having constant connection errors in Mail.app when the computer has been sent to sleep or hibernate. A small alert triangle appears next to all account names (I have several) in the sidebar. Mail reception only resumes after quitting and relaunching Mail.app. I have verified that the net connection is up, and that connections settings and credentials are okay. Similar problems described [here](https://apple.stackexchange.com/q/59735/26522).
2012/12/19
[ "https://apple.stackexchange.com/questions/75353", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/26522/" ]
This might seem weird and unlikely, but these steps (originally written to [restore broken Dictation](https://apple.stackexchange.com/q/68761/26522)) fixed it for me: 1. Go to `~/Library/Preferences` ( `⇧`+`⌘`+`G` ) 2. Locate `com.apple.assistant.plist` and move it to the Trash 3. Open *Dictation & Speech* preference panel, disable dictation 4. Reboot 5. Re-enable *Dictation & Speech*. **Any hints on why this is working are very welcome!**
It's an SSL issue that takes a few steps to fix. 1) Go to the ISP of each email account and find the actual server name for your account. Change your incoming and outgoing email servers from mailorpop.mydomain.com to mailorpop.servername.com. The server name often has a number in it. (e.g. mail.xserver356.com) Do this for each account. 2) Quit Mac Mail. Open Keychain Access (Applications --> Utilities). At the left click on Logins, then below click on Certificates. Find all email certificates, hold the option key down while clicking on them, then select Delete to get rid of them. Quit Keychain Access. 3) Open Mac Mail. For each account, you will be asked to enter your password again. Click on the Certificate button at the bottom of the window, click the Trust triangle, then check Always Trust. Do this for all incoming email. Then send a test email from each account, and do this process for all outgoing email. 4) Open Keychain Access and find your new login certificates. Double click each one, then click the Trust triangle, and select Always Trust on the top scrollbar. Close the window and enter your keychain password to Update. Do this for each email certificate. It's a pain in the neck, but after all this, your email should work fine with again with SSL.
18,099,144
I encountered problems to download floodlight from GitHub. I have googled and tried various methods to clone it. Below is the error: ``` mininet@mininet-vm:~$ git clone git://github.com/floodlight/floodlight.git Cloning into 'floodlight'... fatal: unable to connect to github.com: github.com:Temporary failure in name resolution ``` I'm currently running mininet in a virtual machine and i have tried with https/http instead of git. Still, I encountered errors when trying to download floodlight from GitHub. My virtual machine network is connected with NAT and GitHub.com is up and running. However, when I tried to ping to GitHub.com it won't work. How do I resolve this DNS server issue?
2013/08/07
[ "https://Stackoverflow.com/questions/18099144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2651587/" ]
I had a similar issue, but found it to be intermittent. What I found to resolve the issue was the following: 1. Make sure you have the latest version of virtual box. The latest versions support ping from a NAT guest to the Internet - although I've had mixed success with that 2. If I was using a dongle connection to the Internet, i.e. not persistent, I found that I sometime s I had to reboot the guest, after the connection to the Internet had been made. So nothing particularly technical, and ceratinly nothing to do with forwarding rules. But it worked for me, michael
You must be behind a proxy `git config --global http.proxy %HTTP_PROXY%` to configure the proxy to be the same as yoyur system proxy. IF `%HTTP_PROXY%` is not set(Try `echo %HTTP_PROXY%` if it echoes a hostname, no problem. If it echoes back %HTTP\_PROXY%, you got a problem), try setting the proxy manuallt `git config --global <Host>:<Port> (Generally 8080)` IF you don't know the proxy, go to Internet Explorer>>Tools>Internet Options>>Connections>>LAN Settings and check the proxy server address IF its configured by a script such as .pac, open this file. there should be a function findProxyForUrl or something, its simple pythonish code. You should be able to figure it out from there.
1,538
I've been trying a long time to understand a thing which is obviously extremely simple, but I just can't get it. Read this, please: > > The NTRUEncrypt PKCS uses the ring of truncated polynomials $R$ combined with the modular arithmetic described in Section 1. These are combined by reducing the coefficients of a polynomial a modulo an integer $q$. Thus the expression $$a \pmod q$$ means to reduce the coefficients of $a$ modulo $q$. That is, divide each coefficient by $q$ and take the remainder. Similarly, the relation $$a \equiv b \pmod q$$ means that every coefficient of the difference $a-b$ is a multiple of $q$. > > > This is taken from [NTRU tutorial](http://www.securityinnovation.com/security-lab/crypto/154.html) and that's quite understandable. But. Take a glance at the next excerpt from the same tutorial: > > The inverse modulo $q$ of a polynomial $a$ is a polynomial $A$ with the property that $$a \* A \equiv 1 \pmod q.$$ > > > Not every polynomial has an inverse modulo $q$, but it is easy to determine if $a$ has an inverse, and to compute the inverse if it exists. A fast algorithm for computing the inverse is described in NTRU Technical Note 014, and a theoretical discussion of inverses in truncated polynomial rings is given in NTRU Technical Note 009. These notes may be downloaded from the Technical Center. > > > Example. Take $N=7$, $q=11$, $a=3+2X^2-3X^4+X^6$. The inverse of $a$ modulo 11 is $$A=-2+4X+2X^2+4X^3-4X^4+2X^5-2X^6,$$ since $$(3+2X^2-3X^4+X^6)\*(-2+4X+2X^2+4X^3-4X^4+2X^5-2X^6) \\ = -10+22X+22X^3-22X^6 \equiv 1 \pmod{11}."$$ > > > I do not understand how $-10+22X+22X^3-22X^6$ may be 1 (modulo 11). Why??????? The first excerpt adduced says that each coefficient of the polynomial minus 1 must be a quotient of 11. But it's not. -10? That's not a problem. $-10 - 1 = -11$. $-11 \bmod 11$ is 0, yes, it works, I agree. But how can it work with 22? $22 - 1 = 21$. $21 \bmod 11 = 10$, not 0. also it doesn't work with $- 22$. $-22 - 1 = -23$. $-23 \bmod 11 = -1$. Can anyone, please, explain me this example?
2011/12/26
[ "https://crypto.stackexchange.com/questions/1538", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/1304/" ]
$$(-10+22x+22x^3-22x^6) - 1 = -11+22x+22x^3-22x^6 \equiv 0 \mod 11.$$ When substracting a constant from a polynomial, you do *not* subtract it from every term, only from the constant term. If you need a refresher, see [addition and subtraction of polynomials](http://www.jamesbrennan.org/algebra/polynomials/addition_and_subtraction_of_poly.htm).
> > "how $-10+22X+22X^3-22X^6$ may be 1 (modulo 11) if 22 = 0 mod 11?" > > > Because when you reduce this mod 11 you get $$1 + 0 X + 0 X^3 + 0 X^6 = 1.$$ You seem to think that saying a polynomial is 1 mod 11 means that all its terms are 1 mod 11. What it actually means is that the constant term is 1 mod 11, and all the other terms are 0.
10,084,902
I've been dealing with this before but it seems like the problem came back. Let me explain. I have a web page that lets a user upload a big file, after which it may also take several seconds for the ASP.NET server-side script to process it. In the meantime I wanted to show a loader/spinner animation in a web browser to prevent users from clicking the submit button again. I used the following JQuery code: ``` $('#ButtonImportData').click(function () { $('.importSubmitSpinner').css('display', 'inline'); } ``` here's the HTML for the spinner image: ``` <img src="Graphics/spinner_big.gif" width="28" height="28" class="importSubmitSpinner" alt="Spinner" /> ``` and here's CSS: ``` .importSubmitSpinner { margin: 0px 10px 0px 6px; width: 28px; height: 28px; display: none; } ``` spinner\_big.gif is a simple GIF file with an animation to signal for a user that a page is loading. The above approach works in almost all browsers, except ... guess which one? Yes, IE! What happens in IE is that after a user clicks the ButtonImportData button the spinner is displayed but the animation stops immediately, basically giving a user a false indication that a page got hung up which prompts them to click submit again -- an opposite to what I wanted to do. I stopped using IE a long time ago but evidently there is about half of the Internet community that still uses it. Man, how can people use that piece of \*&^%? Anyway, that is not a question :) The question is, how to make this simple task work in IE and make my animation actually play? PS. I've been testing it with IE 9 or whatever is the current "beauty of the web" for Windows 7. **EDIT:** Thanks to, ShadowScripter, I found a solution. Here's what worked for me: 1 Add the following to HTML to determine if we're running on IE (because we don't need to do this "hack" for any other web browser): ``` <![if !IE]> <script type='text/javascript'> var bNotIE = 1; </script> <![endif]> ``` 2 We need to add ID to the img element: ``` <img src="Graphics/spinner_big.gif" width="28" height="28" class="importSubmitSpinner" alt="Spinner" id="imgSpinnerImport" /> ``` 3 Then to display the GIF animation: ``` $('#ButtonImportData').click(function () { //For "normal" browsers $('.importSubmitSpinner').show(); if (typeof (bNotIE) == 'undefined') { //The following must be done only in case of IE //NOTE: We need to load the same file but with a different name // because if you don't change the file name it won't work! setTimeout('document.images["imgSpinnerImport"].src = "Graphics/spinner_big_ie.gif"', 200); } } ```
2012/04/10
[ "https://Stackoverflow.com/questions/10084902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/670017/" ]
I think problem is with URL. It work <http://www.itrain.com.my/v3/> but doesnt work on <http://itrain.com.my/v3/> Set on your server redirection (301) from non-www URL to www URL.
I would wager you have the font installed on your local machine. I don't see it on any browser. Instead, I get two 404 errors. In other words: please make sure the font files are available at the locations their respective locations: `http://www.itrain.com.my/v3/wp-content/themes/itrain/img/fonts/big_noodle_titling-webfont.woff` and `http://www.itrain.com.my/v3/wp-content/themes/itrain/img/fonts/bebas__-webfont.woff`. [EDIT] I've just looked at the fonts directory listing on your site. The ttf and eot versionf of your fonts are available, the woff and svg are listed, but result in a 404 error. Furthermore, the ttf version (downloaded instead of woff in Firefox, after getting a 404) seems to generate an empty HTTP response. So... Make sure the fonts are there, make sure they have proper privileges set (like 0644). I can't see any other issues than the font files themselves as the CSS appears to be correct. [EDIT 2] @kubedan provides a great tip that seems to fit your concern about the htaccess: the domain the fonts are downloaded from is always preceded with `www`. Firefox will refuse to download such content, you need to use the same domain.
13,791,047
this is possibly much of an elementary question, but I'm having trouble with a procedure I have to write in Scheme. The procedure should return all the prime numbers less or equal to N (N is from input). ``` (define (isPrimeHelper x k) (if (= x k) #t (if (= (remainder x k) 0) #f (isPrimeHelper x (+ k 1))))) (define ( isPrime x ) (cond (( = x 1 ) #t) (( = x 2 ) #t) ( else (isPrimeHelper x 2 ) ))) (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result (if (isPrime x) (cons x result) )) ( helper (+ x 1))) ( helper 1 )) ``` My check for prime works, however the function `printPrimesUpTo` seem to loop forever. Basically the idea is to check whether a number is prime and put it in a result list. Thanks :)
2012/12/09
[ "https://Stackoverflow.com/questions/13791047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1195020/" ]
The `(if)` expression in your `(helper)` function is not the tail expression of the function, and so is not returned, but control will always continue to `(helper (+ x 1))` and recurse.
You can do this much more nicely. I reformated your code: ``` (define (prime? x) (define (prime-helper x k) (cond ((= x k) #t) ((= (remainder x k) 0) #f) (else (prime-helper x (+ k 1))))) (cond ((= x 1) #f) ((= x 2) #t) (else (prime-helper x 2)))) (define (primes-up-to n) (define (helper x) (cond ((= x 0) '()) ((prime? x) (cons x (helper (- x 1)))) (else (helper (- x 1))))) (reverse (helper n))) scheme@(guile-user)> (primes-up-to 20) $1 = (2 3 5 7 11 13 17 19) ``` Please don’t write Scheme like C or Java – and have a look at these [style rules](http://mumble.net/~campbell/scheme/style.txt) for languages of the lisp-family for the sake of readability: Do not use camel-case, do not put parentheses on own lines, mark predicates with `?`, take care of correct indentation, do not put additional whitespace within parentheses.
13,791,047
this is possibly much of an elementary question, but I'm having trouble with a procedure I have to write in Scheme. The procedure should return all the prime numbers less or equal to N (N is from input). ``` (define (isPrimeHelper x k) (if (= x k) #t (if (= (remainder x k) 0) #f (isPrimeHelper x (+ k 1))))) (define ( isPrime x ) (cond (( = x 1 ) #t) (( = x 2 ) #t) ( else (isPrimeHelper x 2 ) ))) (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result (if (isPrime x) (cons x result) )) ( helper (+ x 1))) ( helper 1 )) ``` My check for prime works, however the function `printPrimesUpTo` seem to loop forever. Basically the idea is to check whether a number is prime and put it in a result list. Thanks :)
2012/12/09
[ "https://Stackoverflow.com/questions/13791047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1195020/" ]
First, it is good style to express nested structure by indentation, so it is *visually apparent;* and also to put each of `if`'s clauses, the *consequent* and the *alternative*, on its own line: ``` (define (isPrimeHelper x k) (if (= x k) #t ; consequent (if (= (remainder x k) 0) ; alternative ;; ^^ indentation #f ; consequent (isPrimeHelper x (+ k 1))))) ; alternative (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result ; consequent (if (isPrime x) ; alternative (cons x result) )) ; no alternative! ;; ^^ indentation ( helper (+ x 1))) ( helper 1 )) ``` Now it is plainly seen that the last thing that your `helper` function does is to call itself with an incremented `x` value, always. There's no stopping conditions, i.e. this is an infinite loop. Another thing is, calling `(cons x result)` does not alter `result`'s value in any way. For that, you need to set it, like so: `(set! result (cons x result))`. You also need to put this expression in a `begin` group, as it is evaluated not for its value, but for its [*side-effect*](http://en.wikipedia.org/wiki/Side_effect_(computer_science)): ``` (define (helper x) (if (= x (+ 1 n)) result (begin (if (isPrime x) (set! result (cons x result)) ) ; no alternative! (helper (+ x 1)) ))) ``` Usually, the explicit use of `set!` is considered bad style. One standard way to express loops is as [tail-recursive](http://en.wikipedia.org/wiki/Tail_call) code using *named let*, usually with the canonical name "`loop`" (but it can be any name whatever): ``` (define (primesUpTo n) (let loop ((x n) (result '())) (cond ((<= x 1) result) ; return the result ((isPrime x) (loop (- x 1) (cons x result))) ; alter the result being built (else (loop (- x 1) result))))) ; go on with the same result ``` which, in presence of [tail-call optimization](http://en.wikipedia.org/wiki/Tail_call), is actually equivalent to the previous version.
The `(if)` expression in your `(helper)` function is not the tail expression of the function, and so is not returned, but control will always continue to `(helper (+ x 1))` and recurse.
13,791,047
this is possibly much of an elementary question, but I'm having trouble with a procedure I have to write in Scheme. The procedure should return all the prime numbers less or equal to N (N is from input). ``` (define (isPrimeHelper x k) (if (= x k) #t (if (= (remainder x k) 0) #f (isPrimeHelper x (+ k 1))))) (define ( isPrime x ) (cond (( = x 1 ) #t) (( = x 2 ) #t) ( else (isPrimeHelper x 2 ) ))) (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result (if (isPrime x) (cons x result) )) ( helper (+ x 1))) ( helper 1 )) ``` My check for prime works, however the function `printPrimesUpTo` seem to loop forever. Basically the idea is to check whether a number is prime and put it in a result list. Thanks :)
2012/12/09
[ "https://Stackoverflow.com/questions/13791047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1195020/" ]
You have several things wrong, and your code is very non-idiomatic. First, the number 1 is not prime; in fact, is it neither prime nor composite. Second, the `result` variable isn't doing what you think it is. Third, your use of `if` is incorrect everywhere it appears; `if` is an expression, not a statement as in some other programming languages. And, as a matter of style, closing parentheses are stacked at the end of the line, and don't occupy a line of their own. You need to talk with your professor or teaching assistant to clear up some basic misconceptions about Scheme. The best algorithm to find the primes less than *n* is the Sieve of Eratosthenes, invented about twenty-two centuries ago by a Greek mathematician who invented the leap day and a system of latitude and longitude, accurately measured the circumference of the Earth and the distance from Earth to Sun, and was chief librarian of Ptolemy's library at Alexandria. Here is a simple version of his algorithm: ``` (define (primes n) (let ((bits (make-vector (+ n 1) #t))) (let loop ((p 2) (ps '())) (cond ((< n p) (reverse ps)) ((vector-ref bits p) (do ((i (+ p p) (+ i p))) ((< n i)) (vector-set! bits i #f)) (loop (+ p 1) (cons p ps))) (else (loop (+ p 1) ps)))))) ``` Called as `(primes 50)`, that returns the list `(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47)`. It is much faster than testing numbers for primality by trial division, as you are attempting to do. If you must, here is a proper primality checker: ``` (define (prime? n) (let loop ((d 2)) (cond ((< n (* d d)) #t) ((zero? (modulo n d)) #f) (else (loop (+ d 1)))))) ``` Improvements are possible for both algorithms. If you are interested, I modestly recommend this [essay](http://programmingpraxis.com/essays) on my blog.
You can do this much more nicely. I reformated your code: ``` (define (prime? x) (define (prime-helper x k) (cond ((= x k) #t) ((= (remainder x k) 0) #f) (else (prime-helper x (+ k 1))))) (cond ((= x 1) #f) ((= x 2) #t) (else (prime-helper x 2)))) (define (primes-up-to n) (define (helper x) (cond ((= x 0) '()) ((prime? x) (cons x (helper (- x 1)))) (else (helper (- x 1))))) (reverse (helper n))) scheme@(guile-user)> (primes-up-to 20) $1 = (2 3 5 7 11 13 17 19) ``` Please don’t write Scheme like C or Java – and have a look at these [style rules](http://mumble.net/~campbell/scheme/style.txt) for languages of the lisp-family for the sake of readability: Do not use camel-case, do not put parentheses on own lines, mark predicates with `?`, take care of correct indentation, do not put additional whitespace within parentheses.
13,791,047
this is possibly much of an elementary question, but I'm having trouble with a procedure I have to write in Scheme. The procedure should return all the prime numbers less or equal to N (N is from input). ``` (define (isPrimeHelper x k) (if (= x k) #t (if (= (remainder x k) 0) #f (isPrimeHelper x (+ k 1))))) (define ( isPrime x ) (cond (( = x 1 ) #t) (( = x 2 ) #t) ( else (isPrimeHelper x 2 ) ))) (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result (if (isPrime x) (cons x result) )) ( helper (+ x 1))) ( helper 1 )) ``` My check for prime works, however the function `printPrimesUpTo` seem to loop forever. Basically the idea is to check whether a number is prime and put it in a result list. Thanks :)
2012/12/09
[ "https://Stackoverflow.com/questions/13791047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1195020/" ]
First, it is good style to express nested structure by indentation, so it is *visually apparent;* and also to put each of `if`'s clauses, the *consequent* and the *alternative*, on its own line: ``` (define (isPrimeHelper x k) (if (= x k) #t ; consequent (if (= (remainder x k) 0) ; alternative ;; ^^ indentation #f ; consequent (isPrimeHelper x (+ k 1))))) ; alternative (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result ; consequent (if (isPrime x) ; alternative (cons x result) )) ; no alternative! ;; ^^ indentation ( helper (+ x 1))) ( helper 1 )) ``` Now it is plainly seen that the last thing that your `helper` function does is to call itself with an incremented `x` value, always. There's no stopping conditions, i.e. this is an infinite loop. Another thing is, calling `(cons x result)` does not alter `result`'s value in any way. For that, you need to set it, like so: `(set! result (cons x result))`. You also need to put this expression in a `begin` group, as it is evaluated not for its value, but for its [*side-effect*](http://en.wikipedia.org/wiki/Side_effect_(computer_science)): ``` (define (helper x) (if (= x (+ 1 n)) result (begin (if (isPrime x) (set! result (cons x result)) ) ; no alternative! (helper (+ x 1)) ))) ``` Usually, the explicit use of `set!` is considered bad style. One standard way to express loops is as [tail-recursive](http://en.wikipedia.org/wiki/Tail_call) code using *named let*, usually with the canonical name "`loop`" (but it can be any name whatever): ``` (define (primesUpTo n) (let loop ((x n) (result '())) (cond ((<= x 1) result) ; return the result ((isPrime x) (loop (- x 1) (cons x result))) ; alter the result being built (else (loop (- x 1) result))))) ; go on with the same result ``` which, in presence of [tail-call optimization](http://en.wikipedia.org/wiki/Tail_call), is actually equivalent to the previous version.
You can do this much more nicely. I reformated your code: ``` (define (prime? x) (define (prime-helper x k) (cond ((= x k) #t) ((= (remainder x k) 0) #f) (else (prime-helper x (+ k 1))))) (cond ((= x 1) #f) ((= x 2) #t) (else (prime-helper x 2)))) (define (primes-up-to n) (define (helper x) (cond ((= x 0) '()) ((prime? x) (cons x (helper (- x 1)))) (else (helper (- x 1))))) (reverse (helper n))) scheme@(guile-user)> (primes-up-to 20) $1 = (2 3 5 7 11 13 17 19) ``` Please don’t write Scheme like C or Java – and have a look at these [style rules](http://mumble.net/~campbell/scheme/style.txt) for languages of the lisp-family for the sake of readability: Do not use camel-case, do not put parentheses on own lines, mark predicates with `?`, take care of correct indentation, do not put additional whitespace within parentheses.
13,791,047
this is possibly much of an elementary question, but I'm having trouble with a procedure I have to write in Scheme. The procedure should return all the prime numbers less or equal to N (N is from input). ``` (define (isPrimeHelper x k) (if (= x k) #t (if (= (remainder x k) 0) #f (isPrimeHelper x (+ k 1))))) (define ( isPrime x ) (cond (( = x 1 ) #t) (( = x 2 ) #t) ( else (isPrimeHelper x 2 ) ))) (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result (if (isPrime x) (cons x result) )) ( helper (+ x 1))) ( helper 1 )) ``` My check for prime works, however the function `printPrimesUpTo` seem to loop forever. Basically the idea is to check whether a number is prime and put it in a result list. Thanks :)
2012/12/09
[ "https://Stackoverflow.com/questions/13791047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1195020/" ]
The more efficient `prime?`(from Sedgewick's "Algorithms"): ``` (define (prime? n) (define (F n i) "helper" (cond ((< n (* i i)) #t) ((zero? (remainder n i)) #f) (else (F n (+ i 1))))) "primality test" (cond ((< n 2) #f) (else (F n 2)))) ```
You can do this much more nicely. I reformated your code: ``` (define (prime? x) (define (prime-helper x k) (cond ((= x k) #t) ((= (remainder x k) 0) #f) (else (prime-helper x (+ k 1))))) (cond ((= x 1) #f) ((= x 2) #t) (else (prime-helper x 2)))) (define (primes-up-to n) (define (helper x) (cond ((= x 0) '()) ((prime? x) (cons x (helper (- x 1)))) (else (helper (- x 1))))) (reverse (helper n))) scheme@(guile-user)> (primes-up-to 20) $1 = (2 3 5 7 11 13 17 19) ``` Please don’t write Scheme like C or Java – and have a look at these [style rules](http://mumble.net/~campbell/scheme/style.txt) for languages of the lisp-family for the sake of readability: Do not use camel-case, do not put parentheses on own lines, mark predicates with `?`, take care of correct indentation, do not put additional whitespace within parentheses.
13,791,047
this is possibly much of an elementary question, but I'm having trouble with a procedure I have to write in Scheme. The procedure should return all the prime numbers less or equal to N (N is from input). ``` (define (isPrimeHelper x k) (if (= x k) #t (if (= (remainder x k) 0) #f (isPrimeHelper x (+ k 1))))) (define ( isPrime x ) (cond (( = x 1 ) #t) (( = x 2 ) #t) ( else (isPrimeHelper x 2 ) ))) (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result (if (isPrime x) (cons x result) )) ( helper (+ x 1))) ( helper 1 )) ``` My check for prime works, however the function `printPrimesUpTo` seem to loop forever. Basically the idea is to check whether a number is prime and put it in a result list. Thanks :)
2012/12/09
[ "https://Stackoverflow.com/questions/13791047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1195020/" ]
First, it is good style to express nested structure by indentation, so it is *visually apparent;* and also to put each of `if`'s clauses, the *consequent* and the *alternative*, on its own line: ``` (define (isPrimeHelper x k) (if (= x k) #t ; consequent (if (= (remainder x k) 0) ; alternative ;; ^^ indentation #f ; consequent (isPrimeHelper x (+ k 1))))) ; alternative (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result ; consequent (if (isPrime x) ; alternative (cons x result) )) ; no alternative! ;; ^^ indentation ( helper (+ x 1))) ( helper 1 )) ``` Now it is plainly seen that the last thing that your `helper` function does is to call itself with an incremented `x` value, always. There's no stopping conditions, i.e. this is an infinite loop. Another thing is, calling `(cons x result)` does not alter `result`'s value in any way. For that, you need to set it, like so: `(set! result (cons x result))`. You also need to put this expression in a `begin` group, as it is evaluated not for its value, but for its [*side-effect*](http://en.wikipedia.org/wiki/Side_effect_(computer_science)): ``` (define (helper x) (if (= x (+ 1 n)) result (begin (if (isPrime x) (set! result (cons x result)) ) ; no alternative! (helper (+ x 1)) ))) ``` Usually, the explicit use of `set!` is considered bad style. One standard way to express loops is as [tail-recursive](http://en.wikipedia.org/wiki/Tail_call) code using *named let*, usually with the canonical name "`loop`" (but it can be any name whatever): ``` (define (primesUpTo n) (let loop ((x n) (result '())) (cond ((<= x 1) result) ; return the result ((isPrime x) (loop (- x 1) (cons x result))) ; alter the result being built (else (loop (- x 1) result))))) ; go on with the same result ``` which, in presence of [tail-call optimization](http://en.wikipedia.org/wiki/Tail_call), is actually equivalent to the previous version.
You have several things wrong, and your code is very non-idiomatic. First, the number 1 is not prime; in fact, is it neither prime nor composite. Second, the `result` variable isn't doing what you think it is. Third, your use of `if` is incorrect everywhere it appears; `if` is an expression, not a statement as in some other programming languages. And, as a matter of style, closing parentheses are stacked at the end of the line, and don't occupy a line of their own. You need to talk with your professor or teaching assistant to clear up some basic misconceptions about Scheme. The best algorithm to find the primes less than *n* is the Sieve of Eratosthenes, invented about twenty-two centuries ago by a Greek mathematician who invented the leap day and a system of latitude and longitude, accurately measured the circumference of the Earth and the distance from Earth to Sun, and was chief librarian of Ptolemy's library at Alexandria. Here is a simple version of his algorithm: ``` (define (primes n) (let ((bits (make-vector (+ n 1) #t))) (let loop ((p 2) (ps '())) (cond ((< n p) (reverse ps)) ((vector-ref bits p) (do ((i (+ p p) (+ i p))) ((< n i)) (vector-set! bits i #f)) (loop (+ p 1) (cons p ps))) (else (loop (+ p 1) ps)))))) ``` Called as `(primes 50)`, that returns the list `(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47)`. It is much faster than testing numbers for primality by trial division, as you are attempting to do. If you must, here is a proper primality checker: ``` (define (prime? n) (let loop ((d 2)) (cond ((< n (* d d)) #t) ((zero? (modulo n d)) #f) (else (loop (+ d 1)))))) ``` Improvements are possible for both algorithms. If you are interested, I modestly recommend this [essay](http://programmingpraxis.com/essays) on my blog.
13,791,047
this is possibly much of an elementary question, but I'm having trouble with a procedure I have to write in Scheme. The procedure should return all the prime numbers less or equal to N (N is from input). ``` (define (isPrimeHelper x k) (if (= x k) #t (if (= (remainder x k) 0) #f (isPrimeHelper x (+ k 1))))) (define ( isPrime x ) (cond (( = x 1 ) #t) (( = x 2 ) #t) ( else (isPrimeHelper x 2 ) ))) (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result (if (isPrime x) (cons x result) )) ( helper (+ x 1))) ( helper 1 )) ``` My check for prime works, however the function `printPrimesUpTo` seem to loop forever. Basically the idea is to check whether a number is prime and put it in a result list. Thanks :)
2012/12/09
[ "https://Stackoverflow.com/questions/13791047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1195020/" ]
First, it is good style to express nested structure by indentation, so it is *visually apparent;* and also to put each of `if`'s clauses, the *consequent* and the *alternative*, on its own line: ``` (define (isPrimeHelper x k) (if (= x k) #t ; consequent (if (= (remainder x k) 0) ; alternative ;; ^^ indentation #f ; consequent (isPrimeHelper x (+ k 1))))) ; alternative (define (printPrimesUpTo n) (define result '()) (define (helper x) (if (= x (+ 1 n)) result ; consequent (if (isPrime x) ; alternative (cons x result) )) ; no alternative! ;; ^^ indentation ( helper (+ x 1))) ( helper 1 )) ``` Now it is plainly seen that the last thing that your `helper` function does is to call itself with an incremented `x` value, always. There's no stopping conditions, i.e. this is an infinite loop. Another thing is, calling `(cons x result)` does not alter `result`'s value in any way. For that, you need to set it, like so: `(set! result (cons x result))`. You also need to put this expression in a `begin` group, as it is evaluated not for its value, but for its [*side-effect*](http://en.wikipedia.org/wiki/Side_effect_(computer_science)): ``` (define (helper x) (if (= x (+ 1 n)) result (begin (if (isPrime x) (set! result (cons x result)) ) ; no alternative! (helper (+ x 1)) ))) ``` Usually, the explicit use of `set!` is considered bad style. One standard way to express loops is as [tail-recursive](http://en.wikipedia.org/wiki/Tail_call) code using *named let*, usually with the canonical name "`loop`" (but it can be any name whatever): ``` (define (primesUpTo n) (let loop ((x n) (result '())) (cond ((<= x 1) result) ; return the result ((isPrime x) (loop (- x 1) (cons x result))) ; alter the result being built (else (loop (- x 1) result))))) ; go on with the same result ``` which, in presence of [tail-call optimization](http://en.wikipedia.org/wiki/Tail_call), is actually equivalent to the previous version.
The more efficient `prime?`(from Sedgewick's "Algorithms"): ``` (define (prime? n) (define (F n i) "helper" (cond ((< n (* i i)) #t) ((zero? (remainder n i)) #f) (else (F n (+ i 1))))) "primality test" (cond ((< n 2) #f) (else (F n 2)))) ```
25,903,779
Can you please take a look at [This Demo](http://jsfiddle.net/Behseini/xLea235h/) and let me know how I can loop through and element like `<pre>` and replace all `<` and `>` with some new characters like: ``` .replace("<", "1"); .replace(">", "2"); ``` if we have a `<pre>` like ``` <pre> < This is a test < which must > replace > </pre> ``` Thanks
2014/09/18
[ "https://Stackoverflow.com/questions/25903779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3649067/" ]
You can use [.text()](http://api.jquery.com/text/) and [String.replace()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) using an [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) ```js $('pre').text(function(i, text){ return text.replace(/</g, '1').replace(/>/g, '2') }) ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <pre> < This is a test < which must > replace > </pre> ```
may be like ```js var test = $("pre").text(); var k = test.split("<").join(1).split(">").join(2); alert(k); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <pre>< This is a test < which must > replace ></pre> ``` reference : [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript)
23,475
Let me give you a run down of the board state. I had an [Elderscale Wurm](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Elderscale%20Wurm) enchanted with [Canopy Cover](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Canopy%20Cover) on the battlefield. Damage could not reduce my life total below 7. My opponent had [Forgestoker Dragon](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Forgestoker%20Dragon) on the battlefield and a lot of other, smaller creatures. He could pay to kill any other creature that came out on the battlefield, but had no effects in his deck to deal with Elderscale Wurm nor Canopy Cover. Similarly I had no way to deal with his dragon, and if I attacked with my Elderscale Wurm it would die, and I would lose to his horde. But, I had one more card in my library than he did, so we assumed I would eventually win until we looked at the other two cards my opponent had on the battlefield- [Aether Rift](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Aether%20Rift) and [Library of Leng](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Library%20of%20Leng). Aether Rift says: > > Enchantment > > > At the beginning of your upkeep, discard a card at random. If you discard a creature card this way, return it from your graveyard to the battlefield unless any player pays 5 life. > > > Library of Leng says: > > Artifact > > > You have no maximum hand size. If an effect causes you to discard a card, discard it, but you may put it on top of your library instead of into your graveyard. > > > My opponent only had creatures in his hand. He wanted to use the interaction between these two cards to randomly discard a card, not pay 5 life,(I could not pay the 5 life cost because it would bring me below 7 life, negating Elderscale Wurm's effect) and have it go back to the top of his library, so that he would have 1 more card than I did, thus I would mill out before he did. Is that how this interaction works?
2015/03/20
[ "https://boardgames.stackexchange.com/questions/23475", "https://boardgames.stackexchange.com", "https://boardgames.stackexchange.com/users/12101/" ]
He would be able to put a card on top of his library in order to not lose, but not quite the way you are thinking it works. What happens is a the beginning of your opponent's upkeep Aether Rift's ability goes on the stack, and when it resolves they discard a card at random. when the card gets discarded Library of Leng's replacement effect occurs allowing your opponent to put the card on top of their library. If they chose to put the card on top of their library the rest of Aether Rift's ability doesn't apply since as far as the game knows a creature card was never discarded (a card was discarded if anything else cares about that, but nothing is known about that card, including its type [[CR 701.7c]](http://mtgsalvation.gamepedia.com/Discard)). Your opponent will then draw the card they just "discarded" at the beginning of their draw step. They can keep repeating this process until you run out of cards in your library.
Yes, it would work that way. The paying 5 life is actually irrelevant here, because if he chooses to put the card on top of his library, then the creature will fail to return "from the graveyard to the battlefield", because it won't be in the graveyard. His library shouldn't ever shrink in fact; each turn he will discard a card, putting it on his library, then draw that same card.
7,310,084
So, I'm trying to make a transaction with LINQ to SQL. I read that if I use `SubmitChanges()`, it would create a transaction and execute everything and in case of an exception everything would be rolled back. Do I need to use MULTIPLE `SubmitChanges()`? I'm using something like this code and it isn't working because it isn't saving any data on the first table.. (I need it's ID for the children table). If I do use another `SubmitChanges()` right after the first `InsertOnSubmit` doesn't it lose the idea of a transaction? ``` myDataContext db = new myDataContext(); Process openProcess = new Process(); openProcess.Creation = DateTime.Now; openProcess.Number = pNumber; //Set to insert db.Process.InsertOnSubmit(openProcess); Product product = new Product(); product.Code = pCode; product.Name = pName; product.Process_Id = openProcess.Id; //Submit all changes at once? db.SubmitChanges(); ```
2011/09/05
[ "https://Stackoverflow.com/questions/7310084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110282/" ]
You can make the whole thing transaciotnal using a `TransactionScope` e.g. ``` using (TransactionScope scope = new TransactionScope()) { myDataContext db = new myDataContext(); Process openProcess = new Process(); openProcess.Creation = DateTime.Now; openProcess.Number = pNumber; db.Process.InsertOnSubmit(openProcess); db.SubmitChanges(); //openProcess.Id will be populated Product product = new Product(); product.Code = pCode; product.Name = pName; product.Process_Id = openProcess.Id; db.Products.InsertOnSubmit(product); // I assume you missed this step in your example db.SubmitChanges(); scope.Complete() } ``` If an exception is thrown before `scope.Complete()` is called then the whole thing will be rolled back.
The problem is, that the ID of your process is set when the changes are submitted to the database. Because you submit the changes after the line where you assign the process id to the product (`product.Process_Id = openProcess.Id;`). The correct way to do this would be to correctly setup your database with a foreign key from PRODUCT to PROCESS and use the navigation property `Process` on `Product` to assign the process to the product. The code would look like this: ``` myDataContext db = new myDataContext(); Process openProcess = new Process(); openProcess.Creation = DateTime.Now; openProcess.Number = pNumber; Product product = new Product(); product.Code = pCode; product.Name = pName; product.Process = openProcess; db.Product.InsertOnSubmit(product); db.SubmitChanges(); ``` Because `Process` is a navigation property of `Product`, you don't need to insert the `Process`. It will be inserted automatically, because you insert the "parent" - the `Product`.
23,972,031
I want to merge few code lines of a commit belonging to a different branch into a new commit of my `master`, i.e. using a difftool apply only some changes of another commit. I tried from `master` with ``` merge --no-commit --no-ff newJob git reset . ``` but then I don't know how to choose only part of the changes. This is because I'm writing my CV in latex and I want to create a different branch when I use a different template, a new layout, or when I want to customize it for a particular job. Then it happens that I update or correct details in the branch, let's say, `newJob` and I have to correct these details also into the `master`. Using a difftool would be really quick.
2014/05/31
[ "https://Stackoverflow.com/questions/23972031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3694516/" ]
A recorded merge says all changes that need to be applied have been; later merges of the two histories won't reexamine changes you discard in this merge. It may not be what you want here. To apply just a few changes from commit B, do e.g. ``` git diff-tree -p B file ... | git apply git add -p . # (this is the pick-my-diffs command you wanted) git checkout file ... # (optional, undo any changes not staged) ```
you can use git cherry-pick to achieve it。 ``` git checkout branch-B git cherry-pick commit-a2 ``` it can merge the commit of branch-A to branch-B.
11,058,984
I'm reading in from a CSV file, parsing it, and storing the data, pretty simple. Right now were using the standard `readLine()` method to do that, and I'm trying to squeeze some extra efficency out of this processing loop. I don't know how much they hide behind the scenes, but I assume each call to `getLine` is a new OS call with all the pain that entails? I don't want to pay for OS calls on each line of input. I would provide a huge buffer and have it fill the buffer with many lines at once. However, I only care about full lines. I don't want to have to handle maintaining partial lines from one buffer read to append to the second buffer read to make a full line, that's just ugly and annoying. So, is there a method out there that does this for me? It seems like there almost has to be. Any method which I can instruct to read in x number of lines, or x bytes but don't output the last partial line, or even an easy way for me to manage the memory buffer so I minimize the amount of code for handling partial strings would be appreciated. I can use Boost, though if there is a method in standard C++ I would prefer that. Thanks.
2012/06/15
[ "https://Stackoverflow.com/questions/11058984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/897272/" ]
It's very unlikely that you'll be able to do better than the built-in C++ streams. They're quite fast. In general, the fastest way to completely read a file is to use a single thread to read the entire file from start to end, especially if the file is contiguous on disk. Furthermore, it's likely that the disk is much more of a bottleneck during reading than the OS. If you need to improve the performance of your app, I have a few recommendations. * Use a profiler. If your app is reading a line then parsing it or processing it in some way, it's possible that the parsing or processing is something that can be optimized. This can be determined in profiling. If parsing or processing takes up substantial CPU resources, then optimization may be worth the effort. * If you determine that parsing or processing is responsible for a slow application, and that it can't be easily optimized, consider multiprogramming. If the processing of individual lines does not depend on the results of previous lines being processed, then use multiple threads or CPUs to do the processing. * Use pipelining if you have to process multiple files. For example, suppose you have four stages in your app: reading, parsing, processing, saving. It may be more efficient to read one file at a time rather then all of them all at once. However, while reading the second file, you can still parse the first one. While reading the third file, you can parse the second file and process the first one, etc. One way to implement this is a [staged mult-threaded application design](http://en.wikipedia.org/wiki/Staged_event-driven_architecture). * Use RAID to improve disk reads. Certain raid modes can create faster reads and writes.
i am java programmer, but still i have a hint... read the data in a stream. that means for example 4 or 5 times 2048bytes (or much more)... you can iterate over the stream (and convert it) and search for your line-ends(or some other char)... but i think "readLine" is doing the same anyway...
4,509,899
I would like to fetch some data into my Excel Spreadsheet (Excel 2007) from webservice, but I would like to deploy the spreadsheet as one file only (f.e. spreadsheet.xlsx - nothing more). Without this constraint I would use Visual Studio addons and write it in C#, but it would give me some extra dlls and vsto files. In earlier version of excel, there was Webservices Tolkit, but my research indicate, that it won't work with 2007. Are there any solutions out there? I heard something about Microsoft Office Soap Type library 3.0, but I don't know how to start working with it. Any help / sample code / other solutions will be appreciated.
2010/12/22
[ "https://Stackoverflow.com/questions/4509899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460822/" ]
I find out how to connect with webservice with Ms Office Soap Type library in vba - so no extra files, just xls(x). At this point I know how to get simple datatypes results (like string). But I hope, I'll be able to get and work with more complex types. Here's the code: ``` Dim webservice As SoapClient30 Dim results As String ' Point the SOAP API to the web service that we want to call... Set webservice = New SoapClient30 Call webservice.mssoapinit(par_WSDLFile:="{url to wsdl}") ' Call the web service results = webservice.{method name}() Set webservice = Nothing ``` It's necessary to add "Microsoft Office Soap Type Library v3.0" to your worksheet references.
Have you tried [http://msdn.microsoft.com/en-us/library/dd819156(v=office.12).aspx](http://msdn.microsoft.com/en-us/library/dd819156%28v=office.12%29.aspx)
4,509,899
I would like to fetch some data into my Excel Spreadsheet (Excel 2007) from webservice, but I would like to deploy the spreadsheet as one file only (f.e. spreadsheet.xlsx - nothing more). Without this constraint I would use Visual Studio addons and write it in C#, but it would give me some extra dlls and vsto files. In earlier version of excel, there was Webservices Tolkit, but my research indicate, that it won't work with 2007. Are there any solutions out there? I heard something about Microsoft Office Soap Type library 3.0, but I don't know how to start working with it. Any help / sample code / other solutions will be appreciated.
2010/12/22
[ "https://Stackoverflow.com/questions/4509899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460822/" ]
Sorry to dig up an old post, but I had a similar constraint recently with everything needing to be contained to a single workbook and want to post my solution in case anyone has a similar issue. Ended up writing my own all-VBA library (based heavily on one of my favorites, RestSharp). Warning, shameless plug: <https://github.com/timhall/Excel-REST> Some fun features include authentication (Http Basic, OAuth1, and OAuth2 Client Credentials), Async support, and JSON parsing (thanks to vba-json) It's working awesomely in Excel 2010 (and most likely 2007), but does not work on Excel for Mac due to missing XMLHTTP libraries. I've got it working with Salesforce, Trello, Basecamp, Google Maps, and it should work with pretty much any REST webservice. Example: ``` Function GetDirections(Origin As String, Destination As String) As String ' Create a RestClient for executing requests ' and set a base url that all requests will be appended to Dim MapsClient As New RestClient MapsClient.BaseUrl = "https://maps.googleapis.com/maps/api/" ' Create a RestRequest for getting directions Dim DirectionsRequest As New RestRequest DirectionsRequest.Resource = "directions/{format}" DirectionsRequest.Method = httpGET ' Set the request format -> Sets {format} segment, content-types, and parses the response DirectionsRequest.Format = json ' (Alternatively, replace {format} segment directly) DirectionsRequest.AddUrlSegment "format", "json" ' Add parameters to the request (as querystring for GET calls and body otherwise) DirectionsRequest.AddParameter "origin", Origin DirectionsRequest.AddParameter "destination", Destination ' Force parameter as querystring for all requests DirectionsRequest.AddQuerystringParam "sensor", "false" ' => GET https://maps.../api/directions/json?origin=...&destination=...&sensor=false ' Execute the request and work with the response Dim Response As RestResponse Set Response = MapsClient.Execute(DirectionsRequest) If Response.StatusCode = 200 Then ' Work directly with parsed json data Dim Route As Object Set Route = Response.Data("routes")(1)("legs")(1) GetDirections = "It will take " & Route("duration")("text") & _ " to travel " & Route("distance")("text") & _ " from " & Route("start_address") & _ " to " & Route("end_address") Else GetDirections = "Error: " & Response.Content End If End Function ```
Have you tried [http://msdn.microsoft.com/en-us/library/dd819156(v=office.12).aspx](http://msdn.microsoft.com/en-us/library/dd819156%28v=office.12%29.aspx)
4,509,899
I would like to fetch some data into my Excel Spreadsheet (Excel 2007) from webservice, but I would like to deploy the spreadsheet as one file only (f.e. spreadsheet.xlsx - nothing more). Without this constraint I would use Visual Studio addons and write it in C#, but it would give me some extra dlls and vsto files. In earlier version of excel, there was Webservices Tolkit, but my research indicate, that it won't work with 2007. Are there any solutions out there? I heard something about Microsoft Office Soap Type library 3.0, but I don't know how to start working with it. Any help / sample code / other solutions will be appreciated.
2010/12/22
[ "https://Stackoverflow.com/questions/4509899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460822/" ]
I find out how to connect with webservice with Ms Office Soap Type library in vba - so no extra files, just xls(x). At this point I know how to get simple datatypes results (like string). But I hope, I'll be able to get and work with more complex types. Here's the code: ``` Dim webservice As SoapClient30 Dim results As String ' Point the SOAP API to the web service that we want to call... Set webservice = New SoapClient30 Call webservice.mssoapinit(par_WSDLFile:="{url to wsdl}") ' Call the web service results = webservice.{method name}() Set webservice = Nothing ``` It's necessary to add "Microsoft Office Soap Type Library v3.0" to your worksheet references.
Sorry to dig up an old post, but I had a similar constraint recently with everything needing to be contained to a single workbook and want to post my solution in case anyone has a similar issue. Ended up writing my own all-VBA library (based heavily on one of my favorites, RestSharp). Warning, shameless plug: <https://github.com/timhall/Excel-REST> Some fun features include authentication (Http Basic, OAuth1, and OAuth2 Client Credentials), Async support, and JSON parsing (thanks to vba-json) It's working awesomely in Excel 2010 (and most likely 2007), but does not work on Excel for Mac due to missing XMLHTTP libraries. I've got it working with Salesforce, Trello, Basecamp, Google Maps, and it should work with pretty much any REST webservice. Example: ``` Function GetDirections(Origin As String, Destination As String) As String ' Create a RestClient for executing requests ' and set a base url that all requests will be appended to Dim MapsClient As New RestClient MapsClient.BaseUrl = "https://maps.googleapis.com/maps/api/" ' Create a RestRequest for getting directions Dim DirectionsRequest As New RestRequest DirectionsRequest.Resource = "directions/{format}" DirectionsRequest.Method = httpGET ' Set the request format -> Sets {format} segment, content-types, and parses the response DirectionsRequest.Format = json ' (Alternatively, replace {format} segment directly) DirectionsRequest.AddUrlSegment "format", "json" ' Add parameters to the request (as querystring for GET calls and body otherwise) DirectionsRequest.AddParameter "origin", Origin DirectionsRequest.AddParameter "destination", Destination ' Force parameter as querystring for all requests DirectionsRequest.AddQuerystringParam "sensor", "false" ' => GET https://maps.../api/directions/json?origin=...&destination=...&sensor=false ' Execute the request and work with the response Dim Response As RestResponse Set Response = MapsClient.Execute(DirectionsRequest) If Response.StatusCode = 200 Then ' Work directly with parsed json data Dim Route As Object Set Route = Response.Data("routes")(1)("legs")(1) GetDirections = "It will take " & Route("duration")("text") & _ " to travel " & Route("distance")("text") & _ " from " & Route("start_address") & _ " to " & Route("end_address") Else GetDirections = "Error: " & Response.Content End If End Function ```
33,982,545
I've receiving this error in every project I make, new or otherwise. [![Error in Android Studio](https://i.stack.imgur.com/UxnnV.png)](https://i.stack.imgur.com/UxnnV.png) I've attempted reinstalling Android Studio fresh without any luck and I've also scoured the Internet for the exact error and nothing seems to be coming up. Does anyone have an idea of what's causing this error when I add a new layout to my project?
2015/11/29
[ "https://Stackoverflow.com/questions/33982545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5279721/" ]
Instead of adding the new activity by right clicking on the file labeled "layout", right click on the file labeled "res" to add a new activity and it should work fine.
If you want to add a layout file to your project, follow below way - app -> res -> New -> Acivity -> select activity which u want.
33,982,545
I've receiving this error in every project I make, new or otherwise. [![Error in Android Studio](https://i.stack.imgur.com/UxnnV.png)](https://i.stack.imgur.com/UxnnV.png) I've attempted reinstalling Android Studio fresh without any luck and I've also scoured the Internet for the exact error and nothing seems to be coming up. Does anyone have an idea of what's causing this error when I add a new layout to my project?
2015/11/29
[ "https://Stackoverflow.com/questions/33982545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5279721/" ]
As your screenshot shows,current package name is layout,but maybe you don't have a package named `layout`,so such error existed. If you want to add a layout file to your project,you should right click **layout** folder under **res** folder,and create a layout file.
It's simply because you are trying to create new Activity / Layout file in a wrong package. To do so, You have to navigate to ***app >> java >> firstfolder***. Right Click on this first folder and go to ***NEW >> Activity >> EmptyActivity*** or AnyOtherTypeYouWant. Then enter the correct name for your Activity and you will face no errors. As simple as that.
33,982,545
I've receiving this error in every project I make, new or otherwise. [![Error in Android Studio](https://i.stack.imgur.com/UxnnV.png)](https://i.stack.imgur.com/UxnnV.png) I've attempted reinstalling Android Studio fresh without any luck and I've also scoured the Internet for the exact error and nothing seems to be coming up. Does anyone have an idea of what's causing this error when I add a new layout to my project?
2015/11/29
[ "https://Stackoverflow.com/questions/33982545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5279721/" ]
Instead of adding the new activity by right clicking on the file labeled "layout", right click on the file labeled "res" to add a new activity and it should work fine.
Just to add some details to what Infamous said. You can copy the package name from another existing activity. ``` package com.mycompany.myself.myapplication; ``` I agree, I'm surprised that Android Studio is not able to default that with the right value, given during the project creation: Project structure/app/Flavors/defaultConfig/Application Id
33,982,545
I've receiving this error in every project I make, new or otherwise. [![Error in Android Studio](https://i.stack.imgur.com/UxnnV.png)](https://i.stack.imgur.com/UxnnV.png) I've attempted reinstalling Android Studio fresh without any luck and I've also scoured the Internet for the exact error and nothing seems to be coming up. Does anyone have an idea of what's causing this error when I add a new layout to my project?
2015/11/29
[ "https://Stackoverflow.com/questions/33982545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5279721/" ]
Change the package name **Layout** to project package name. [![enter image description here](https://i.stack.imgur.com/TshPt.png)](https://i.stack.imgur.com/TshPt.png) After changing the Package name. It will allow to finish process. **OR** Copy project package name from any java class and paste in **Package name** section.
It's simply because you are trying to create new Activity / Layout file in a wrong package. To do so, You have to navigate to ***app >> java >> firstfolder***. Right Click on this first folder and go to ***NEW >> Activity >> EmptyActivity*** or AnyOtherTypeYouWant. Then enter the correct name for your Activity and you will face no errors. As simple as that.
33,982,545
I've receiving this error in every project I make, new or otherwise. [![Error in Android Studio](https://i.stack.imgur.com/UxnnV.png)](https://i.stack.imgur.com/UxnnV.png) I've attempted reinstalling Android Studio fresh without any luck and I've also scoured the Internet for the exact error and nothing seems to be coming up. Does anyone have an idea of what's causing this error when I add a new layout to my project?
2015/11/29
[ "https://Stackoverflow.com/questions/33982545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5279721/" ]
In Android Studio, in the **java directory**, **select the package**, for example com.mycompany.myfirstapp, right-click, and select **New > Activity > Blank Activity.** ![package name is not set to a valid package name](https://i.stack.imgur.com/GmcRc.png)
I was seeing the same error message (`Package name is not a valid package name`) when I was trying to add a new activity. The problem was that I was trying to add a new activity to the wrong place. I was trying to add the activity (`new -> activity -> blank activity`) in the `res/layout` directory. The solution was to add the activity in the `java/your_app` directory.
33,982,545
I've receiving this error in every project I make, new or otherwise. [![Error in Android Studio](https://i.stack.imgur.com/UxnnV.png)](https://i.stack.imgur.com/UxnnV.png) I've attempted reinstalling Android Studio fresh without any luck and I've also scoured the Internet for the exact error and nothing seems to be coming up. Does anyone have an idea of what's causing this error when I add a new layout to my project?
2015/11/29
[ "https://Stackoverflow.com/questions/33982545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5279721/" ]
just "layout" cannot be a package name check other activities and try to take that packag name on top of the file
For me it was because I right-clicked on the Activity node in my project explorer. If I click on the "app" root node, this doesn't happen.
33,982,545
I've receiving this error in every project I make, new or otherwise. [![Error in Android Studio](https://i.stack.imgur.com/UxnnV.png)](https://i.stack.imgur.com/UxnnV.png) I've attempted reinstalling Android Studio fresh without any luck and I've also scoured the Internet for the exact error and nothing seems to be coming up. Does anyone have an idea of what's causing this error when I add a new layout to my project?
2015/11/29
[ "https://Stackoverflow.com/questions/33982545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5279721/" ]
In Android Studio, in the **java directory**, **select the package**, for example com.mycompany.myfirstapp, right-click, and select **New > Activity > Blank Activity.** ![package name is not set to a valid package name](https://i.stack.imgur.com/GmcRc.png)
It's simply because you are trying to create new Activity / Layout file in a wrong package. To do so, You have to navigate to ***app >> java >> firstfolder***. Right Click on this first folder and go to ***NEW >> Activity >> EmptyActivity*** or AnyOtherTypeYouWant. Then enter the correct name for your Activity and you will face no errors. As simple as that.
33,982,545
I've receiving this error in every project I make, new or otherwise. [![Error in Android Studio](https://i.stack.imgur.com/UxnnV.png)](https://i.stack.imgur.com/UxnnV.png) I've attempted reinstalling Android Studio fresh without any luck and I've also scoured the Internet for the exact error and nothing seems to be coming up. Does anyone have an idea of what's causing this error when I add a new layout to my project?
2015/11/29
[ "https://Stackoverflow.com/questions/33982545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5279721/" ]
Just to add some details to what Infamous said. You can copy the package name from another existing activity. ``` package com.mycompany.myself.myapplication; ``` I agree, I'm surprised that Android Studio is not able to default that with the right value, given during the project creation: Project structure/app/Flavors/defaultConfig/Application Id
just "layout" cannot be a package name check other activities and try to take that packag name on top of the file
33,982,545
I've receiving this error in every project I make, new or otherwise. [![Error in Android Studio](https://i.stack.imgur.com/UxnnV.png)](https://i.stack.imgur.com/UxnnV.png) I've attempted reinstalling Android Studio fresh without any luck and I've also scoured the Internet for the exact error and nothing seems to be coming up. Does anyone have an idea of what's causing this error when I add a new layout to my project?
2015/11/29
[ "https://Stackoverflow.com/questions/33982545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5279721/" ]
1 - to find the right package name go to (main activity) page . 2 - First line you will see this for example : package alqahtani.dhafer.myapp; copy this text **alqahtani.dhafer.myapp** 3 - go to layout --> right click --> new activity --> paste package name in layout name . ![enter image description here](https://i.stack.imgur.com/8Y7Ye.png)
When adding a new activity to my application, it shows the following problem: Package name is not set to a valid package name, and does not allow adding the activity. \*\* Solution 1 **: Instead of adding the new activity by right-clicking on the file named "** layout **", right click on the "** res \*\*" file to add a new activity. And no longer shows the problem: Package name is not set to a valid package name, this is because I could not find the package layout. \*\* Solution 2 \*\*: In the field \*\* Package name \*\*, put us as package \*\* layout \*\* delete it and put the full name of your application package. \*\* Example \*\*: com.mx.softmolina.example <http://blog.softmolina.com.mx/wp/2016/11/30/solucion-package-name-is-not-set-to-a-valid-package-name-agregar-nueva-actividad/> I hope it will be you useful. Regards!! :)
33,982,545
I've receiving this error in every project I make, new or otherwise. [![Error in Android Studio](https://i.stack.imgur.com/UxnnV.png)](https://i.stack.imgur.com/UxnnV.png) I've attempted reinstalling Android Studio fresh without any luck and I've also scoured the Internet for the exact error and nothing seems to be coming up. Does anyone have an idea of what's causing this error when I add a new layout to my project?
2015/11/29
[ "https://Stackoverflow.com/questions/33982545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5279721/" ]
Hope this helps Option 1: 1. Click the Project tab. From there you can see a dropdown. Click the dropdown and go to Packages and then you can see the layout folder. From there you can create another Blank Activity. Option 2: 1. From the dropdown again go to Android. Click the java folder, you can see the package name com.example... Write it down on a paper. Then go to layout and create a blank activity. Change the package name to what you had just wrote down on the paper. Hope it helps.
It's simply because you are trying to create new Activity / Layout file in a wrong package. To do so, You have to navigate to ***app >> java >> firstfolder***. Right Click on this first folder and go to ***NEW >> Activity >> EmptyActivity*** or AnyOtherTypeYouWant. Then enter the correct name for your Activity and you will face no errors. As simple as that.
67,583,686
So what I want to do is take the input from the radio buttons (**metric** or **imperial**) from *Forecast.js*, use them in a function in *Conditions.js* to determine whether it's hot or cold. I've exported the variable **unit** from *Forecast.js* but when I try to use it in the **clothes()** function it doesn't work. I've tried everything I found online and I tried to understand but I'm new to Reactjs. Conditions.js <https://pastebin.com/RHbLuqZD> ``` import { unit } from '../Forecast/Forecast.js'; function clothes(t) { if (unit === "metric") { if (Number('t') <= 20) return (<> <img src={Cold} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} /> It's cold, dress accordingly! </>); else return (<> <img src={Hot} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} /> It's Warm, dress accordingly! </>); } if (unit === "imperial") { if (Number('t') <= 70) return (<> <img src={Cold} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} /> It's cold, dress accordingly! </>); else return (<> <img src={Hot} alt="wind icon" style={{ width: 50, marginRight: 20, height: 50 }} /> It's Warm, dress accordingly! </>); } } ``` Forecast.js <https://pastebin.com/wcBu8bwA> ``` export default Forecast; export let unit = this.state.unit; ``` The reason it doesn't work could be because I didn't do the import and export properly or because I didn't use the imported variable properly. **Edit:** As I specified I'm a beginner, I don't know a lot, what I want is to see how to solve the problem and then understand how to do it. I just need to understand the problem with my code, or an alternative.
2021/05/18
[ "https://Stackoverflow.com/questions/67583686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6372847/" ]
You switch on `TypeOfDatabase` in the constructor before the property has been set. Move the `switch` statement to the `OnTypeOfDatabaseChanged` callback or to a `Loaded` event handler: ``` public BaseConnection() { InitializeComponent(); _languageCode = Thread.CurrentThread.CurrentCulture.Name; this.Resources = _cultureHelper.FindRessourcesDictionnary(this.Resources, "UserControlsResources", _languageCode); Loaded += OnLoaded; } private void OnLoaded(object sender, RoutedEventArgs e) { List<UcConnection> connectionListByDatabaseType = new List<UcConnection>(); switch (TypeOfDatabase) { case DataBaseType.MySql: foreach (UcConnection ucConnection in UcConnectionList) { if (ucConnection.DriverName.ToLower().Contains("mysql")) { connectionListByDatabaseType.Add(ucConnection); } } UcConnectionList = connectionListByDatabaseType; break; case DataBaseType.SqlServer: break; default: break; } } ```
First, I wouldn't advice you to change the value of dependency property in DPChanged call back. Then what you do in constructor you have to do in DPChanged call back. This should work: ``` public DataBaseType TypeOfDatabase { get { return (DataBaseType)GetValue(TypeOfDatabaseProperty); } set { SetValue(TypeOfDatabaseProperty, value); } } public static readonly DependencyProperty TypeOfDatabaseProperty = DependencyProperty.Register(nameof(TypeOfDatabase), typeof(DataBaseType), typeof(BaseConnection), new PropertyMetadata(DataBaseType.All, new PropertyChangedCallback(OnTypeOfDatabaseChanged))); private static void OnTypeOfDatabaseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var connectionListByDatabaseType = new List<UcConnection>(); switch((DataBaseType)e.NewValue) { case DataBaseType.MySql: foreach(UcConnection ucConnection in UcConnectionList) { if(ucConnection.DriverName.ToLower().Contains("mysql")) { connectionListByDatabaseType.Add(ucConnection); } } UcConnectionList = connectionListByDatabaseType; break; case DataBaseType.SqlServer: break; default: break; } } ```
65,070
I want the user to be able to choose whether to show a description or not for each node in the view. Adding the filter only works on the entire object, I just want to show/hide one field. How can I achieve this?
2013/03/10
[ "https://drupal.stackexchange.com/questions/65070", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/13976/" ]
You can do this with Views out of the box. No need for Views PHP here. 1. Add your boolean field in Views. (This assumes the default boolean set up, i.e. 0 for not checked and 1 for checked.) 2. Use the **Key** formatter - this isn't obvious, but I couldn't get it to work without this. 3. Select **REWRITE RESULTS** and put the description you want in there. This can include tokens so you can grab material from other fields in the node if that's what you need. 4. On **NO RESULTS BEHAVIOR** check all the boxes (Count the number 0 as empty, Hide if empty, Hide rewriting if empty)
You should be able to accomplish this with th [Views PHP](http://drupal.org/project/views_php) module. Set up your view with the checkbox and description fields included but not visible. Then include a Global:PHP field, and under the field configuration put something like: ``` <?php echo ($row->checkbox) ? $row->description : ''; ?> ``` in the Display box.
2,481,903
i m designing a simple c code to call the iptables command according to the need. i just want to drop the packets from a particular ipaddress using my c code. thats why i have to use the iptables command according to input given. is it possible to call the command using c code? if it is then how??? thanks in advance..
2010/03/20
[ "https://Stackoverflow.com/questions/2481903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/297864/" ]
Assuming that your program is running as root, just use fork() and exec(), and pass the iptables command to exec(). Something like ``` if (0 == fork()) { execl("/sbin/iptables", ...); // supply the proper arguments to iptables. } ``` Edit: I see from other people that system() is a better way than fork/exec. It sounds like Neha is not sure how to use sprintf to format the command so that it contains an IP address which is stored in some other variable. I think it should look like this: ``` char *host_to_block = .... char comm[1000]; snprintf(comm, sizeof(comm), "iptables -A INPUT -s %s -j DROP", host_to_block); system(comm); ``` Note that this will be a **security vulnerability** unless you have code to verify that host\_to\_block contains an IP address and not some other shell command. You may want to use the following question for reference if the source of the string is not already known to be valid: [how to validate an ip address](https://stackoverflow.com/questions/318236/how-do-you-validate-that-a-string-is-a-valid-ip-address-in-c)
It is possible to do this without using the system() or exec\*() family of commands, however I'm sure that you are also interested in actually completing your project :) If, however you only need very rudimentary functionality from iptables within your program, or need precision error handling, you can obtain the source to the `iptables` package. Advanced warning: studying the iptables ioctl hooks and the corresponding netfilter modules is known to be a mind liquefying task.
3,135,770
$$\sum \_{k=1}^n\sqrt[3]{k}\:>\frac{3}{4}n\sqrt[3]{n}$$ We have the inequality as defined as above. Clearly, one can prove it by induction; it would not be hard. However, it looks suspiciously like it could be done by Jensen's inequality; I am just not sure how. I tried the obvious substitution $f(x)=x^{1/3}$, but then this function is concave, and I cannot use it to prove the inequality. So, I was just wondering if anyone is able to use Jensen's to prove this inequality? Or is there any other inequality that anyone knows that can be used to prove this question without induction?
2019/03/05
[ "https://math.stackexchange.com/questions/3135770", "https://math.stackexchange.com", "https://math.stackexchange.com/users/646705/" ]
$$\sum\_{k=1}^n\sqrt[3]{k}\geq1+\int\limits\_1^n\sqrt[3]xdx=\frac{3}{4}\sqrt[3]{n^4}+\frac{1}{4}>\frac{3}{4}n\sqrt[3]n.$$
*Probably not an answer.* Using generalized harmonic numbers, you could consider that $$\sum \_{k=1}^n\sqrt[3]{k}=H\_n^{\left(-\frac{1}{3}\right)}$$ and when $n$ is "sufficiently" large, $$H\_n^{\left(-\frac{1}{3}\right)}=\frac{3 }{4}n^{4/3}+\frac{1}{2}n^{1/3}+\zeta \left(-\frac{1}{3}\right)+O\left(\frac{1}{n^{2/3}}\right)$$ making $$\sum \_{k=1}^n\sqrt[3]{k}-\frac{3}{4}n\sqrt[3]{n}=\frac{1}{2}n^{1/3}+\zeta \left(-\frac{1}{3}\right)+O\left(\frac{1}{n^{2/3}}\right)$$ and the result is correct as soon as $n \geq 1$.
66,145,860
I have data with uniquely identified individuals, in groups, which were surveyed multiple times. Sometimes new individuals showed up after the first survey, and I want to find those new individuals by group. E.g., ``` group <- rep(1:2, each=9) surv <- c(1,1,2,2,2,3,3,3,3,1,1,1,2,2,2,2,3,3) ind <- c("a","b","a","b","c","a","b","c","d", "a","b","c", "a", "b","c","d", "a","b") dat <- data.table(surv=surv, group=group, ind=ind) setkey(dat, surv, group) ``` I want a new data table with the new inviduals i.e., ``` survey 2, group 1, "c" survey 2, group 2, "d" survey 3, group 1, "d" ``` I'm flummoxed by this, which the following starter code shows: ``` dat[surv==2, !(ind %in% surv==1), by = group] ```
2021/02/10
[ "https://Stackoverflow.com/questions/66145860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773126/" ]
This is the first survey each individual appeared in each group, ``` dat[order(ind, surv), .SD[1], .(group, ind)][surv != 1] #> group ind surv #> 1: 1 c 2 #> 2: 2 d 2 #> 3: 1 d 3 ``` Note I've excluded the individuals who first appeared in the first survey.
The `duplicated` function lets you know where a value appears first. ``` dat[!duplicated(ind), ] # surv group ind # 1: 1 1 a # 2: 1 1 b # 3: 1 2 c # 4: 2 2 d ```
58,475,748
``` name: test-publish on: [push] jobs: test: strategy: ... steps: ... publish: needs: test if: github.event_name == 'push' && github.ref??? steps: ... # eg: publish package to PyPI ``` What should I put in `jobs.publish.if` in order to check that this commit is new release? Is this okay: `contains(github.ref, '/tags/')`? What will happen if I push code and tag at the same time?
2019/10/20
[ "https://Stackoverflow.com/questions/58475748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6689249/" ]
You could do this to check if the current push event is for a tag starting with `v`. ``` publish: needs: test if: startsWith(github.ref, 'refs/tags/v') ``` As you pointed out though, I don't think you can guarantee that this is a new release. My suggestion would be to use `on: release` instead of `on: push`. This will only trigger on a newly tagged release. See the docs for `on: release` here: <https://docs.github.com/en/actions/reference/events-that-trigger-workflows#release>
An alternative way to use a GitHub Release as a trigger (in case if you want to use tags freely and release specific versions only): ``` on: release: types: [created] jobs: release-job: name: Releasing if: github.event_name == 'release' && github.event.action == 'created' ```
60,337,287
We are deploying Spring Boot app to the Kubernetes. When the firs user requests comes it takes more than 10s to response. Subsequent requests take 200ms. I have created a warmup procedure to run the key services in `@PostConstruct`. I reduces the time to process the first query to 4s. So I wanted to simulate this first call. I know that Kubernetes rediness probe can make a POST request, but I need authorization and other things. Can I make a real HTTP call to the controller from the app itself?
2020/02/21
[ "https://Stackoverflow.com/questions/60337287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/506078/" ]
Sure, you can always make an HTTP client to localhost The solution isnt specific to k8s or Spring or Java, but any web server You could also try making your readiness probe just the tcp port or some internal script
try [RestTemplate](https://howtodoinjava.com/spring-boot2/resttemplate/spring-restful-client-resttemplate-example/) , you can consume any web service
59,642
Suppose $w(t)$ is a white noise with uniform spectral density $N\_0/2$. It is bandpass filtered to get a narrowband white noise $n(t)$ for $f\_c - B\_T/2 \leqslant |f| \leqslant f\_c + B\_T/2$. We write this in polar form by splitting into inphase and quad-phase wrt $2\pi f\_ct$. $n(t) = n\_I \cos(2\pi f\_ct) - n\_Q \sin(2\pi f\_ct)$ such that we get a phase $\phi\_n = \tan^{-1} (n\_Q/n\_I) $. Is this phase uniformly distributed on $[ 0, 2\pi ]$? If yes, why?
2019/07/20
[ "https://dsp.stackexchange.com/questions/59642", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/44018/" ]
...And now for a differing opinion.... The OP's representation of bandpass white noise as $$n(t) = n\_I \cos(2\pi f\_ct) - n\_Q \sin(2\pi f\_ct)\tag{1}$$ is inadequate; because each sample path of this noise process is a *pure sinusoid* of *fixed* frequency $f\_c$ Hz which is not noise-like at all. Why so? Well, a sample path is what one gets when all the random variables are assumed to have taken on appropriate values, and so with $n\_I = \frac{\sqrt{3}}{2}$ and $n\_Q = \frac 12$ (say), we get the sample path $$\frac{\sqrt{3}}{2}\cos(2\pi f\_ct) - \frac 12 \sin(2\pi f\_ct) = \cos\left(2\pi f\_ct+\frac{\pi}{6}\right)$$ which is a pure sinusoid as claimed. A better representation of $n(t)$ is $$n(t) = n\_I(t) \cos(2\pi f\_ct) - n\_Q(t) \sin(2\pi f\_ct)\tag{2}$$ where $\{n\_I(t)\}$ and $\{n\_Q(t)\}$ are *low-pass* *uncorrelated* white noise processes with *identical* power spectral densities that have constant value for $|f| \leq \frac{B\_T}{2}$. Note that a typical sample path from $(2)$ is "sort of" sinusoidal-looking at frequency *approximately* $f\_c$ Hz, but the instantaneous amplitude and instantaneous phase (as well as instantaneous frequency (derivative of instantaneous phase) are "slowly varying" functions of time. Here, "slowly varying" means in comparison to the approximate time period $f\_c^{-1}$ of each cycle of the sinusoid. --- All this is fine and dandy but has *nothing* to do with the question being considered: the distribution of the instantaneous phase $\operatorname{atan2}(n\_Q(t),n\_I(t))$. The WSS theory tells us *nothing* about the *distributions* of the random variables $n\_Q(t)$ and $n\_I(t)$, except, of course, when $n(t)$ is a *Gaussian* process in which case $\{n\_I(t)\}$ and $\{n\_Q(t)\}$ are *independent* Gaussian processes and we know for sure that $\operatorname{atan2}(n\_Q(t),n\_I(t))$ is indeed uniformly distributed on $[0,2\pi)$. *But*, I contend that since we are discussing *white noise* processes, *any* distribution *other* than $\mathcal U(0,2\pi)$ for the phase would mean that the noise exhibits a *preference* for some phases and a dislike for some other phases, and this idea sticks in my craw as being totally unrepresentative of white noise. Indeed, even the answer by @StanleyPawlukiewicz that $\arctan(n\_Q(t)/n\_I(t))$ is uniformly distributed on $[-\pi/2,\pi/2]$ is disturbing because it *suggests* that it might be the case that $n\_I(t)$ is always positive while $n\_Q(t)$ has a more symmetric distribution. We really need $\operatorname{atan2}(n\_Q(t),n\_I(t))$ for defining the phase; $\arctan$ is inadequate for the job. So, there you have it, folks, The phase is uniformly distributed on $[0,2\pi)$ because it offends my sensibilities to have any other distribution for the phase, and that's all there is to it; ymmv.
$$ -\frac{\pi}{2}\le \mathrm{arctan}(x)\le \frac{\pi}{2} \quad x\in (-\infty , \infty) $$ so as asked, no. Perhaps $$ Y(f)=|H(f)|^2 X(f) $$ where $H(f)$ is your narrow band filter, would imply that the random phase of the input $x(t)$ is the same nature at the output.
1,895,769
Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?
2009/12/13
[ "https://Stackoverflow.com/questions/1895769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230582/" ]
The problem assumes that the node to be deleted is known and a pointer to that node is available. In order to delete a node and connect the previous and the next node together, you need to know their pointers. In a doubly-linked list, both pointers are available in the node that is to be deleted. The time complexity is constant in this case, i.e., O(1). Whereas in a singly-linked list, the pointer to the previous node is unknown and can be found only by traversing the list from head until it reaches the node that has a next node pointer to the node that is to be deleted. The time complexity in this case is O(n). In cases where the node to be deleted is known only by value, the list has to be searched and the time complexity becomes O(n) in both singly- and doubly-linked lists.
Suppose there is a linked list from 1 to 10 and you have to delete node 5 whose location is given to you. ``` 1 -> 2 -> 3 -> 4 -> 5-> 6-> 7-> 8 -> 9 -> 10 ``` You will have to connect the next pointer of 4 to 6 in order to delete 5. 1. Doubly Linked list You can use the previous pointer on 5 to go to 4. Then you can do ``` 4->next = 5->next; ``` or ``` Node* temp = givenNode->prev; temp->next = givenNode->next; ``` Time Complexity = O(1) 2. singly Linked List Since you don't have a previous pointer in Singly linked list you cant go backwards so you will have to traverse the list from head ``` Node* temp = head; while(temp->next != givenNode) { temp = temp->next; } temp->next = givenNode->next; ``` Time Complexity = O(N)
1,895,769
Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?
2009/12/13
[ "https://Stackoverflow.com/questions/1895769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230582/" ]
It has to do with the complexity of fixing up the next pointer in the node previous to the one you're deleting.
In LRU cache design, deletion in doubly linked list takes `O(1)` time. LRU cache is implemented with hash map and doubly linked list. In the doubly linked list, we store the values and it hash maps we store the pointers of linked list nodes. [![enter image description here](https://i.stack.imgur.com/QLlpz.png)](https://i.stack.imgur.com/QLlpz.png) In case of a `cache hit`, we have to move the element to the front of the list. If the node is somewhere in the middle of doubly linked list, since we keep the pointers in the hash map and we retrieved in O(1) time, we can delete it by ``` next_temp=retrieved_node.next prev_temp=retrieved_node.prev ``` then set the pointers to None ``` retrieved_node.next=None retrieved_node.prev=None ``` and then you can reconnect the missing parts of the linked list ``` prev_temp.next=next_temp ```
1,895,769
Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?
2009/12/13
[ "https://Stackoverflow.com/questions/1895769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230582/" ]
I don't think Its O(1) unless you know the address of the node whichh has to be deleted ..... Don't you loop to reach the node which has to be deleted from head ???? It is O(1) provided you have the address of the node which has to be deleted because you have it's prev node link and next node link . As you have all the necessary links available just make the "node of interest " out of the list by re arranging the links and then free() it . But in a single linked list you have to traverse from head to get it's previous and next address doesn't matter whether you have the address to f the node to be deleted or the node position ( as in 1st ,2nd ,10th etc.,.) To be deleted .
Suppose there is a linked list from 1 to 10 and you have to delete node 5 whose location is given to you. ``` 1 -> 2 -> 3 -> 4 -> 5-> 6-> 7-> 8 -> 9 -> 10 ``` You will have to connect the next pointer of 4 to 6 in order to delete 5. 1. Doubly Linked list You can use the previous pointer on 5 to go to 4. Then you can do ``` 4->next = 5->next; ``` or ``` Node* temp = givenNode->prev; temp->next = givenNode->next; ``` Time Complexity = O(1) 2. singly Linked List Since you don't have a previous pointer in Singly linked list you cant go backwards so you will have to traverse the list from head ``` Node* temp = head; while(temp->next != givenNode) { temp = temp->next; } temp->next = givenNode->next; ``` Time Complexity = O(N)
1,895,769
Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?
2009/12/13
[ "https://Stackoverflow.com/questions/1895769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230582/" ]
The problem assumes that the node to be deleted is known and a pointer to that node is available. In order to delete a node and connect the previous and the next node together, you need to know their pointers. In a doubly-linked list, both pointers are available in the node that is to be deleted. The time complexity is constant in this case, i.e., O(1). Whereas in a singly-linked list, the pointer to the previous node is unknown and can be found only by traversing the list from head until it reaches the node that has a next node pointer to the node that is to be deleted. The time complexity in this case is O(n). In cases where the node to be deleted is known only by value, the list has to be searched and the time complexity becomes O(n) in both singly- and doubly-linked lists.
Insertion and deletion at a known position is O(1). However, finding that position is O(n), unless it is the head or tail of the list. When we talk about insertion and deletion complexity, we generally assume we already know where that's going to occur.
1,895,769
Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?
2009/12/13
[ "https://Stackoverflow.com/questions/1895769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230582/" ]
Actually deletion in singly linked lists can also be implemented in O(1). Given a singly linked list with the following state: ``` SinglyLinkedList: Node 1 -> Node 2 Node 2 -> Node 3 Node 3 -> Node 4 Node 4 -> None Head = Node 1 ``` We can implement `delete Node 2` in such a way: ``` Node 2 Value <- Node 3 Value Node 2 -> Node 4 ``` Here we replace the value of `Node 2` with the value of its next node (`Node 3`) and set its next value pointer to the next value pointer of `Node 3` (`Node 4`), skipping over the now effectively "duplicate" `Node 3`. Thus no traversal needed.
Unless the element to be deleted is the head(or first) node, we need to traverse to the node before the one to be deleted. Hence, in worst case, i.e., when we need to delete the last node, the pointer has to go all the way to the second last node thereby traversing (n-1) positions, which gives us a time complexity of O(n).
1,895,769
Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?
2009/12/13
[ "https://Stackoverflow.com/questions/1895769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230582/" ]
The problem assumes that the node to be deleted is known and a pointer to that node is available. In order to delete a node and connect the previous and the next node together, you need to know their pointers. In a doubly-linked list, both pointers are available in the node that is to be deleted. The time complexity is constant in this case, i.e., O(1). Whereas in a singly-linked list, the pointer to the previous node is unknown and can be found only by traversing the list from head until it reaches the node that has a next node pointer to the node that is to be deleted. The time complexity in this case is O(n). In cases where the node to be deleted is known only by value, the list has to be searched and the time complexity becomes O(n) in both singly- and doubly-linked lists.
I don't think Its O(1) unless you know the address of the node whichh has to be deleted ..... Don't you loop to reach the node which has to be deleted from head ???? It is O(1) provided you have the address of the node which has to be deleted because you have it's prev node link and next node link . As you have all the necessary links available just make the "node of interest " out of the list by re arranging the links and then free() it . But in a single linked list you have to traverse from head to get it's previous and next address doesn't matter whether you have the address to f the node to be deleted or the node position ( as in 1st ,2nd ,10th etc.,.) To be deleted .
1,895,769
Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?
2009/12/13
[ "https://Stackoverflow.com/questions/1895769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230582/" ]
Insertion and deletion at a known position is O(1). However, finding that position is O(n), unless it is the head or tail of the list. When we talk about insertion and deletion complexity, we generally assume we already know where that's going to occur.
Unless the element to be deleted is the head(or first) node, we need to traverse to the node before the one to be deleted. Hence, in worst case, i.e., when we need to delete the last node, the pointer has to go all the way to the second last node thereby traversing (n-1) positions, which gives us a time complexity of O(n).
1,895,769
Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?
2009/12/13
[ "https://Stackoverflow.com/questions/1895769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230582/" ]
The problem assumes that the node to be deleted is known and a pointer to that node is available. In order to delete a node and connect the previous and the next node together, you need to know their pointers. In a doubly-linked list, both pointers are available in the node that is to be deleted. The time complexity is constant in this case, i.e., O(1). Whereas in a singly-linked list, the pointer to the previous node is unknown and can be found only by traversing the list from head until it reaches the node that has a next node pointer to the node that is to be deleted. The time complexity in this case is O(n). In cases where the node to be deleted is known only by value, the list has to be searched and the time complexity becomes O(n) in both singly- and doubly-linked lists.
It has to do with the complexity of fixing up the next pointer in the node previous to the one you're deleting.
1,895,769
Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?
2009/12/13
[ "https://Stackoverflow.com/questions/1895769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230582/" ]
Because you can't look backwards...
In LRU cache design, deletion in doubly linked list takes `O(1)` time. LRU cache is implemented with hash map and doubly linked list. In the doubly linked list, we store the values and it hash maps we store the pointers of linked list nodes. [![enter image description here](https://i.stack.imgur.com/QLlpz.png)](https://i.stack.imgur.com/QLlpz.png) In case of a `cache hit`, we have to move the element to the front of the list. If the node is somewhere in the middle of doubly linked list, since we keep the pointers in the hash map and we retrieved in O(1) time, we can delete it by ``` next_temp=retrieved_node.next prev_temp=retrieved_node.prev ``` then set the pointers to None ``` retrieved_node.next=None retrieved_node.prev=None ``` and then you can reconnect the missing parts of the linked list ``` prev_temp.next=next_temp ```
1,895,769
Why is the time complexity of node deletion in doubly linked lists (O(1)) faster than node deletion in singly linked lists (O(n))?
2009/12/13
[ "https://Stackoverflow.com/questions/1895769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230582/" ]
The problem assumes that the node to be deleted is known and a pointer to that node is available. In order to delete a node and connect the previous and the next node together, you need to know their pointers. In a doubly-linked list, both pointers are available in the node that is to be deleted. The time complexity is constant in this case, i.e., O(1). Whereas in a singly-linked list, the pointer to the previous node is unknown and can be found only by traversing the list from head until it reaches the node that has a next node pointer to the node that is to be deleted. The time complexity in this case is O(n). In cases where the node to be deleted is known only by value, the list has to be searched and the time complexity becomes O(n) in both singly- and doubly-linked lists.
Because you can't look backwards...
69,758,091
I am trying to write a window popup function, so whenever person types character v in Chrome, it will open popup. The following is not working, I type "v" on keyboard, and no popup window opens. How can I fix this? Using this in F12 Console to write the function. ``` function doc_keyUp(e) { if (e.keyCode == 86) { alert("Test!"); } } ``` Resource Hotkey: <https://keycode.info/>
2021/10/28
[ "https://Stackoverflow.com/questions/69758091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15435022/" ]
Try it: ``` window.addEventListener("keydown", e => { if ( e.keyCode == 86 ) { //window.open("url") } }); ```
Use [keyCode Search](https://keycode.info/) to get correct keyCode [demo page](http://jsfiddle.net/4f3z5dsu/) ``` window.addEventListener("keyup", function(e) { if ( e.keyCode == 86 ) { window.open('http://www.google.com','GoogleWindow', 'width=800, height=600'); } }); ```
35,022,647
I have the following code:- ``` if( $featured_query->have_posts() ): $property_increment = 0; while( $featured_query->have_posts() ) : $featured_query->the_post(); $town = get_field('house_town'); $a = array($town); $b = array_unique($a); sort($b); var_dump($b); $property_increment++; endwhile; ?> <?php endif; wp_reset_query(); ``` `var_dump(b)` shows:- > > array(1) { [0]=> string(10) "Nottingham" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(11) "Mountsorrel" } array(1) { [0]=> string(12) "Loughborough" } array(1) { [0]=> string(12) "Loughborough" } > > > `var_dump($town)` shows:- > > string(10) "Nottingham" string(9) "Leicester" string(9) "Leicester" string(11) "Mountsorrel" string(12) "Loughborough" string(12) "Loughborough" > > > `var_dump($a)` shows:- > > array(1) { [0]=> string(10) "Nottingham" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(11) "Mountsorrel" } array(1) { [0]=> string(12) "Loughborough" } array(1) { [0]=> string(12) "Loughborough" } > > > What I want to do is get the unique vales of `$town` and output them into a select option:- ``` <select> <option value="Leicester">Leicester</option>'; <option value="Loughborough">Loughborough</option>'; <option value="Mountsorrel">Mountsorrel</option>'; </select>'; ``` In alpha as above, any help would be much appreciated.
2016/01/26
[ "https://Stackoverflow.com/questions/35022647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1128694/" ]
Your code isn't working, because `WebView` is strecthing to its parent height when you load and url there, so the `Button` will be out of screen. You just need not to place `Button` under `WebView`, but `WebView` above `Button` using `layout_above` property: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.webviewwithbutton.WebViewWithButton"> <android.support.design.widget.CoordinatorLayout android:layout_above="@+id/button" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="@dimen/app_bar_height" android:fitsSystemWindows="true" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/toolbar_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/AppTheme.PopupOverlay"/> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <android.support.v4.widget.NestedScrollView android:id="@+id/nested_scroll_view" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="wrap_content"/> </android.support.v4.widget.NestedScrollView> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_dialog_email" app:layout_anchor="@id/app_bar" app:layout_anchorGravity="bottom|end"/> </android.support.design.widget.CoordinatorLayout> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_alignParentBottom="true" android:text="test"/> </RelativeLayout> ``` **EDIT:** I've found the way how you can do that - you just need to put your `CoordinatorLayout` and `Button` inside `RelativeLayout`, and make the same thing: place `CoordinatorLayout` above `Button` using `layout_above` property. It should work as expected. Just replace my xml above with yours.
**Try this:** ``` <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.webviewwithbutton.WebViewWithButton"> <android.support.design.widget.AppBarLayout android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true" android:theme="@style/AppTheme"> <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/toolbar_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/AppTheme" /> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> </ScrollView> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_dialog_email" app:layout_anchor="@id/app_bar" app:layout_anchorGravity="bottom|end" /> </android.support.design.widget.CoordinatorLayout> ```
79,291
More or less exactly what it says on the tin: How does the released and upcoming Fantastic Beasts film series, written by JK Rowling, fit into the existing Harry Potter canon? Do they have the same level of authority as the books, the utter lack of authority of the movies, or somewhere in between?
2015/01/15
[ "https://scifi.stackexchange.com/questions/79291", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
There's no "official" canon in Potterverse the way LucasFilm had. So there's no way to answer your question precisely. Having said that, JKR will (at least according to my interpretation of her quotes) be the screenwriter for the films (unlike the original 8 Potter films) - see the bolded text for confirmation, all quotes from [BBC interview/article](http://www.bbc.co.uk/news/entertainment-arts-24067557): > > "It all started when Warner Bros came to me with the suggestion of turning Fantastic Beasts and Where to Find Them into a film," said Rowling. > > > "I thought it was a fun idea, **but the idea of seeing Newt Scamander, the supposed author of Fantastic Beasts, realised by another writer was difficult**. > > > "Having lived for so long in my fictional universe, **I feel very protective of it and I already knew a lot about Newt**. As hard-core Harry Potter fans will know, I liked him so much that I even married his grandson, Rolf, to one of my favourite characters from the Harry Potter series, Luna Lovegood. > > > She went on: "As I considered Warners' proposal, an idea took shape that I couldn't dislodge. **That is how I ended up pitching my own idea for a film to Warner Bros.** > > > As such, * the realistic out of universe canonicity would definitely be **WAY more than original Potter films** (where JKR wasn't a screenwriter), * but personally I would rate it **slightly less than the books' canonicity** because JKR as a screenwriter is under the control/influence of the director/producer of the movies. * Of course, this could all change if JKR officially states some canon rules. --- In addition, as far as in-universe continuity, Rowling said: > > "Although it will be set in the worldwide community of witches and wizards where I was so happy for 17 years, Fantastic Beasts and Where to Find Them is neither a prequel nor a sequel to the Harry Potter series, but an extension of the wizarding world. > > >
According to [this](http://harrypotter.wikia.com/wiki/Fantastic_Beasts_and_Where_to_Find_Them_%28film_trilogy%29) the films will be indeed written by JKR but I doubt they can be written according to the book strictly, as the book is not a story, but rather an documentary or journal of the magical creatures in the Harry Potter world. The movies can indeed be just about the trip of the author but it is likely more action will be needed to make a good movie.
79,291
More or less exactly what it says on the tin: How does the released and upcoming Fantastic Beasts film series, written by JK Rowling, fit into the existing Harry Potter canon? Do they have the same level of authority as the books, the utter lack of authority of the movies, or somewhere in between?
2015/01/15
[ "https://scifi.stackexchange.com/questions/79291", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
Now that we have established that J.K. Rowling will indeed be writing the screenplay to *Fantastic Beasts and Where to Find Them*, I wanted to answer your actual question. According to JKR, *Fantastic Beasts* will not be an extension of the *Harry Potter* universe: > > "Although it will be set in the worldwide community of witches and wizards where I was so happy for seventeen years, ***Fantastic Beasts and Where to Find Them* is neither a prequel nor a sequel to the Harry Potter series, but an extension of the wizarding world.** The laws and customs of the hidden magical society will be familiar to anyone who has read the Harry Potter books or seen the films, but Newt's story will start in New York, seventy years before Harry's gets underway." > > [J.K. Rowling to Write *Harry Potter* Spinoff](http://www.npr.org/blogs/thetwo-way/2013/09/12/221724567/j-k-rowling-to-write-screenplay-for-harry-potter-spinoff) -- NPR -- 9.12.13 > > > So, *Fantastic Beasts* will *not* fit into existing *Harry Potter* canon. Since we haven't seen the movie yet, it's impossible to assess its authenticity in comparison to the *Harry Potter* movies, but I would suggest that perhaps *Fantastic Beasts* might have a higher level of authenticity within the wizarding world's canon (which stands alone from Harry and his story) because it's a stand alone set within the wizarding world. This is just an idea, though, on my part. As a movie, compared to the *Harry Potter* movies, in the same way as I mentioned above, I think *Fantastic Beasts* would have greater authority. One, the author herself is writing the screenplay, and she is very protective of her universe; she's also very exacting. Two, while the *Fantastic Beasts* and *Harry Potter* movies come from the same universe, their stories do not intersect. While the book *Fantastic Beasts and Where to Find Them* is a bestiary, it also has a brief one page bio of Newt Scamander and an introduction that has a good bit of canon information on Magizoology. Whether JKR will use this in her screenplay, I don't know, but should she use her existing canon, and build Newt's story on that canon foundation, it would put *Fantastic Beasts* closer to JKR's personal wizarding canon *as a movie*.
According to [this](http://harrypotter.wikia.com/wiki/Fantastic_Beasts_and_Where_to_Find_Them_%28film_trilogy%29) the films will be indeed written by JKR but I doubt they can be written according to the book strictly, as the book is not a story, but rather an documentary or journal of the magical creatures in the Harry Potter world. The movies can indeed be just about the trip of the author but it is likely more action will be needed to make a good movie.
79,291
More or less exactly what it says on the tin: How does the released and upcoming Fantastic Beasts film series, written by JK Rowling, fit into the existing Harry Potter canon? Do they have the same level of authority as the books, the utter lack of authority of the movies, or somewhere in between?
2015/01/15
[ "https://scifi.stackexchange.com/questions/79291", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
While as the answers have already made clear that the Harry Potter universe has no official canon policy, it is interesting to note that Rowling has said on twitter that these movies are canon. > > **There were obviously some major changes from the HP books to the films... Are we to take everything in these films as canonical?** > > > **J.K. Rowling**: *Yes, because I'm writing them!* > > [Twitter](https://twitter.com/jk_rowling/status/800653857764282368) > > > Of course, Rowling has failed to address why the parts of the movies which aren't from her script should be canon just because she wrote other parts of it.
According to [this](http://harrypotter.wikia.com/wiki/Fantastic_Beasts_and_Where_to_Find_Them_%28film_trilogy%29) the films will be indeed written by JKR but I doubt they can be written according to the book strictly, as the book is not a story, but rather an documentary or journal of the magical creatures in the Harry Potter world. The movies can indeed be just about the trip of the author but it is likely more action will be needed to make a good movie.
79,291
More or less exactly what it says on the tin: How does the released and upcoming Fantastic Beasts film series, written by JK Rowling, fit into the existing Harry Potter canon? Do they have the same level of authority as the books, the utter lack of authority of the movies, or somewhere in between?
2015/01/15
[ "https://scifi.stackexchange.com/questions/79291", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
There's no "official" canon in Potterverse the way LucasFilm had. So there's no way to answer your question precisely. Having said that, JKR will (at least according to my interpretation of her quotes) be the screenwriter for the films (unlike the original 8 Potter films) - see the bolded text for confirmation, all quotes from [BBC interview/article](http://www.bbc.co.uk/news/entertainment-arts-24067557): > > "It all started when Warner Bros came to me with the suggestion of turning Fantastic Beasts and Where to Find Them into a film," said Rowling. > > > "I thought it was a fun idea, **but the idea of seeing Newt Scamander, the supposed author of Fantastic Beasts, realised by another writer was difficult**. > > > "Having lived for so long in my fictional universe, **I feel very protective of it and I already knew a lot about Newt**. As hard-core Harry Potter fans will know, I liked him so much that I even married his grandson, Rolf, to one of my favourite characters from the Harry Potter series, Luna Lovegood. > > > She went on: "As I considered Warners' proposal, an idea took shape that I couldn't dislodge. **That is how I ended up pitching my own idea for a film to Warner Bros.** > > > As such, * the realistic out of universe canonicity would definitely be **WAY more than original Potter films** (where JKR wasn't a screenwriter), * but personally I would rate it **slightly less than the books' canonicity** because JKR as a screenwriter is under the control/influence of the director/producer of the movies. * Of course, this could all change if JKR officially states some canon rules. --- In addition, as far as in-universe continuity, Rowling said: > > "Although it will be set in the worldwide community of witches and wizards where I was so happy for 17 years, Fantastic Beasts and Where to Find Them is neither a prequel nor a sequel to the Harry Potter series, but an extension of the wizarding world. > > >
Now that we have established that J.K. Rowling will indeed be writing the screenplay to *Fantastic Beasts and Where to Find Them*, I wanted to answer your actual question. According to JKR, *Fantastic Beasts* will not be an extension of the *Harry Potter* universe: > > "Although it will be set in the worldwide community of witches and wizards where I was so happy for seventeen years, ***Fantastic Beasts and Where to Find Them* is neither a prequel nor a sequel to the Harry Potter series, but an extension of the wizarding world.** The laws and customs of the hidden magical society will be familiar to anyone who has read the Harry Potter books or seen the films, but Newt's story will start in New York, seventy years before Harry's gets underway." > > [J.K. Rowling to Write *Harry Potter* Spinoff](http://www.npr.org/blogs/thetwo-way/2013/09/12/221724567/j-k-rowling-to-write-screenplay-for-harry-potter-spinoff) -- NPR -- 9.12.13 > > > So, *Fantastic Beasts* will *not* fit into existing *Harry Potter* canon. Since we haven't seen the movie yet, it's impossible to assess its authenticity in comparison to the *Harry Potter* movies, but I would suggest that perhaps *Fantastic Beasts* might have a higher level of authenticity within the wizarding world's canon (which stands alone from Harry and his story) because it's a stand alone set within the wizarding world. This is just an idea, though, on my part. As a movie, compared to the *Harry Potter* movies, in the same way as I mentioned above, I think *Fantastic Beasts* would have greater authority. One, the author herself is writing the screenplay, and she is very protective of her universe; she's also very exacting. Two, while the *Fantastic Beasts* and *Harry Potter* movies come from the same universe, their stories do not intersect. While the book *Fantastic Beasts and Where to Find Them* is a bestiary, it also has a brief one page bio of Newt Scamander and an introduction that has a good bit of canon information on Magizoology. Whether JKR will use this in her screenplay, I don't know, but should she use her existing canon, and build Newt's story on that canon foundation, it would put *Fantastic Beasts* closer to JKR's personal wizarding canon *as a movie*.
79,291
More or less exactly what it says on the tin: How does the released and upcoming Fantastic Beasts film series, written by JK Rowling, fit into the existing Harry Potter canon? Do they have the same level of authority as the books, the utter lack of authority of the movies, or somewhere in between?
2015/01/15
[ "https://scifi.stackexchange.com/questions/79291", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
While as the answers have already made clear that the Harry Potter universe has no official canon policy, it is interesting to note that Rowling has said on twitter that these movies are canon. > > **There were obviously some major changes from the HP books to the films... Are we to take everything in these films as canonical?** > > > **J.K. Rowling**: *Yes, because I'm writing them!* > > [Twitter](https://twitter.com/jk_rowling/status/800653857764282368) > > > Of course, Rowling has failed to address why the parts of the movies which aren't from her script should be canon just because she wrote other parts of it.
Now that we have established that J.K. Rowling will indeed be writing the screenplay to *Fantastic Beasts and Where to Find Them*, I wanted to answer your actual question. According to JKR, *Fantastic Beasts* will not be an extension of the *Harry Potter* universe: > > "Although it will be set in the worldwide community of witches and wizards where I was so happy for seventeen years, ***Fantastic Beasts and Where to Find Them* is neither a prequel nor a sequel to the Harry Potter series, but an extension of the wizarding world.** The laws and customs of the hidden magical society will be familiar to anyone who has read the Harry Potter books or seen the films, but Newt's story will start in New York, seventy years before Harry's gets underway." > > [J.K. Rowling to Write *Harry Potter* Spinoff](http://www.npr.org/blogs/thetwo-way/2013/09/12/221724567/j-k-rowling-to-write-screenplay-for-harry-potter-spinoff) -- NPR -- 9.12.13 > > > So, *Fantastic Beasts* will *not* fit into existing *Harry Potter* canon. Since we haven't seen the movie yet, it's impossible to assess its authenticity in comparison to the *Harry Potter* movies, but I would suggest that perhaps *Fantastic Beasts* might have a higher level of authenticity within the wizarding world's canon (which stands alone from Harry and his story) because it's a stand alone set within the wizarding world. This is just an idea, though, on my part. As a movie, compared to the *Harry Potter* movies, in the same way as I mentioned above, I think *Fantastic Beasts* would have greater authority. One, the author herself is writing the screenplay, and she is very protective of her universe; she's also very exacting. Two, while the *Fantastic Beasts* and *Harry Potter* movies come from the same universe, their stories do not intersect. While the book *Fantastic Beasts and Where to Find Them* is a bestiary, it also has a brief one page bio of Newt Scamander and an introduction that has a good bit of canon information on Magizoology. Whether JKR will use this in her screenplay, I don't know, but should she use her existing canon, and build Newt's story on that canon foundation, it would put *Fantastic Beasts* closer to JKR's personal wizarding canon *as a movie*.
3,893,616
Let $G$ be an Abelian group of order $n$ and for a positive integer $m$ we have that $\text{gcd}(m,n)=1$. Then the function $\Psi:G \to G$ with $g \mapsto g^m$ is an automorphism. --- My try: First I show that the function is homomorphism: Let $g\_1,g\_2 \in G$ and consider $\Psi(g\_1g\_2)=(g\_1g\_2)^m$ and this is true since $G$ is a group,besides it's Abelian and so $\Psi(g\_1g\_2)=g\_1^{m}g\_2^{m}=\Psi(g\_1)\Psi(g\_1)$. The function is clearly surjective. To show that it's injective we need to show $\text{ker}(\Psi)=\left\{e\_G\right\}$, if we assume there exists $e\_G\ne g \in\text{ker}(\Psi)$ then $\Psi(g)=e\_G=g^m$,but I don't know how to continue. Any help is appreciated.
2020/11/04
[ "https://math.stackexchange.com/questions/3893616", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Any $f\colon X\to X$ is bijective if it is surjective/injective when $X$ is finite. In this case, you can also use the following. Since $\gcd(m, n) = 1$ there are integers $r, s$ such that $rm+sn = 1$, so if $g^m = 1$, then $g^{rm+sn} = g^{sn} = 1$ because $|G| = n$, but at the same time $g^{rm+sn} = g^1 = g$, hence $\Psi$ is injective. To obtain surjectivity, observe that by $rm+sn=1$, we have for any $g\in G, (g^r)^m=g$.
A (purely) group-theoretical argument here: Suppose $g^m=e\_G$, then $\text{ord}(g)|m$. By Lagrange's theorem we have $\text{ord}(g)|n$. Therefore $\text{ord}(g)$ is a common divisor of two relatively prime numbers, so $\text{ord(g)}=1$ and $g=e\_G$.
3,893,616
Let $G$ be an Abelian group of order $n$ and for a positive integer $m$ we have that $\text{gcd}(m,n)=1$. Then the function $\Psi:G \to G$ with $g \mapsto g^m$ is an automorphism. --- My try: First I show that the function is homomorphism: Let $g\_1,g\_2 \in G$ and consider $\Psi(g\_1g\_2)=(g\_1g\_2)^m$ and this is true since $G$ is a group,besides it's Abelian and so $\Psi(g\_1g\_2)=g\_1^{m}g\_2^{m}=\Psi(g\_1)\Psi(g\_1)$. The function is clearly surjective. To show that it's injective we need to show $\text{ker}(\Psi)=\left\{e\_G\right\}$, if we assume there exists $e\_G\ne g \in\text{ker}(\Psi)$ then $\Psi(g)=e\_G=g^m$,but I don't know how to continue. Any help is appreciated.
2020/11/04
[ "https://math.stackexchange.com/questions/3893616", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Any $f\colon X\to X$ is bijective if it is surjective/injective when $X$ is finite. In this case, you can also use the following. Since $\gcd(m, n) = 1$ there are integers $r, s$ such that $rm+sn = 1$, so if $g^m = 1$, then $g^{rm+sn} = g^{sn} = 1$ because $|G| = n$, but at the same time $g^{rm+sn} = g^1 = g$, hence $\Psi$ is injective. To obtain surjectivity, observe that by $rm+sn=1$, we have for any $g\in G, (g^r)^m=g$.
To show injectivity, suppose that $g^m = g\_{1}^{m}$. Then $g^mg\_{1}^{-m} = 1 \implies g^mg\_{-1}^m = 1 \implies (gg\_{1}^{-1})^{m}=1$. Since $(m,n)=1, mx+ny=1$ and so $1=(gg\_{1}^{-1})^{m} = (gg\_{1}^{-1})^{1-ny} = gg\_{1}^{-1} \implies g = g\_{1}$ because $|G| = n$.
3,893,616
Let $G$ be an Abelian group of order $n$ and for a positive integer $m$ we have that $\text{gcd}(m,n)=1$. Then the function $\Psi:G \to G$ with $g \mapsto g^m$ is an automorphism. --- My try: First I show that the function is homomorphism: Let $g\_1,g\_2 \in G$ and consider $\Psi(g\_1g\_2)=(g\_1g\_2)^m$ and this is true since $G$ is a group,besides it's Abelian and so $\Psi(g\_1g\_2)=g\_1^{m}g\_2^{m}=\Psi(g\_1)\Psi(g\_1)$. The function is clearly surjective. To show that it's injective we need to show $\text{ker}(\Psi)=\left\{e\_G\right\}$, if we assume there exists $e\_G\ne g \in\text{ker}(\Psi)$ then $\Psi(g)=e\_G=g^m$,but I don't know how to continue. Any help is appreciated.
2020/11/04
[ "https://math.stackexchange.com/questions/3893616", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
A (purely) group-theoretical argument here: Suppose $g^m=e\_G$, then $\text{ord}(g)|m$. By Lagrange's theorem we have $\text{ord}(g)|n$. Therefore $\text{ord}(g)$ is a common divisor of two relatively prime numbers, so $\text{ord(g)}=1$ and $g=e\_G$.
To show injectivity, suppose that $g^m = g\_{1}^{m}$. Then $g^mg\_{1}^{-m} = 1 \implies g^mg\_{-1}^m = 1 \implies (gg\_{1}^{-1})^{m}=1$. Since $(m,n)=1, mx+ny=1$ and so $1=(gg\_{1}^{-1})^{m} = (gg\_{1}^{-1})^{1-ny} = gg\_{1}^{-1} \implies g = g\_{1}$ because $|G| = n$.
50,819
The ISS recently jettison some garbage and expects it to take 2-4 years to de-orbit and burn up. From Gizmodo's [ISS Ditches 2.9-Ton Pallet of Batteries, Creating Its Most Massive Piece of Space Trash](https://gizmodo.com/iss-ditches-2-9-ton-pallet-of-batteries-creating-its-m-1846476992): > > The pallet is packed with nickel-hydrogen batteries, and it will stay in low Earth orbit for the next two to four years “before burning up harmlessly in the atmosphere,” according to a [NASA statement](https://blogs.nasa.gov/spacestation/2021/03/11/worm-observations-eye-checks-as-weekend-spacewalk-approaches/). SpaceFlightNow [reports that](https://spaceflightnow.com/2021/03/12/garbage-pallet-jettisoned-from-space-station-will-stay-in-orbit-two-to-four-years/) the pallet is the “most massive object ever jettisoned from the orbiting outpost.” > > > How come they don't give it a little extra push towards earth and have it de-orbit sooner? Or perhaps they did shove it as hard as they could and this is just how long it takes. It just seems logical that they would want to get it out of the way ASAP.
2021/03/16
[ "https://space.stackexchange.com/questions/50819", "https://space.stackexchange.com", "https://space.stackexchange.com/users/13320/" ]
I assume you refer to the jettison of the garbage pallet containing the old batteries, which came in at about 2.9 tons. Those were jettisoned using the Canadarm2. The Canadarm2 has the following operational limits: **Speed of Operations** * Unloaded: 37 centimeters / second (1.21 feet / second) * Loaded: + Station Assembly - 2 centimeters / second (.79 inches / second) + EVA Support - 15 centimeters / second (5.9 inches / second) + Orbiter - 1.2 centimeters / second (.47 inches / second) (Numbers from [Canadarm2 and the Mobile Servicing Subsystem](https://www.nasa.gov/mission_pages/station/structure/elements/subsystems.html)) I am not exactly sure where on this range the pallet falls - but presumably somewhere between 2cm/s and 15cm/s. The upper limits is 37cm/s. Orbital velocity of the ISS is ~7660m/s. That means the pallet can only get about 0.005% of change of velocity from the arm. Combine this with the fact that the pallet is very dense and has a small-ish cross-sectional area, the ballistic coefficient is rather high, so it doesn't experience much drag (compared to a large, light object). Going by this [Q&A](https://space.stackexchange.com/questions/50717/this-iss-trash-deployment-looks-more-like-2-feet-than-2-inches-per-second-was-i), jettisoning stuff by hand yields velocities of about 0.6m/s, but only for stuff that is significantly lighter than 2.9 *tons*. @Uwe already gave a good comparison with the Shuttle, which needed 90m/s for the re-entry burn. The jettison was done with 0.37m/s. You can not simply "push harder" because of the operational limits of the Canadarm2 and the human body, depending on who does the jettison. And with such a small change in velocity, it takes a while to de-orbit. Which doesn't really matter. Making it de-orbit faster would incurs high costs for no apparent benefit.
The Space shuttle did a deorbit burn for three minutes to decrease the orbital velocity by only 1 %. This delta v was only 90 m/s. But 90 m/s are 324 km/h, much more than a little extra push. A slow walker needs about 10 minutes for one km, 1.67 m/s or 6 km/h. If the gentle push is similar to the slow walkers speed, it is only 1.85 % of the neccessary delta v of 90 m/s. The deorbit burn speed is comparable to a ICE-3 high-speed electric multiple unit train licensed for 330 km/h. Try to imagine an ICE-3 passing by at full speed in a distance of some 20 m. Is this like a gentle push?
50,819
The ISS recently jettison some garbage and expects it to take 2-4 years to de-orbit and burn up. From Gizmodo's [ISS Ditches 2.9-Ton Pallet of Batteries, Creating Its Most Massive Piece of Space Trash](https://gizmodo.com/iss-ditches-2-9-ton-pallet-of-batteries-creating-its-m-1846476992): > > The pallet is packed with nickel-hydrogen batteries, and it will stay in low Earth orbit for the next two to four years “before burning up harmlessly in the atmosphere,” according to a [NASA statement](https://blogs.nasa.gov/spacestation/2021/03/11/worm-observations-eye-checks-as-weekend-spacewalk-approaches/). SpaceFlightNow [reports that](https://spaceflightnow.com/2021/03/12/garbage-pallet-jettisoned-from-space-station-will-stay-in-orbit-two-to-four-years/) the pallet is the “most massive object ever jettisoned from the orbiting outpost.” > > > How come they don't give it a little extra push towards earth and have it de-orbit sooner? Or perhaps they did shove it as hard as they could and this is just how long it takes. It just seems logical that they would want to get it out of the way ASAP.
2021/03/16
[ "https://space.stackexchange.com/questions/50819", "https://space.stackexchange.com", "https://space.stackexchange.com/users/13320/" ]
I assume you refer to the jettison of the garbage pallet containing the old batteries, which came in at about 2.9 tons. Those were jettisoned using the Canadarm2. The Canadarm2 has the following operational limits: **Speed of Operations** * Unloaded: 37 centimeters / second (1.21 feet / second) * Loaded: + Station Assembly - 2 centimeters / second (.79 inches / second) + EVA Support - 15 centimeters / second (5.9 inches / second) + Orbiter - 1.2 centimeters / second (.47 inches / second) (Numbers from [Canadarm2 and the Mobile Servicing Subsystem](https://www.nasa.gov/mission_pages/station/structure/elements/subsystems.html)) I am not exactly sure where on this range the pallet falls - but presumably somewhere between 2cm/s and 15cm/s. The upper limits is 37cm/s. Orbital velocity of the ISS is ~7660m/s. That means the pallet can only get about 0.005% of change of velocity from the arm. Combine this with the fact that the pallet is very dense and has a small-ish cross-sectional area, the ballistic coefficient is rather high, so it doesn't experience much drag (compared to a large, light object). Going by this [Q&A](https://space.stackexchange.com/questions/50717/this-iss-trash-deployment-looks-more-like-2-feet-than-2-inches-per-second-was-i), jettisoning stuff by hand yields velocities of about 0.6m/s, but only for stuff that is significantly lighter than 2.9 *tons*. @Uwe already gave a good comparison with the Shuttle, which needed 90m/s for the re-entry burn. The jettison was done with 0.37m/s. You can not simply "push harder" because of the operational limits of the Canadarm2 and the human body, depending on who does the jettison. And with such a small change in velocity, it takes a while to de-orbit. Which doesn't really matter. Making it de-orbit faster would incurs high costs for no apparent benefit.
There are two main reasons it takes so long: 1. lots of mass and very little delta-v. 2. a large ballistic coefficient. The first is due to the limitation of the deployment mechanism. The second means that the drag takes longer than say a flimsy structure.
40,986,385
I want to make a script, that measures how fast a participant is to press enter or space bar, only when they hear 2/30 sounds from sound files. So some times the user does not have to press anything, and the script still moves on to the next sound file. How do I do this? What I have right now is this: (instead of sound files, I have text atm.): ``` # Grounding of Words Experiment # #Import libraries import re import glob from psychopy import sound, visual, event, data, core, gui # imports a module for visual presentation and one for controlling events like key presses # ID, age, gender box display myDlg = gui.Dlg(title="Experiment") #, pos=(400,400) myDlg.addField('ID:') myDlg.addField('Age:') myDlg.addField('Gender:', choices = ['Female', 'Male']) myDlg.show()#you have to call show() for a Dlg if myDlg.OK: ID = myDlg.data[0] Age = myDlg.data[1] Gender = myDlg.data[2] else: core.quit() trial=0 #Creates the outfile, that will be the file containing our data, the name of the file, as saved on the computer is the filename out_file="Grounding_experiment_results.csv" #Creates the header for the data header="trial,ID,Gender,Age,Word,rt,SpaceKlik\n" #opens the outfile in writemode with open(out_file,"w") as f: f.write(header)#writes the header in the outfile # define window win = visual.Window(fullscr=True) # defines a window using default values (= gray screen, fullscr=False, etc) # Instruction box display def instruct(txt): instructions = visual.TextStim(win, text=txt, height = 0.05) # create an instruction text instructions.draw() # draw the text stimulus in a "hidden screen" so that it is ready to be presented win.flip() # flip the screen to reveal the stimulus event.waitKeys() # wait for any key press instruct(''' Welcome to the experiment! You will be hearing different words. Whenever you hear the word "Klik" and "Kast" please press the left mouse button. Whenever you hear any other word - do nothing. Try to be as fast and accurate as possible. Please put on the headphones. The experiment will take 5 minutes. Press any key to start the experiment''') # Play sound # Function that makes up a trial trial(word): global trial trial += 1 if word in ["Klik", "Press", "Throw"]: condition = "press" else : condition = "no_press" event.clearEvents() for frame in range(90): text = visual.TextStim(win, text=word, height = 0.05) text.draw() # draw the text stimulus in a "hidden screen" so that it is ready to be presented time_start=win.flip() try: key, time_key=event.getKeys(keyList=['space', 'escape'], timeStamped = True)[0] # wait for any key press except IndexError: key = "0" rt = "NA" else: if key=='escape': core.quit() rt = time_key - time_start if key == "space" and condition=="press": accuracy = 1 elif key == "0" and condition=="no_press": accuracy = 1 else: accuracy = 0 with open(out_file,"a") as f: f.write("{},{},{},{},{},{},{},{}\n".format(trial,ID,Gender,Age,word,accuracy,rt,SpaceKlik)) # s = sound.Sound('sound.wav') # s.play() # Register space bar press or mouse click # Measure reaction time # Check to see if answer is correct to sound - certain sound files are "klik". Others "kast", "løb", "sko" and so on # Write csv logfile with coloumns: "ID", "Gender", "Word", "Correct/incorrect", "Reaction time", "Space/click" ``` I will all run in PsychoPy in the end. Thank you in advance for your kind assistance.
2016/12/06
[ "https://Stackoverflow.com/questions/40986385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7254731/" ]
It may seem entirely logical to you, but the compiler has no idea what *order* your conceptual definition of "priority" means regarding your thing called a `Coord`. Your objects being stored in your queue look like this: ``` std::pair<int, Coord> ``` and understanding how `std::priority_queue` compares elements is warranted. The adapter [`std::priority_queue`](http://en.cppreference.com/w/cpp/container/priority_queue) defaults to using [`std::less`](http://en.cppreference.com/w/cpp/utility/functional/less) for the item comparator to determine order. As you have now-discovered, that comparator does little more than manufacture a simple *`a < b`* construct to compare objects for order, and if the object class (or its bases) provide this, great; if not, you need to do so. as it turns out, [`std::pair` *does* provide an `operator <`](http://en.cppreference.com/w/cpp/utility/pair/operator_cmp), which basically establishes strict weak ordering across `first` and `second`. For two pair objects it essentially does this: ``` return lhs.first < rhs.first || (!(rhs.first < lhs.first) && lhs.second < rhs.second); ``` Why is *that* important? Note that `second` usage in the last expression. It's important because the `second` in the above is of *your* type `Coord`, Therefore, `operator <` is being applied to `Coord` and since there is no such operator, compiler = not-happy. As a side-note, you've noticed this *works* out of the box for `std::pair<int, std::pair<int,int>>` because as mentioned earlier, `std::pair` has an operator <`overload, and in that case two different instantiations of`operator <` are manifested. To solve this, you have to provide such an `operator` for your type. There are essentially only two ways to do this: a member function or a free-function either of which define a `operator <` overload for `Coord`. Usually implemented as a member function, but also possible as a free-function, this essentially provides the operator `std::less` is looking for. This is the most common mechanism for providing order (and imho the easiest to understand): ``` // member function struct Coord { int x, y; bool operator <(const Coord& rhs) { return x < rhs.x || (!(rhs.x < x) && y < rhs.y) } }; ``` or ``` // free function bool operator <(const Coord& lhs, const Coord& rhs) { return lhs.x < rhs.x || (!(rhs.x < lhs.x) && lhs.y < rhs.y) } ``` --- **General Comparator Guidelines** Beyond making `std::less<>` happy for a given type by overloading `operator <`, many containers, adapters, and algorithms allow you to provide your own custom comparator type. For example: * `std::map` * `std::set` * `std::sort` * `std::priority_queue` * many others... To that, there are several possible ways to do this. Examples include: * Provide an `operator <` for instances of your `Type` type (easy, example shown prior). This allows the continued default `std::less` to do it's job of firing `operator <` that is provided by you. * Provide a comparator to the container/algorithm that performs the comparison for you (also easy). In essence you're writing a replacement for `std::less` that *you* specify for the container, adapater, or algorithm when declaring or invoking them. * Provide a template specialization of `std::less<Coord>` (moderately easy, but rarely done and less intuitive for beginners). This *replaces* `std::less` with your specialization wherever it would normally be used. Examples of the last two appear below. We'll assume we're just using your `Coord` rather than your `std::pair<int, Coord>`, explained earlier **Provide custom comparator** You don't have to use `std::less` for ordering. You can also provide your own functor that does the same job. The third template parameter to `std::priority_queue` is what you use to provide this: ``` struct CoordLess { bool operator()(Coord const& lhs, Coord const& rhs) const { return lhs.x < rhs.x || (!(rhs.x < lhs.x) && lhs.y < rhs.y) } }; std::priority_queue<Coord, std::vector<Coord>, CoordLess> myqueue; ``` This is handy when you need to implement different orderings on the same object class for different containers. For example, you could have one container that orders small-to-large, another large-to-small. Different comparators allow you to do that. For example, you could create a `std::set` of `Coord` objects with your comparator by doing ``` std::set<Coord, CoordLess> myset; ``` or sort a vector `vec` of `Coord` objects by doing this: ``` std::sort(vec.begin(), vec.end(), CoordLess()); ``` Note in both cases we specify at declaration or invocation the custom comparator. **Provide a `std::less` specialization** This is not as easy to understand, rarely done, but just as easy to implement. Since `std::less` is the default comparator, so long as the type is a custom type (not a native language type or library type) you can provide a `std::less` specialization for `Coord`. This means *everything* that normally uses `std::less<Coord>` for ordering will get this implicitly if the definition below is provided beforehand. ``` namespace std { template<> struct less<Coord> { bool operator ()(Coord const& lhs, Coord const& rhs) const { return lhs.x < rhs.x || (!(rhs.x < lhs.x) && lhs.y < rhs.y) } }; } ``` With that provided (usually immediately after your custom type in the same header), you can simply use default template parameters, whereas before we had to specify them. For example now we can declare a `std::set` like this: ``` std::set<Coord> myset; ``` or perform a sort like this: ``` std::sort(vec.begin(), vec.end()); ``` Both of those default to using `std::less<Coord>` and since we've specialized that ourselves, it uses *ours*. This is a handy, enveloping way of changing default behavior in *many* places, but with great power comes great responsibility, so be careful, and *never* do this with native or library-provided types. Hopefully that give you some ideas on different ways you can solve your error.
You need to define a comparison operation for your `Coord` class. Add a `bool operator<(const Coord &rhs) const;` to your class that will determine which of the two Coords (\*this or rhs) comes first.
589,657
I want to divide the row into the columns, starting a new row each time the `New Data` phrase is found in the file: Input ``` New Data 52.6114082616 41.8319773432 75.6986111112 74.6176129172 New Data 100.0 100.0 100.0 8.00000000003 99.7916666667 42.435664564566 ``` Output ``` 52.6114082616 41.8319773432 75.6986111112 74.6176129172 100.0 100.0 100.0 8.00000000003 99.7916666667 42.435664564566 ``` I have tried with `xargs`: ``` awk '{print$1}' file.txt | xargs -n2 echo ``` but this will not include blank lines, and I want the blank lines as well.
2020/05/29
[ "https://unix.stackexchange.com/questions/589657", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/415180/" ]
Use `awk` to provide alternate separator: ``` awk '/^New Data/ {sep=ORS; next} {printf "%s", sep $0; sep=OFS} END{print ""}' file ``` If the record matches regular expression `^New Data`, `sep` will be changed to `ORS`/newline, otherwise `sep` will be `OFS`/space.
Using perl : ``` $ perl -lne '$\=" ";if (/New Data/){ $\="\n"; s/.*//g; } ;print $_;print "\n" if eof' file 52.6114082616 41.8319773432 75.6986111112 74.6176129172 100.0 100.0 100.0 8.00000000003 99.7916666667 42.435664564566 ```
589,657
I want to divide the row into the columns, starting a new row each time the `New Data` phrase is found in the file: Input ``` New Data 52.6114082616 41.8319773432 75.6986111112 74.6176129172 New Data 100.0 100.0 100.0 8.00000000003 99.7916666667 42.435664564566 ``` Output ``` 52.6114082616 41.8319773432 75.6986111112 74.6176129172 100.0 100.0 100.0 8.00000000003 99.7916666667 42.435664564566 ``` I have tried with `xargs`: ``` awk '{print$1}' file.txt | xargs -n2 echo ``` but this will not include blank lines, and I want the blank lines as well.
2020/05/29
[ "https://unix.stackexchange.com/questions/589657", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/415180/" ]
Use `awk` to provide alternate separator: ``` awk '/^New Data/ {sep=ORS; next} {printf "%s", sep $0; sep=OFS} END{print ""}' file ``` If the record matches regular expression `^New Data`, `sep` will be changed to `ORS`/newline, otherwise `sep` will be `OFS`/space.
POSIX sed. In the sed's pattern space we accumulate all the lines read until we meet the New Data containing line. At which point we Print and Delete the pattern space and go back to the top of sed script for more. The thing to note is that we behead the leading New Data line from the pattern space. The test command t shall keep converting tge newlines to spaces till we meet the next New Data. Then the cycle repeats. ``` sed -e ':a $!N;/^New Data\n/D /\nNew Data$/! s/\n/ /;ta P;D ' file ``` GNU sed: Here we accumulate the non New Data lines in the hold space. Upon encountering the New Data line (drop its first) we fetch what was stored in the hold + null the hold. Then change all newlines to spaces. ``` sed -e ' /^New Data$/!{H;$!d;} 1d;z;x;s/.//;y/\n/ / ' file ``` Perl in the slurrp mode: we read in the whole file into the perl's pattern space $\_. Options: ``` : `-0777` slurps the input intob$_. : `-l` sets ORS = RS = \n : `-a` autosplits the pattern space ibto fields and pytsin @F array. `-n` no print the pattern space by default. : `-F` specifies the field delimiter used to split the pattern space. ``` Special Variables: ``` : `$"` value is space by default. : `$\ ` output record separator newline : `$#F` index of the last element of tge array @F, indices start from zero. perl -F'/^New\hData\n/m' -lan -0777e ' print join $", split $\ for @F[1..$#F]; ' file perl -lne ' push @A, $_ if ! /^New Data$/; print join $", splice @A if eof || // && $.>1; ' file perl -lpe ' ($_, $p, $\) = /New/ ? ($p, undef, defined $p ? $/ : $,) : ! eof ? ($p, $_, defined $p ? $" : $,) : (qq[$p$"$_], "foo", $/) ; ' file ``` Output: ``` 52.6114082616 41.8319773432 75.6986111112 74.6176129172 100.0 100.0 100.0 8.00000000003 99.7916666667 42.435664564566 ```
91,611
Has anyone a good source of **free** information for VFR approach charts in Italy? I know that for major airports (e.g. LIMW), <https://www.enav.it> publishes the charts. However for small airfields (e.g. LIVV), I was not able to find anything. I am looking for something like [this](https://www.sia.aviation-civile.gouv.fr/documents/htmlshow?f=dvd/eAIP_27_JAN_2022/Atlas-VAC/home.htm), from France.
2022/02/03
[ "https://aviation.stackexchange.com/questions/91611", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/31167/" ]
You are right, in Italy, VFR approach charts are published by [ENAV](https://www.enav.it/) for major airports only (you could get them georeferenced for free using [Airmate](https://www.airmate.aero) app). For small airfields and ultralight bases, the main source is [Avioportolano](https://www.avioportolano.it/en/) but it is a commercial source. There is no free information source to the best of my knowledge. In France, the source you quote [SIA Service de l'Information Aéronautique](https://www.sia.aviation-civile.gouv.fr/) is indeed the right one for all airfields having an ICAO code assigned. In addition, you have more than 700 ultralight airfields having numeric codes assigned by the ULM Federation (such LF8357 for Pampelonne). You could find for them free information and charts on [FFPULM BASULM site](https://basulm.ffplum.fr/).
I can recommend two free solutions which are using the official government (ENAV) issued charts: [openaip.net](https://www.openaip.net/map#7.17/45.429/12.388) [openflightmaps.org](https://www.openflightmaps.org/li-italy/?airac=2205&language=local) Openflightmaps is maintained by the [University of Graz](https://en.wikipedia.org/wiki/University_of_Graz): > > The mission of the project is to develop and maintain a universal > database of aeronautical data, in order to facilitate the rendering of > high quality VFR maps to assist the general aviation community. > > > You can generate pdf exports for kneeboard printouts or iPad reference easily: [![enter image description here](https://i.stack.imgur.com/kKhmI.jpg)](https://i.stack.imgur.com/kKhmI.jpg)
44,505,554
Using the command: ``` describe formatted my_table partition my_partition ``` we are able to list the metadata including hdfs location of the partition `my_partition` in `my_table`. But how can we get an output with 2 columns: ``` Partition | Location ``` which would list all the partitions in `my_table` and their hdfs locations?
2017/06/12
[ "https://Stackoverflow.com/questions/44505554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/147530/" ]
Query the metastore. ### Demo **Hive** ``` create table mytable (i int) partitioned by (dt date,type varchar(10)) ; alter table mytable add partition (dt=date '2017-06-10',type='A') partition (dt=date '2017-06-11',type='A') partition (dt=date '2017-06-12',type='A') partition (dt=date '2017-06-10',type='B') partition (dt=date '2017-06-11',type='B') partition (dt=date '2017-06-12',type='B') ; ``` **Metastore** (MySQL) ``` select p.part_name ,s.location from metastore.DBS as d join metastore.TBLS as t on t.db_id = d.db_id join metastore.PARTITIONS as p on p.tbl_id = t.tbl_id join metastore.SDS as s on s.sd_id = p.sd_id where d.name = 'default' and t.tbl_name = 'mytable' ; ``` --- ``` +----------------------+----------------------------------------------------------------------------------+ | part_name | location | +----------------------+----------------------------------------------------------------------------------+ | dt=2017-06-10/type=A | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-10/type=A | | dt=2017-06-11/type=A | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-11/type=A | | dt=2017-06-12/type=A | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-12/type=A | | dt=2017-06-10/type=B | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-10/type=B | | dt=2017-06-11/type=B | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-11/type=B | | dt=2017-06-12/type=B | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-12/type=B | +----------------------+----------------------------------------------------------------------------------+ ```
If it is not necessary to get the information in a nice tabular format - and you do not have access to the HMS database, you may want to run the `explain extended`: ``` explain extended select * from default.mytable; ``` and then you can grep out the essential information, the `partition values` and the `location`. ``` root@ubuntu:/home/sathya# hive -e "explain extended select * from default.mytable;" | grep location OK location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-10/type=A location hdfs://localhost:9000/user/hive/warehouse/mytable location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-10/type=B location hdfs://localhost:9000/user/hive/warehouse/mytable location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-11/type=A location hdfs://localhost:9000/user/hive/warehouse/mytable location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-11/type=B location hdfs://localhost:9000/user/hive/warehouse/mytable location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-12/type=A location hdfs://localhost:9000/user/hive/warehouse/mytable location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-12/type=B location hdfs://localhost:9000/user/hive/warehouse/mytable ```
44,505,554
Using the command: ``` describe formatted my_table partition my_partition ``` we are able to list the metadata including hdfs location of the partition `my_partition` in `my_table`. But how can we get an output with 2 columns: ``` Partition | Location ``` which would list all the partitions in `my_table` and their hdfs locations?
2017/06/12
[ "https://Stackoverflow.com/questions/44505554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/147530/" ]
Query the metastore. ### Demo **Hive** ``` create table mytable (i int) partitioned by (dt date,type varchar(10)) ; alter table mytable add partition (dt=date '2017-06-10',type='A') partition (dt=date '2017-06-11',type='A') partition (dt=date '2017-06-12',type='A') partition (dt=date '2017-06-10',type='B') partition (dt=date '2017-06-11',type='B') partition (dt=date '2017-06-12',type='B') ; ``` **Metastore** (MySQL) ``` select p.part_name ,s.location from metastore.DBS as d join metastore.TBLS as t on t.db_id = d.db_id join metastore.PARTITIONS as p on p.tbl_id = t.tbl_id join metastore.SDS as s on s.sd_id = p.sd_id where d.name = 'default' and t.tbl_name = 'mytable' ; ``` --- ``` +----------------------+----------------------------------------------------------------------------------+ | part_name | location | +----------------------+----------------------------------------------------------------------------------+ | dt=2017-06-10/type=A | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-10/type=A | | dt=2017-06-11/type=A | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-11/type=A | | dt=2017-06-12/type=A | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-12/type=A | | dt=2017-06-10/type=B | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-10/type=B | | dt=2017-06-11/type=B | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-11/type=B | | dt=2017-06-12/type=B | hdfs://quickstart.cloudera:8020/user/hive/warehouse/mytable/dt=2017-06-12/type=B | +----------------------+----------------------------------------------------------------------------------+ ```
The best solution from my point of view is to get this info from Hive Metastore via Thrift protocol. If you write code in python, you can use from [hmsclient](https://pypi.org/project/hmsclient/) library: Hive cli: ```sql hive> create table test_table_with_partitions(f1 string, f2 int) partitioned by (dt string); OK Time taken: 0.127 seconds hive> alter table test_table_with_partitions add partition(dt=20210504) partition(dt=20210505); OK Time taken: 0.152 seconds ``` Python cli: ```py >>> from hmsclient import hmsclient >>> client = hmsclient.HMSClient(host='hive.metastore.location', port=9083) >>> with client as c: ... all_partitions = c.get_partitions(db_name='default', ... tbl_name='test_table_with_partitions', ... max_parts=24 * 365 * 3) ... >>> print([{'dt': part.values[0], 'location': part.sd.location} for part in all_partitions]) [{'dt': '20210504', 'location': 'hdfs://hdfs.master.host:8020/user/hive/warehouse/test_table_with_partitions/dt=20210504'}, {'dt': '20210505', 'location': 'hdfs://hdfs.master.host:8020/user/hive/warehouse/test_table_with_partitions/dt=20210505'}] ``` If you have Airflow installed together with `apache.hive` extra, you create `hmsclient` using data from Airflow Connections quite easy: ```py hive_hook = HiveMetastoreHook() with hive_hook.metastore as hive_client: ... your code goes here ... ```
44,505,554
Using the command: ``` describe formatted my_table partition my_partition ``` we are able to list the metadata including hdfs location of the partition `my_partition` in `my_table`. But how can we get an output with 2 columns: ``` Partition | Location ``` which would list all the partitions in `my_table` and their hdfs locations?
2017/06/12
[ "https://Stackoverflow.com/questions/44505554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/147530/" ]
If it is not necessary to get the information in a nice tabular format - and you do not have access to the HMS database, you may want to run the `explain extended`: ``` explain extended select * from default.mytable; ``` and then you can grep out the essential information, the `partition values` and the `location`. ``` root@ubuntu:/home/sathya# hive -e "explain extended select * from default.mytable;" | grep location OK location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-10/type=A location hdfs://localhost:9000/user/hive/warehouse/mytable location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-10/type=B location hdfs://localhost:9000/user/hive/warehouse/mytable location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-11/type=A location hdfs://localhost:9000/user/hive/warehouse/mytable location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-11/type=B location hdfs://localhost:9000/user/hive/warehouse/mytable location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-12/type=A location hdfs://localhost:9000/user/hive/warehouse/mytable location hdfs://localhost:9000/user/hive/warehouse/mytable/dt=2017-06-12/type=B location hdfs://localhost:9000/user/hive/warehouse/mytable ```
The best solution from my point of view is to get this info from Hive Metastore via Thrift protocol. If you write code in python, you can use from [hmsclient](https://pypi.org/project/hmsclient/) library: Hive cli: ```sql hive> create table test_table_with_partitions(f1 string, f2 int) partitioned by (dt string); OK Time taken: 0.127 seconds hive> alter table test_table_with_partitions add partition(dt=20210504) partition(dt=20210505); OK Time taken: 0.152 seconds ``` Python cli: ```py >>> from hmsclient import hmsclient >>> client = hmsclient.HMSClient(host='hive.metastore.location', port=9083) >>> with client as c: ... all_partitions = c.get_partitions(db_name='default', ... tbl_name='test_table_with_partitions', ... max_parts=24 * 365 * 3) ... >>> print([{'dt': part.values[0], 'location': part.sd.location} for part in all_partitions]) [{'dt': '20210504', 'location': 'hdfs://hdfs.master.host:8020/user/hive/warehouse/test_table_with_partitions/dt=20210504'}, {'dt': '20210505', 'location': 'hdfs://hdfs.master.host:8020/user/hive/warehouse/test_table_with_partitions/dt=20210505'}] ``` If you have Airflow installed together with `apache.hive` extra, you create `hmsclient` using data from Airflow Connections quite easy: ```py hive_hook = HiveMetastoreHook() with hive_hook.metastore as hive_client: ... your code goes here ... ```
42,189,354
ive successfully created a helper and function that display data from a json file in a styled list using handlebars.But im struggling with the view more section of my code.Basically what im trying to achieve is,if user clicks on a list item,handlebars should get the id of that item and display it on a different page.My console correctly displays the correct id for each item clicked on the new page(viewdetail page)but the page only displays the styling but with no content from my json.This is my handlebars code: ``` function getParameterByName(name,url){ 'use strict'; if(!url)url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]"+name+"(=([^&#]*)|&|#|$)"), results = regex.exec(url); if(!results)return null; if(!results[2])return ''; return decodeURIComponent(results[2].replace(/\+/g,"")); } var ourRequest = new XMLHttpRequest(); ourRequest.open('GET', 'jj.json'); ourRequest.onload = function () { if (ourRequest.status >= 200 && ourRequest.status < 400) { var data = JSON.parse(ourRequest.responseText); createHTML(data); } else { console.log("You are connected to the server, but it returned an error."); } }; ourRequest.onerror = function() { console.log("Connection error"); }; ourRequest.send(); function createHTML(myData) { var rawTemplate = document.getElementById("myTemplate").innerHTML; var compiledTemplate = Handlebars.compile(rawTemplate); var myContainer = document.getElementById("this-container"); var ourGeneratedHTML = compiledTemplate(myData); myContainer.innerHTML = ourGeneratedHTML; var characterId = getParameterByName("id"); console.log(characterId); $.ajax("jj.json").done(function(cast){ if ($("body").hasClass("viewdetail")){ ///i cant seem to figure out how to render it here var ourGeneratedHTML = compiledTemplate(myData); myContainer.innerHTML = ourGeneratedHTML; } else var ourGeneratedHTML = compiledTemplate(myData); myContainer.innerHTML = ourGeneratedHTML; { } }); } ``` And my html is as folows:(The viewdetails page) ``` <body class="viewdetail" <div class="page-wrap"> <div id="this-container"></div> </div> <script id="myTemplate" type="text/x-handlebars-template"> <span class="username"><a href="#">{{cname}}</a></span> </script> ``` Ive tried using {{#each}} and {{#each myjsonobject}} but i keep getting the correct id on the detail page,but no data in the styling. What am i doing wrong here,please help :( my detail page is being hrefed from my index page as follows: ``` <a href="detailpage.php?id={{id}}" class="btn btn-primary btn-xs view-detail"><b>View</b></a> ``` And heres a portion of my json data: ``` {"content":[{"id":"60","cname":"Admin","crep":"wew","sub_type":"memember ","token":"887618243","reference":"#5754","company_email":"rereee@gmail.com","company_phone":"234556566","service1":"erty","service2":"vbnmj","service3":"yjyt","service4":"uikjyj","company_website":"www.memeber.com","company_address":null,"company_location":"namibia","company_shortbio":"sasasa","company_longbio":"bvbvbvbvb","logos":"891319.png","logopath":"","imageA":"309129.png","imageB":"898798.jpg","imageC":"452926.jpg","imageD":"326704.jpg","company_facebook":null,"company_twitter":null,"company_linkedin":null,"company_stumbleupon":null,"company_pinterest":null,"company_googleplus":null,"user_backgroundpicture":null,"created_on":"2017-01-20 15:37:02","company_skype":null,"company_youtube":null,"company_vimeo":null,"headerimg":"993621.png","join_date":"2017-01-20 15:37:02.069147":""} ```
2017/02/12
[ "https://Stackoverflow.com/questions/42189354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7441151/" ]
* I learned that all puppetized hosts within a zone were recently configured for an http apt cache proxy. Once the apt cache proxy was removed from the host and the install began to work properly. * The sbt.list was restored to use the https prefix.
Anyone landing here with the 403 occurring 2021 should be aware that bintray has [been removed by JFrog](https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/) the original suppliers of it. This affects sbt which has been until recently distributed through bintray. Confirm by ``` cd /etc/apt/sources.list.d ``` then ``` > grep bintray * sbt.list:deb https://dl.bintray.com/sbt/debian / sbt.list.save:deb https://dl.bintray.com/sbt/debian / ``` if you see bintray in the sbt.list files,do ``` rm sbt.list* ``` and sudo apt update should no longer show 403 It may be an idea to refresh the sbt source at this point, see [here](https://www.scala-sbt.org/download.html).
9,791,192
Recently I was looking at some source code provided by community leaders in their open source implementations. One these projects made use of IOC. Here is sample hypothetical code: ``` public class Class1 { private ISomeInterface _someObject; public Class1(ISomeInterface someObject) { _someObject = someObject; } // some more code and then var someOtherObject = new SomeOtherObject(); } ``` My question is not about what the IOCs are for and how to use them in technical terms but rather what are the guidelines regarding object creation. All that effort and then this line using "new" operator. I don't quite understand. Which object should be created by IOC and for which ones it is permissible to be created via the new operator?
2012/03/20
[ "https://Stackoverflow.com/questions/9791192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/981375/" ]
As a general rule of thumb, if something is providing a *service* which may want to be replaced either for testing or to use a different implementation (e.g. different authentication services) then inject the dependency. If it's something like a collection, or a simple data object which isn't providing behaviour which you'd ever want to vary, then it's fine to instantiate it within the class.
Usually you use `IoC` because: * A dependency that can change in the future * To code against interfaces, not concrete types * To enable mocking these dependencies in Unit Testing scenarios You could avoid using `IoC` in the case where you don't control the dependency, for example an `StringBuilder` is always going to be an `StringBuilder` and have a defined behavior, and you usually don't really need to mock that; while you might want to mock an `HttpRequestBase`, because it's an external dependency on having an internet connection, for example, which is a problem during unit tests (longer execution times, and it's something out of your control). The same happens for database access repositories and so on.
71,737,908
I am trying to characterise my class with init but the website says I have to add the last two lines of code but I don't know what they do? Could someone explain? Code: ``` class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("My awesome name is " + self.name) p1 = Person("bob", 69) p1.myfunc() ```
2022/04/04
[ "https://Stackoverflow.com/questions/71737908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18702372/" ]
It is pretty simple. Let's say you create a string. ``` a = "Hello" ``` This basically creates a new string `object` called `a`. Now you can use a variety of functions like `.isdigit()`, `.isalnum()` etc. These functions are basically the functions of the String `class` and when called, they perform the function in relation to the object they are associated with. So Saying, ``` print(a.isalnum()) ``` Would give `True` as the function is defined to check of the `String object` is alphanumeric. In the same way, ``` p1 = Person("bob", 69) p1.myfunc() ``` First-line creates a new `Person` object with `name='bob'` and `age=69`. The second line then calls the function `myfunc()` in association with the Person `p1` and executes with the attributes of `p1` as its own local variables.
The first chunk of code is defining a class. This says what the class should be called, what attributes it has, and defines its behaviour. ```py class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("My awesome name is " + self.name) ``` Once those lines are run, the *class* exists in your session, but no instances of it do. This creates an instance of the class: ```py p1 = Person("bob", 69) ``` And this line is that instance calling its method `myfunc()`: ```py p1.myfunc() ```