qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
35,296,213 | in Windows 10 app I try to read string from .txt file and set the text to RichEditBox:
Code variant 1:
```
var read = await FileIO.ReadTextAsync(file, Windows.Storage.Streams.UnicodeEncoding.Utf8);
txt.Document.SetText(Windows.UI.Text.TextSetOptions.None, read);
```
Code variant 2:
```
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
ulong size = stream.Size;
using (var inputStream = stream.GetInputStreamAt(0))
{
using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))
{
dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
string text = dataReader.ReadString(numBytesLoaded);
txt.Document.SetText(Windows.UI.Text.TextSetOptions.FormatRtf, text);
}
}
```
On some files I have this error - "No mapping for the Unicode character exists in the target multi-byte code page"
I found one solution:
```
IBuffer buffer = await FileIO.ReadBufferAsync(file);
DataReader reader = DataReader.FromBuffer(buffer);
byte[] fileContent = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(fileContent);
string text = Encoding.UTF8.GetString(fileContent, 0, fileContent.Length);
txt.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);
```
But with this code the text looks like question marks in rhombus.
How I can read and display same text files in normal encoding? | 2016/02/09 | [
"https://Stackoverflow.com/questions/35296213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5235485/"
]
| Solution:
1) I made a port of Mozilla Universal Charset Detector to UWP (added to [Nuget](https://www.nuget.org/packages/UDE.CSharp.UWP/))
```
ICharsetDetector cdet = new CharsetDetector();
cdet.Feed(fileContent, 0, fileContent.Length);
cdet.DataEnd();
```
2) Nuget library [Portable.Text.Encoding](https://www.nuget.org/packages/Portable.Text.Encoding/)
```
if (cdet.Charset != null)
string text = Portable.Text.Encoding.GetEncoding(cdet.Charset).GetString(fileContent, 0, fileContent.Length);
```
That's all. Now unicode ecnodings (include cp1251, cp1252) - works good )) | ```
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/FontFiles/" + fileName));
using (var inputStream = await file.OpenReadAsync())
using (var classicStream = inputStream.AsStreamForRead())
using (var streamReader = new StreamReader(classicStream))
{
while (streamReader.Peek() >= 0)
{
line = streamReader.ReadLine();
}
}
``` |
2,508,327 | **Introduction**
We have an OpenID Provider which we created using the DotNetOpenAuth component. Everything works great when we run the provider on a single node, but when we move the provider to a load balanced cluster where multiple servers are handling requests for each session we get issue with the message signing as the DotNetOpenAuth component seems to be using something unique from each cluster node to create the signature.
**Exception**
```
DotNetOpenAuth.Messaging.Bindings.InvalidSignatureException: Message signature was incorrect.
at DotNetOpenAuth.OpenId.ChannelElements.SigningBindingElement.ProcessIncomingMessage(IProtocolMessage message) in c:\BuildAgent\work\7ab20c0d948e028f\src\DotNetOpenAuth\OpenId\ChannelElements\SigningBindingElement.cs:line 139
at DotNetOpenAuth.Messaging.Channel.ProcessIncomingMessage(IProtocolMessage message) in c:\BuildAgent\work\7ab20c0d948e028f\src\DotNetOpenAuth\Messaging\Channel.cs:line 940
at DotNetOpenAuth.OpenId.ChannelElements.OpenIdChannel.ProcessIncomingMessage(IProtocolMessage message) in c:\BuildAgent\work\7ab20c0d948e028f\src\DotNetOpenAuth\OpenId\ChannelElements\OpenIdChannel.cs:line 172
at DotNetOpenAuth.Messaging.Channel.ReadFromRequest(HttpRequestInfo httpRequest) in c:\BuildAgent\work\7ab20c0d948e028f\src\DotNetOpenAuth\Messaging\Channel.cs:line 378
at DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.GetResponse(HttpRequestInfo httpRequestInfo) in c:\BuildAgent\work\7ab20c0d948e028f\src\DotNetOpenAuth\OpenId\RelyingParty\OpenIdRelyingParty.cs:line 493
```
**Setup**
We have the machine config setup to use the same machine key on all cluster nodes and we have setup an out of process session with SQL Server.
**Question**
How do we configure the key used by DotNetOpenAuth to sign its messages so that the client will trust responses from all servers in the cluster during the same session? | 2010/03/24 | [
"https://Stackoverflow.com/questions/2508327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/295648/"
]
| You must implement `IProviderApplicationStore` and pass an instance of this object to the `OpenIdProvider` instance you create, or set the store type in your web.config file. Your implementation of this interface must provide the access to a database that all servers in your web farm share. | When you create your OpenIdRelyingParty make sure you pass null in the constructor.
This puts your web site into OpenID stateless or 'dumb' mode. It's slightly slower for users to log in (if you even notice) but you avoid having to write an IRelyingPartyApplicationStore to allow DotNetOpenAuth to work across your farm;
```
var openIdRelyingParty = new OpenIdRelyingParty(null);
``` |
3,466,405 | >
> **Theorem.** If $x$ is a cycle of odd length then $x^2$ is also a cycle.
>
>
>
*This is the main idea behind the proof.*
When you look at $(a\_1a\_2a\_3...a\_n)(a\_1a\_2a\_3...a\_n)$, you can see that $a\_1$ goes to $a\_3$, $a\_3$ to $a\_5$, etc... continuing to skip every other element, and because there's an odd number of elements, this skipping goes through every element.
*This is how I began formalizing the previous idea using generators.*
$\langle x \rangle = \mathbb{Z}\_{|x|}$. Because $|x|$ is odd $x^2$ generates $\langle x \rangle$. Therefore...
...but I don't know how to translate the idea of skipping.
1. How do I complete this proof?
2. Which parts of the correct completion corresponds to skipping? | 2019/12/07 | [
"https://math.stackexchange.com/questions/3466405",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/261956/"
]
| Here's the most elementary way I can think of doing this.
If the cycle $x$ has order $n$, then we may think of $x$ as the operation $k\mapsto k+1$ on $\mathbb Z/n\mathbb Z$ (we are considering a faithful, transitive action of the subgroup $\langle x\rangle \subset S\_m$, modelled as $\mathbb Z/n\mathbb Z$ acting on itself by translation). Thus $x^2$ corresponds to the operation $k\mapsto k+2$. In this formulation, $x^2$ is a cycle if and only if the action of $\langle x^2\rangle $ is transitive, meaning that we can get between any two elements of $\mathbb Z/n\mathbb Z$ by repeatedly adding $2$. But this is the same as saying that any $k\in \mathbb Z/n\mathbb Z$ is of the form $k=2l$ for some $l\in \mathbb Z/n\mathbb Z$ (meaning we can get from $0$ to $k$ by adding $2$ a total of $l$ times). In other words, we see that $x^2$ is a cycle $\Longleftrightarrow$ $2$ generates $\mathbb Z/n\mathbb Z$ $\Longleftrightarrow$ $\gcd(2,n)=1$.
More generally, this line of reasoning shows that if $x$ is an $n$-cycle, then $x^k$ is a cycle if and only if $\gcd(k,n)=1$. Or even more generally, if $x$ is an $n$-cycle and $g=\gcd(n,k)$, then $x^k$ is the product of $g$ cycles, eaching having length $n/g$ (this uses something about quotients of cyclic groups).
I would imagine that you can also give an argument using Burnside's lemma. | Let $x$ be a cycle of odd length; say it is an element of $S\_N$ for some $N$, and let $X$ be the support of $x$; that is,
$$ X = \mathrm{supp}(x) = \{i\mid 1\leq i\leq N\text{ and }x(i)\neq i\}$$
the elements of $\{1,\ldots,N\}$ that are "moved" by $x$.
Let $G=\langle x\rangle$. Then $G$ is a group of order the length of $x$, that is, $|G|$ is odd. Also, $G$ acts on $X$, by letting $h\in G$ act as $h\cdot a = h(a)$ (note that $h$ is a permutation of $X$).
The **Orbit-Stabilizer Theorem** says that if $X$ is a set, $G$ is a group acting on $X$, then for every $a\in X$, there is a bijection between the $G$-orbit of $a$ and the cosets of the stabilizer of $a$ in $G$; that is, if we let
$$\begin{align\*}
G\cdot a &= \{ g\cdot a\mid g\in G\}\\
G\_a &= \{g\in G\mid g(a)=a\},
\end{align\*}$$
then
$$|G\cdot a | = [G:G\_a]$$
in the sense of cardinality. The bijection is given by taking a coset $gG\_a$ and sending it to the element $g\cdot a$ of $G\cdot a$. It is not hard to verify this is well defined and gives the desired bijection.
Note that for $G$, we have that $G\cdot a = X$ for all $a\in X$, since $x$ is a cycle. So $[G:G\_a] = |X| = |G|$ for all $a\in X$.
Now let $a\in X$, and we want to verify that the orbit of $a$ under $\langle x^2\rangle$ is all of $X$. Because $x$ has odd length, $|x|$ is odd, so $|x^2| = |x|/\gcd(2,|x|) = |x|$, hence $\langle x^2\rangle = \langle x\rangle= G$; so we have:
$$|X|=[G:G\_a] = [\langle x^2\rangle:\langle x^2\rangle\_a] = \langle x^2\rangle\cdot a \leq |X|.$$
Thus, we have equality throughout, and in particular $\langle x^2\rangle\cdot a = X$. That is, the orbit of $a$ is all of $X$, so the action of $x^2$ is a cycle. |
133,165 | In a cross-genre game, is there a spell/power that a mage can use to heal a vampire?
I’ve looked through the mage spells in Death and Life but neither show how a vampire can be healed. | 2018/10/08 | [
"https://rpg.stackexchange.com/questions/133165",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/38724/"
]
| **Temporal Summoning**
At the page 190 of Mage the Awakened's second edition there is a spell called Temporal Summoning. The spell description reads
>
> Return the subject to an younger version of itself. Buildings can be restored and injuries healed. Once the spell ends any changed made revert back to normal. Any injuries and Conditions obtained while this spell was active carry over to the subjects present self. Limits of Spell includes not being able to bring the dead back and a vampire returned to 'Childhood' becomes a vampiric child
>
>
>
Other than this there is also a spell called Shared Fate at Page 137 which reads
>
> Two or more subjects are bound together. Any damage, Tilt or Condition suffered by one will also affect the other
> +1 Reach: Link is only one way
> +2 Reach: Subject is not linked to any other subjects. Instead, she suffers any damage, Tilt or Condition she inflicts on others
>
>
>
If you were to connect yourself to a vampire and gain a condition that heals you then by extension the vampire would be healed. | Apart from the two rotes above you always have
Creative Taumaturgy
-------------------
>
> Within the bounds of their power, mages can conjure nearly any effect they can imagine. (MtA2 p125)
>
>
>
The practice for healing is **Perfecting**
>
> Perfecting spells are the opposite of Fraying spells in many
> ways: they bolster, strengthen, and improve rather than
> weakening and eroding. A Perfecting spell might repair
> damage to an object or a person (Matter or Life)... (MtA2 p123)
>
>
>
Now you have the opportunity of turning this into a
Mystery
-------
>
> Any magical puzzle, any lingering spell, any otherworldly
> enigma is potentially a Mystery. The Storyteller decides on the
> particulars of the Mystery, which break down into three parts:
> Opacity, surface information, and deep information. (MtA2 p93)
>
>
>
The Mage could Scrutinize the Mystery of the vampiric condition to design the imago to heal a vampire.
In my games the spell required Arcana imho would be Matter 3 (to repair the structure of the corpse) and Death 2 (to redirect the flow of death that powers it).
But you could argue that a different combination makes more sense (Life instead of Death, or even Prime), perhaps depending on the nature of the damage, or depending on how well the Mage unveils the Mystery, or depending on what suits your game better. |
22,708,819 | On <http://internet.org> there is an image of a world map showing internet access across the world.
I like this image and want to get it. I cannot use take a screenshot because there is text in the way. I can't find any tags. How do I obtain the image? | 2014/03/28 | [
"https://Stackoverflow.com/questions/22708819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3324865/"
]
| If you have developer tools on your browser, you can right click and then `inspect element`.
It will come up with something like this (assuming you're using chrome).

Here is Firefox's dev tools:

On the right, you can see there are CSS properties. Under `background-image:` you see there is a `url` and then a link to a photo.
That photo is the world map.
Here is the image link: [Here](https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/851586_236045159890577_1605622836_n.jpg) | Maybe it's called in the CSS as a `background-image:url('?');` ? So look for `background-image` in the site's CSS. |
50,494,714 | Below is a code to merge multiple workbooks into a single workbook. However, the files that are being extracted from the local folder comes up incomplete once the process is done. My guess is the workbooks/files in that local folder far exceeds the range that's in the code.
How do I extend the range, preferably "unlimited" or to the maximum limit of excel to transfer and combine the workbooks as much as possible?
Below is the code that I use.
Please advise and our help is much appreciated.
Vincent
```
Sub Merger()
Dim bookList As Workbook
Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
Application.ScreenUpdating = False
Set mergeObj = CreateObject("Scripting.FileSystemObject")
Set dirObj = mergeObj.Getfolder("C:\Users\Vincent\Desktop\856")
Set filesObj = dirObj.Files
For Each everyObj In filesObj
Set bookList = Workbooks.Open(everyObj)
Range("A2:IV" & Range("A65536").End(xlUp).Row).Copy
ThisWorkbook.Worksheets(1).Activate
Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
Application.CutCopyMode = False
bookList.Close
Application.DisplayAlerts = False
Next
End Sub
``` | 2018/05/23 | [
"https://Stackoverflow.com/questions/50494714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7704959/"
]
| Mixing the code for your gradle plugin with the project code the plugin is supposed to help build is probably a bad idea.
You should check out the gradle documentation on [organizing your build logic](https://docs.gradle.org/current/userguide/organizing_build_logic.html) and specifically I would have probably started by sticking your plugin source in the [buildSrc directory](https://docs.gradle.org/current/userguide/organizing_build_logic.html#sec:build_sources).
If you put your plugin source in a directory called `buildSrc` as per the documentation above, it will be automatically compiled and included in your build classpath. It will also not be deleted when you clean your project. All you really need is the `apply plugin: x` statement.
It should be noted that even though `buildSrc` is convenient, it is still there for the development phase of your plugin. If you intend to use the plugin more often, in more places, or otherwise share it, it is probably good to actually build a jar with the plugin. | It is an old question , but for the new visitors: you can build the plugin code while you build the code. there can be even a parent project that build all the plugins.
please check [this answer](https://stackoverflow.com/questions/35302414/adding-local-plugin-to-a-gradle-project) |
6,335,335 | I currently have the following MySQL query, which executes fine without any errors:
```
SELECT topic_id,
topic_title,
topic_author,
topic_type
FROM forum_topics
WHERE ( ( ( forum_id = '2' )
OR ( forum_id != '4'
AND topic_type = 2 ) )
AND deleted = 0 )
ORDER BY topic_id DESC
```
However it's not doing what I intend it too, I want it to return all the results of topics WHERE the forum\_id is 2 and deleted equals 0 aswell as return the results of topics where the forum\_id does not equal 4 and the topic\_type is 2 and deleted equals 0 (if they exist).
But currently its just doing the first just returning results of topics WHERE the forum\_id is 2 and deleted equals 0 and not the other (even though they exist! :/).
I believe I'm doing something wrong...
All help is greatly appreciated. | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/717768/"
]
| To make it simpler for yourself, put the consistent part of your query (deleted=0) first:
```
SELECT
topic_id,
topic_title,
topic_author,
topic_type
FROM forum_topics
WHERE deleted = 0 AND
( ( forum_id = '2' )
OR ( forum_id != '4'
AND topic_type = 2 ) )
ORDER BY topic_id DESC
```
Other than that your query looks right, I would try using an IN statement if you cant get it to work. | Try this:
```
SELECT topic_id, topic_title, topic_author, topic_type
FROM forum_topics
WHERE forum_id = 2
OR (forum_id != 4 AND topic_type = 2)
AND deleted = 0
ORDER BY topic_id DESC
``` |
6,335,335 | I currently have the following MySQL query, which executes fine without any errors:
```
SELECT topic_id,
topic_title,
topic_author,
topic_type
FROM forum_topics
WHERE ( ( ( forum_id = '2' )
OR ( forum_id != '4'
AND topic_type = 2 ) )
AND deleted = 0 )
ORDER BY topic_id DESC
```
However it's not doing what I intend it too, I want it to return all the results of topics WHERE the forum\_id is 2 and deleted equals 0 aswell as return the results of topics where the forum\_id does not equal 4 and the topic\_type is 2 and deleted equals 0 (if they exist).
But currently its just doing the first just returning results of topics WHERE the forum\_id is 2 and deleted equals 0 and not the other (even though they exist! :/).
I believe I'm doing something wrong...
All help is greatly appreciated. | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/717768/"
]
| I think your where clause would be something like this:
```
WHERE ( (forum_id = '2' AND deleted = 0)
OR
(forum_id != '4' AND topic_type = '2' AND deleted = 0)
)
``` | To make it simpler for yourself, put the consistent part of your query (deleted=0) first:
```
SELECT
topic_id,
topic_title,
topic_author,
topic_type
FROM forum_topics
WHERE deleted = 0 AND
( ( forum_id = '2' )
OR ( forum_id != '4'
AND topic_type = 2 ) )
ORDER BY topic_id DESC
```
Other than that your query looks right, I would try using an IN statement if you cant get it to work. |
6,335,335 | I currently have the following MySQL query, which executes fine without any errors:
```
SELECT topic_id,
topic_title,
topic_author,
topic_type
FROM forum_topics
WHERE ( ( ( forum_id = '2' )
OR ( forum_id != '4'
AND topic_type = 2 ) )
AND deleted = 0 )
ORDER BY topic_id DESC
```
However it's not doing what I intend it too, I want it to return all the results of topics WHERE the forum\_id is 2 and deleted equals 0 aswell as return the results of topics where the forum\_id does not equal 4 and the topic\_type is 2 and deleted equals 0 (if they exist).
But currently its just doing the first just returning results of topics WHERE the forum\_id is 2 and deleted equals 0 and not the other (even though they exist! :/).
I believe I'm doing something wrong...
All help is greatly appreciated. | 2011/06/13 | [
"https://Stackoverflow.com/questions/6335335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/717768/"
]
| I think your where clause would be something like this:
```
WHERE ( (forum_id = '2' AND deleted = 0)
OR
(forum_id != '4' AND topic_type = '2' AND deleted = 0)
)
``` | Try this:
```
SELECT topic_id, topic_title, topic_author, topic_type
FROM forum_topics
WHERE forum_id = 2
OR (forum_id != 4 AND topic_type = 2)
AND deleted = 0
ORDER BY topic_id DESC
``` |
3,087,992 | How do you find the number of floors,in a tetraphobic numbering system like 1,2,3,5,6,7,..,12,13,15..,39,50.
I am trying to find the pattern and the mathematical algorithm to solve for floor numbered n.
for eg
n = 3 : ans = 3
n = 8 : ans = 7
n = 22 : ans = 20
Note: This is not a HW problem , I read about it and tried to solve it as fun, I am stuck so I am asking here | 2019/01/26 | [
"https://math.stackexchange.com/questions/3087992",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/589436/"
]
| Let $\pi$ be a uniformizer of $A$. Suppose $\phi(X\_{i}) = u/\pi^{m}$ for some $u \in A^{\times}$ and $m \ge 0$. Then $\pi^{m}X\_{i}-u$ is a unit of $A[[X\_{1},\dotsc,X\_{n}]]$ that gets mapped to $0$ in $K$, contradiction. | This is true. More generally, for any finite extension $K^\prime$ of $K$, any $A$-algebra map $A[[X\_1,\ldots,X\_n]]\to K^\prime$ has image in the valuation ring $A^\prime$ of $K^\prime$, and the induced map $A[[X\_1,\ldots,X\_n]]\to A^\prime$ is local (i.e., the $X\_i$ are sent to elements of the maximal ideal of $A^\prime$).
To prove this, first note that $A$-algebra maps $A[[X\_1,\ldots,X\_n]]\to K^\prime$ are in natural bijection with $A^\prime$-algebra maps
$$A^\prime[[X\_1,\ldots,X\_n]]=A^\prime\otimes\_AA[[X\_1,\ldots,X\_n]]\to K^\prime,$$
where the first identification is valid because $A^\prime$ is a finite free $A$-module (the analogous identity with $K^\prime$ in place of $A^\prime$ is not valid for $n\geq 1$). So we may assume $K=K^\prime$ (hence also $A=A^\prime$), and consider an $A$-algebra map $A[[X\_1,\ldots,X\_n]]\to K$. If we can show that this map necessarily sends each $X\_i$ to an element in the maximal ideal $\mathfrak{m}$ of $A$, then completeness of $A$ can be used to deduce that the image of the map is contained in $A$, so it is enough to verify the former claim. Moreover, this claim holds if and only if the analogous claim holds for the $n$ compositions
$$A[[X\_i]]\hookrightarrow A[[X\_1,\ldots,X\_n]]\to K,$$
(here $1\leq i\leq n$). Thus we may also assume that $n=1$, in which case we can apply the structure theory of the $2$-dimensional regular local ring $A[[X\_1]]$ (especially the Weierstrass Preparation Theorem). The kernel of $A[[X\_1]]\to K$ must be nonzero because $K\otimes\_AA[[X\_1]]$ is an infinite-dimensional $K$-vector space. Therefore the kernel contains a height one prime ideal, and any such ideal is generated by a "distinguished polynomial" $f\in A[X\_1]$ (this is a monic polynomial of positive degree whose lower-degree coefficients lie in $\mathfrak{m}$). The division algorithm for $A[[X\_1]]$ shows that for such an $f$, the natural map $A[X\_1]/(f)\hookrightarrow A[[X\_1]]/(f)$ is an isomorphism, so the map in question can be thought of as an $A$-algebra map $A[X\_1]/(f)\to K$. Thus the image $a\_1$ of $X\_1$ in $K$ is a root of $f$. Because $f$ is monic and $A$ is integrally closed, we must have $a\_1\in A$, and since the lower-degree coefficients of $f$ are in $\mathfrak{m}$, we may conclude that $a\_1$ is as well. |
68,515,268 | I'm currently building a recommender system using Goodreads data.
I want to change string user ids into integers.
Current user ids are like this: `'0d688fe079530ee1fe6fa85eab10ec5c'`
I want to change it into integers(e.g. `1`, `2`, `3`, ...), to have the same integer ids which share the same string ids. I've considered using function `df.groupby('user_id')`, but I couldn't figure out how to do this.
I would be very thankful if anybody let me know how to change.
 | 2021/07/25 | [
"https://Stackoverflow.com/questions/68515268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16473029/"
]
| Use `pd.factorize` as suggested by @AsishM.
Input data:
```
user_id book_id ratings
0 831a1e2505e44a2f81e670db82c9a3c0 1942 3
1 58d3869488a648aebef32b6c2ec4fb16 3116 5
2 f05ad4c0978c4d0eb3ca41921f7a80af 3558 4
3 511c8f47d75c427eae8bead7ff80307b 2467 3
4 db74d6df03644e61b4cd830db35de6a8 2318 2
5 58d3869488a648aebef32b6c2ec4fb16 5882 4
6 db74d6df03644e61b4cd830db35de6a8 6318 5
```
```
df['uid'] = pd.factorize(df['user_id'])[0]
```
Output result:
```
user_id book_id ratings uid
0 831a1e2505e44a2f81e670db82c9a3c0 1942 3 0
1 58d3869488a648aebef32b6c2ec4fb16 3116 5 1 # user 1
2 f05ad4c0978c4d0eb3ca41921f7a80af 3558 4 2
3 511c8f47d75c427eae8bead7ff80307b 2467 3 3
4 db74d6df03644e61b4cd830db35de6a8 2318 2 4 # user 4
5 58d3869488a648aebef32b6c2ec4fb16 5882 4 1 # user 1
6 db74d6df03644e61b4cd830db35de6a8 6318 5 4 # user 4
``` | The `groupby` option would be [`groupby ngroup`](https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.ngroup.html#pandas-core-groupby-groupby-ngroup):
```
df['uid'] = df.groupby('user_id', sort=False).ngroup()
```
```
user_id book_id ratings uid
0 831a1e2505e44a2f81e670db82c9a3c0 1942 3 0
1 58d3869488a648aebef32b6c2ec4fb16 3116 5 1
2 f05ad4c0978c4d0eb3ca41921f7a80af 3558 4 2
3 511c8f47d75c427eae8bead7ff80307b 2467 3 3
4 db74d6df03644e61b4cd830db35de6a8 2318 2 4
5 58d3869488a648aebef32b6c2ec4fb16 5882 4 1
6 db74d6df03644e61b4cd830db35de6a8 6318 5 4
```
\*`sort=False` so `user_id` are grouped in the order they appear in the DataFrame.
---
DataFrame:
```
import pandas as pd
df = pd.DataFrame({
'user_id': ['831a1e2505e44a2f81e670db82c9a3c0',
'58d3869488a648aebef32b6c2ec4fb16',
'f05ad4c0978c4d0eb3ca41921f7a80af',
'511c8f47d75c427eae8bead7ff80307b',
'db74d6df03644e61b4cd830db35de6a8',
'58d3869488a648aebef32b6c2ec4fb16',
'db74d6df03644e61b4cd830db35de6a8'],
'book_id': [1942, 3116, 3558, 2467, 2318, 5882, 6318],
'ratings': [3, 5, 4, 3, 2, 4, 5]
})
``` |
55,223,983 | My application becomes slow because I make too many calls to the API to retrieve information. I would like to create a large object with all the information shared with all the pages and get them from localStorage so that the application is more fluid. I work in Angular 7 with Ionic 4. thank you in advance. | 2019/03/18 | [
"https://Stackoverflow.com/questions/55223983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11208846/"
]
| use **`@media`** rule to specify any style change for mobile windows or larger windows,here the **`max-width`** property is specifies the maximum width of your mobile window.use overflow-y to provide scroll across y-axis
```
@media screen and (max-width: 480px) {
body{
overflow-y : scroll;
}
}
``` | Use media queries, specify on what size you want it to be scrollable and thats it!! You can get some help to use media queries from here:
<https://www.w3schools.com/css/css3_mediaqueries_ex.asp> |
48,864,639 | I would like to merge date & time. I have used 'CONCAT' function & also '||' function. But both of functions taking more times and very slow for query. Can somebody tell me how i can reduce the query time? & What function can be used to merge the date & time? Thanks for any help.
```
where CONCAT (TO_CHAR (Date, 'YYYYMMDD'), LPAD (Time, 6, 0))
between CONCAT ('20180215', '130528') AND CONCAT ('20180215', '133003')
``` | 2018/02/19 | [
"https://Stackoverflow.com/questions/48864639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8422152/"
]
| You do not need to convert your date to a string - just convert your static values to a date:
```
WHERE "Date" BETWEEN TO_DATE( '20180215130528', 'YYYYMMDDHH24MISS' )
AND TO_DATE( '20180215133003', 'YYYYMMDDHH24MISS' )
```
If you want to use `CONCAT` then:
```
WHERE "Date" BETWEEN TO_DATE( CONCAT( '20180215', '130528' ), 'YYYYMMDDHH24MISS' )
AND TO_DATE( CONCAT( '20180215', '133003' ), 'YYYYMMDDHH24MISS' )
```
You could also use a `TIMESTAMP` literal:
```
WHERE "Date" BETWEEN TIMESTAMP '2018-02-15 13:05:28'
AND TIMESTAMP '2018-02-15 13:30:03'
``` | You want to have an index on Date to speed up the query.
And better yet would be to have Date and Time combined into a single field Date, with type Date (and have index on Date).
This would give you a simple performant query:
```
WHERE Date between to_date('20180215' || '130528', 'YYYYMMDDHH24MISS') and to_date('20180215'||'133003', 'YYYYMMDDHH24MISS')
```
For your current scheme, you will get better performance structuring WHERE like this:
```
where Date between to_date('20180215', 'YYYYMMDD') and to_date('20180215', 'YYYYMMDD') and Date || LPAD (Time, 6, 0)) between CONCAT ('20180215', '130528') AND CONCAT ('20180215', '133003')
``` |
13,604,290 | I'm just curious as to to how to implement multi-threading without using a Windows API WaitFor\* function that stops the program until the thread has returned. What's the point of using threads if they stop the main application from being resized or moved etc.?
Is there any form of windows messaging with threading, which will allow me to call my thread function and then return, and handle the return values of the thread when it finishes running? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13604290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853098/"
]
| You can use `MsgWaitForMultipleObjectsEx` to wait for the thread to finish and also process messages at the same time. | Have a look at std::thread, boost::thread, just::thread, for multithreading in general for c++.
But about Windows messaging win32 and MFC, the MSDN states **explicitely** that **it is not multithread, it is monothread**. ( Undefined behaviour is to be expected if multithreading is used)
For asynchronous message emited in other thread than the main application window thread, you should use ::PostMessage(), that will insert message events in the monothread message pump of the mono threaded window. |
13,604,290 | I'm just curious as to to how to implement multi-threading without using a Windows API WaitFor\* function that stops the program until the thread has returned. What's the point of using threads if they stop the main application from being resized or moved etc.?
Is there any form of windows messaging with threading, which will allow me to call my thread function and then return, and handle the return values of the thread when it finishes running? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13604290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853098/"
]
| If you want your UI thread to know when a task thread has finished it's task then you could have your task thread post a (custom - WM\_USER and above) message to your main window (along with thread id plus the handle). And the window proc of the main window can know that a particular task thread has finished it's task. This way the UI thread does not have to wait actively (using WaitFor\*) on the thread(s) object. | Have a look at std::thread, boost::thread, just::thread, for multithreading in general for c++.
But about Windows messaging win32 and MFC, the MSDN states **explicitely** that **it is not multithread, it is monothread**. ( Undefined behaviour is to be expected if multithreading is used)
For asynchronous message emited in other thread than the main application window thread, you should use ::PostMessage(), that will insert message events in the monothread message pump of the mono threaded window. |
13,604,290 | I'm just curious as to to how to implement multi-threading without using a Windows API WaitFor\* function that stops the program until the thread has returned. What's the point of using threads if they stop the main application from being resized or moved etc.?
Is there any form of windows messaging with threading, which will allow me to call my thread function and then return, and handle the return values of the thread when it finishes running? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13604290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853098/"
]
| You can use `MsgWaitForMultipleObjectsEx` to wait for the thread to finish and also process messages at the same time. | [`WaitForSingleObject`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms687032%28v=vs.85%29.aspx) can be non-blocking, just pass zero timeout as second parameter:
```
// Check is thread has been finished
if(::WaitForSingleObject(threadHandle, 0) == WAIT_OBJECT_0)
{
// Process results
...
}
```
You will need to periodically check this condition, e.g. on timer or after processing any message in message loop.
Or you can use [`MsgWaitForMultipleObjectsEx`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms684245%28v=vs.85%29.aspx). It will unblock and return when some message/input event occured in calling thread message queue.
As other answers mentioned there is another way - using Windows asynchronously posted message to signal that thread has done its work. This way has disadvantage - the working thread must know target window or thread to post message to. This dependency complicates design and raises issues about checking thread/window lifetime. To avoid it message broadcasting (`PostMessage(HWND_BROADCAST,...)`)
can be used, but this is overkill for your case, I don't recommend it. |
13,604,290 | I'm just curious as to to how to implement multi-threading without using a Windows API WaitFor\* function that stops the program until the thread has returned. What's the point of using threads if they stop the main application from being resized or moved etc.?
Is there any form of windows messaging with threading, which will allow me to call my thread function and then return, and handle the return values of the thread when it finishes running? | 2012/11/28 | [
"https://Stackoverflow.com/questions/13604290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853098/"
]
| If you want your UI thread to know when a task thread has finished it's task then you could have your task thread post a (custom - WM\_USER and above) message to your main window (along with thread id plus the handle). And the window proc of the main window can know that a particular task thread has finished it's task. This way the UI thread does not have to wait actively (using WaitFor\*) on the thread(s) object. | [`WaitForSingleObject`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms687032%28v=vs.85%29.aspx) can be non-blocking, just pass zero timeout as second parameter:
```
// Check is thread has been finished
if(::WaitForSingleObject(threadHandle, 0) == WAIT_OBJECT_0)
{
// Process results
...
}
```
You will need to periodically check this condition, e.g. on timer or after processing any message in message loop.
Or you can use [`MsgWaitForMultipleObjectsEx`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms684245%28v=vs.85%29.aspx). It will unblock and return when some message/input event occured in calling thread message queue.
As other answers mentioned there is another way - using Windows asynchronously posted message to signal that thread has done its work. This way has disadvantage - the working thread must know target window or thread to post message to. This dependency complicates design and raises issues about checking thread/window lifetime. To avoid it message broadcasting (`PostMessage(HWND_BROADCAST,...)`)
can be used, but this is overkill for your case, I don't recommend it. |
32,075,273 | I'm multiplexing 3 IMU-6050 using a MUX4051. This is the original code:
```
#include "Wire.h"
const int MPU=0x68; // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
int Acc_ctrl_1 = 9;
int Acc_ctrl_2 = 10;
int Acc_ctrl_3 = 11;
int chip_enable1 = 5;
void setup() {
Wire.begin(); // wake up I2C bus
// set I/O pins to outputs
Wire.beginTransmission(MPU);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(115200);
pinMode(Acc_ctrl_1, OUTPUT); //S0
pinMode(Acc_ctrl_2, OUTPUT); //S1
pinMode(Acc_ctrl_3, OUTPUT); //S2 address lines
pinMode(chip_enable1, OUTPUT);
//S0=1, S1=2 and S2=4 so Y0= S0=0,S1=0,S2=0, Y4=S0=0,S1=0,S2=1
}
void loop() {
//Enable the MUX Chip 1 - Active Low
digitalWrite(chip_enable1, LOW);
// control signal for First Accelerometer
Serial.println("IMU 1");
digitalWrite(Acc_ctrl_1, LOW);
digitalWrite(Acc_ctrl_2, LOW);
digitalWrite(Acc_ctrl_3, LOW);
readAccele();
delay(500);
// control signal for SECOND Accelerometer
Serial.println("IMU 2");
digitalWrite(Acc_ctrl_1, HIGH);
digitalWrite(Acc_ctrl_2, LOW);
digitalWrite(Acc_ctrl_3, LOW);
readAccele();
delay(500);
// control signal for THIRD Accelerometer
Serial.println("IMU 3");
digitalWrite(Acc_ctrl_1, LOW);
digitalWrite(Acc_ctrl_2, HIGH);
digitalWrite(Acc_ctrl_3, LOW);
readAccele();
delay(500);
}
void readAccele()
{
Wire.beginTransmission(MPU);// I2C address code thanks to John Boxall
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,true); // request a total of 14 registers
AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
Serial.print("AcX = "); Serial.print(AcX);
Serial.print(" | AcY = "); Serial.print(AcY);
Serial.print(" | AcZ = "); Serial.print(AcZ);
Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53); //equation for temperature in degrees C from datasheet
Serial.print(" | GyX = "); Serial.print(GyX);
Serial.print(" | GyY = "); Serial.print(GyY);
Serial.print(" | GyZ = "); Serial.println(GyZ);
delay(5);
}
```
I implemented it into the Jeff Rowberg example code:
```
// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <[email protected]>
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
bool dmpReady = false; // set true if DMP init was successful
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64];
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
MPU6050 mpu;
// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION
// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_EULER
// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
#define OUTPUT_READABLE_WORLDACCEL
int Acc_ctrl_1 = 9;
int Acc_ctrl_2 = 10;
int Acc_ctrl_3 = 11;
int chip_enable1 = 5;
int chip_enable2 = 6;
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;
// MPU control/status vars
//uint8_t fifoBuffer[64]; // FIFO storage buffer
// orientation/motion vars
Quaternion q; // [w, x, y, z] quaternion container
VectorInt16 aa; // [x, y, z] accel sensor measurements
VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi] Euler angle container
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };
// ================================================================
// === INTERRUPT DETECTION ROUTINE ===
// ================================================================
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}
// ================================================================
// === INITIAL SETUP ===
// ================================================================
void setup() {
pinMode(Acc_ctrl_1, OUTPUT); //S0
pinMode(Acc_ctrl_2, OUTPUT); //S1
pinMode(Acc_ctrl_3, OUTPUT); //S2 address lines
pinMode(chip_enable1, OUTPUT);
// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
// initialize serial communication
// (115200 chosen because it is required for Teapot Demo output, but it's
// really up to you depending on your project)
Serial.begin(115200);
while (!Serial); // wait for Leonardo enumeration, others continue immediately
// initialize device
Serial.println(F("Initializing I2C devices..."));
mpu.initialize();
// verify connection
Serial.println(F("Testing device connections..."));
Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
// wait for ready
Serial.println(F("\nSend any character to begin DMP programming and demo: "));
while (Serial.available() && Serial.read()); // empty buffer
while (!Serial.available()); // wait for data
while (Serial.available() && Serial.read()); // empty buffer again
// load and configure the DMP
Serial.println(F("Initializing DMP..."));
devStatus = mpu.dmpInitialize();
// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(220);
mpu.setYGyroOffset(76);
mpu.setZGyroOffset(-85);
mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
// make sure it worked (returns 0 if so)
if (devStatus == 0) {
// turn on the DMP, now that it's ready
Serial.println(F("Enabling DMP..."));
mpu.setDMPEnabled(true);
// enable Arduino interrupt detection
Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
attachInterrupt(0, dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
// set our DMP Ready flag so the main loop() function knows it's okay to use it
Serial.println(F("DMP ready! Waiting for first interrupt..."));
dmpReady = true;
// get expected DMP packet size for later comparison
packetSize = mpu.dmpGetFIFOPacketSize();
} else {
// ERROR!
// 1 = initial memory load failed
// 2 = DMP configuration updates failed
// (if it's going to break, usually the code will be 1)
Serial.print(F("DMP Initialization failed (code "));
Serial.print(devStatus);
Serial.println(F(")"));
}
// configure LED for output
pinMode(LED_PIN, OUTPUT);
}
// ================================================================
// === MAIN PROGRAM LOOP ===
// ================================================================
void loop() {
//Enable the MUX Chip 1 - Active Low
digitalWrite(chip_enable1, LOW);
// control signal for First Accelerometer
Serial.println("IMU 1");
digitalWrite(Acc_ctrl_1, LOW);
digitalWrite(Acc_ctrl_2, LOW);
digitalWrite(Acc_ctrl_3, LOW);
readAccele();
delay(500);
// control signal for SECOND Accelerometer
Serial.println("IMU 2");
digitalWrite(Acc_ctrl_1, HIGH);
digitalWrite(Acc_ctrl_2, LOW);
digitalWrite(Acc_ctrl_3, LOW);
readAccele();
delay(500);
// control signal for THIRD Accelerometer
Serial.println("IMU 3");
digitalWrite(Acc_ctrl_1, LOW);
digitalWrite(Acc_ctrl_2, HIGH);
digitalWrite(Acc_ctrl_3, LOW);
readAccele();
delay(500);
}
void readAccele(){
// if programming failed, don't try to do anything
if (!dmpReady) return;
// wait for MPU interrupt or extra packet(s) available
while (!mpuInterrupt && fifoCount < packetSize) {
// other program behavior stuff here
}
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
Serial.println(F("FIFO overflow!"));
// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
#ifdef OUTPUT_READABLE_QUATERNION
// display quaternion values in easy matrix form: w x y z
mpu.dmpGetQuaternion(&q, fifoBuffer);
Serial.print("quat\t");
Serial.print(q.w);
Serial.print("\t");
Serial.print(q.x);
Serial.print("\t");
Serial.print(q.y);
Serial.print("\t");
Serial.println(q.z);
#endif
#ifdef OUTPUT_READABLE_EULER
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
Serial.print("euler\t");
Serial.print(euler[0] * 180/M_PI);
Serial.print("\t");
Serial.print(euler[1] * 180/M_PI);
Serial.print("\t");
Serial.println(euler[2] * 180/M_PI);
#endif
#ifdef OUTPUT_READABLE_WORLDACCEL
// display initial world-frame acceleration, adjusted to remove gravity
// and rotated based on known orientation from quaternion
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetAccel(&aa, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
Serial.print("aworld\t");
Serial.print(aaWorld.x);
Serial.print("\t");
Serial.print(aaWorld.y);
Serial.print("\t");
Serial.println(aaWorld.z);
#endif
;
}
}
```
But this is what the serial prints, FIFO Overflow.. I tried to fix it but couldn't. I can't upload an image so Ill copy and paste the serial output here as code...
```
Send any character to begin DMP programming and demo:
Initializing DMP...
Enabling DMP...
Enabling interrupt detection (Arduino external interrupt 0)...
DMP ready! Waiting for first interrupt...
IMU 1
IMU 2
IMU 3
IMU 1
FIFO overflow!
IMU 2
IMU 3
IMU 1
FIFO overflow!
IMU 2
IMU 3
IMU 1
FIFO overflow!
IMU 2
IMU 3
IMU 1
FIFO overflow!
IMU 2
IMU 3
IMU 1
FIFO overflow!
IMU 2
IMU 3
IMU 1
FIFO overflow!
IMU 2
IMU 3
IMU 1
FIFO overflow!
IMU 2
IMU 3
IMU 1
``` | 2015/08/18 | [
"https://Stackoverflow.com/questions/32075273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5221887/"
]
| Use the `passenger-status` command. For example, this shows me passenger is running the `production` environment (the first line under the `Application groups` heading):
```
(production-web) ubuntu@ip-10-0-3-146 ~% sudo passenger-status
Version : 5.0.15
Date : 2015-08-20 17:40:24 +0000
Instance: lNNFwV1C (Apache/2.4.7 (Ubuntu) Phusion_Passenger/5.0.15)
----------- General information -----------
Max pool size : 12
App groups : 1
Processes : 6
Requests in top-level queue : 0
----------- Application groups -----------
/home/my-app/deploy/current (production):
App root: /home/my-app/deploy/current
Requests in queue: 0
* PID: 11123 Sessions: 0 Processed: 12997 Uptime: 21h 14m 2s
CPU: 0% Memory : 190M Last used: 1s ago
* PID: 11130 Sessions: 0 Processed: 140 Uptime: 21h 14m 2s
CPU: 0% Memory : 153M Last used: 9m 32s a
* PID: 11137 Sessions: 0 Processed: 15 Uptime: 21h 14m 2s
CPU: 0% Memory : 103M Last used: 57m 54s
* PID: 11146 Sessions: 0 Processed: 6 Uptime: 21h 14m 2s
CPU: 0% Memory : 101M Last used: 7h 47m 4
* PID: 11153 Sessions: 0 Processed: 5 Uptime: 21h 14m 1s
CPU: 0% Memory : 100M Last used: 8h 42m 3
* PID: 11160 Sessions: 0 Processed: 2 Uptime: 21h 14m 1s
CPU: 0% Memory : 81M Last used: 8h 42m 3
```
rails console is not reliable - it only tells you what environment the console is running under. Passenger may be configured to run in a different environment. | Your environment is found on `Rails.env`.
```
Loading development environment (Rails 4.2.3)
2.1.2 :001 > Rails.env
=> "development"
```
You can also use the environment in a question format for conditionals:
```
2.1.2 :002 > Rails.env.production?
=> false
2.1.2 :003 > Rails.env.pickle?
=> false
2.1.2 :004 > Rails.env.development?
=> true
```
Word of warning - this is if you want to program something within your code that checks the environment. |
13,938,930 | I have two strings in PHP:
```
$Str1 = "/welcome/files/birthday.php?business_id=0";
$Str2 = "/welcome/index.php?page=birthday";
```
I have to get word birthday from this two string with a single function.
I need a function which returns birthday on both case.
example
```
function getBaseWord($word){
...
return $base_word;
}
getBaseWord('/welcome/files/birthday.php?business_id=0');
getBaseWord('/welcome/index.php?page=birthday');
```
both function call should return "birthday".
How can i do it. | 2012/12/18 | [
"https://Stackoverflow.com/questions/13938930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/811621/"
]
| So what you will need to do is get all of the actual GET variables extracted from the string:
```
//Seperate the URL and the GET Data
list($url,$querystring) = explode('?', $string, 2);
//Seperate the Variable name from its value
list($GETName, $GETValue) = explode("=", $querystring);
//Check to see if we have the right variable name
if($GETName == "page"){
//Return the value of that variable.
return $GETValue;
}
```
**NOTE**
This is very BASIC and will not accept more then one GET parameter. You will need to modify it if you plan on have more variables. | I have no idea what you are talking about but, you can cut the word "birthday" with str\_replace and replace with another word, or you can find the position with stripos, I have no idea what we are trying to do here, so those are the only things come to my mind |
13,938,930 | I have two strings in PHP:
```
$Str1 = "/welcome/files/birthday.php?business_id=0";
$Str2 = "/welcome/index.php?page=birthday";
```
I have to get word birthday from this two string with a single function.
I need a function which returns birthday on both case.
example
```
function getBaseWord($word){
...
return $base_word;
}
getBaseWord('/welcome/files/birthday.php?business_id=0');
getBaseWord('/welcome/index.php?page=birthday');
```
both function call should return "birthday".
How can i do it. | 2012/12/18 | [
"https://Stackoverflow.com/questions/13938930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/811621/"
]
| If I correctly understand what you are trying to do then this should do what you need:
```
function getWord(){
return $_GET['page'];
}
```
or $\_GET['business\_id'];
I think $\_GET is an associative array made from the GET request that was sent to the page. An associative array is one where you access something like ['name of the element'] instead of [1] or [2] or whatever. | I have no idea what you are talking about but, you can cut the word "birthday" with str\_replace and replace with another word, or you can find the position with stripos, I have no idea what we are trying to do here, so those are the only things come to my mind |
56,206,567 | I have a page that is used by Doctors, where they can write the patient email select a bounce of documents, and via "mailto" create a formatted email. This doesn't work on Safari iOS.
The problem I found is mailto does not work with Safari iOS if launched from home screen (as a web app). It works using onclick=window.location I tried to implement it on my function but it is not working
so I am trying to implement something like this:
```
<a href="#" onclick="window.location='mailto:[email protected]?subject=Docs&body=Hallo%20you%20and%20links'; return false;" class="noHighlight">Write and email</a>
```
in my function:
```
function buildMailto(recipient, subject, body) {
var mailToLink = "mailto:" + recipient + "?";
var mailContent = "Subject=" + subject + "&";
mailContent += "[email protected]&";
mailContent += "body="
mailContent += encodeURIComponent(body);
a.href = mailToLink + mailContent;
}
```
I am trying to edit:
```
function buildMailto(recipient, subject, body) {
var mailToLink = " '#' onclick=\"window.location='mailto:" + recipient +"?";
var mailContent = "Subject=" + subject + "&";
mailContent += "[email protected]&";
mailContent += "body="
mailContent += encodeURIComponent(body);
mailContent += "return false; class='noHighlight' ";
a.href = mailToLink + mailContent;
}
```
Not having any results at the moment | 2019/05/19 | [
"https://Stackoverflow.com/questions/56206567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11505368/"
]
| There were a few issues with your code:
* `a` was never defined. Give your link an ID and select id by using `document.getElementById()`
* You cannot set the `href` attribute of the link and "break out" using double quotes in order to add the onclick attribute to the element. Instead:
* add the `click` event using `.addEventListener()`. Alternatively, you could use `.setAttribute('onclick', 'window.location.href = "' + mailToLink + mailContent + '"; return false;');` if you wanted to be able to see the click event using your browser's DOM inspector, but it doesn't really make sense.
```js
function buildMailto(recipient, subject, body) {
var mailToLink = "mailto:" + recipient +"?";
var mailContent = "Subject=" + subject + "&";
mailContent += "[email protected]&";
mailContent += "body="
mailContent += encodeURIComponent(body);
document.getElementById('myLink').addEventListener('click', function() {
window.location.href = mailToLink + mailContent;
return false;
});
}
buildMailto('[email protected]', 'a subject', 'mail content');
```
```html
<a href="#" id="myLink" class="noHighlight">Write and email</a>
``` | Try embedding your actionable into a form. Like this:
```
<form action="mailto:[email protected]?subject=Docs&body=Hallo%20you%20and%20links" method="GET">
<button class="noHighlight" type="submit">Write and email</a>
</form>
``` |
56,206,567 | I have a page that is used by Doctors, where they can write the patient email select a bounce of documents, and via "mailto" create a formatted email. This doesn't work on Safari iOS.
The problem I found is mailto does not work with Safari iOS if launched from home screen (as a web app). It works using onclick=window.location I tried to implement it on my function but it is not working
so I am trying to implement something like this:
```
<a href="#" onclick="window.location='mailto:[email protected]?subject=Docs&body=Hallo%20you%20and%20links'; return false;" class="noHighlight">Write and email</a>
```
in my function:
```
function buildMailto(recipient, subject, body) {
var mailToLink = "mailto:" + recipient + "?";
var mailContent = "Subject=" + subject + "&";
mailContent += "[email protected]&";
mailContent += "body="
mailContent += encodeURIComponent(body);
a.href = mailToLink + mailContent;
}
```
I am trying to edit:
```
function buildMailto(recipient, subject, body) {
var mailToLink = " '#' onclick=\"window.location='mailto:" + recipient +"?";
var mailContent = "Subject=" + subject + "&";
mailContent += "[email protected]&";
mailContent += "body="
mailContent += encodeURIComponent(body);
mailContent += "return false; class='noHighlight' ";
a.href = mailToLink + mailContent;
}
```
Not having any results at the moment | 2019/05/19 | [
"https://Stackoverflow.com/questions/56206567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11505368/"
]
| In your `buildMailto` function, you didn't specify what is `a`. Instead of updating `onclick` attribute value when the anchor link is clicked, you should build a mailto URL and update `window.location.href`. Here is an example:
```
<a href="#" id="email-link" class="noHighlight">Write and email</a>
```
Event listener for anchor link:
```
document.querySelector('#email-link').addEventListener('click', function (e) {
e.preventDefault();
buildMailto('[email protected]', 'Docs', 'Hi, there!');
});
```
Change your `buildMailto` to the following:
```
function buildMailto(recipient, subject, body) {
var mailLink = "mailto:" + recipient + "?";
mailLink += "Subject=" + subject + "&";
mailLink += "[email protected]&";
mailLink += "body="
mailLink += encodeURIComponent(body);
window.location.href = mailLink;
}
``` | Try embedding your actionable into a form. Like this:
```
<form action="mailto:[email protected]?subject=Docs&body=Hallo%20you%20and%20links" method="GET">
<button class="noHighlight" type="submit">Write and email</a>
</form>
``` |
38,103,295 | I have this CSS:
```
div[data-role="page"]{
min-height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
border: 0px;
background-image:url('../img/blue_background.jpg');}
```
and this is my function:
Note:
on the variables initialized in the function, the val() is from a selectbox that when changed, is saved in localStorage.
```
function saveParam(){
var result=$("#param_results option:selected").val();
var scan=$("#param_scan option:selected").val();
var scan_speed=$("#param_scan_speed option:selected").val();
var scan_bg=$("#param_scan_bg option:selected").val();
var font=$("#param_font option:selected").val();
var screen_bg=$("#param_screen_bg option:selected").val();
var waiting_time=$("#param_waiting_time option:selected").val();
window.localStorage.setItem("param_results", result);
window.localStorage.setItem("param_scan", scan);
window.localStorage.setItem("param_scan_speed", scan_speed);
window.localStorage.setItem("param_scan_bg", scan_bg);
window.localStorage.setItem("param_font", font);
window.localStorage.setItem("param_screen_bg", screen_bg);
window.localStorage.setItem("param_waiting_time", waiting_time);
//$('div[data-role="page"]').css("background-image", "url('../img/green.jpg')");
back();}
```
I have several html pages, all of them have the div[data-role="page"] so all of them have the same background, etc... but when param\_screen\_bg is changed, I want to permanently change the background image to another but it's not working. The comment line at the end it's just my attempt to try to change the background but it's still not working.
EDIT:
<https://jsfiddle.net/42zbcbge/1/>
on this jsfiddle is a small example of what i want. when you press the save button, i want to change the background on the css and therefor on the page too but it's not changing | 2016/06/29 | [
"https://Stackoverflow.com/questions/38103295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6529031/"
]
| The first thing that you need to do is georectify your data by your Country. What this does is match your Countries with a coordinate from a database or reference table. You will need a column that has ONE country for each row. You can also have Regions, Cities, Zip Codes, etc. The steps are lengthy to type, but Spotfire has a great short video on this. For your situation, you can start the video at the 2:18 mark.
<http://spotfire.tibco.com/qrt/5G93S/5G93S.html> | I was able to use the geocode my data but was still having issues due to my data being a multi-select. To simplify things for me, i made changes to the source (Made a different table, which would clean the data and have a single country in each column, this is then imported into Spotfire) and was able to make it work.
This is a workaround, not a solution. Thanks. |
33,299 | Ok so I want to change operating systems, I got a new PC recently that had no operating system so I installed Ubuntu on it. I now want to install Windows 7 but when I put in the install disk it says it needs my hard drive to be in the NTFS format. How can I change my hard rive to this format in Ubuntu? | 2011/04/03 | [
"https://askubuntu.com/questions/33299",
"https://askubuntu.com",
"https://askubuntu.com/users/-1/"
]
| A Kubuntu Mobile technology preview was part of the [10.10 release](http://www.kubuntu.org/news/10.10-release). I don't believe it is being shipped on any real hardware yet, but you can [download it](http://cdimage.ubuntu.com/kubuntu-mobile/releases/10.10/release/) to try out in a virtual machine. Builds for Natty are also [available](http://cdimages.ubuntu.com/kubuntu-mobile/daily-live/current/).
 | The answer is no, Ubuntu was not designed for phones. There are some [hacks](http://www.phonesreview.co.uk/2010/03/10/video-htc-touch-pro2-runs-ubuntu/) to make it work on phones, but not in a usable way.
PS. Looks like there was a project called [Ubuntu Mobile](http://en.wikipedia.org/wiki/Ubuntu_Mobile), but it's already dead.
**Edit:** [Ubuntu for phones](http://www.ubuntu.com/devices/phone) has been announced, but it still isn't shipping yet. |
2,897,717 | I'd like to use some existing C++ code, [NvTriStrip](http://developer.nvidia.com/object/nvtristrip_library.html), in a Python tool.
SWIG easily handles the functions with simple parameters, but the main function, `GenerateStrips`, is much more complicated.
What do I need to put in the SWIG interface file to indicate that `primGroups` is really an output parameter and that it must be cleaned up with `delete[]`?
```
///////////////////////////////////////////////////////////////////////////
// GenerateStrips()
//
// in_indices: input index list, the indices you would use to render
// in_numIndices: number of entries in in_indices
// primGroups: array of optimized/stripified PrimitiveGroups
// numGroups: number of groups returned
//
// Be sure to call delete[] on the returned primGroups to avoid leaking mem
//
bool GenerateStrips( const unsigned short* in_indices,
const unsigned int in_numIndices,
PrimitiveGroup** primGroups,
unsigned short* numGroups,
bool validateEnabled = false );
```
FYI, here is the `PrimitiveGroup` declaration:
```
enum PrimType
{
PT_LIST,
PT_STRIP,
PT_FAN
};
struct PrimitiveGroup
{
PrimType type;
unsigned int numIndices;
unsigned short* indices;
PrimitiveGroup() : type(PT_STRIP), numIndices(0), indices(NULL) {}
~PrimitiveGroup()
{
if(indices)
delete[] indices;
indices = NULL;
}
};
``` | 2010/05/24 | [
"https://Stackoverflow.com/questions/2897717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/99377/"
]
| Have you looked at the documentation of SWIG regarding their "cpointer.i" and "carray.i" libraries? They're found [here](http://www.swig.org/Doc1.3/Library.html#Library_nn4). That's how you have to manipulate things unless you want to create your own utility libraries to accompany the wrapped code. Here's the link to the Python handling of pointers with [SWIG](http://www.swig.org/Doc1.3/SWIG.html#SWIG_nn15).
Onto your question on getting it to recognize input versus output. They've got another section in the documentation [here](http://www.swig.org/Doc1.3/Arguments.html#Arguments_nn5), that describes exactly that. You lable things `OUTPUT` in the \*.i file. So in your case you'd write:
```
%inline{
extern bool GenerateStrips( const unsigned short* in_dices,
const unsigned short* in_numIndices,
PrimitiveGroup** OUTPUT,
unsigned short* numGroups,
bool validated );
%}
```
which gives you a function that returns both the bool and the `PrimitiveGroup*` array as a tuple.
Does that help? | I don't know how to do it with SWIG, but you might want to consider moving to a more modern binding system like [Pyrex](http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/) or [Cython](http://cython.org/).
For example, Pyrex gives you access to C++ delete for cases like this. Here's an excerpt from the documentation:
>
> **Disposal**
>
>
> The del statement can be applied to a pointer to a C++ struct
> to deallocate it. This is equivalent to delete in C++.
>
>
>
> ```
> cdef Shrubbery *big_sh
> big_sh = new Shrubbery(42.0)
> display_in_garden_show(big_sh)
> del big_sh
>
> ```
>
>
<http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/version/Doc/Manual/using_with_c++.html> |
2,897,717 | I'd like to use some existing C++ code, [NvTriStrip](http://developer.nvidia.com/object/nvtristrip_library.html), in a Python tool.
SWIG easily handles the functions with simple parameters, but the main function, `GenerateStrips`, is much more complicated.
What do I need to put in the SWIG interface file to indicate that `primGroups` is really an output parameter and that it must be cleaned up with `delete[]`?
```
///////////////////////////////////////////////////////////////////////////
// GenerateStrips()
//
// in_indices: input index list, the indices you would use to render
// in_numIndices: number of entries in in_indices
// primGroups: array of optimized/stripified PrimitiveGroups
// numGroups: number of groups returned
//
// Be sure to call delete[] on the returned primGroups to avoid leaking mem
//
bool GenerateStrips( const unsigned short* in_indices,
const unsigned int in_numIndices,
PrimitiveGroup** primGroups,
unsigned short* numGroups,
bool validateEnabled = false );
```
FYI, here is the `PrimitiveGroup` declaration:
```
enum PrimType
{
PT_LIST,
PT_STRIP,
PT_FAN
};
struct PrimitiveGroup
{
PrimType type;
unsigned int numIndices;
unsigned short* indices;
PrimitiveGroup() : type(PT_STRIP), numIndices(0), indices(NULL) {}
~PrimitiveGroup()
{
if(indices)
delete[] indices;
indices = NULL;
}
};
``` | 2010/05/24 | [
"https://Stackoverflow.com/questions/2897717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/99377/"
]
| It's actually so easy to make python bindings for things directly that I don't know why people bother with confusing wrapper stuff like SWIG.
Just use [Py\_BuildValue](http://docs.python.org/c-api/arg.html) once per element of the outer array, producing one tuple per row. Store those tuples in a C array. Then Call [PyList\_New](http://docs.python.org/c-api/list.html) and [PyList\_SetSlice](http://docs.python.org/c-api/list.html) to generate a list of tuples, and return the list pointer from your C function. | I don't know how to do it with SWIG, but you might want to consider moving to a more modern binding system like [Pyrex](http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/) or [Cython](http://cython.org/).
For example, Pyrex gives you access to C++ delete for cases like this. Here's an excerpt from the documentation:
>
> **Disposal**
>
>
> The del statement can be applied to a pointer to a C++ struct
> to deallocate it. This is equivalent to delete in C++.
>
>
>
> ```
> cdef Shrubbery *big_sh
> big_sh = new Shrubbery(42.0)
> display_in_garden_show(big_sh)
> del big_sh
>
> ```
>
>
<http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/version/Doc/Manual/using_with_c++.html> |
2,010,957 | [](https://i.stack.imgur.com/LIcaV.png)
I think I must first prove that I(A) is a subring and then prove that A is in the ideal I(A) and I(A) is the largest sub-ring containing A. but I have problems to show that I(A) is a subring because let x and y in I(A), so $xa\in A$ and $ya \in A$
but I do not know how to prove that $xy\in I(A)$ and the rest. | 2016/11/12 | [
"https://math.stackexchange.com/questions/2010957",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/386771/"
]
| Let $x,y \in I(A)$. Then $xa, ya \in A$ for all $a \in A$. Now $(xy)a = x(ya) = xa'$ for $a' = ya \in A$. Thus $xa' \in A$ and therefore $xy \in I(A)$. That $x+y \in I(A)$ follows from $(x+y)a = xa + xy$ and since $A$ is an ideal. Now since $A$ is a right ideal of $R$ it is also a right ideal in $I(A) \subseteq R$. By definition $A$ is a left ideal in $I(A)$ and thus an ideal. Let now $R' \subseteq R$ be a subring such that $A \subseteq R'$ is an ideal. Then for all $x \in R', a \in A$ we have $xa \in A$. Hence $R' \subseteq I(A)$. | Let $R'$ be a subring of $R$ such that $A\subset R'$ is an ideal, take $x\in R'$ then $\forall a\in A$, $xa\in A$ since $A$ is an ideal in $R'$ so $x\in I(A)$.
Take $x,y\in I(A)$ then $(x+y)a=xa+ya\in A$ for every $a\in A$, so $x+y\in I(A)$. Similarly $x\cdot y \in I(A)$. Also $0\_R,1\_R\in I(A)$ trivially.
It is easy to see that $A$ is a two sided ideal in $I(A)$, since $A\subset I(A)$ we have that for every $x\in R$ and $a\in A$, $ax\in A$. In particular this happens for every $x\in I(A)$. So $A$ is a right ideal of $I(A)$ and a left ideal of $I(A)$ by construction. |
11,873,652 | I have been tortured by this for quite a while.
Because of table sorter pagination will completely remove the invisible rows from the table for faster sorting. I could not get the checkbox in each row to work as my desired.
Here is my jsfiddle ->
<http://jsfiddle.net/NcqfY/3/>
*click the variable trigger to bring up the table*
Basically what I want to do is get the id for all selected rows and pushed them into an array `selectedID`. Empty `selectedID` array when the report is created (or the "create report" button is clicked). So after I clicked the button, I hope that all the checkboxes in the table should get unchecked. I am using the following code:
`$('table.tablesorter tbody tr').find('input[type=checkbox]').prop('checked', false);
// I can only uncheck the boxes in current page`
However I can only uncheck the boxes in current page, not include the pages that are invisible. This really gives me hard time to get the correct ID for selected rows.
Anyone could help me out would be greatly appreciated! | 2012/08/08 | [
"https://Stackoverflow.com/questions/11873652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1413598/"
]
| It's a [**positive lookahead**](http://www.regular-expressions.info/lookaround.html). In that particular expression, it is saying that your password must have at least two digits (`\d`).
Also note that a lookahead doesn't *consume* input, it is merely an **assertion**.
For example, in your regex, the lookahead part (`(?=.*\\d.*\\d.*)`) asserts that your `password` contains at least two digits, and the rest of the expression consumes the entire string, and tries to match at least 8 word characters (i.e., `[a-zA-Z_0-9]`) at the beginning of the string. | It's a lookahead: A zero-width match that checks to see if the position is followed by the given expression.
<http://www.regular-expressions.info/lookaround.html>
In your scenario, you are looking for a string that:
* begins with a string containing two digits (enforced by the lookahead)
* begins with 8 word characters (matched by the rest of the regex)
The lookahead is not actually part of the match. It behaves much like a word boundary (`\b`) or beginning of string (`^`). |
56,240,613 | I want to display "n = (n)" over the whiskers of each of my boxplots. I have figured out how to put these labels over the top of each box (q75) using fivenum, but I can't get them working above the whisker. Above the whiskers is better because my plots are very cluttered.
Here I've reproduced the plots using mtcars
Edit: mtcars has no significant outliers, but my dataset does. That's why the label needs to be on top of the whisker, and not just on the highest data point.
sidenote: I am working with a lot of outliers and want to take them out of the display. GGplot can do this, but it will still include outliers in the axis, which gives me a very "zoomed out" plot. My workaround for this is included. I've used the base boxplot function to calculate the highest whisker, and used coord\_cartesian to set the upper limit just above that.
```
> data("mtcars")
> head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
>
> d = data.table(mtcars)
>
> give.n <- function(x){
+ return(data.frame(y = fivenum(x)[4],
+ label = paste("n =",length(x))))
+ }
>
> p1 <- boxplot(mpg~cyl, data=mtcars, outline=FALSE,
+ plot=0)
> p1stats <- p1$stats[5,]
> head(p1stats)
[1] 33.9 21.4 19.2
> upperlim <- max(p1$stats, na.rm = TRUE) * 1.05
>
> p <- ggplot(d, aes(x=factor(cyl), y=mpg)) +
+ geom_boxplot() +
+ stat_summary(fun.data = give.n, geom = "text", vjust=-.5)
>
> p <- p + coord_cartesian(ylim = c(0, upperlim))
```
I tried changing this function (which works):
```
> give.n <- function(x){
+ return(data.frame(y = fivenum(x)[4],
+ label = paste("n =",length(x))))
+ }
```
To this, using the 5th row of p1 stats (the upper whiskers):
```
give.n <- function(x){
return(data.frame(y = p1stats,
label = paste("n =",length(x))))
}
```
But that returns this:
[bad plot](https://i.stack.imgur.com/v7Z6s.png)
How do I get this to display the label on only the correct whisker point for each box?
PS - My apologies, I'm unfamiliar with posting here but I tried | 2019/05/21 | [
"https://Stackoverflow.com/questions/56240613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10576625/"
]
| Here is a ggplot solution with dpylr:
```
ggplot(mtcars, aes(x=cyl, y=mpg, group=cyl)) +
geom_boxplot() +
geom_text(data=mtcars %>% group_by(cyl) %>% summarise(top = max(mpg), n=n()), aes(x=cyl, y=top, label= paste0("n = ", n)), nudge_y=1)
```
[](https://i.stack.imgur.com/CjwGd.png)
EDIT
There's probably a more concise way, but I think this works. I edited a data point for cyl=8 for emphasis:
```
ggplot(mtcars, aes(x=cyl, y=mpg, group=cyl)) +
geom_boxplot() +
geom_text(data=mtcars %>%
group_by(cyl) %>%
summarise(q3 = quantile(mpg, 0.75),
q1 = quantile(mpg, 0.25),
iqr = q3 - q1,
top = min(q3 + 1.5*iqr, max(mpg)),
n=n()),
aes(x=cyl, y=top, label= paste0("n = ", n)), nudge_y=1)
```
[](https://i.stack.imgur.com/TxdlQ.png) | Edit: see the comment below and my other answer!
Okay I figured it out using the format of Alan's answer. It needed boxplot.stats to get the correct whisker calculation:
```
geom_text(data=mtcars %>% group_by(cyl) %>%
summarise(n = n(),
boxstats = boxplot.stats(mpg)[1],
whisker = boxstats[5]),
aes(x=cyl, y=whisker, label=paste0("n =", n)))
``` |
56,240,613 | I want to display "n = (n)" over the whiskers of each of my boxplots. I have figured out how to put these labels over the top of each box (q75) using fivenum, but I can't get them working above the whisker. Above the whiskers is better because my plots are very cluttered.
Here I've reproduced the plots using mtcars
Edit: mtcars has no significant outliers, but my dataset does. That's why the label needs to be on top of the whisker, and not just on the highest data point.
sidenote: I am working with a lot of outliers and want to take them out of the display. GGplot can do this, but it will still include outliers in the axis, which gives me a very "zoomed out" plot. My workaround for this is included. I've used the base boxplot function to calculate the highest whisker, and used coord\_cartesian to set the upper limit just above that.
```
> data("mtcars")
> head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
>
> d = data.table(mtcars)
>
> give.n <- function(x){
+ return(data.frame(y = fivenum(x)[4],
+ label = paste("n =",length(x))))
+ }
>
> p1 <- boxplot(mpg~cyl, data=mtcars, outline=FALSE,
+ plot=0)
> p1stats <- p1$stats[5,]
> head(p1stats)
[1] 33.9 21.4 19.2
> upperlim <- max(p1$stats, na.rm = TRUE) * 1.05
>
> p <- ggplot(d, aes(x=factor(cyl), y=mpg)) +
+ geom_boxplot() +
+ stat_summary(fun.data = give.n, geom = "text", vjust=-.5)
>
> p <- p + coord_cartesian(ylim = c(0, upperlim))
```
I tried changing this function (which works):
```
> give.n <- function(x){
+ return(data.frame(y = fivenum(x)[4],
+ label = paste("n =",length(x))))
+ }
```
To this, using the 5th row of p1 stats (the upper whiskers):
```
give.n <- function(x){
return(data.frame(y = p1stats,
label = paste("n =",length(x))))
}
```
But that returns this:
[bad plot](https://i.stack.imgur.com/v7Z6s.png)
How do I get this to display the label on only the correct whisker point for each box?
PS - My apologies, I'm unfamiliar with posting here but I tried | 2019/05/21 | [
"https://Stackoverflow.com/questions/56240613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10576625/"
]
| Okay scratch that last attempt. I figured it out. boxplot.stats and geom\_boxplot calculate quartile stats differently, and that skews everything in small sample sizes. We can call the actual stats geom\_boxplot uses with ggplot\_build.
This is how it's done, son. First, make your plot, like above, I called it p.
Now calculate sample size for each x variable
```
samp <- count(mtcars, cyl)
```
now retrieve the data from the plot using ggplot\_build
```
ggstat <- ggplot_build(p)$data
ggwhisk1 <- ggstat[[1]]$ymax
```
now combine that with the sample size, and call that data in geom\_text
```
ggwhisk2 <- data.frame(samp, whisk = ggwhisk1)
p <- p + geom_text(data = ggwhisk2, size = 2,
aes(x = cyl, y = whisk, label = paste0("n =", n), vjust = -.5))
```
Voila!! | Here is a ggplot solution with dpylr:
```
ggplot(mtcars, aes(x=cyl, y=mpg, group=cyl)) +
geom_boxplot() +
geom_text(data=mtcars %>% group_by(cyl) %>% summarise(top = max(mpg), n=n()), aes(x=cyl, y=top, label= paste0("n = ", n)), nudge_y=1)
```
[](https://i.stack.imgur.com/CjwGd.png)
EDIT
There's probably a more concise way, but I think this works. I edited a data point for cyl=8 for emphasis:
```
ggplot(mtcars, aes(x=cyl, y=mpg, group=cyl)) +
geom_boxplot() +
geom_text(data=mtcars %>%
group_by(cyl) %>%
summarise(q3 = quantile(mpg, 0.75),
q1 = quantile(mpg, 0.25),
iqr = q3 - q1,
top = min(q3 + 1.5*iqr, max(mpg)),
n=n()),
aes(x=cyl, y=top, label= paste0("n = ", n)), nudge_y=1)
```
[](https://i.stack.imgur.com/TxdlQ.png) |
56,240,613 | I want to display "n = (n)" over the whiskers of each of my boxplots. I have figured out how to put these labels over the top of each box (q75) using fivenum, but I can't get them working above the whisker. Above the whiskers is better because my plots are very cluttered.
Here I've reproduced the plots using mtcars
Edit: mtcars has no significant outliers, but my dataset does. That's why the label needs to be on top of the whisker, and not just on the highest data point.
sidenote: I am working with a lot of outliers and want to take them out of the display. GGplot can do this, but it will still include outliers in the axis, which gives me a very "zoomed out" plot. My workaround for this is included. I've used the base boxplot function to calculate the highest whisker, and used coord\_cartesian to set the upper limit just above that.
```
> data("mtcars")
> head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
>
> d = data.table(mtcars)
>
> give.n <- function(x){
+ return(data.frame(y = fivenum(x)[4],
+ label = paste("n =",length(x))))
+ }
>
> p1 <- boxplot(mpg~cyl, data=mtcars, outline=FALSE,
+ plot=0)
> p1stats <- p1$stats[5,]
> head(p1stats)
[1] 33.9 21.4 19.2
> upperlim <- max(p1$stats, na.rm = TRUE) * 1.05
>
> p <- ggplot(d, aes(x=factor(cyl), y=mpg)) +
+ geom_boxplot() +
+ stat_summary(fun.data = give.n, geom = "text", vjust=-.5)
>
> p <- p + coord_cartesian(ylim = c(0, upperlim))
```
I tried changing this function (which works):
```
> give.n <- function(x){
+ return(data.frame(y = fivenum(x)[4],
+ label = paste("n =",length(x))))
+ }
```
To this, using the 5th row of p1 stats (the upper whiskers):
```
give.n <- function(x){
return(data.frame(y = p1stats,
label = paste("n =",length(x))))
}
```
But that returns this:
[bad plot](https://i.stack.imgur.com/v7Z6s.png)
How do I get this to display the label on only the correct whisker point for each box?
PS - My apologies, I'm unfamiliar with posting here but I tried | 2019/05/21 | [
"https://Stackoverflow.com/questions/56240613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10576625/"
]
| Okay scratch that last attempt. I figured it out. boxplot.stats and geom\_boxplot calculate quartile stats differently, and that skews everything in small sample sizes. We can call the actual stats geom\_boxplot uses with ggplot\_build.
This is how it's done, son. First, make your plot, like above, I called it p.
Now calculate sample size for each x variable
```
samp <- count(mtcars, cyl)
```
now retrieve the data from the plot using ggplot\_build
```
ggstat <- ggplot_build(p)$data
ggwhisk1 <- ggstat[[1]]$ymax
```
now combine that with the sample size, and call that data in geom\_text
```
ggwhisk2 <- data.frame(samp, whisk = ggwhisk1)
p <- p + geom_text(data = ggwhisk2, size = 2,
aes(x = cyl, y = whisk, label = paste0("n =", n), vjust = -.5))
```
Voila!! | Edit: see the comment below and my other answer!
Okay I figured it out using the format of Alan's answer. It needed boxplot.stats to get the correct whisker calculation:
```
geom_text(data=mtcars %>% group_by(cyl) %>%
summarise(n = n(),
boxstats = boxplot.stats(mpg)[1],
whisker = boxstats[5]),
aes(x=cyl, y=whisker, label=paste0("n =", n)))
``` |
28,748,242 | Dear friends I'reading a csv file that contains some file like this *1.086,12*. Now my problem is that I have to format it a way that allows my to create a BigDecimal, them my correct value should be 1086.12. But I could also have another value 99,11 and in this case I have to get 99.11.
I write this snippet of code:
```
BigDecimal bigDecimal = null;
String str = value.replace(',','.');
bigDecimal = new BigDecimal(str);
```
My code works just in the latter cese, Is there some regular expression that allows this? | 2015/02/26 | [
"https://Stackoverflow.com/questions/28748242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2069976/"
]
| You do not need a regex. You can/should use [DecimalFormat](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html) for that:
```
DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.GERMAN);
DecimalFormat df= new DecimalFormat();
df.setDecimalFormatSymbols(dfs);
Double valCEWithUKFormat = df.parse(str).doubleValue();
``` | You can use this Java code:
```
String[] arr = {"1.086,12", "99.11"};
for (String tok: arr) {
if (tok.matches("[^.]*\\.[^,]+,.*"))
tok= tok.replace(".", "").replace(",", ".");
System.out.println( tok );
}
```
**output:**
```
1086.12
99.11
``` |
59,616,740 | I'm troubleshooting liveness probe failures. I'm able to extract specific entries from k8s event using this approach
```
k get events --sort-by=.metadata.creationTimestamp | grep Liveness
```
I'd like to get only the pod(s) that causing the issue.
I'm considering to pipe a cut, but I'm not sure which delimiter should I use to get the specific column.
Where I can find the delimiter related to that specific k8s resource(Events) used to printout the kubectl output?
Any other suggestion is appreciated
UPDATE
so far these are the best options (w/o using extra tools) satisfying my specific needs:
```
k get events -o jsonpath='{range .items[*]}{.involvedObject.name}/{.involvedObject.namespace}: {.message}{"\n"}{end}' | grep Liveness
k get events -o custom-columns=POD:.involvedObject.name,NS:.involvedObject.namespace,MGG:.message | grep Liveness
``` | 2020/01/06 | [
"https://Stackoverflow.com/questions/59616740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/539684/"
]
| there is a feature in kubernetes called [jsonpath](https://kubernetes.io/docs/reference/kubectl/jsonpath/)
validate if your jsonpath is correct with this online tool: <https://jsonpath.com/>
easily go through json keys with this online tool, so you needn't manually type the key names any more): <http://jsonpathfinder.com/>
so your command will be:
```
k get events --sort-by=.metadata.creationTimestamp --jsonpath '{ .xxxxxx }'
```
[](https://i.stack.imgur.com/GYtsY.png)
[](https://i.stack.imgur.com/PggIZ.png) | Jsonpath is a little bit limited to be used with filter and conditions, maybe for your case `jq` will be more suitable.
I did a test using `jq` to filter the Output of my probe:
I've tested using the yaml from this [link](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/)
The message of probe failure from this pod is:
>
> Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
>
>
>
and the path for this message in json is `.items[*].message`
Using `jq` I can filter only `message` that contains "Liveness probe failed": and show the pod name:
```
k get events --sort-by=.metadata.creationTimestamp -o json | jq -c '.items[] | select(.message|test("Liveness probe failed")) | .metadata.name'
```
The output is:
```
"liveness-exec.15e791c17b80a3c1"
```
You can use `jq` to format the message in order to get a more helpful output, with pod details.
Try to look this references links:
[./jq](https://stedolan.github.io/jq/)
[filter array based on values](https://stackoverflow.com/questions/26701538/how-to-filter-an-array-of-objects-based-on-values-in-an-inner-array-with-jq)
I hope it helps! |
24,024 | I need a little help navigating this ferrite core memory technology. My end goal is to use it in a calculator or something straightforward.
I understand the writing process to each core but how is reading accomplished? Do you have to measure the voltage on the sense wire and flip each of the bits while collecting the bits on the sense wire? Because I feel if you flipped all the bits at once you would have several voltages just summed together.
My memory pane is a 64K in size and has a front and back that are mirror and in parallel with the front. The sides have 4 windows and has 64x(s) and 64y(s) that I counted. How should I go about driving all these?
Any suggestions would be great help.
[](https://i.stack.imgur.com/JNIAc.jpg) | 2022/03/04 | [
"https://retrocomputing.stackexchange.com/questions/24024",
"https://retrocomputing.stackexchange.com",
"https://retrocomputing.stackexchange.com/users/24176/"
]
| Reading a bit from core is a destructive process; essentially you try to write a '1' and monitor the sense line to see if there's a current spike when you do that. There's only a current spike if writing the core flipped the bit, i.e. if it was '0' to start with. I believe most core controllers would automatically write back any 0's so detected. (Or, just as easily, write 0s, detect pulse if bit was 1, and write-back 1s)
The way you write to just one core in the whole array depends on the non linear response of the magnetics to the drive currents. You run 1/2 the necessary current through one of the column lines, and 1/2 through one of the row lines. Only that core at the intersection of the row and column gets enough of a kick to change state. | CuriousMarc has some really interesting and educational content about core memory (and a lot of other stuff) in YouTube. Watch [Core Memory Explained and Demonstrated](https://youtu.be/AwsInQLmjXc) for details. |
24,024 | I need a little help navigating this ferrite core memory technology. My end goal is to use it in a calculator or something straightforward.
I understand the writing process to each core but how is reading accomplished? Do you have to measure the voltage on the sense wire and flip each of the bits while collecting the bits on the sense wire? Because I feel if you flipped all the bits at once you would have several voltages just summed together.
My memory pane is a 64K in size and has a front and back that are mirror and in parallel with the front. The sides have 4 windows and has 64x(s) and 64y(s) that I counted. How should I go about driving all these?
Any suggestions would be great help.
[](https://i.stack.imgur.com/JNIAc.jpg) | 2022/03/04 | [
"https://retrocomputing.stackexchange.com/questions/24024",
"https://retrocomputing.stackexchange.com",
"https://retrocomputing.stackexchange.com/users/24176/"
]
| >
> I understand the writing process to each core but how is reading accomplished?
>
>
>
By writing a zero and looking at the sense line:
* If that bit was a **zero** nothing happenes
* If that bit was a **one** a pulse can be sensed on the sense line.
After that the stored content is zero, that's why it's called a destructive read, so content needs to be written again.
Reading is essentially a combination of clearing the bit to read, reporting if a blip was seen (=1) or not (=0) and then writing it again. That's why each core stacks usually not only had dedicated amplifier logic, but also a register (one flip flop per plane) to hold what was read and logic to write it back without interaction of the host - much like later DRAM.
>
> Do you have to measure the voltage on the sense wire and flip each of the bits while collecting the bits on the sense wire?
>
>
>
Yes.
>
> Because I feel if you flipped all the bits at once you would have several voltages just summed together.
>
>
>
Oh, I guess that's where you're stuck. What your picture shows is a single plane. **Only one bit can be read or written at a time**. To form bytes or words, several planes are stacked to form a ... well ... *Stack* (of core).
And yes, the plane seems to be four dedicated 64x64 sub-planes, but it does not allow a bit operation per sub-plane (working independently), as they use all the same X/Y lines. Any attempt to address two different bits in different sub-planes will also activate two mirrored bits (\*1).
Then again, one can use this type of sub-plane to make a single board stack always writing(reading) the same bit in each sub-plane combining them to a 4-bit word (or 8-bit, if there's another 4 planes on the back).
This means activating the same row/column on each sub-plane. It still needs the same amount of drivers (one per X and Y line and plane, to be able to do 0/1 independently) but only one board with core. Very handy for small machines.
>
> My memory pane is a 64K in size and has a front and back that are mirror and in parallel with the front. The sides have 4 windows and has 64x(s) and 64y(s) that I counted.
>
>
>
That doesn't really add up. 64x64 cores per sub-plane is 4,096 - with 4 of them on the front and back this adds up to 16,768 bits or 4 KiB.
>
> How should I go about driving all these?
>
>
>
Well, you need a pair of drivers for all X and Y able to be switched per sub plane, 8 sense amplifiers to read and some logic to handle decoding and store the result in a register to be read by some consuming device.
Depending on your goal, this might be either a full figured parallel acting hardware, or a microcontroller with some decoders handling the 8 sub-planes in a serial fashion - which of course will be slower, at least for writing (2).
Personally I'd go with a microcontroller, a single adjustable write source and a set of CMOS multiplexers to 'scan' across the planes. Might be slower, but saves greatly on part count (\*3).
---
\*1 - Assume one writing bit 1;1 in the upper left sub-plane and 2;2 in the upper right, then bit 1;2 in the upper left and 2;1 in the upper right would also be written with the same value.
\*2 - One can use 8 parallel inputs to read all 8 planes in parallel, while writing back in serial would be done only for ones, thus saving time.
\*3 - Depending on circuit design one could interleave reading/writing the planes to some degree. Might be fun to fiddle with that :)) | CuriousMarc has some really interesting and educational content about core memory (and a lot of other stuff) in YouTube. Watch [Core Memory Explained and Demonstrated](https://youtu.be/AwsInQLmjXc) for details. |
24,024 | I need a little help navigating this ferrite core memory technology. My end goal is to use it in a calculator or something straightforward.
I understand the writing process to each core but how is reading accomplished? Do you have to measure the voltage on the sense wire and flip each of the bits while collecting the bits on the sense wire? Because I feel if you flipped all the bits at once you would have several voltages just summed together.
My memory pane is a 64K in size and has a front and back that are mirror and in parallel with the front. The sides have 4 windows and has 64x(s) and 64y(s) that I counted. How should I go about driving all these?
Any suggestions would be great help.
[](https://i.stack.imgur.com/JNIAc.jpg) | 2022/03/04 | [
"https://retrocomputing.stackexchange.com/questions/24024",
"https://retrocomputing.stackexchange.com",
"https://retrocomputing.stackexchange.com/users/24176/"
]
| >
> I understand the writing process to each core but how is reading accomplished?
>
>
>
By writing a zero and looking at the sense line:
* If that bit was a **zero** nothing happenes
* If that bit was a **one** a pulse can be sensed on the sense line.
After that the stored content is zero, that's why it's called a destructive read, so content needs to be written again.
Reading is essentially a combination of clearing the bit to read, reporting if a blip was seen (=1) or not (=0) and then writing it again. That's why each core stacks usually not only had dedicated amplifier logic, but also a register (one flip flop per plane) to hold what was read and logic to write it back without interaction of the host - much like later DRAM.
>
> Do you have to measure the voltage on the sense wire and flip each of the bits while collecting the bits on the sense wire?
>
>
>
Yes.
>
> Because I feel if you flipped all the bits at once you would have several voltages just summed together.
>
>
>
Oh, I guess that's where you're stuck. What your picture shows is a single plane. **Only one bit can be read or written at a time**. To form bytes or words, several planes are stacked to form a ... well ... *Stack* (of core).
And yes, the plane seems to be four dedicated 64x64 sub-planes, but it does not allow a bit operation per sub-plane (working independently), as they use all the same X/Y lines. Any attempt to address two different bits in different sub-planes will also activate two mirrored bits (\*1).
Then again, one can use this type of sub-plane to make a single board stack always writing(reading) the same bit in each sub-plane combining them to a 4-bit word (or 8-bit, if there's another 4 planes on the back).
This means activating the same row/column on each sub-plane. It still needs the same amount of drivers (one per X and Y line and plane, to be able to do 0/1 independently) but only one board with core. Very handy for small machines.
>
> My memory pane is a 64K in size and has a front and back that are mirror and in parallel with the front. The sides have 4 windows and has 64x(s) and 64y(s) that I counted.
>
>
>
That doesn't really add up. 64x64 cores per sub-plane is 4,096 - with 4 of them on the front and back this adds up to 16,768 bits or 4 KiB.
>
> How should I go about driving all these?
>
>
>
Well, you need a pair of drivers for all X and Y able to be switched per sub plane, 8 sense amplifiers to read and some logic to handle decoding and store the result in a register to be read by some consuming device.
Depending on your goal, this might be either a full figured parallel acting hardware, or a microcontroller with some decoders handling the 8 sub-planes in a serial fashion - which of course will be slower, at least for writing (2).
Personally I'd go with a microcontroller, a single adjustable write source and a set of CMOS multiplexers to 'scan' across the planes. Might be slower, but saves greatly on part count (\*3).
---
\*1 - Assume one writing bit 1;1 in the upper left sub-plane and 2;2 in the upper right, then bit 1;2 in the upper left and 2;1 in the upper right would also be written with the same value.
\*2 - One can use 8 parallel inputs to read all 8 planes in parallel, while writing back in serial would be done only for ones, thus saving time.
\*3 - Depending on circuit design one could interleave reading/writing the planes to some degree. Might be fun to fiddle with that :)) | Reading a bit from core is a destructive process; essentially you try to write a '1' and monitor the sense line to see if there's a current spike when you do that. There's only a current spike if writing the core flipped the bit, i.e. if it was '0' to start with. I believe most core controllers would automatically write back any 0's so detected. (Or, just as easily, write 0s, detect pulse if bit was 1, and write-back 1s)
The way you write to just one core in the whole array depends on the non linear response of the magnetics to the drive currents. You run 1/2 the necessary current through one of the column lines, and 1/2 through one of the row lines. Only that core at the intersection of the row and column gets enough of a kick to change state. |
6,917,188 | Trying some basic jQuery and JavaScript here.
The `.width()` gives me an integer value. The `.css('min-width')` gives me a value ending in `px`. Therefore I can't do math on this as is. What is the recommended work around?
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width')) {
...
}
``` | 2011/08/02 | [
"https://Stackoverflow.com/questions/6917188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834505/"
]
| Use `replace()`:
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').replace('px', ''));
```
Alternatively, you could use the `parseInt` function:
```
alert(parseInt('1px')); //Result: 1
``` | ```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').substring(0,indexOf('px'));
``` |
6,917,188 | Trying some basic jQuery and JavaScript here.
The `.width()` gives me an integer value. The `.css('min-width')` gives me a value ending in `px`. Therefore I can't do math on this as is. What is the recommended work around?
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width')) {
...
}
``` | 2011/08/02 | [
"https://Stackoverflow.com/questions/6917188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834505/"
]
| Use `replace()`:
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').replace('px', ''));
```
Alternatively, you could use the `parseInt` function:
```
alert(parseInt('1px')); //Result: 1
``` | Use substring to the value returning from the min-width to remove the px |
6,917,188 | Trying some basic jQuery and JavaScript here.
The `.width()` gives me an integer value. The `.css('min-width')` gives me a value ending in `px`. Therefore I can't do math on this as is. What is the recommended work around?
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width')) {
...
}
``` | 2011/08/02 | [
"https://Stackoverflow.com/questions/6917188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834505/"
]
| Some string manipulation to remove 'px' and then use `parseInt` to get it as a number:
```
var minWidth = parseInt($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').replace('px', ''), 10)
``` | ```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').substring(0,indexOf('px'));
``` |
6,917,188 | Trying some basic jQuery and JavaScript here.
The `.width()` gives me an integer value. The `.css('min-width')` gives me a value ending in `px`. Therefore I can't do math on this as is. What is the recommended work around?
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width')) {
...
}
``` | 2011/08/02 | [
"https://Stackoverflow.com/questions/6917188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834505/"
]
| Use `replace()`:
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').replace('px', ''));
```
Alternatively, you could use the `parseInt` function:
```
alert(parseInt('1px')); //Result: 1
``` | If you pass the return value from `.css('min-width')` to `parseInt` first, it will remove the "px" for you.
```
parseInt(
$('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'),
10
);
```
(Don't forget the second parameter to `parseInt`.) |
6,917,188 | Trying some basic jQuery and JavaScript here.
The `.width()` gives me an integer value. The `.css('min-width')` gives me a value ending in `px`. Therefore I can't do math on this as is. What is the recommended work around?
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width')) {
...
}
``` | 2011/08/02 | [
"https://Stackoverflow.com/questions/6917188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834505/"
]
| The better way is to use `parseInt`. jQuery functions `.width()` and `.height()` work quite so.
Also, it would be good to encapsulate fetching of this values in standalone functions:
* `.minHeight()`, `.minHeight( size )`, `.minHeight( function() )`
* `.maxHeight()`, `...`
* `.minWidth()`, `...`
* `.maxWidth()`, `...`
Like this:
```
(function($, undefined) {
var oldPlugins = {};
$.each([ "min", "max" ], function(_, name) {
$.each([ "Width", "Height" ], function(_, dimension) {
var type = name + dimension,
cssProperty = [name, dimension.toLowerCase()].join('-');
oldPlugins[ type ] = $.fn[ type ];
$.fn[ type ] = function(size) {
var elem = this[0];
if (!elem) {
return !size ? null : this;
}
if ($.isFunction(size)) {
return this.each(function(i) {
var $self = $(this);
$self[ type ](size.call(this, i, $self[ type ]()));
});
}
if (size === undefined) {
var orig = $.css(elem, cssProperty),
ret = parseFloat(orig);
return jQuery.isNaN(ret) ? orig : ret;
} else {
return this.css(cssProperty, typeof size === "string" ? size : size + "px");
}
};
});
});
})(jQuery);
```
And your code will turn to:
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth()) {
``` | Some string manipulation to remove 'px' and then use `parseInt` to get it as a number:
```
var minWidth = parseInt($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').replace('px', ''), 10)
``` |
6,917,188 | Trying some basic jQuery and JavaScript here.
The `.width()` gives me an integer value. The `.css('min-width')` gives me a value ending in `px`. Therefore I can't do math on this as is. What is the recommended work around?
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width')) {
...
}
``` | 2011/08/02 | [
"https://Stackoverflow.com/questions/6917188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834505/"
]
| The better way is to use `parseInt`. jQuery functions `.width()` and `.height()` work quite so.
Also, it would be good to encapsulate fetching of this values in standalone functions:
* `.minHeight()`, `.minHeight( size )`, `.minHeight( function() )`
* `.maxHeight()`, `...`
* `.minWidth()`, `...`
* `.maxWidth()`, `...`
Like this:
```
(function($, undefined) {
var oldPlugins = {};
$.each([ "min", "max" ], function(_, name) {
$.each([ "Width", "Height" ], function(_, dimension) {
var type = name + dimension,
cssProperty = [name, dimension.toLowerCase()].join('-');
oldPlugins[ type ] = $.fn[ type ];
$.fn[ type ] = function(size) {
var elem = this[0];
if (!elem) {
return !size ? null : this;
}
if ($.isFunction(size)) {
return this.each(function(i) {
var $self = $(this);
$self[ type ](size.call(this, i, $self[ type ]()));
});
}
if (size === undefined) {
var orig = $.css(elem, cssProperty),
ret = parseFloat(orig);
return jQuery.isNaN(ret) ? orig : ret;
} else {
return this.css(cssProperty, typeof size === "string" ? size : size + "px");
}
};
});
});
})(jQuery);
```
And your code will turn to:
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth()) {
``` | ```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').substring(0,indexOf('px'));
``` |
6,917,188 | Trying some basic jQuery and JavaScript here.
The `.width()` gives me an integer value. The `.css('min-width')` gives me a value ending in `px`. Therefore I can't do math on this as is. What is the recommended work around?
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width')) {
...
}
``` | 2011/08/02 | [
"https://Stackoverflow.com/questions/6917188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834505/"
]
| Use `replace()`:
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').replace('px', ''));
```
Alternatively, you could use the `parseInt` function:
```
alert(parseInt('1px')); //Result: 1
``` | Some string manipulation to remove 'px' and then use `parseInt` to get it as a number:
```
var minWidth = parseInt($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').replace('px', ''), 10)
``` |
6,917,188 | Trying some basic jQuery and JavaScript here.
The `.width()` gives me an integer value. The `.css('min-width')` gives me a value ending in `px`. Therefore I can't do math on this as is. What is the recommended work around?
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width')) {
...
}
``` | 2011/08/02 | [
"https://Stackoverflow.com/questions/6917188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834505/"
]
| Use `replace()`:
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width').replace('px', ''));
```
Alternatively, you could use the `parseInt` function:
```
alert(parseInt('1px')); //Result: 1
``` | The better way is to use `parseInt`. jQuery functions `.width()` and `.height()` work quite so.
Also, it would be good to encapsulate fetching of this values in standalone functions:
* `.minHeight()`, `.minHeight( size )`, `.minHeight( function() )`
* `.maxHeight()`, `...`
* `.minWidth()`, `...`
* `.maxWidth()`, `...`
Like this:
```
(function($, undefined) {
var oldPlugins = {};
$.each([ "min", "max" ], function(_, name) {
$.each([ "Width", "Height" ], function(_, dimension) {
var type = name + dimension,
cssProperty = [name, dimension.toLowerCase()].join('-');
oldPlugins[ type ] = $.fn[ type ];
$.fn[ type ] = function(size) {
var elem = this[0];
if (!elem) {
return !size ? null : this;
}
if ($.isFunction(size)) {
return this.each(function(i) {
var $self = $(this);
$self[ type ](size.call(this, i, $self[ type ]()));
});
}
if (size === undefined) {
var orig = $.css(elem, cssProperty),
ret = parseFloat(orig);
return jQuery.isNaN(ret) ? orig : ret;
} else {
return this.css(cssProperty, typeof size === "string" ? size : size + "px");
}
};
});
});
})(jQuery);
```
And your code will turn to:
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth()) {
``` |
6,917,188 | Trying some basic jQuery and JavaScript here.
The `.width()` gives me an integer value. The `.css('min-width')` gives me a value ending in `px`. Therefore I can't do math on this as is. What is the recommended work around?
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width')) {
...
}
``` | 2011/08/02 | [
"https://Stackoverflow.com/questions/6917188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834505/"
]
| The better way is to use `parseInt`. jQuery functions `.width()` and `.height()` work quite so.
Also, it would be good to encapsulate fetching of this values in standalone functions:
* `.minHeight()`, `.minHeight( size )`, `.minHeight( function() )`
* `.maxHeight()`, `...`
* `.minWidth()`, `...`
* `.maxWidth()`, `...`
Like this:
```
(function($, undefined) {
var oldPlugins = {};
$.each([ "min", "max" ], function(_, name) {
$.each([ "Width", "Height" ], function(_, dimension) {
var type = name + dimension,
cssProperty = [name, dimension.toLowerCase()].join('-');
oldPlugins[ type ] = $.fn[ type ];
$.fn[ type ] = function(size) {
var elem = this[0];
if (!elem) {
return !size ? null : this;
}
if ($.isFunction(size)) {
return this.each(function(i) {
var $self = $(this);
$self[ type ](size.call(this, i, $self[ type ]()));
});
}
if (size === undefined) {
var orig = $.css(elem, cssProperty),
ret = parseFloat(orig);
return jQuery.isNaN(ret) ? orig : ret;
} else {
return this.css(cssProperty, typeof size === "string" ? size : size + "px");
}
};
});
});
})(jQuery);
```
And your code will turn to:
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth()) {
``` | If you pass the return value from `.css('min-width')` to `parseInt` first, it will remove the "px" for you.
```
parseInt(
$('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'),
10
);
```
(Don't forget the second parameter to `parseInt`.) |
6,917,188 | Trying some basic jQuery and JavaScript here.
The `.width()` gives me an integer value. The `.css('min-width')` gives me a value ending in `px`. Therefore I can't do math on this as is. What is the recommended work around?
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width'));
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').css('min-width')) {
...
}
``` | 2011/08/02 | [
"https://Stackoverflow.com/questions/6917188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834505/"
]
| The better way is to use `parseInt`. jQuery functions `.width()` and `.height()` work quite so.
Also, it would be good to encapsulate fetching of this values in standalone functions:
* `.minHeight()`, `.minHeight( size )`, `.minHeight( function() )`
* `.maxHeight()`, `...`
* `.minWidth()`, `...`
* `.maxWidth()`, `...`
Like this:
```
(function($, undefined) {
var oldPlugins = {};
$.each([ "min", "max" ], function(_, name) {
$.each([ "Width", "Height" ], function(_, dimension) {
var type = name + dimension,
cssProperty = [name, dimension.toLowerCase()].join('-');
oldPlugins[ type ] = $.fn[ type ];
$.fn[ type ] = function(size) {
var elem = this[0];
if (!elem) {
return !size ? null : this;
}
if ($.isFunction(size)) {
return this.each(function(i) {
var $self = $(this);
$self[ type ](size.call(this, i, $self[ type ]()));
});
}
if (size === undefined) {
var orig = $.css(elem, cssProperty),
ret = parseFloat(orig);
return jQuery.isNaN(ret) ? orig : ret;
} else {
return this.css(cssProperty, typeof size === "string" ? size : size + "px");
}
};
});
});
})(jQuery);
```
And your code will turn to:
```
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
alert($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth());
if ($('#<%=lstProcessName.ClientID%>').parent('.column4').width() >= $('#<%=lstProcessName.ClientID%>').parent('.column4').minWidth()) {
``` | Use substring to the value returning from the min-width to remove the px |
48,809,433 | I want to read pfm format images in python. I tried with imageio.read but it is throwing an error. Can I have any suggestion, please?
`img = imageio.imread('image.pfm')` | 2018/02/15 | [
"https://Stackoverflow.com/questions/48809433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8036071/"
]
| I am not at all familiar with Python, but here are a few suggestions on reading a `PFM` (**Portable Float Map**) file.
---
**Option 1**
The **ImageIO** documentation [here](http://imageio.readthedocs.io/en/latest/format_pfm-fi.html#pfm-fi) suggests there is a **FreeImage** reader you can download and use.
---
**Option 2**
I pieced together a simple reader myself below that seems to work fine on a few sample images I found around the 'net and generated with **ImageMagick**. It may contain inefficiencies or bad practices because I do not speak Python.
```
#!/usr/local/bin/python3
import sys
import re
from struct import *
# Enable/disable debug output
debug = True
with open("image.pfm","rb") as f:
# Line 1: PF=>RGB (3 channels), Pf=>Greyscale (1 channel)
type=f.readline().decode('latin-1')
if "PF" in type:
channels=3
elif "Pf" in type:
channels=1
else:
print("ERROR: Not a valid PFM file",file=sys.stderr)
sys.exit(1)
if(debug):
print("DEBUG: channels={0}".format(channels))
# Line 2: width height
line=f.readline().decode('latin-1')
width,height=re.findall('\d+',line)
width=int(width)
height=int(height)
if(debug):
print("DEBUG: width={0}, height={1}".format(width,height))
# Line 3: +ve number means big endian, negative means little endian
line=f.readline().decode('latin-1')
BigEndian=True
if "-" in line:
BigEndian=False
if(debug):
print("DEBUG: BigEndian={0}".format(BigEndian))
# Slurp all binary data
samples = width*height*channels;
buffer = f.read(samples*4)
# Unpack floats with appropriate endianness
if BigEndian:
fmt=">"
else:
fmt="<"
fmt= fmt + str(samples) + "f"
img = unpack(fmt,buffer)
```
---
**Option 3**
If you cannot read your `PFM` files in Python, you could convert them at the command line using **ImageMagick** to another format, such as TIFF, that can store floating point samples. **ImageMagick** is installed on most Linux distros and is available for macOS and Windows:
```
magick input.pfm output.tif
``` | ```
img = imageio.imread('image.pfm')
```
will just do it. For easy use it can be converted to numpy array.
```
img = numpy.asarray(img)
``` |
48,809,433 | I want to read pfm format images in python. I tried with imageio.read but it is throwing an error. Can I have any suggestion, please?
`img = imageio.imread('image.pfm')` | 2018/02/15 | [
"https://Stackoverflow.com/questions/48809433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8036071/"
]
| The following Python 3 implementation will decode .pfm files.
Download the example [memorial.pfm](http://www.pauldebevec.com/Research/HDR/memorial.pfm) from [Paul Devebec's page](http://www.pauldebevec.com/Research/HDR/PFM/).
```
from pathlib import Path
import numpy as np
import struct
def read_pfm(filename):
with Path(filename).open('rb') as pfm_file:
line1, line2, line3 = (pfm_file.readline().decode('latin-1').strip() for _ in range(3))
assert line1 in ('PF', 'Pf')
channels = 3 if "PF" in line1 else 1
width, height = (int(s) for s in line2.split())
scale_endianess = float(line3)
bigendian = scale_endianess > 0
scale = abs(scale_endianess)
buffer = pfm_file.read()
samples = width * height * channels
assert len(buffer) == samples * 4
fmt = f'{"<>"[bigendian]}{samples}f'
decoded = struct.unpack(fmt, buffer)
shape = (height, width, 3) if channels == 3 else (height, width)
return np.flipud(np.reshape(decoded, shape)) * scale
import matplotlib.pyplot as plt
image = read_pfm('memorial.pfm')
plt.imshow(image)
plt.show()
``` | I am not at all familiar with Python, but here are a few suggestions on reading a `PFM` (**Portable Float Map**) file.
---
**Option 1**
The **ImageIO** documentation [here](http://imageio.readthedocs.io/en/latest/format_pfm-fi.html#pfm-fi) suggests there is a **FreeImage** reader you can download and use.
---
**Option 2**
I pieced together a simple reader myself below that seems to work fine on a few sample images I found around the 'net and generated with **ImageMagick**. It may contain inefficiencies or bad practices because I do not speak Python.
```
#!/usr/local/bin/python3
import sys
import re
from struct import *
# Enable/disable debug output
debug = True
with open("image.pfm","rb") as f:
# Line 1: PF=>RGB (3 channels), Pf=>Greyscale (1 channel)
type=f.readline().decode('latin-1')
if "PF" in type:
channels=3
elif "Pf" in type:
channels=1
else:
print("ERROR: Not a valid PFM file",file=sys.stderr)
sys.exit(1)
if(debug):
print("DEBUG: channels={0}".format(channels))
# Line 2: width height
line=f.readline().decode('latin-1')
width,height=re.findall('\d+',line)
width=int(width)
height=int(height)
if(debug):
print("DEBUG: width={0}, height={1}".format(width,height))
# Line 3: +ve number means big endian, negative means little endian
line=f.readline().decode('latin-1')
BigEndian=True
if "-" in line:
BigEndian=False
if(debug):
print("DEBUG: BigEndian={0}".format(BigEndian))
# Slurp all binary data
samples = width*height*channels;
buffer = f.read(samples*4)
# Unpack floats with appropriate endianness
if BigEndian:
fmt=">"
else:
fmt="<"
fmt= fmt + str(samples) + "f"
img = unpack(fmt,buffer)
```
---
**Option 3**
If you cannot read your `PFM` files in Python, you could convert them at the command line using **ImageMagick** to another format, such as TIFF, that can store floating point samples. **ImageMagick** is installed on most Linux distros and is available for macOS and Windows:
```
magick input.pfm output.tif
``` |
48,809,433 | I want to read pfm format images in python. I tried with imageio.read but it is throwing an error. Can I have any suggestion, please?
`img = imageio.imread('image.pfm')` | 2018/02/15 | [
"https://Stackoverflow.com/questions/48809433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8036071/"
]
| The following Python 3 implementation will decode .pfm files.
Download the example [memorial.pfm](http://www.pauldebevec.com/Research/HDR/memorial.pfm) from [Paul Devebec's page](http://www.pauldebevec.com/Research/HDR/PFM/).
```
from pathlib import Path
import numpy as np
import struct
def read_pfm(filename):
with Path(filename).open('rb') as pfm_file:
line1, line2, line3 = (pfm_file.readline().decode('latin-1').strip() for _ in range(3))
assert line1 in ('PF', 'Pf')
channels = 3 if "PF" in line1 else 1
width, height = (int(s) for s in line2.split())
scale_endianess = float(line3)
bigendian = scale_endianess > 0
scale = abs(scale_endianess)
buffer = pfm_file.read()
samples = width * height * channels
assert len(buffer) == samples * 4
fmt = f'{"<>"[bigendian]}{samples}f'
decoded = struct.unpack(fmt, buffer)
shape = (height, width, 3) if channels == 3 else (height, width)
return np.flipud(np.reshape(decoded, shape)) * scale
import matplotlib.pyplot as plt
image = read_pfm('memorial.pfm')
plt.imshow(image)
plt.show()
``` | ```
img = imageio.imread('image.pfm')
```
will just do it. For easy use it can be converted to numpy array.
```
img = numpy.asarray(img)
``` |
71,082,202 | I have a function in my component inside of `setup()`:
```js
export default defineComponent({
setup() {
const handleResume = async () => {
msg.value = {}
try {
} catch (err) {
}
}
return { handleResume }
}
})
```
Now in my test, I want to create a spy function like this:
```js
import App from '@/views/Frame'
jest.spyOn(App, 'handleResume')
```
But I am getting this error:
```
Cannot spy the handleResume property because it is not a function; undefined given instead
``` | 2022/02/11 | [
"https://Stackoverflow.com/questions/71082202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17970696/"
]
| This requires Vue [3.2.31](https://github.com/vuejs/core/releases/tag/v3.2.31) (released yesterday), which adds [support for mocking `Proxy` methods](https://github.com/vuejs/core/pull/4216), enabling spies on the [`wrapper.vm` from `@vue/test-utils`](https://vue-test-utils.vuejs.org/api/wrapper/#vm).
You can expose methods (or other data) from `setup()` with the [`expose` property from the `context` argument](https://vuejs.org/api/composition-api-setup.html#exposing-public-properties). For example, this component exposes `handleResume` only in tests:
```html
<!-- MyComponent.vue -->
<script>
import { defineComponent } from 'vue'
export default defineComponent({
setup(props, { expose }) {
const handleResume = async () => true
if (process.env.NODE_ENV === 'test') {
expose({ handleResume })
}
return { handleResume }
}
})
</script>
<template>
<button @click="handleResume">Click</button>
</template>
```
If you have `<script setup>` instead, use the [`defineExpose()` macro](https://vuejs.org/api/sfc-script-setup.html#defineexpose):
```html
<!-- MyComponent.vue -->
<script setup>
const handleResume = async () => true
if (process.env.NODE_ENV === 'test') {
defineExpose({ handleResume })
}
</script>
```
Then spy on the exposed `handleResume` from the `wrapper.vm`:
```js
// MyComponent.spec.js
import { shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
describe('MyComponent', () => {
it('handles resume', async () => {
const wrapper = shallowMount(MyComponent)
const handleResume = jest.spyOn(wrapper.vm, 'handleResume')
await wrapper.find('button').trigger('click')
expect(handleResume).toHaveBeenCalled()
})
})
```
[demo](https://stackblitz.com/edit/vue-spy-on-setup-methods?file=tests%2Funit%2FMyComponent.spec.js) | you have to switch setup from object to function which return object. So your setup should looks like this:
```js
setup() {
const handleResume = async () => {
msg.value = {}
try {
} catch (err) {
}
}
return { handleResume }
}
```
After this you have two options, you can use @vue/test-utils, mount component as wrapper in test file and you should get access to your function by wrapper.vm.handleResume. Other solution, you can export your setup to composable and import composable into test instead of mounting component. |
9,303,386 | I was just wondering if it is possible to display a javascript message (either popup or something nice) which is triggered by something which isn't a mouse click, so for example:
```
<?php if(a == b) {
Then auto pop up something
}
```
I have had a look around and cant seem to find anything, also how do people make like stylistic popups like.. i guess maybe CSS but really fancy ones which cant be done with CSS any ideas?
Thanks a bunch :) | 2012/02/15 | [
"https://Stackoverflow.com/questions/9303386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404392/"
]
| Just add a script block to open an alert or what ever you need to open
```
<?php if(a == b) { ?>
<script>
alert('hello');
// or
window.open("http://wwwstackoverflow.com");
// or any type of script you want to run
</script>
<?php } ?>
``` | For anyone coming here these days: `window.open()` called like that will be blocked by any modern browser.
If you're okay with including [a third-party script](https://github.com/colorfulfool/rails-popup), you can do this instead:
```
<?php if(a == b) { ?>
<script>
Popup("<div>Hello</div>").show('up')
</script>
<?php } ?>
``` |
152,796 | On 12th of February in the later afternoon I would like to travel from Kamjanez-Podilsky to Lwiw as I need to catch a plane in the morning.
I would like to go by train, but that's not an option. The arrival time is rather unsafe and I have to change the trains in the middle of the night.
<http://ticket.bus.com.ua/order/forming_bn?point_from=UA6810400000&point_to=UA4610100000&date=12.02.20&date_add=1&fn=round_search> which is recommended by rome2rio doesn't give any result at all. (despite writing 3 busses a day)
Is there any Marschrutka or how do the Ukrainians travel?
Taxis are +130€ and I want to avoid that.
Thank you for the help. | 2020/01/25 | [
"https://travel.stackexchange.com/questions/152796",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/105125/"
]
| There are some results [on Yandex Timetables](https://rasp.yandex.ru/search/?fromId=c23169&fromName=%D0%9A%D0%B0%D0%BC%D0%B5%D0%BD%D0%B5%D1%86-%D0%9F%D0%BE%D0%B4%D0%BE%D0%BB%D1%8C%D1%81%D0%BA%D0%B8%D0%B9&toId=c144&toName=%D0%9B%D1%8C%D0%B2%D0%BE%D0%B2&when=12%20%D1%84%D0%B5%D0%B2%D1%80%D0%B0%D0%BB%D1%8F).
Not sure if they are super accurate. Have you tried phoning the Central Bus Station of departure? | Apparently, no option seem to completely satisfy your criteria: trains require changing the train in the night, and buses depart in the morning and arrive on lunch time.
1. **Train.**
[The timetable](https://www.uz.gov.ua/en/passengers/timetable/?station=22260&by_station=1) of Kamianets-Podilskyi train station shows that the only two trains are:
* № 770 Kamianets-Podilsky — Kyiv (departure time 00:55)
* № 118 Chernivtsi — Kyiv (departure time 23:57)Both make a stop in **Khmelnytskyy** (around 03:00 in the night) where there are [plenty of trains](https://www.uz.gov.ua/route_2/index.php?start_st=22260&fin_st=47548,23092,23081,23215,36921,23200&fs=%D0%9A%D0%B0%D0%BC%27%D0%AF%D0%BD%D0%B5%D1%86%D1%8C-%D0%9F%D0%BE%D0%B4%D1%96%D0%BB%D1%8C%D1%81%D1%8C%D0%BA%D0%B8%D0%B9%20(%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D0%B0)&ts=%D0%9B%D1%8C%D0%B2%D1%96%D0%B2%20%D0%9C%D1%96%D1%81%D1%82%D0%BE%20(%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D0%B0)) heading to Lviv., including
2. **Bus.** There are two of non-stop ones:
* departure 06:00, arrival 13:00
* departure 09:45, arrival 17:33As another answer suggests, Web sites may not display routes/tickets earlier than 3 weeks ahead, but you can check one or two weeks earlier to see the expected schedule.
Here are direct links to various ticketing companies; I've chosen February 5th for the reason above: [Busfor.ua](https://busfor.ua/%D0%B0%D0%B2%D1%82%D0%BE%D0%B1%D1%83%D1%81%D0%B8/%D0%9A%D0%B0%D0%BC-%D1%8F%D0%BD%D0%B5%D1%86%D1%8C-%D0%9F%D0%BE%D0%B4%D1%96%D0%BB%D1%8C%D1%81%D1%8C%D0%BA%D0%B8%D0%B9/%D0%9B%D1%8C%D0%B2%D1%96%D0%B2?from_id=3809&on=2020-02-05&passengers=1&search=true&to_id=4037), [Bus.tickets.ua](https://bus.tickets.ua/en/search/result/98f288f221b36c9bb01ae70d1bd8989a), [Bilet-ua.com](https://bus.bilet-ua.com/order/forming_bn?point_to=UA4610100000&lang=en&date=05.02.20&date_add=3&point_from=UA6810400000&fn=round_search)
Usual caveat: many sites do not have proper English parts; use online translate tools. |
152,796 | On 12th of February in the later afternoon I would like to travel from Kamjanez-Podilsky to Lwiw as I need to catch a plane in the morning.
I would like to go by train, but that's not an option. The arrival time is rather unsafe and I have to change the trains in the middle of the night.
<http://ticket.bus.com.ua/order/forming_bn?point_from=UA6810400000&point_to=UA4610100000&date=12.02.20&date_add=1&fn=round_search> which is recommended by rome2rio doesn't give any result at all. (despite writing 3 busses a day)
Is there any Marschrutka or how do the Ukrainians travel?
Taxis are +130€ and I want to avoid that.
Thank you for the help. | 2020/01/25 | [
"https://travel.stackexchange.com/questions/152796",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/105125/"
]
| Here's the solution.
I fear I have to confess it's more a question of an [XY-Problem](http://xyproblem.info/). I mainly needed to get to Katwice, but I really wanted to re-visit Lwiw. In the last days of my journey I found a solution and would like to share it with you. You have to understand I needed to be in Katowice in the morning of the next day, so my time-budget was limited.
I decided to take an early **bus** from Kamjanez-Podilsky to **Ternopol** (as I recall it it was at 8am and I arrived at 10am - there are earlier ones too. The ticked I obtained straight at the station the day before). I had around 3h to see Ternopol (which is not that many, but I enjoyed).
Then I took the **train** from Ternopol to **Lwiw** and arrived at around 5pm.
From here I beg you: Please be smarter than me!
**Don't do**: Stay in Lwiw over night and take the early flight from Lwiw to Krakow, then the bus to Katowice. Lwiw got pretty expensive and even a cheap hotel was not so cheap as in other parts of Ukraine. I forgot to do the check-in at in the evening and had to pay a penalty at the airport of 55€. From Krakow I got a Flixbus to Katowice.
Also I sent my whole luggage from Kamjanez-Podilsky back home.
Total extra costs: Around 150 Euro.
**Do**: Stay in Lwiw from 5pm to 10pm and take the night train to Krakow. Then the morning train to Katowice.
I used to do something like that back in 2009, but was not very happy about it. In retrospective of the current trip it's still *much* better. | There are some results [on Yandex Timetables](https://rasp.yandex.ru/search/?fromId=c23169&fromName=%D0%9A%D0%B0%D0%BC%D0%B5%D0%BD%D0%B5%D1%86-%D0%9F%D0%BE%D0%B4%D0%BE%D0%BB%D1%8C%D1%81%D0%BA%D0%B8%D0%B9&toId=c144&toName=%D0%9B%D1%8C%D0%B2%D0%BE%D0%B2&when=12%20%D1%84%D0%B5%D0%B2%D1%80%D0%B0%D0%BB%D1%8F).
Not sure if they are super accurate. Have you tried phoning the Central Bus Station of departure? |
152,796 | On 12th of February in the later afternoon I would like to travel from Kamjanez-Podilsky to Lwiw as I need to catch a plane in the morning.
I would like to go by train, but that's not an option. The arrival time is rather unsafe and I have to change the trains in the middle of the night.
<http://ticket.bus.com.ua/order/forming_bn?point_from=UA6810400000&point_to=UA4610100000&date=12.02.20&date_add=1&fn=round_search> which is recommended by rome2rio doesn't give any result at all. (despite writing 3 busses a day)
Is there any Marschrutka or how do the Ukrainians travel?
Taxis are +130€ and I want to avoid that.
Thank you for the help. | 2020/01/25 | [
"https://travel.stackexchange.com/questions/152796",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/105125/"
]
| I didn't see any results after 9th Feb, which is 15 days from now, so I went digging into the site's terms and conditions, where I found [this relevant bit](http://ticket.bus.com.ua/rules):
>
> 3.2.5.4. The extreme date of operations is determined by server of bus terminal (bus station, transporter). Of course it is not less than 15 days from current date.
>
>
>
So it appears that you can only book tickets 15 days or less from the departure date. A very strange restriction, but there you have it. | Apparently, no option seem to completely satisfy your criteria: trains require changing the train in the night, and buses depart in the morning and arrive on lunch time.
1. **Train.**
[The timetable](https://www.uz.gov.ua/en/passengers/timetable/?station=22260&by_station=1) of Kamianets-Podilskyi train station shows that the only two trains are:
* № 770 Kamianets-Podilsky — Kyiv (departure time 00:55)
* № 118 Chernivtsi — Kyiv (departure time 23:57)Both make a stop in **Khmelnytskyy** (around 03:00 in the night) where there are [plenty of trains](https://www.uz.gov.ua/route_2/index.php?start_st=22260&fin_st=47548,23092,23081,23215,36921,23200&fs=%D0%9A%D0%B0%D0%BC%27%D0%AF%D0%BD%D0%B5%D1%86%D1%8C-%D0%9F%D0%BE%D0%B4%D1%96%D0%BB%D1%8C%D1%81%D1%8C%D0%BA%D0%B8%D0%B9%20(%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D0%B0)&ts=%D0%9B%D1%8C%D0%B2%D1%96%D0%B2%20%D0%9C%D1%96%D1%81%D1%82%D0%BE%20(%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D0%B0)) heading to Lviv., including
2. **Bus.** There are two of non-stop ones:
* departure 06:00, arrival 13:00
* departure 09:45, arrival 17:33As another answer suggests, Web sites may not display routes/tickets earlier than 3 weeks ahead, but you can check one or two weeks earlier to see the expected schedule.
Here are direct links to various ticketing companies; I've chosen February 5th for the reason above: [Busfor.ua](https://busfor.ua/%D0%B0%D0%B2%D1%82%D0%BE%D0%B1%D1%83%D1%81%D0%B8/%D0%9A%D0%B0%D0%BC-%D1%8F%D0%BD%D0%B5%D1%86%D1%8C-%D0%9F%D0%BE%D0%B4%D1%96%D0%BB%D1%8C%D1%81%D1%8C%D0%BA%D0%B8%D0%B9/%D0%9B%D1%8C%D0%B2%D1%96%D0%B2?from_id=3809&on=2020-02-05&passengers=1&search=true&to_id=4037), [Bus.tickets.ua](https://bus.tickets.ua/en/search/result/98f288f221b36c9bb01ae70d1bd8989a), [Bilet-ua.com](https://bus.bilet-ua.com/order/forming_bn?point_to=UA4610100000&lang=en&date=05.02.20&date_add=3&point_from=UA6810400000&fn=round_search)
Usual caveat: many sites do not have proper English parts; use online translate tools. |
152,796 | On 12th of February in the later afternoon I would like to travel from Kamjanez-Podilsky to Lwiw as I need to catch a plane in the morning.
I would like to go by train, but that's not an option. The arrival time is rather unsafe and I have to change the trains in the middle of the night.
<http://ticket.bus.com.ua/order/forming_bn?point_from=UA6810400000&point_to=UA4610100000&date=12.02.20&date_add=1&fn=round_search> which is recommended by rome2rio doesn't give any result at all. (despite writing 3 busses a day)
Is there any Marschrutka or how do the Ukrainians travel?
Taxis are +130€ and I want to avoid that.
Thank you for the help. | 2020/01/25 | [
"https://travel.stackexchange.com/questions/152796",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/105125/"
]
| Here's the solution.
I fear I have to confess it's more a question of an [XY-Problem](http://xyproblem.info/). I mainly needed to get to Katwice, but I really wanted to re-visit Lwiw. In the last days of my journey I found a solution and would like to share it with you. You have to understand I needed to be in Katowice in the morning of the next day, so my time-budget was limited.
I decided to take an early **bus** from Kamjanez-Podilsky to **Ternopol** (as I recall it it was at 8am and I arrived at 10am - there are earlier ones too. The ticked I obtained straight at the station the day before). I had around 3h to see Ternopol (which is not that many, but I enjoyed).
Then I took the **train** from Ternopol to **Lwiw** and arrived at around 5pm.
From here I beg you: Please be smarter than me!
**Don't do**: Stay in Lwiw over night and take the early flight from Lwiw to Krakow, then the bus to Katowice. Lwiw got pretty expensive and even a cheap hotel was not so cheap as in other parts of Ukraine. I forgot to do the check-in at in the evening and had to pay a penalty at the airport of 55€. From Krakow I got a Flixbus to Katowice.
Also I sent my whole luggage from Kamjanez-Podilsky back home.
Total extra costs: Around 150 Euro.
**Do**: Stay in Lwiw from 5pm to 10pm and take the night train to Krakow. Then the morning train to Katowice.
I used to do something like that back in 2009, but was not very happy about it. In retrospective of the current trip it's still *much* better. | I didn't see any results after 9th Feb, which is 15 days from now, so I went digging into the site's terms and conditions, where I found [this relevant bit](http://ticket.bus.com.ua/rules):
>
> 3.2.5.4. The extreme date of operations is determined by server of bus terminal (bus station, transporter). Of course it is not less than 15 days from current date.
>
>
>
So it appears that you can only book tickets 15 days or less from the departure date. A very strange restriction, but there you have it. |
152,796 | On 12th of February in the later afternoon I would like to travel from Kamjanez-Podilsky to Lwiw as I need to catch a plane in the morning.
I would like to go by train, but that's not an option. The arrival time is rather unsafe and I have to change the trains in the middle of the night.
<http://ticket.bus.com.ua/order/forming_bn?point_from=UA6810400000&point_to=UA4610100000&date=12.02.20&date_add=1&fn=round_search> which is recommended by rome2rio doesn't give any result at all. (despite writing 3 busses a day)
Is there any Marschrutka or how do the Ukrainians travel?
Taxis are +130€ and I want to avoid that.
Thank you for the help. | 2020/01/25 | [
"https://travel.stackexchange.com/questions/152796",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/105125/"
]
| Here's the solution.
I fear I have to confess it's more a question of an [XY-Problem](http://xyproblem.info/). I mainly needed to get to Katwice, but I really wanted to re-visit Lwiw. In the last days of my journey I found a solution and would like to share it with you. You have to understand I needed to be in Katowice in the morning of the next day, so my time-budget was limited.
I decided to take an early **bus** from Kamjanez-Podilsky to **Ternopol** (as I recall it it was at 8am and I arrived at 10am - there are earlier ones too. The ticked I obtained straight at the station the day before). I had around 3h to see Ternopol (which is not that many, but I enjoyed).
Then I took the **train** from Ternopol to **Lwiw** and arrived at around 5pm.
From here I beg you: Please be smarter than me!
**Don't do**: Stay in Lwiw over night and take the early flight from Lwiw to Krakow, then the bus to Katowice. Lwiw got pretty expensive and even a cheap hotel was not so cheap as in other parts of Ukraine. I forgot to do the check-in at in the evening and had to pay a penalty at the airport of 55€. From Krakow I got a Flixbus to Katowice.
Also I sent my whole luggage from Kamjanez-Podilsky back home.
Total extra costs: Around 150 Euro.
**Do**: Stay in Lwiw from 5pm to 10pm and take the night train to Krakow. Then the morning train to Katowice.
I used to do something like that back in 2009, but was not very happy about it. In retrospective of the current trip it's still *much* better. | Apparently, no option seem to completely satisfy your criteria: trains require changing the train in the night, and buses depart in the morning and arrive on lunch time.
1. **Train.**
[The timetable](https://www.uz.gov.ua/en/passengers/timetable/?station=22260&by_station=1) of Kamianets-Podilskyi train station shows that the only two trains are:
* № 770 Kamianets-Podilsky — Kyiv (departure time 00:55)
* № 118 Chernivtsi — Kyiv (departure time 23:57)Both make a stop in **Khmelnytskyy** (around 03:00 in the night) where there are [plenty of trains](https://www.uz.gov.ua/route_2/index.php?start_st=22260&fin_st=47548,23092,23081,23215,36921,23200&fs=%D0%9A%D0%B0%D0%BC%27%D0%AF%D0%BD%D0%B5%D1%86%D1%8C-%D0%9F%D0%BE%D0%B4%D1%96%D0%BB%D1%8C%D1%81%D1%8C%D0%BA%D0%B8%D0%B9%20(%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D0%B0)&ts=%D0%9B%D1%8C%D0%B2%D1%96%D0%B2%20%D0%9C%D1%96%D1%81%D1%82%D0%BE%20(%D0%A3%D0%BA%D1%80%D0%B0%D1%97%D0%BD%D0%B0)) heading to Lviv., including
2. **Bus.** There are two of non-stop ones:
* departure 06:00, arrival 13:00
* departure 09:45, arrival 17:33As another answer suggests, Web sites may not display routes/tickets earlier than 3 weeks ahead, but you can check one or two weeks earlier to see the expected schedule.
Here are direct links to various ticketing companies; I've chosen February 5th for the reason above: [Busfor.ua](https://busfor.ua/%D0%B0%D0%B2%D1%82%D0%BE%D0%B1%D1%83%D1%81%D0%B8/%D0%9A%D0%B0%D0%BC-%D1%8F%D0%BD%D0%B5%D1%86%D1%8C-%D0%9F%D0%BE%D0%B4%D1%96%D0%BB%D1%8C%D1%81%D1%8C%D0%BA%D0%B8%D0%B9/%D0%9B%D1%8C%D0%B2%D1%96%D0%B2?from_id=3809&on=2020-02-05&passengers=1&search=true&to_id=4037), [Bus.tickets.ua](https://bus.tickets.ua/en/search/result/98f288f221b36c9bb01ae70d1bd8989a), [Bilet-ua.com](https://bus.bilet-ua.com/order/forming_bn?point_to=UA4610100000&lang=en&date=05.02.20&date_add=3&point_from=UA6810400000&fn=round_search)
Usual caveat: many sites do not have proper English parts; use online translate tools. |
218,183 | I would like to programatically populate a paragraph field with a default value for one of my content types.
I came up with the following solution:
```
use \Drupal\Node\NodeInterface;
use \Drupal\paragraphs\Entity\Paragraph;
function my_site_node_create(NodeInterface $node) {
switch ($node->getType()){
case 'my_content_type':
$paragraph = Paragraph::create([
'type' => 'references', // paragraph type machine name
'field_references_title' => [ // paragraph's field machine name
'value' => 'Some examples of what we have done' // body field value
],
]);
$paragraph->save();
$node->set('field_paragraphs_content', [
[
'target_id' => $paragraph->id(),
'target_revision_id' => $paragraph->getRevisionId(),
],
]);
break;
}
}
```
This code seems to work but im worried I might be creating useless Paragraph-entities when the user doesn't save this node (because of the '$paragraph->save()').
How can I avoid this? | 2016/10/19 | [
"https://drupal.stackexchange.com/questions/218183",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/68349/"
]
| The standard solution is to use the [Services module](https://www.drupal.org/project/services), which provides hooks for you to define your own endpoints.
There's also [Restful Web Services](https://www.drupal.org/project/restws) which has similar functionality but is geared more towards entity API integration.
If you literally want to write your own API from scratch then just use your best judgement - there aren't any Drupal-specific standards for that. | You can try [services views](https://www.drupal.org/project/services_views), It can be used with views Module.
>
> Views support for the Services module version 3.x and later.
>
>
> It has currently two features:
> - Create view based resource creating Services display in a view
> - Execute any view of the system via views resource call
>
>
> Demo video <http://youtu.be/DZEhJKMeR5w>
>
>
> |
59,834,659 | I have a list of products with their name and time. I want to create a list that retrieved the most recent date for the kind of product. My initial plan is to create a sublist for each kind of product and the get the most recent of that sublist. I want to know if there is more efficient way of doing it since there could be more on the list.
```
products = [{'name': 'Veggie', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
{'name': 'Fruit', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]
Veggies = [x for x in products if x['name'] == 'Veggie']
...
new_products.append(get_recent(Veggies))
```
Desired output:
```
new_products = [{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]
```
Thanks in advance! | 2020/01/21 | [
"https://Stackoverflow.com/questions/59834659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9879869/"
]
| Here is an option using `collections.defaultdict`:
```py
from collections import defaultdict
from pprint import pprint
products = [
{'name': 'Veggie', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
{'name': 'Fruit', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}
]
d = defaultdict(list)
for product in products:
d[product['name']].append(product['time'])
new_products = [{'name': item, 'time': max(times)} for item, times in d.items()]
```
And the result will be:
```py
pprint(new_products)
[{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]
``` | You can order a list of dictionary by any key you want.
In this example, products(or Veggies ) is passed to the built-in sorted() function, which accepts a keyword argument key. Itemgetter creates a callable that accepts a single item from the product(or Veggies) array and as input and returns a value that will be used as the basis for sorting it.
```py
from operator import itemgetter
products = [{'name': 'Veggie', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
{'name': 'Fruit', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]
rows_by_date = sorted(products, key=itemgetter('time'))
print(rows_by_date)
```
OUTPUT
```
[{'name': 'Veggie', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Fruit', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]
``` |
59,834,659 | I have a list of products with their name and time. I want to create a list that retrieved the most recent date for the kind of product. My initial plan is to create a sublist for each kind of product and the get the most recent of that sublist. I want to know if there is more efficient way of doing it since there could be more on the list.
```
products = [{'name': 'Veggie', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
{'name': 'Fruit', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]
Veggies = [x for x in products if x['name'] == 'Veggie']
...
new_products.append(get_recent(Veggies))
```
Desired output:
```
new_products = [{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]
```
Thanks in advance! | 2020/01/21 | [
"https://Stackoverflow.com/questions/59834659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9879869/"
]
| Here is an option using `collections.defaultdict`:
```py
from collections import defaultdict
from pprint import pprint
products = [
{'name': 'Veggie', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
{'name': 'Fruit', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}
]
d = defaultdict(list)
for product in products:
d[product['name']].append(product['time'])
new_products = [{'name': item, 'time': max(times)} for item, times in d.items()]
```
And the result will be:
```py
pprint(new_products)
[{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]
``` | I think you need to sort your data first then you can do reduce to eliminate duplicate record
```py
from functools import reduce
from operator import itemgetter
products = [{'name': 'Veggie', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'},
{'name': 'Fruit', 'time': '2020-01-06T07:53:29Z'},
{'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]
def validate_unique_product(a, b):
if b['name'] in map(lambda x: x['name'], a):
return a
a.append(b)
return a
sorted_products = sorted(products, key=itemgetter('time'), reverse=True)
unique_products = reduce(validate_unique_product, sorted_products, [])
print(unique_products)
```
output
------
```
>> [{'name': 'Veggie', 'time': '2020-02-02T07:12:13Z'}, {'name': 'Fruit', 'time': '2020-02-02T07:12:13Z'}]
``` |
2,530,104 | Can someone tell me, what the href with the "#" means?
```
<a id="logoutLink" href="#">Logout</a>
``` | 2010/03/27 | [
"https://Stackoverflow.com/questions/2530104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198183/"
]
| If points to an anchor on the page. In this case the anchor is just default. You could have multiple anchors on the page
<a name="anchor1"></a>
<a name="anchor2"></a>
<a name="anchor3"></a>
and link to them as
<a href="#anchor1">link 1</a>
<a href="#anchor2">link 2</a>
<a href="#anchor3">link 3</a> | The hash symbol (i.e., `<a id="logoutLink" href="#">Logout</a>`) is a placeholder, so that you can preview the "Logout" link in a browser as you develop your page. Eventually, the hash symbol will be replaced with a real URL. |
2,530,104 | Can someone tell me, what the href with the "#" means?
```
<a id="logoutLink" href="#">Logout</a>
``` | 2010/03/27 | [
"https://Stackoverflow.com/questions/2530104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198183/"
]
| It means nothing... ;) Normally we use `#something` to create anchor to some element. If your URL ends with `...#comments` then your browser will automatiacly jump (scroll the page) to element with `id="comments"`.
`href="#"` is often used to create a link that leads to nowhere. | If points to an anchor on the page. In this case the anchor is just default. You could have multiple anchors on the page
<a name="anchor1"></a>
<a name="anchor2"></a>
<a name="anchor3"></a>
and link to them as
<a href="#anchor1">link 1</a>
<a href="#anchor2">link 2</a>
<a href="#anchor3">link 3</a> |
2,530,104 | Can someone tell me, what the href with the "#" means?
```
<a id="logoutLink" href="#">Logout</a>
``` | 2010/03/27 | [
"https://Stackoverflow.com/questions/2530104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198183/"
]
| It means nothing... ;) Normally we use `#something` to create anchor to some element. If your URL ends with `...#comments` then your browser will automatiacly jump (scroll the page) to element with `id="comments"`.
`href="#"` is often used to create a link that leads to nowhere. | It means make this page an anchor and navigate to it - which is why you see '#' after your URL in the address line (which can have nasty side-effects). Its also why your page will scroll back up to the top if you click on the link (sidenote: you can avoid this by adding "return false;" at the end of your onclick handler) |
2,530,104 | Can someone tell me, what the href with the "#" means?
```
<a id="logoutLink" href="#">Logout</a>
``` | 2010/03/27 | [
"https://Stackoverflow.com/questions/2530104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198183/"
]
| It is the shortest way to say "go nowhere" :)
Often something else is bound to that link, a javascript event handler in most cases. But if an `<a>` doesn't have a `href`, most browsers don't render it with the same styling...so you need a short something to put there.
If it had something following the hash, like `<a href="#topics">Go to Topics</a>` it is a scroll to link, it goes to where the element with `id="topics"` is at the top of the page. A common example is `<a href="#top">Go to Top</a>`, and you stick a `<div id="top"></div>` at the very top of the page. | The hash symbol (i.e., `<a id="logoutLink" href="#">Logout</a>`) is a placeholder, so that you can preview the "Logout" link in a browser as you develop your page. Eventually, the hash symbol will be replaced with a real URL. |
2,530,104 | Can someone tell me, what the href with the "#" means?
```
<a id="logoutLink" href="#">Logout</a>
``` | 2010/03/27 | [
"https://Stackoverflow.com/questions/2530104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198183/"
]
| As others have pointed out, hash anchors (those beginning with the # sign) typically lead to a named anchor on the page. A table of contents on a page might be a good example of where you'd see this:
```
<ul>
<li><a href="#history">Company History</a></li>
<li><a href="#goals">Our Goals</a></li>
<li><a href="#products">Products We Offer</a></li>
<li><a href="#services">Services We Offer</a></li>
</ul>
<h2><a name="history">History</a></h2>
<p>The #history anchor tag will lead to the named anchor above.</p>
<h2><a name="goals">Our Goals</a></h2>
<p>The #goals anchor tag will lead to the named anchor above.</p>
<h2><a name="products">Products We Offer</a></h2>
<p>The #products anchor tag will lead to the named anchor above.</p>
<h2><a name="services">Services We Offer</a></h2>
<p>The #services anchor tag will lead to the named anchor above.</p>
```
One thing to note is that when you have a blank hash as the anchor href (i.e.: `<a href="#">Blah</a>`), some browsers make that jump to the top of the page, which is not the desired effect. To work around this and prevent the page from scrolling all the way to the top, a JavaScript implementation is often included to prevent the anchor tag from acting as it normally would by returning false.
```
<a href="#" onclick="return false;">Blah</a>
``` | It means make this page an anchor and navigate to it - which is why you see '#' after your URL in the address line (which can have nasty side-effects). Its also why your page will scroll back up to the top if you click on the link (sidenote: you can avoid this by adding "return false;" at the end of your onclick handler) |
2,530,104 | Can someone tell me, what the href with the "#" means?
```
<a id="logoutLink" href="#">Logout</a>
``` | 2010/03/27 | [
"https://Stackoverflow.com/questions/2530104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198183/"
]
| As others have pointed out, hash anchors (those beginning with the # sign) typically lead to a named anchor on the page. A table of contents on a page might be a good example of where you'd see this:
```
<ul>
<li><a href="#history">Company History</a></li>
<li><a href="#goals">Our Goals</a></li>
<li><a href="#products">Products We Offer</a></li>
<li><a href="#services">Services We Offer</a></li>
</ul>
<h2><a name="history">History</a></h2>
<p>The #history anchor tag will lead to the named anchor above.</p>
<h2><a name="goals">Our Goals</a></h2>
<p>The #goals anchor tag will lead to the named anchor above.</p>
<h2><a name="products">Products We Offer</a></h2>
<p>The #products anchor tag will lead to the named anchor above.</p>
<h2><a name="services">Services We Offer</a></h2>
<p>The #services anchor tag will lead to the named anchor above.</p>
```
One thing to note is that when you have a blank hash as the anchor href (i.e.: `<a href="#">Blah</a>`), some browsers make that jump to the top of the page, which is not the desired effect. To work around this and prevent the page from scrolling all the way to the top, a JavaScript implementation is often included to prevent the anchor tag from acting as it normally would by returning false.
```
<a href="#" onclick="return false;">Blah</a>
``` | If points to an anchor on the page. In this case the anchor is just default. You could have multiple anchors on the page
<a name="anchor1"></a>
<a name="anchor2"></a>
<a name="anchor3"></a>
and link to them as
<a href="#anchor1">link 1</a>
<a href="#anchor2">link 2</a>
<a href="#anchor3">link 3</a> |
2,530,104 | Can someone tell me, what the href with the "#" means?
```
<a id="logoutLink" href="#">Logout</a>
``` | 2010/03/27 | [
"https://Stackoverflow.com/questions/2530104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198183/"
]
| It means nothing... ;) Normally we use `#something` to create anchor to some element. If your URL ends with `...#comments` then your browser will automatiacly jump (scroll the page) to element with `id="comments"`.
`href="#"` is often used to create a link that leads to nowhere. | The hash symbol (i.e., `<a id="logoutLink" href="#">Logout</a>`) is a placeholder, so that you can preview the "Logout" link in a browser as you develop your page. Eventually, the hash symbol will be replaced with a real URL. |
2,530,104 | Can someone tell me, what the href with the "#" means?
```
<a id="logoutLink" href="#">Logout</a>
``` | 2010/03/27 | [
"https://Stackoverflow.com/questions/2530104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198183/"
]
| It is the shortest way to say "go nowhere" :)
Often something else is bound to that link, a javascript event handler in most cases. But if an `<a>` doesn't have a `href`, most browsers don't render it with the same styling...so you need a short something to put there.
If it had something following the hash, like `<a href="#topics">Go to Topics</a>` it is a scroll to link, it goes to where the element with `id="topics"` is at the top of the page. A common example is `<a href="#top">Go to Top</a>`, and you stick a `<div id="top"></div>` at the very top of the page. | If points to an anchor on the page. In this case the anchor is just default. You could have multiple anchors on the page
<a name="anchor1"></a>
<a name="anchor2"></a>
<a name="anchor3"></a>
and link to them as
<a href="#anchor1">link 1</a>
<a href="#anchor2">link 2</a>
<a href="#anchor3">link 3</a> |
2,530,104 | Can someone tell me, what the href with the "#" means?
```
<a id="logoutLink" href="#">Logout</a>
``` | 2010/03/27 | [
"https://Stackoverflow.com/questions/2530104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198183/"
]
| As others have pointed out, hash anchors (those beginning with the # sign) typically lead to a named anchor on the page. A table of contents on a page might be a good example of where you'd see this:
```
<ul>
<li><a href="#history">Company History</a></li>
<li><a href="#goals">Our Goals</a></li>
<li><a href="#products">Products We Offer</a></li>
<li><a href="#services">Services We Offer</a></li>
</ul>
<h2><a name="history">History</a></h2>
<p>The #history anchor tag will lead to the named anchor above.</p>
<h2><a name="goals">Our Goals</a></h2>
<p>The #goals anchor tag will lead to the named anchor above.</p>
<h2><a name="products">Products We Offer</a></h2>
<p>The #products anchor tag will lead to the named anchor above.</p>
<h2><a name="services">Services We Offer</a></h2>
<p>The #services anchor tag will lead to the named anchor above.</p>
```
One thing to note is that when you have a blank hash as the anchor href (i.e.: `<a href="#">Blah</a>`), some browsers make that jump to the top of the page, which is not the desired effect. To work around this and prevent the page from scrolling all the way to the top, a JavaScript implementation is often included to prevent the anchor tag from acting as it normally would by returning false.
```
<a href="#" onclick="return false;">Blah</a>
``` | It means nothing... ;) Normally we use `#something` to create anchor to some element. If your URL ends with `...#comments` then your browser will automatiacly jump (scroll the page) to element with `id="comments"`.
`href="#"` is often used to create a link that leads to nowhere. |
2,530,104 | Can someone tell me, what the href with the "#" means?
```
<a id="logoutLink" href="#">Logout</a>
``` | 2010/03/27 | [
"https://Stackoverflow.com/questions/2530104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198183/"
]
| It is the shortest way to say "go nowhere" :)
Often something else is bound to that link, a javascript event handler in most cases. But if an `<a>` doesn't have a `href`, most browsers don't render it with the same styling...so you need a short something to put there.
If it had something following the hash, like `<a href="#topics">Go to Topics</a>` it is a scroll to link, it goes to where the element with `id="topics"` is at the top of the page. A common example is `<a href="#top">Go to Top</a>`, and you stick a `<div id="top"></div>` at the very top of the page. | It means nothing... ;) Normally we use `#something` to create anchor to some element. If your URL ends with `...#comments` then your browser will automatiacly jump (scroll the page) to element with `id="comments"`.
`href="#"` is often used to create a link that leads to nowhere. |
5,193,743 | **Prove by induction**.Every **partial order** on a **nonempty finite** set at least one **minimal** element.
How can **I** solve that question ? | 2011/03/04 | [
"https://Stackoverflow.com/questions/5193743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| It is trivially true if there is only one element in the poset. Now suppose it is true for all sets of size < n. Compare the nth element to the minimal element of the (n-1) poset, which we know to exist. It will either be the new minimal or not or incomparable. It doesn't matter either way. (Why?) | If the partial order has size 1, it is obvious.
Assume it is true for partial orders `<n`, and then take a partial order `(P,<)` has size `n`.
Pick `x` in `P`. Let `P(<x) = { y in P : y<x }`
If `P(<x)` is empty, then `x` is a minimal element.
Otherwise, `P(<x)` is strictly smaller than `P`, since `x` is not in `P(<x)`. So the poset `(P(<x),<)`
must have a minimal element, `y`.
This `y` must be a minimal element of `P` since, if `z<y` in `P`, then `z<x`, and hence `z` would be in `P(<x)` and smaller than `y`, which contradicts the assumption that `y` was minimal in `P(<x)`. |
35,984,783 | ```js
// Code goes here
angular
.module('imgapp', [])
.controller('mainCtrl', mainCtrl);
function mainCtrl() {
var vm = this;
vm.first = {
title: 'Image 1',
url: 'http://www.image-mapper.com/photos/original/missing.png'
}
vm.second = {
title: 'Image 2',
url: 'http://www.keenthemes.com/preview/conquer/assets/plugins/jcrop/demos/demo_files/image1.jpg'
}
vm.primary = vm.first;
vm.changeObject = function() {
vm.primary = vm.second;
}
}
```
```html
<html ng-app="imgapp">
<head>
<script data-require="[email protected]" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="mainCtrl as vm">
<button ng-click="vm.changeObject();">Change object</button>
<h1>{{vm.primary.title}}</h1>
<img ng-src="{{vm.primary.url}}">
</body>
</html>
```
I have a block with a title and an image in it. Data in this block **can** be changed, therefore another image should be loaded.
If you have slow internet connection, you can see that the title was changed, where image **wasn't**, cause it hasn't loaded yet.
[Demo](http://plnkr.co/edit/wfzWKIeu1vllJKAzBJde?p=preview): (press `change object` to load a new image and change the title)
**How can I hide an old image until a new image has been loaded?**
*Note: I don't use jQuery* | 2016/03/14 | [
"https://Stackoverflow.com/questions/35984783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598876/"
]
| [Working demo](http://plnkr.co/edit/byJc95CyVaxNJYOxqblW?p=info)
I have just created a directive which will call a function upon image load.
```
.directive('imageonload', function() {
return {
restrict: 'A',
scope: {
ngShow : '='
},
link: function(scope, element, attrs) {
element.bind('load', function() {
alert('image is loaded');
scope.$apply(function(){
scope.ngShow = true;
});
});
element.bind('error', function(){
alert('image could not be loaded');
});
}
};
});
```
And modified html like,
```
<img ng-show="vm.isImageVisible" ng-src="{{vm.primary.url}}" imageonload >
``` | I believe you're looking for ng-cloak directive: <https://docs.angularjs.org/api/ng/directive/ngCloak>
So your example can look like this:
```
<body ng-controller="mainCtrl as vm">
<button ng-click="vm.changeObject();">Change object</button>
<div ng-cloak>
<h1>{{vm.primary.title}}</h1>
<img ng-src="{{vm.primary.url}}">
</div>
</body>
```
<http://plnkr.co/edit/rf8hM9JvR7EnjS1eWOgp?p=preview> |
35,984,783 | ```js
// Code goes here
angular
.module('imgapp', [])
.controller('mainCtrl', mainCtrl);
function mainCtrl() {
var vm = this;
vm.first = {
title: 'Image 1',
url: 'http://www.image-mapper.com/photos/original/missing.png'
}
vm.second = {
title: 'Image 2',
url: 'http://www.keenthemes.com/preview/conquer/assets/plugins/jcrop/demos/demo_files/image1.jpg'
}
vm.primary = vm.first;
vm.changeObject = function() {
vm.primary = vm.second;
}
}
```
```html
<html ng-app="imgapp">
<head>
<script data-require="[email protected]" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="mainCtrl as vm">
<button ng-click="vm.changeObject();">Change object</button>
<h1>{{vm.primary.title}}</h1>
<img ng-src="{{vm.primary.url}}">
</body>
</html>
```
I have a block with a title and an image in it. Data in this block **can** be changed, therefore another image should be loaded.
If you have slow internet connection, you can see that the title was changed, where image **wasn't**, cause it hasn't loaded yet.
[Demo](http://plnkr.co/edit/wfzWKIeu1vllJKAzBJde?p=preview): (press `change object` to load a new image and change the title)
**How can I hide an old image until a new image has been loaded?**
*Note: I don't use jQuery* | 2016/03/14 | [
"https://Stackoverflow.com/questions/35984783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598876/"
]
| [Working demo](http://plnkr.co/edit/byJc95CyVaxNJYOxqblW?p=info)
I have just created a directive which will call a function upon image load.
```
.directive('imageonload', function() {
return {
restrict: 'A',
scope: {
ngShow : '='
},
link: function(scope, element, attrs) {
element.bind('load', function() {
alert('image is loaded');
scope.$apply(function(){
scope.ngShow = true;
});
});
element.bind('error', function(){
alert('image could not be loaded');
});
}
};
});
```
And modified html like,
```
<img ng-show="vm.isImageVisible" ng-src="{{vm.primary.url}}" imageonload >
``` | This may help you:
```
var image = imageDomReferenceHere;
var downloadingImage = new Image();
downloadingImage.onload = function(){
image.src = this.src;
};
downloadingImage.src = "image path here";
```
<http://blog.teamtreehouse.com/learn-asynchronous-image-loading-javascript> |
35,984,783 | ```js
// Code goes here
angular
.module('imgapp', [])
.controller('mainCtrl', mainCtrl);
function mainCtrl() {
var vm = this;
vm.first = {
title: 'Image 1',
url: 'http://www.image-mapper.com/photos/original/missing.png'
}
vm.second = {
title: 'Image 2',
url: 'http://www.keenthemes.com/preview/conquer/assets/plugins/jcrop/demos/demo_files/image1.jpg'
}
vm.primary = vm.first;
vm.changeObject = function() {
vm.primary = vm.second;
}
}
```
```html
<html ng-app="imgapp">
<head>
<script data-require="[email protected]" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="mainCtrl as vm">
<button ng-click="vm.changeObject();">Change object</button>
<h1>{{vm.primary.title}}</h1>
<img ng-src="{{vm.primary.url}}">
</body>
</html>
```
I have a block with a title and an image in it. Data in this block **can** be changed, therefore another image should be loaded.
If you have slow internet connection, you can see that the title was changed, where image **wasn't**, cause it hasn't loaded yet.
[Demo](http://plnkr.co/edit/wfzWKIeu1vllJKAzBJde?p=preview): (press `change object` to load a new image and change the title)
**How can I hide an old image until a new image has been loaded?**
*Note: I don't use jQuery* | 2016/03/14 | [
"https://Stackoverflow.com/questions/35984783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598876/"
]
| [Working demo](http://plnkr.co/edit/byJc95CyVaxNJYOxqblW?p=info)
I have just created a directive which will call a function upon image load.
```
.directive('imageonload', function() {
return {
restrict: 'A',
scope: {
ngShow : '='
},
link: function(scope, element, attrs) {
element.bind('load', function() {
alert('image is loaded');
scope.$apply(function(){
scope.ngShow = true;
});
});
element.bind('error', function(){
alert('image could not be loaded');
});
}
};
});
```
And modified html like,
```
<img ng-show="vm.isImageVisible" ng-src="{{vm.primary.url}}" imageonload >
``` | You can do it with two steps. First add **ng-show** to hide or show element when it is loading. Second use **onLoad** event to know when it is done loading. I picked directive from this [answer](https://stackoverflow.com/questions/17884399/image-loaded-event-in-for-ng-src-in-angularjs)
**html**
```
vm.notLoading = true;
vm.imageLoaded = imageLoaded;
```
**directive**
```
function imageonload() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
//call the function that was passed
scope.$apply(attrs.imageonload);
});
}
}
```
**controller**
```
...
vm.notLoading = true;
vm.imageLoaded = imageLoaded;
...
vm.changeObject = function() {
vm.notLoading = false;
vm.primary = vm.second;
}
function imageLoaded() {
vm.notLoading = true;
}
```
[plunker](http://plnkr.co/edit/fmst3xQfXaEHbMkkqy7N?p=preview) |
43,791,292 | So I have two fields in s template page:
```
<?php echo get_post_field('post_content', 12345); ?>
<?php the_field('advertisement_one', 12345); ?>
```
The first field renders as:
```
<p>
<img src="test.jpg">
</p>
```
The second field renders as:
```
<p>
<img src="test2.jpg">
</p>
```
Is there a way that I can just pull the text content from the "src" in both fields?
My goal is to write/display:
```
test.jpg
or
test2.jpg
``` | 2017/05/04 | [
"https://Stackoverflow.com/questions/43791292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7082108/"
]
| Quoting the [Redux FAQ entry on dispatching multiple actions](http://redux.js.org/docs/faq/Actions.html#actions-multiple-actions):
>
> There's no specific rule for how you should structure your actions. Using an async middleware like Redux Thunk certainly enables scenarios such as dispatching multiple distinct but related actions in a row, dispatching actions to represent progression of an AJAX request, dispatching actions conditionally based on state, or even dispatching an action and checking the updated state immediately afterwards.
>
>
> In general, ask if these actions are related but independent, or should actually be represented as one action. Do what makes sense for your own situation but try to balance the readability of reducers with readability of the action log. For example, an action that includes the whole new state tree would make your reducer a one-liner, but the downside is now you have no history of why the changes are happening, so debugging gets really difficult. On the other hand, if you emit actions in a loop to keep them granular, it's a sign that you might want to introduce a new action type that is handled in a different way.
>
>
> Try to avoid dispatching several times synchronously in a row in the places where you're concerned about performance. There are a number of addons and approaches that can batch up dispatches as well.
>
>
> | I would say your first approach is better and that is the one I use commonly. Yes it may affect readability of your code when you multiple reducers are acting upon same action type but it helps keep code less verbose (which is my major complain with React ecosystem) and a bit of performance. Actions like login would not have huge impact on performance but when I am making API calls on user actions, I just handle same action type in multiple reducers. For readability, I add comments and documentation. |
43,791,292 | So I have two fields in s template page:
```
<?php echo get_post_field('post_content', 12345); ?>
<?php the_field('advertisement_one', 12345); ?>
```
The first field renders as:
```
<p>
<img src="test.jpg">
</p>
```
The second field renders as:
```
<p>
<img src="test2.jpg">
</p>
```
Is there a way that I can just pull the text content from the "src" in both fields?
My goal is to write/display:
```
test.jpg
or
test2.jpg
``` | 2017/05/04 | [
"https://Stackoverflow.com/questions/43791292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7082108/"
]
| I would say your first approach is better and that is the one I use commonly. Yes it may affect readability of your code when you multiple reducers are acting upon same action type but it helps keep code less verbose (which is my major complain with React ecosystem) and a bit of performance. Actions like login would not have huge impact on performance but when I am making API calls on user actions, I just handle same action type in multiple reducers. For readability, I add comments and documentation. | Do you really need to store the user icon in Redux? A better approach in this case is to have a selector that returns the icon based on the logged in user. That way you can keep the minimal amount of state in the store.
You can use the [Reselect](https://github.com/reactjs/reselect) library to cache selectors. |
43,791,292 | So I have two fields in s template page:
```
<?php echo get_post_field('post_content', 12345); ?>
<?php the_field('advertisement_one', 12345); ?>
```
The first field renders as:
```
<p>
<img src="test.jpg">
</p>
```
The second field renders as:
```
<p>
<img src="test2.jpg">
</p>
```
Is there a way that I can just pull the text content from the "src" in both fields?
My goal is to write/display:
```
test.jpg
or
test2.jpg
``` | 2017/05/04 | [
"https://Stackoverflow.com/questions/43791292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7082108/"
]
| Quoting the [Redux FAQ entry on dispatching multiple actions](http://redux.js.org/docs/faq/Actions.html#actions-multiple-actions):
>
> There's no specific rule for how you should structure your actions. Using an async middleware like Redux Thunk certainly enables scenarios such as dispatching multiple distinct but related actions in a row, dispatching actions to represent progression of an AJAX request, dispatching actions conditionally based on state, or even dispatching an action and checking the updated state immediately afterwards.
>
>
> In general, ask if these actions are related but independent, or should actually be represented as one action. Do what makes sense for your own situation but try to balance the readability of reducers with readability of the action log. For example, an action that includes the whole new state tree would make your reducer a one-liner, but the downside is now you have no history of why the changes are happening, so debugging gets really difficult. On the other hand, if you emit actions in a loop to keep them granular, it's a sign that you might want to introduce a new action type that is handled in a different way.
>
>
> Try to avoid dispatching several times synchronously in a row in the places where you're concerned about performance. There are a number of addons and approaches that can batch up dispatches as well.
>
>
> | Do you really need to store the user icon in Redux? A better approach in this case is to have a selector that returns the icon based on the logged in user. That way you can keep the minimal amount of state in the store.
You can use the [Reselect](https://github.com/reactjs/reselect) library to cache selectors. |
9,918,005 | I'm working on a scavenger hunt app and I'm stuck. So I've set up the CRUD for the hunts and for the tasks associated with hunts. But I don't know how to set it up so that the user can associate a particular task with a particular hunt. I think I've got the models setup correctly, but I'm not really sure how to setup the views that allow this association of tasks with a hunt.
```
class Hunt < ActiveRecord::Base
has_many :tasks
attr_accessible :name
validates :name, :presence => true,
:length => { :maximum => 50 } ,
:uniqueness => { :case_sensitive => false }
end
class Task < ActiveRecord::Base
belongs_to :hunts
attr_accessible :name
validates :name, :presence => true,
:length => { :maximum => 50 } ,
:uniqueness => { :case_sensitive => false }
end
```
I'm guessing I need write a view that shows a hunt and then lists all the available tasks. Then I need a way to for the user to "pick" a task and add it to a hunt. It's this last part that has me stumped. | 2012/03/29 | [
"https://Stackoverflow.com/questions/9918005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144475/"
]
| >
> I'm guessing I need write a view that shows a hunt and then lists all the available tasks. Then I need a way to for the user to "pick" a task and add it to a hunt. It's this last part that has me stumped.
>
>
>
Above implies that there's a `has_and_belongs_to_many` (`*..*`) relationship between `Hunt` and `Task` and not `has_many` (since a Hunt can be associated with multiple Tasks and a Task can belong to multiple Hunts within your system).
You could go with:
```
class Hunt < ActiveRecord::Base
[...]
has_and_belongs_to_many :tasks
[...]
end # Hunt
class Task < ActiveRecord::Base
[...]
has_and_belongs_to_many :hunts
[...]
end
```
Doing so shall enable you to associate multiple Tasks (or you could associate just one if you want) and also having a Task belong to more than one Hunts. Further, you could go with a simple `f.select` form tag helper to render a list of available Tasks in your system.
Hope this helps. | Your `belongs_to` declaration in the `Task` class should be for `:hunt`, not `:hunts`.
As far as the view goes, it's pretty simple. Just use `f.select` (assuming your form helper variable name is `f`) on `:hunt_id`, and update the `hunt_id` attribute inside `Task`.
This will associate the `Hunt` with the `Task`.
Be sure to check out `options_for_select`, so you can display the `Hunt` name with the `hunt_id` option value in the form. I also recommend reading through the Rails guide on associations: <http://guides.rubyonrails.org/association_basics.html> |
9,918,005 | I'm working on a scavenger hunt app and I'm stuck. So I've set up the CRUD for the hunts and for the tasks associated with hunts. But I don't know how to set it up so that the user can associate a particular task with a particular hunt. I think I've got the models setup correctly, but I'm not really sure how to setup the views that allow this association of tasks with a hunt.
```
class Hunt < ActiveRecord::Base
has_many :tasks
attr_accessible :name
validates :name, :presence => true,
:length => { :maximum => 50 } ,
:uniqueness => { :case_sensitive => false }
end
class Task < ActiveRecord::Base
belongs_to :hunts
attr_accessible :name
validates :name, :presence => true,
:length => { :maximum => 50 } ,
:uniqueness => { :case_sensitive => false }
end
```
I'm guessing I need write a view that shows a hunt and then lists all the available tasks. Then I need a way to for the user to "pick" a task and add it to a hunt. It's this last part that has me stumped. | 2012/03/29 | [
"https://Stackoverflow.com/questions/9918005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144475/"
]
| Some good sources of information are:
1. [Ruby on Rails Guides: ActionView Helpers](http://guides.rubyonrails.org/form_helpers.html) - gives a good starting point and overview
2. [Blog on dealing with Categories](http://agilewarrior.wordpress.com/2011/10/22/rails-drop-downs/) - discusses using categories derived from the associate table and presenting them in the view
3. [Rails Casts Nested Model](http://railscasts.com/episodes/196-nested-model-form-part-1) - this shows how to deal with a nested or has\_many relationship.
Now on the question of adding the task and adding a hunt, with a form that uses the nested attributes you can have a view that displays the task, allowing to add the hunt. The adding operation may require some Javascript (as demonstrated in RailsCasts), or otherwise have popup that executes a *hunt.tasks.build* in the controller. The build, on the association will assign the current hunt id to the task that is created.
Now if you have a list of tasks pre-assigned to the hunt you would need to have the form display the select list for the tasks belonging to the hunt. Using the nested attributes in the model definition as in:
```
class Hunt < ActiveRecord::Base
has_many :tasks
accepts_nested_attributes_for :tasks
end
class Task < ActiveRecord::Base
belongs_to :hunts
end
```
So now on the form submit the params will be posted with the associated task id nested allowing you to do the update\_attributes.
More details are in [Rails API accepts nested attributes](http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for) and the RailsCast reference will give a step by step example. | Your `belongs_to` declaration in the `Task` class should be for `:hunt`, not `:hunts`.
As far as the view goes, it's pretty simple. Just use `f.select` (assuming your form helper variable name is `f`) on `:hunt_id`, and update the `hunt_id` attribute inside `Task`.
This will associate the `Hunt` with the `Task`.
Be sure to check out `options_for_select`, so you can display the `Hunt` name with the `hunt_id` option value in the form. I also recommend reading through the Rails guide on associations: <http://guides.rubyonrails.org/association_basics.html> |
570,738 | I created a Nagios check which checks our pacemaker using the `crm_mon` command.
The check is configured in the same way on both Nagios server and client's `nrpe.cfg`:
The command definition in `nrpe.cfg` looks like that:
```
[root@Nagios_clt plugins]# grep pacemaker /etc/nagios/nrpe.cfg
command[check_pacemaker]=/usr/bin/sudo /usr/sbin/crm_mon -s
```
I did two tests:
In the first one, I'm just using the line you see above and then from the Nagios server I get:
```
[root@Nagios_srv ]# /usr/lib64/nagios/plugins/check_nrpe -H 192.168.57.157 -c check_pacemaker
NRPE: Unable to read output
[root@Nagios_srv ]# /usr/lib64/nagios/plugins/check_nrpe -H 192.168.57.157
NRPE v2.14
```
In the second one, I wrote a different command definition:
```
[root@Nagios_srv ]# grep pacemaker /etc/nagios/nrpe.cfg
command[check_pacemaker]=/usr/lib64/nagios/plugins/check_pacemaker.sh
```
While `/usr/lib64/nagios/plugins/check_pacemaker.sh` looks like that:
```
[root@Nagios_svr ]# cat /usr/lib64/nagios/plugins/check_pacemaker.sh
#!/bin/bash
/usr/bin/sudo /usr/sbin/crm_mon -s
```
I've chmod +x the `check_pacemaker.sh` file.
None of these worked.
If I run the `check_pacemaker.sh` file locally on the Nagios client, I get the correct result:
```
[root@Nagios_clt ]# /usr/lib64/nagios/plugins/check_pacemaker.sh
Ok: 2 nodes online, 10 resources configured
```
If I run the command locally using `check_nrpe` I get this result:
```
[root@Nagios_clt plugins]# /usr/lib64/nagios/plugins/check_nrpe -H localhost
NRPE v2.14
[root@Nagios_clt plugins]# /usr/lib64/nagios/plugins/check_nrpe -H localhost -c check_pacemaker
NRPE: Unable to read output
```
Some other stuff I've configured:
```
[root@Nagios_clt plugins]# grep Defaults /etc/sudoers
#Defaults requiretty
[root@Nagios_clt plugins]# grep nagios /etc/sudoers
nagios ALL=NOPASSWD:/usr/lib64/nagios/plugins/*
```
The check\_command looks like that:
```
define command{
command_name check_pacemaker
command_line /usr/lib64/nagios/plugins/check_pacemaker.sh
}
[root@Nagios_clt plugins]# service iptables status
iptables: Firewall is not running.
```
Other checks on this server are working using nrpe:

And I don't understand why, does anyone have an idea? | 2014/01/29 | [
"https://serverfault.com/questions/570738",
"https://serverfault.com",
"https://serverfault.com/users/109833/"
]
| Your issue is lack of clarity about who's running what with `sudo`. Your plugin calls crm\_mon with `sudo /usr/bin/crm_mon`, but instead of giving the `nagios` user sudo privileges to run the `crm_mon` binary, it only has privileges to run plugins (ie, anything in `/usr/lib64/nagios/plugins/`).
**Either** add passwordless sudo privileges for the `/usr/bin/crm_mon` binary for the `nagios` user, **or** change the plugin invocation to use sudo:
```
define command{
command_name check_pacemaker
command_line sudo /usr/lib64/nagios/plugins/check_pacemaker.sh
}
```
and remove the `sudo` from `check_pacemaker.sh`. | When troubleshooting a command run as a regular user via nrpe, you can fully imitate the solution, sudo and all, with another user first. Stop testing it as root.
You might find there is an issue with the sudoers set up, or there may be file access issues on secondary files such as those under /etc or /var used by the shell script.
Whatever the problem is, you can see the actual error by setting up your non-root user (e.g. itai) to have the same sudoers rights and try /usr/lib64/nagios/plugins/check\_pacemaker.sh as that user. nrpe does not pass back errors, so you'll never get clues that way. |
34,312,938 | ### Introduction
I need to serialize a java object (`Fahrweg`) that contains nested objects (all implement the interface `FahrwegEreignis`) to json.
My code to do this is as follows:
```
Fahrweg fahrweg = new Fahrweg();
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(FahrwegEreignis.class, FahrwegEreignisMixIn.class);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
try {
String json = ow.writeValueAsString(fahrweg);
System.out.print(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
```
By default, the type of the object is not contained in the resulting json (I assume because JS is dynamically typed).
I would like to add a field to every object about like so: `"type" : "classname"`.
I've read about the Jackson annotations, and I'm using mixin because I cannot modify the classes in question. My mixin interface (`FahrwegEreignisMixIn`) looks like this:
```
import com.fasterxml.jackson.annotation.JsonProperty;
public interface FahrwegEreignisMixIn {
@JsonProperty("type")
//TODO
}
```
### Question
What do I need to put at `//TODO`?
My first instinct was `Class<?> getClass();` but that doesn't work.
### Answer
The answer in the duplicate question worked for me. I had to change
my `FahrwegEreignisMixIn` to this:
```
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "type")
public interface FahrwegEreignisMixIn {}
``` | 2015/12/16 | [
"https://Stackoverflow.com/questions/34312938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2941551/"
]
| I managed to solve the problem.
By mistake my AndroidManifest.xml file did not include the Service. | In my case the problem was that I declared the Service in the androidTest Manifest file, which isn't working for any reason. |
17,692,637 | So I have a form, when the form is filled and submit is pressed, I want the form to be "hidden" away and for a few images to appear.
However, I am currently stuck on "hiding" away the form because I need the form to appear again after the user presses a back button on the page(not on the browser) and I also need the values on the form to be brought forward to that page after submit is pressed.
form:
```
<form id = "step1" onsubmit = "return formcheck()">
<p>
Creator:
<select name="creator" id = "creator">
<option></option>
<option name = "abc" value = "nba">nba</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
Trip Title:
<select name="title" id = "title">
<option></option>
<option value = "cba">cbz</option>
</select>
</p>
<p>
Device:
<select name="device" id = "device">
<option name = "SN" value = "SN">Samsung Note</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
No. of devices:
<select id = "deviceno" name = "deviceno">
<option></option>
<option value = "1">1</option>
</select>
</p>
<p>
<input type="submit" name="next" id="next" value="Next"></input>
</p>
</form>
```
javascript function formcheck():
```
function formcheck()
{
var Ccreator = document.getElementById('creator').value;
var Ctitle = document.getElementById('title').value;
var Cdevice = document.getElementById('device').value;
var Cdeviceno = document.getElementById('deviceno').value;
if(Ccreator == ""||Ctitle == ""||Cdevice == ""||Cdeviceno == "")
{
alert("Form incomplete!");
return false;
}
else
{
$("#step1").hide();
return true;
}
}
``` | 2013/07/17 | [
"https://Stackoverflow.com/questions/17692637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527131/"
]
| Your issue is just after validating the form values you are returning 'true'. so the form get submitted and page gets refreshed and then again your file comes to the initial state and form get visible | you could use jquery ui tabs <http://jqueryui.com/tabs/>
or some kind of pagination like this plugin <http://archive.plugins.jquery.com/project/pagination> |
17,692,637 | So I have a form, when the form is filled and submit is pressed, I want the form to be "hidden" away and for a few images to appear.
However, I am currently stuck on "hiding" away the form because I need the form to appear again after the user presses a back button on the page(not on the browser) and I also need the values on the form to be brought forward to that page after submit is pressed.
form:
```
<form id = "step1" onsubmit = "return formcheck()">
<p>
Creator:
<select name="creator" id = "creator">
<option></option>
<option name = "abc" value = "nba">nba</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
Trip Title:
<select name="title" id = "title">
<option></option>
<option value = "cba">cbz</option>
</select>
</p>
<p>
Device:
<select name="device" id = "device">
<option name = "SN" value = "SN">Samsung Note</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
No. of devices:
<select id = "deviceno" name = "deviceno">
<option></option>
<option value = "1">1</option>
</select>
</p>
<p>
<input type="submit" name="next" id="next" value="Next"></input>
</p>
</form>
```
javascript function formcheck():
```
function formcheck()
{
var Ccreator = document.getElementById('creator').value;
var Ctitle = document.getElementById('title').value;
var Cdevice = document.getElementById('device').value;
var Cdeviceno = document.getElementById('deviceno').value;
if(Ccreator == ""||Ctitle == ""||Cdevice == ""||Cdeviceno == "")
{
alert("Form incomplete!");
return false;
}
else
{
$("#step1").hide();
return true;
}
}
``` | 2013/07/17 | [
"https://Stackoverflow.com/questions/17692637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527131/"
]
| Make sure you have included [jQuery](http://jquery.com/) to your html script as the [$(form).hide()](http://api.jquery.com/hide/) is not a pure js method, Check the working demo [here](http://jsfiddle.net/RBBte/1/). You can hide the form in javascript by
```
document.getElementById("your form id").style.display="none";
```
and please be noted that if you are returning true form the formcheck() method, the form gets submitted and page will be refreshed. | you could use jquery ui tabs <http://jqueryui.com/tabs/>
or some kind of pagination like this plugin <http://archive.plugins.jquery.com/project/pagination> |
17,692,637 | So I have a form, when the form is filled and submit is pressed, I want the form to be "hidden" away and for a few images to appear.
However, I am currently stuck on "hiding" away the form because I need the form to appear again after the user presses a back button on the page(not on the browser) and I also need the values on the form to be brought forward to that page after submit is pressed.
form:
```
<form id = "step1" onsubmit = "return formcheck()">
<p>
Creator:
<select name="creator" id = "creator">
<option></option>
<option name = "abc" value = "nba">nba</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
Trip Title:
<select name="title" id = "title">
<option></option>
<option value = "cba">cbz</option>
</select>
</p>
<p>
Device:
<select name="device" id = "device">
<option name = "SN" value = "SN">Samsung Note</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
No. of devices:
<select id = "deviceno" name = "deviceno">
<option></option>
<option value = "1">1</option>
</select>
</p>
<p>
<input type="submit" name="next" id="next" value="Next"></input>
</p>
</form>
```
javascript function formcheck():
```
function formcheck()
{
var Ccreator = document.getElementById('creator').value;
var Ctitle = document.getElementById('title').value;
var Cdevice = document.getElementById('device').value;
var Cdeviceno = document.getElementById('deviceno').value;
if(Ccreator == ""||Ctitle == ""||Cdevice == ""||Cdeviceno == "")
{
alert("Form incomplete!");
return false;
}
else
{
$("#step1").hide();
return true;
}
}
``` | 2013/07/17 | [
"https://Stackoverflow.com/questions/17692637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527131/"
]
| Your issue is just after validating the form values you are returning 'true'. so the form get submitted and page gets refreshed and then again your file comes to the initial state and form get visible | ```
<form id="step1">
<p>
Creator:
<select name="creator" id = "creator">
<option></option>
<option name = "abc" value = "nba">nba</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
Trip Title:
<select name="title" id = "title">
<option></option>
<option value = "cba">cbz</option>
</select>
</p>
<p>
Device:
<select name="device" id = "device">
<option name = "SN" value = "SN">Samsung Note</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
No. of devices:
<select id = "deviceno" name = "deviceno">
<option></option>
<option value = "1">1</option>
</select>
</p>
<p>
<input type="submit" name="next" id="next" value="Next"></input>
</p>
</form>
```
jquery:
```
$('#next').click(function(){
return false;
$('#step1').hide();
// show anything here.
})
``` |
17,692,637 | So I have a form, when the form is filled and submit is pressed, I want the form to be "hidden" away and for a few images to appear.
However, I am currently stuck on "hiding" away the form because I need the form to appear again after the user presses a back button on the page(not on the browser) and I also need the values on the form to be brought forward to that page after submit is pressed.
form:
```
<form id = "step1" onsubmit = "return formcheck()">
<p>
Creator:
<select name="creator" id = "creator">
<option></option>
<option name = "abc" value = "nba">nba</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
Trip Title:
<select name="title" id = "title">
<option></option>
<option value = "cba">cbz</option>
</select>
</p>
<p>
Device:
<select name="device" id = "device">
<option name = "SN" value = "SN">Samsung Note</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
No. of devices:
<select id = "deviceno" name = "deviceno">
<option></option>
<option value = "1">1</option>
</select>
</p>
<p>
<input type="submit" name="next" id="next" value="Next"></input>
</p>
</form>
```
javascript function formcheck():
```
function formcheck()
{
var Ccreator = document.getElementById('creator').value;
var Ctitle = document.getElementById('title').value;
var Cdevice = document.getElementById('device').value;
var Cdeviceno = document.getElementById('deviceno').value;
if(Ccreator == ""||Ctitle == ""||Cdevice == ""||Cdeviceno == "")
{
alert("Form incomplete!");
return false;
}
else
{
$("#step1").hide();
return true;
}
}
``` | 2013/07/17 | [
"https://Stackoverflow.com/questions/17692637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527131/"
]
| Make sure you have included [jQuery](http://jquery.com/) to your html script as the [$(form).hide()](http://api.jquery.com/hide/) is not a pure js method, Check the working demo [here](http://jsfiddle.net/RBBte/1/). You can hide the form in javascript by
```
document.getElementById("your form id").style.display="none";
```
and please be noted that if you are returning true form the formcheck() method, the form gets submitted and page will be refreshed. | ```
<form id="step1">
<p>
Creator:
<select name="creator" id = "creator">
<option></option>
<option name = "abc" value = "nba">nba</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
Trip Title:
<select name="title" id = "title">
<option></option>
<option value = "cba">cbz</option>
</select>
</p>
<p>
Device:
<select name="device" id = "device">
<option name = "SN" value = "SN">Samsung Note</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
No. of devices:
<select id = "deviceno" name = "deviceno">
<option></option>
<option value = "1">1</option>
</select>
</p>
<p>
<input type="submit" name="next" id="next" value="Next"></input>
</p>
</form>
```
jquery:
```
$('#next').click(function(){
return false;
$('#step1').hide();
// show anything here.
})
``` |
17,692,637 | So I have a form, when the form is filled and submit is pressed, I want the form to be "hidden" away and for a few images to appear.
However, I am currently stuck on "hiding" away the form because I need the form to appear again after the user presses a back button on the page(not on the browser) and I also need the values on the form to be brought forward to that page after submit is pressed.
form:
```
<form id = "step1" onsubmit = "return formcheck()">
<p>
Creator:
<select name="creator" id = "creator">
<option></option>
<option name = "abc" value = "nba">nba</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
Trip Title:
<select name="title" id = "title">
<option></option>
<option value = "cba">cbz</option>
</select>
</p>
<p>
Device:
<select name="device" id = "device">
<option name = "SN" value = "SN">Samsung Note</option>
<option name = "abc" value = "abc"> oiasfn</option>
</select>
</p>
<p>
No. of devices:
<select id = "deviceno" name = "deviceno">
<option></option>
<option value = "1">1</option>
</select>
</p>
<p>
<input type="submit" name="next" id="next" value="Next"></input>
</p>
</form>
```
javascript function formcheck():
```
function formcheck()
{
var Ccreator = document.getElementById('creator').value;
var Ctitle = document.getElementById('title').value;
var Cdevice = document.getElementById('device').value;
var Cdeviceno = document.getElementById('deviceno').value;
if(Ccreator == ""||Ctitle == ""||Cdevice == ""||Cdeviceno == "")
{
alert("Form incomplete!");
return false;
}
else
{
$("#step1").hide();
return true;
}
}
``` | 2013/07/17 | [
"https://Stackoverflow.com/questions/17692637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527131/"
]
| Make sure you have included [jQuery](http://jquery.com/) to your html script as the [$(form).hide()](http://api.jquery.com/hide/) is not a pure js method, Check the working demo [here](http://jsfiddle.net/RBBte/1/). You can hide the form in javascript by
```
document.getElementById("your form id").style.display="none";
```
and please be noted that if you are returning true form the formcheck() method, the form gets submitted and page will be refreshed. | Your issue is just after validating the form values you are returning 'true'. so the form get submitted and page gets refreshed and then again your file comes to the initial state and form get visible |
139,829 | I know this could be a strange question. But was there any algorithm ever found to compute an NP-problem, whether it be hard or complete, in polynomial time. I know this dabbles into the "does P=NP" problem, but I was wondering whether there were any particular instances when people were close to it. I've also heard about the factoring number problem being solved by a quantum computer by Shor's algorithm. Would this count as an algorithm which solved an NP-problem in polynomial time please ? Please do ask if you want me to clarify any parts in my questions. Thanks in advance. | 2021/05/03 | [
"https://cs.stackexchange.com/questions/139829",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/136141/"
]
| By definition, if you were to find a polynomial time algorithm for an NP-hard (or NP-complete) problem, then $P=NP$. So, short answer is - no.
However, its possible to think instead of solving the problems fully, to [approximate a solution](https://en.wikipedia.org/wiki/Approximation_algorithm), or [to solve them randomly](https://en.wikipedia.org/wiki/Randomized_algorithm). There are attempts at attacking from those points of view, but they are not perfect at all. Randomization isn't known to help "as-is", and many NP-hard problems are known that are also hard to approximate (finding an approximation will yield $P=NP$)
There are also attemps taking a look at notions much *stronger* than the usual turing machine. For instance, the quantum computer can be considered one. Another obvious example is the non-deterministic turing machines, in which - by definition - $NP$ would be in polynomial time. | Strictly speaking, as the other answers explain, no. A polynomial-time algorithm for an NP-hard problem is not known nor expected to exist. But I think your underlying question is whether or not there are examples of natural NP-hard problems that are, in some sense, easier to solve than some other NP-hard problems.
There are several flavors in which you can quantify the hardness of NP-hard problems more closely. For example, there are problems that are extremely difficult to *approximate* (e.g., maximum clique) while some problems we can approximate arbitrarily close (e.g., knapsack). You could also have a look at *exact algorithms*: there are natural problems for which the best algorithms run in time $O^\*(2^n)$ and there is some evidence no algorithms faster than that exists, while others admit runtimes of roughly $O^\*(2^\sqrt{n})$ (e.g., planar problems) or even better. Or, you could look at *parameterized complexity*, where the idea is to do a two-dimensional analysis, i.e., take not only the size of the input $n$ but also pick some additional parameter, such as solution size or some structural parameter $k$. Then, some problems admit algorithms whose runtime is of the form $f(k) n^{O(1)}$, where $f$ is some computable function depending only on $k$, while some problems don't (e.g., $k$-clique). |
139,829 | I know this could be a strange question. But was there any algorithm ever found to compute an NP-problem, whether it be hard or complete, in polynomial time. I know this dabbles into the "does P=NP" problem, but I was wondering whether there were any particular instances when people were close to it. I've also heard about the factoring number problem being solved by a quantum computer by Shor's algorithm. Would this count as an algorithm which solved an NP-problem in polynomial time please ? Please do ask if you want me to clarify any parts in my questions. Thanks in advance. | 2021/05/03 | [
"https://cs.stackexchange.com/questions/139829",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/136141/"
]
| By definition, if you were to find a polynomial time algorithm for an NP-hard (or NP-complete) problem, then $P=NP$. So, short answer is - no.
However, its possible to think instead of solving the problems fully, to [approximate a solution](https://en.wikipedia.org/wiki/Approximation_algorithm), or [to solve them randomly](https://en.wikipedia.org/wiki/Randomized_algorithm). There are attempts at attacking from those points of view, but they are not perfect at all. Randomization isn't known to help "as-is", and many NP-hard problems are known that are also hard to approximate (finding an approximation will yield $P=NP$)
There are also attemps taking a look at notions much *stronger* than the usual turing machine. For instance, the quantum computer can be considered one. Another obvious example is the non-deterministic turing machines, in which - by definition - $NP$ would be in polynomial time. | The other answers are correct, but f I may add an observation: it seems like you are conflating classes of problems and particular instances. There are a number of instances that can be solved in polynomial time in classes that are NP-hard in general. For instance, Boolean satisfiability is NP-hard in general, since it reduces to 3SAT. However, there are a bunch of instances called Horn clauses which can actually be solved in linear time. Notice that these instances are a subset of all instances of SAT. If you do not know whether the instance you have to solve is a Horn clause, the problem is NP-hard. If you do know that your instances are restricted that way, you have HORNSAT, which is in P. It all depends what your input potentially could be, and complexity goes by the worst-case instance. |
139,829 | I know this could be a strange question. But was there any algorithm ever found to compute an NP-problem, whether it be hard or complete, in polynomial time. I know this dabbles into the "does P=NP" problem, but I was wondering whether there were any particular instances when people were close to it. I've also heard about the factoring number problem being solved by a quantum computer by Shor's algorithm. Would this count as an algorithm which solved an NP-problem in polynomial time please ? Please do ask if you want me to clarify any parts in my questions. Thanks in advance. | 2021/05/03 | [
"https://cs.stackexchange.com/questions/139829",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/136141/"
]
| If the answer to the first question were to be yes, then $P=NP$, as stated in [nir shahar](https://cs.stackexchange.com/a/139832/61663)'s answer. This has not been done.
### "The easiest NP hard problem"
However you next asked if any NP-hard problems have been solved in ***close*** to polynomial time, for which you might love to learn about what has been called "[The easiest NP hard problem](http://bit-player.org/wp-content/extras/bph-publications/AmSci-2002-03-Hayes-NPP.pdf)" because there's a [pseudo-polynomial time](https://en.wikipedia.org/wiki/Pseudo-polynomial_time) solution using [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming), and there are [heuristics](https://en.wikipedia.org/wiki/Heuristic) that solve the problem in many cases, sometimes optimally. The problem is the [partitioning problem](https://en.wikipedia.org/wiki/Partition_problem): Decide whether a set of positive integers can be partitioned into two sets such that the sum of the numbers in one set equal the sum of the numbers in the first set. Despite it being an NP-complete problem, it can be solved quite efficiently, as for example described in [this PDF](https://www.ijcai.org/Proceedings/09/Papers/096.pdf). | Strictly speaking, as the other answers explain, no. A polynomial-time algorithm for an NP-hard problem is not known nor expected to exist. But I think your underlying question is whether or not there are examples of natural NP-hard problems that are, in some sense, easier to solve than some other NP-hard problems.
There are several flavors in which you can quantify the hardness of NP-hard problems more closely. For example, there are problems that are extremely difficult to *approximate* (e.g., maximum clique) while some problems we can approximate arbitrarily close (e.g., knapsack). You could also have a look at *exact algorithms*: there are natural problems for which the best algorithms run in time $O^\*(2^n)$ and there is some evidence no algorithms faster than that exists, while others admit runtimes of roughly $O^\*(2^\sqrt{n})$ (e.g., planar problems) or even better. Or, you could look at *parameterized complexity*, where the idea is to do a two-dimensional analysis, i.e., take not only the size of the input $n$ but also pick some additional parameter, such as solution size or some structural parameter $k$. Then, some problems admit algorithms whose runtime is of the form $f(k) n^{O(1)}$, where $f$ is some computable function depending only on $k$, while some problems don't (e.g., $k$-clique). |
139,829 | I know this could be a strange question. But was there any algorithm ever found to compute an NP-problem, whether it be hard or complete, in polynomial time. I know this dabbles into the "does P=NP" problem, but I was wondering whether there were any particular instances when people were close to it. I've also heard about the factoring number problem being solved by a quantum computer by Shor's algorithm. Would this count as an algorithm which solved an NP-problem in polynomial time please ? Please do ask if you want me to clarify any parts in my questions. Thanks in advance. | 2021/05/03 | [
"https://cs.stackexchange.com/questions/139829",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/136141/"
]
| If the answer to the first question were to be yes, then $P=NP$, as stated in [nir shahar](https://cs.stackexchange.com/a/139832/61663)'s answer. This has not been done.
### "The easiest NP hard problem"
However you next asked if any NP-hard problems have been solved in ***close*** to polynomial time, for which you might love to learn about what has been called "[The easiest NP hard problem](http://bit-player.org/wp-content/extras/bph-publications/AmSci-2002-03-Hayes-NPP.pdf)" because there's a [pseudo-polynomial time](https://en.wikipedia.org/wiki/Pseudo-polynomial_time) solution using [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming), and there are [heuristics](https://en.wikipedia.org/wiki/Heuristic) that solve the problem in many cases, sometimes optimally. The problem is the [partitioning problem](https://en.wikipedia.org/wiki/Partition_problem): Decide whether a set of positive integers can be partitioned into two sets such that the sum of the numbers in one set equal the sum of the numbers in the first set. Despite it being an NP-complete problem, it can be solved quite efficiently, as for example described in [this PDF](https://www.ijcai.org/Proceedings/09/Papers/096.pdf). | The other answers are correct, but f I may add an observation: it seems like you are conflating classes of problems and particular instances. There are a number of instances that can be solved in polynomial time in classes that are NP-hard in general. For instance, Boolean satisfiability is NP-hard in general, since it reduces to 3SAT. However, there are a bunch of instances called Horn clauses which can actually be solved in linear time. Notice that these instances are a subset of all instances of SAT. If you do not know whether the instance you have to solve is a Horn clause, the problem is NP-hard. If you do know that your instances are restricted that way, you have HORNSAT, which is in P. It all depends what your input potentially could be, and complexity goes by the worst-case instance. |
2,592,350 | This is a sample from my build.xml
```
<mxmlc
file="${SRC_DIR}/Main.mxml"
output="${DEPLOY_DIR}/@{market}.air"
locale="@{locale}"
debug="false"
optimize="true">
<arg value="+configname=air"/>
<load-config filename="${FLEX_HOME}/frameworks/flex-config.xml"/>
<library-path dir="${FLEX_HOME}/frameworks/libs/air" append="true">
<include name="*.swc" />
</library-path>
</mxmlc>
```
There are no errors produced when this runs and a .air file is produced but when the .air file is double clicked I get the error message:
"The application could not be installed because the AIR file is damaged. Try obtaining a new AIR file from the application author."
Any help would be appreciated. | 2010/04/07 | [
"https://Stackoverflow.com/questions/2592350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63461/"
]
| An example of how to do this is here: <http://blog.devsandbox.co.uk/wp-content/uploads/2009/09/example_air_build.xml> | You need to use the AIR compiler (amxmlc) : <http://livedocs.adobe.com/flex/3/html/help.html?content=CommandLineTools_2.html>
Not sure if they also have an ANT task for this, but it's worth a try. |
4,220,311 | There is a ball drawer.
Seven color balls will be drawn with the same probability ($1/7$).
(black, blue, green, yellow, white, pink, orange)
If Anson attempts $9$ times,
what is the probability that he gets all $7$ different color balls?
My work:
I separate the answer to $3$ ways.
1. $7$ attempts -> done (get $7$ colors)
2. $8$ attempts -> done (get $7$ colors)
3. $9$ attempts -> done (get $7$ colors)
Therefore, my answer is $$\frac{9C7 + 8C7 + 7C7}{7^7 \cdot (7!)}$$
However, I don't know it is correct or not. | 2021/08/09 | [
"https://math.stackexchange.com/questions/4220311",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/957014/"
]
| The statement is equivalent to
$$\DeclareMathOperator{\arccot}{arccot}
\arccot7+\arccot8=\arccot3-\arccot18
$$
The right-hand side is positive because the arccotangent is decreasing, so it is in the interval $(0,\pi/2)$ and we have to ensure that the same holds for the left-hand side, but this is easy, because $7>1$ and $8>1$, hence
$$
\arccot7+\arccot8<2\arccot1=\frac{\pi}{2}
$$
The two sides are equal if and only if their cotangents are.
Since
$$
\cot(\alpha+\beta)=\frac{\cot\alpha\cot\beta-1}{\cot\alpha+\cot\beta}
\qquad
\cot(\alpha-\beta)=\frac{\cot\alpha\cot\beta+1}{\cot\beta-\cot\alpha}
$$
this amounts to proving that
$$
\frac{7\cdot8-1}{7+8}=\frac{3\cdot18+1}{18-3}
$$ | I can't resist, even though your request for a critique makes this response somewhat off-topic. Let the 3 LHS angles be denoted as $a,b,c$, and use the formula
$$\cot(a + b) = \frac{[\cot(a)\cot(b)] - 1}{\cot(a) + \cot(b)}.$$
This gives $\cot(a + b) = \frac{55}{15} = \frac{11}{3}.$
Therefore,
$$\cot[(a+b) + c] = \frac{\left[\left(\frac{11}{3}\right)\left(18\right)\right] - 1}{\frac{11}{3} + 18} = 3.$$
Further, since each of $a,b,c$ are in the first quadrant, as is $(a + b + c)$, you have that $(a + b + c) = \text{Arccot}(3).$ |
4,220,311 | There is a ball drawer.
Seven color balls will be drawn with the same probability ($1/7$).
(black, blue, green, yellow, white, pink, orange)
If Anson attempts $9$ times,
what is the probability that he gets all $7$ different color balls?
My work:
I separate the answer to $3$ ways.
1. $7$ attempts -> done (get $7$ colors)
2. $8$ attempts -> done (get $7$ colors)
3. $9$ attempts -> done (get $7$ colors)
Therefore, my answer is $$\frac{9C7 + 8C7 + 7C7}{7^7 \cdot (7!)}$$
However, I don't know it is correct or not. | 2021/08/09 | [
"https://math.stackexchange.com/questions/4220311",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/957014/"
]
| I can't resist, even though your request for a critique makes this response somewhat off-topic. Let the 3 LHS angles be denoted as $a,b,c$, and use the formula
$$\cot(a + b) = \frac{[\cot(a)\cot(b)] - 1}{\cot(a) + \cot(b)}.$$
This gives $\cot(a + b) = \frac{55}{15} = \frac{11}{3}.$
Therefore,
$$\cot[(a+b) + c] = \frac{\left[\left(\frac{11}{3}\right)\left(18\right)\right] - 1}{\frac{11}{3} + 18} = 3.$$
Further, since each of $a,b,c$ are in the first quadrant, as is $(a + b + c)$, you have that $(a + b + c) = \text{Arccot}(3).$ | Obviously $\pi+\cot^{-1} 3 \neq \cot^{-1} 3$, since $\pi \neq 0$. Your second method is incorrect because $$\tan^{-1} a+\tan^{-1}b+\tan^{-1}c=\tan^{-1} \left(\frac {a+b+c-abc}{1-ab-bc-ac}\right)$$ is only true for $a,b,c>0$ if $ab+bc+ac<1$.
It is better for you to combine the $\arctan$s two at a time. We have:
$$\tan^{-1}7+\tan^{-1}8=\pi-\tan^{-1} \frac {3}{11} {\tag 1}$$
So $$\tan^{-1}7+\tan^{-1}8+\tan^{-1}18=\left(\pi-\tan^{-1} \frac {3}{11}\right)+\tan^{-1}18=\pi+\left(\tan^{-1}18-\tan^{-1} \frac {3}{11}\right)=\pi+\left(\tan^{-1}\frac {195}{65}\right)=\pi+\tan^{-1} 3$$
Thus we get $$\frac {3\pi}{2}-(\tan^{-1}7+\tan^{-1}8+\tan^{-1} 18)=\frac {3\pi}{2}-(\pi+\tan^{-1}3)=\frac {\pi}{2}-\tan^{-1}3=\cot^{-1}3$$ as expected.
**Note:**
$(1)$: I used the formula $\tan^{-1}a+\tan^{-1}b=\pi+\tan^{-1} \left( \frac {a+b}{1-ab}\right)$ which is true iff $ab>1, a>0, b>0$.
●For calculating $\tan^{-1}18-\tan^{-1}\frac {3}{11}$, I used $\tan^{-1}a-\tan^{-1}b=\tan^{-1}\left(\frac {a-b}{1+ab}\right)$ which is true iff $ab>-1$. |
4,220,311 | There is a ball drawer.
Seven color balls will be drawn with the same probability ($1/7$).
(black, blue, green, yellow, white, pink, orange)
If Anson attempts $9$ times,
what is the probability that he gets all $7$ different color balls?
My work:
I separate the answer to $3$ ways.
1. $7$ attempts -> done (get $7$ colors)
2. $8$ attempts -> done (get $7$ colors)
3. $9$ attempts -> done (get $7$ colors)
Therefore, my answer is $$\frac{9C7 + 8C7 + 7C7}{7^7 \cdot (7!)}$$
However, I don't know it is correct or not. | 2021/08/09 | [
"https://math.stackexchange.com/questions/4220311",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/957014/"
]
| The statement is equivalent to
$$\DeclareMathOperator{\arccot}{arccot}
\arccot7+\arccot8=\arccot3-\arccot18
$$
The right-hand side is positive because the arccotangent is decreasing, so it is in the interval $(0,\pi/2)$ and we have to ensure that the same holds for the left-hand side, but this is easy, because $7>1$ and $8>1$, hence
$$
\arccot7+\arccot8<2\arccot1=\frac{\pi}{2}
$$
The two sides are equal if and only if their cotangents are.
Since
$$
\cot(\alpha+\beta)=\frac{\cot\alpha\cot\beta-1}{\cot\alpha+\cot\beta}
\qquad
\cot(\alpha-\beta)=\frac{\cot\alpha\cot\beta+1}{\cot\beta-\cot\alpha}
$$
this amounts to proving that
$$
\frac{7\cdot8-1}{7+8}=\frac{3\cdot18+1}{18-3}
$$ | Obviously $\pi+\cot^{-1} 3 \neq \cot^{-1} 3$, since $\pi \neq 0$. Your second method is incorrect because $$\tan^{-1} a+\tan^{-1}b+\tan^{-1}c=\tan^{-1} \left(\frac {a+b+c-abc}{1-ab-bc-ac}\right)$$ is only true for $a,b,c>0$ if $ab+bc+ac<1$.
It is better for you to combine the $\arctan$s two at a time. We have:
$$\tan^{-1}7+\tan^{-1}8=\pi-\tan^{-1} \frac {3}{11} {\tag 1}$$
So $$\tan^{-1}7+\tan^{-1}8+\tan^{-1}18=\left(\pi-\tan^{-1} \frac {3}{11}\right)+\tan^{-1}18=\pi+\left(\tan^{-1}18-\tan^{-1} \frac {3}{11}\right)=\pi+\left(\tan^{-1}\frac {195}{65}\right)=\pi+\tan^{-1} 3$$
Thus we get $$\frac {3\pi}{2}-(\tan^{-1}7+\tan^{-1}8+\tan^{-1} 18)=\frac {3\pi}{2}-(\pi+\tan^{-1}3)=\frac {\pi}{2}-\tan^{-1}3=\cot^{-1}3$$ as expected.
**Note:**
$(1)$: I used the formula $\tan^{-1}a+\tan^{-1}b=\pi+\tan^{-1} \left( \frac {a+b}{1-ab}\right)$ which is true iff $ab>1, a>0, b>0$.
●For calculating $\tan^{-1}18-\tan^{-1}\frac {3}{11}$, I used $\tan^{-1}a-\tan^{-1}b=\tan^{-1}\left(\frac {a-b}{1+ab}\right)$ which is true iff $ab>-1$. |
4,220,311 | There is a ball drawer.
Seven color balls will be drawn with the same probability ($1/7$).
(black, blue, green, yellow, white, pink, orange)
If Anson attempts $9$ times,
what is the probability that he gets all $7$ different color balls?
My work:
I separate the answer to $3$ ways.
1. $7$ attempts -> done (get $7$ colors)
2. $8$ attempts -> done (get $7$ colors)
3. $9$ attempts -> done (get $7$ colors)
Therefore, my answer is $$\frac{9C7 + 8C7 + 7C7}{7^7 \cdot (7!)}$$
However, I don't know it is correct or not. | 2021/08/09 | [
"https://math.stackexchange.com/questions/4220311",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/957014/"
]
| The statement is equivalent to
$$\DeclareMathOperator{\arccot}{arccot}
\arccot7+\arccot8=\arccot3-\arccot18
$$
The right-hand side is positive because the arccotangent is decreasing, so it is in the interval $(0,\pi/2)$ and we have to ensure that the same holds for the left-hand side, but this is easy, because $7>1$ and $8>1$, hence
$$
\arccot7+\arccot8<2\arccot1=\frac{\pi}{2}
$$
The two sides are equal if and only if their cotangents are.
Since
$$
\cot(\alpha+\beta)=\frac{\cot\alpha\cot\beta-1}{\cot\alpha+\cot\beta}
\qquad
\cot(\alpha-\beta)=\frac{\cot\alpha\cot\beta+1}{\cot\beta-\cot\alpha}
$$
this amounts to proving that
$$
\frac{7\cdot8-1}{7+8}=\frac{3\cdot18+1}{18-3}
$$ | ${tan^{-1}(1/7)+tan^{-1}(1/8)+tan^{-1}(1/18)}$
* ${tan^{-1} \left[ \frac{ (1/7)+(1/8) } { \left( 1 \right) - (1/7)(1/8) } \right] + tan^{-1}(1/18) }$
* = ${tan^{-1} \frac {3}{11} + tan^{-1} \frac{1}{18}}$
* =${tan^{-1} \left[ \frac {(3/11)+(1/18)} {\left (1 \right) - (3/11)(1/18)} \right] }$
* = ${tan^{-1} \frac{1}{3} }$ or ${cot^{-1} {3}}$ |
4,220,311 | There is a ball drawer.
Seven color balls will be drawn with the same probability ($1/7$).
(black, blue, green, yellow, white, pink, orange)
If Anson attempts $9$ times,
what is the probability that he gets all $7$ different color balls?
My work:
I separate the answer to $3$ ways.
1. $7$ attempts -> done (get $7$ colors)
2. $8$ attempts -> done (get $7$ colors)
3. $9$ attempts -> done (get $7$ colors)
Therefore, my answer is $$\frac{9C7 + 8C7 + 7C7}{7^7 \cdot (7!)}$$
However, I don't know it is correct or not. | 2021/08/09 | [
"https://math.stackexchange.com/questions/4220311",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/957014/"
]
| ${tan^{-1}(1/7)+tan^{-1}(1/8)+tan^{-1}(1/18)}$
* ${tan^{-1} \left[ \frac{ (1/7)+(1/8) } { \left( 1 \right) - (1/7)(1/8) } \right] + tan^{-1}(1/18) }$
* = ${tan^{-1} \frac {3}{11} + tan^{-1} \frac{1}{18}}$
* =${tan^{-1} \left[ \frac {(3/11)+(1/18)} {\left (1 \right) - (3/11)(1/18)} \right] }$
* = ${tan^{-1} \frac{1}{3} }$ or ${cot^{-1} {3}}$ | Obviously $\pi+\cot^{-1} 3 \neq \cot^{-1} 3$, since $\pi \neq 0$. Your second method is incorrect because $$\tan^{-1} a+\tan^{-1}b+\tan^{-1}c=\tan^{-1} \left(\frac {a+b+c-abc}{1-ab-bc-ac}\right)$$ is only true for $a,b,c>0$ if $ab+bc+ac<1$.
It is better for you to combine the $\arctan$s two at a time. We have:
$$\tan^{-1}7+\tan^{-1}8=\pi-\tan^{-1} \frac {3}{11} {\tag 1}$$
So $$\tan^{-1}7+\tan^{-1}8+\tan^{-1}18=\left(\pi-\tan^{-1} \frac {3}{11}\right)+\tan^{-1}18=\pi+\left(\tan^{-1}18-\tan^{-1} \frac {3}{11}\right)=\pi+\left(\tan^{-1}\frac {195}{65}\right)=\pi+\tan^{-1} 3$$
Thus we get $$\frac {3\pi}{2}-(\tan^{-1}7+\tan^{-1}8+\tan^{-1} 18)=\frac {3\pi}{2}-(\pi+\tan^{-1}3)=\frac {\pi}{2}-\tan^{-1}3=\cot^{-1}3$$ as expected.
**Note:**
$(1)$: I used the formula $\tan^{-1}a+\tan^{-1}b=\pi+\tan^{-1} \left( \frac {a+b}{1-ab}\right)$ which is true iff $ab>1, a>0, b>0$.
●For calculating $\tan^{-1}18-\tan^{-1}\frac {3}{11}$, I used $\tan^{-1}a-\tan^{-1}b=\tan^{-1}\left(\frac {a-b}{1+ab}\right)$ which is true iff $ab>-1$. |
32,829,536 | Im having trouble figuring out why my code doesnt work. First off, Im new to Java so bear with me.
The task is:
Write a program that reads a sequence of integer inputs and prints the cumulative totals. If the input is 1 7 2 9, the program should print 1 8 10 19.
```
package lektion05forb;
import java.util.Scanner;
/**
*
* @author Lars
*/
public class P52LoopsC
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Numbers: ");
double cumulative_sum = 0;
String output_cumulative_sum= "";
while (input.hasNextDouble())
{
double input_number = input.nextDouble();
cumulative_sum += input_number;
output_cumulative_sum += String.format("%s ", String.valueOf(cumulative_sum));
break;
}
input.close();
System.out.println(output_cumulative_sum);
}
}
```
When I input a sequence of numbers like 3 4 5 8 2, it returns with 34582, instead of the cumulative sum of the numbers. Can anyone explain why, and how i can fix it so it returns the cumulative total of the sequence? | 2015/09/28 | [
"https://Stackoverflow.com/questions/32829536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5385869/"
]
| You can do this with [parse\_url](http://php.net/manual/en/function.parse-url.php)
```
$url = 'www.google.be';
if (parse_url($url, PHP_URL_SCHEME) === null) $url = 'http://'.$url;
``` | Just use [str\_replace](http://php.net/manual/en/function.str-replace.php):
```
<a href="http://<?php str_replace('http://', '', $model->www); ?>" Click me</a>
```
UPDATE: If you are also concerned about other protocols (see DarkBee's comment):
```
<a href="http://<?php str_replace(array('http://', 'https://', 'ftp://'), '', $model->www); ?>" Click me</a>
``` |
25,277,775 | I have a model in Rails that has an enum attribute "status". I want to have a concept of public and private statuses, like so:
```
class Something < ActiveRecord::Base
@public_statuses = [:open, :closed, :current]
@private_statuses = [:deleted]
enum status: @public_statuses + @private_statuses
end
```
So that I can do the following in a view:
```
<select>
<% Something.public_statuses.each do |status| %>
<option value="<%= status %>"><%= status.humanize %></option>
<% end %>
</select>
```
This way, I don't expose the private statuses to the end user.
Unfortunately I don't understand Ruby classes very well and just cannot get this to work regardless of whether I do @public\_statuses, @@public\_statuses, public\_statuses=[...] etc. I'm familiar with Java and other OO languages but just don't get what to do in Ruby here.
What is the right way to do this? | 2014/08/13 | [
"https://Stackoverflow.com/questions/25277775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3011531/"
]
| You can treat your variables like Class methods and define private the ones you don't want to be accessed (that's not absolutely true in Ruby). Like:
```
def self.public_statuses
[:open, :closed, :current]
end
def self.private_statuses
[:deleted]
end
private_class_method :private_statuses
```
But if you really gonna go with variables, in this case, constants, it's very similar:
```
PUBLIC_STATUSES = [:open, :closed, :current]
PRIVATE_STATUSES = [:deleted]
private_constant :PRIVATE_STATUSES
```
So, you can use it:
```
puts Something::PUBLIC_STATUSES
=> [:open, :closed, :current]
puts Something::PRIVATE_STATUSES
NameError: private constant Client::PRIVATE_STATUSES referenced
``` | What you've done is defined two instance variables not class variables so accessing them as `Foo.instance_variable` is not going to work. You need an instance of `Foo` to access them. So you'd replace your view each block with:
```
<% Something.new.public_statuses.each do |status| %>
<option value="<%= status %>"><%= status.humanize %></option>
<% end %>
```
Here you instantiate `Something` then call `pubic_statuses.each` on that instance. So this will work for you.
However, if you'd like to use them as class variables then you need to add a class accessor method in your model class:
```
class Something < ActiveRecord::Base
@@public_statuses = [:open, :closed, :current]
@private_statuses = [:deleted]
enum status: public_statuses + @private_statuses
def self.public_statuses
@@public_statuses
end
end
```
As you are using Rails, you could also define a `cattr_reader :public_statuses` instead of the getter method defined in the code above. With these options of adding class method, you needn't change your view.
Another option is to make them constants:
```
class Something < ActiveRecord::Base
PUBLIC_STATUSES = [:open, :closed, :current]
PRIVATE_STATUSES = [:deleted]
enum status: PUBLIC_STATUSES + PRIVATE_STATUSES
end
```
Then in your view:
```
<% Something::PUBLIC_STATUSES.each do |status| %>
``` |
8,211,128 | Is there any way to have multiple distinct HTML pages contained within a single HTML file? For example, suppose I have a website with two pages:
```
Page 1 : click here for page 2
```
and
```
Page 2 : click here for page 1
```
Can I create a single HTML file that embeds simple static HTML for both pages but only displays one at a time? My actual pages are of course more complicated with images, tables and javascript to expand table rows. I would prefer to avoid too much script code. Thanks! | 2011/11/21 | [
"https://Stackoverflow.com/questions/8211128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/674683/"
]
| I used the following trick for the same problem. The good thing is it doesn't require any javascript.
CSS:
```
.body {
margin: 0em;
}
.page {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: -100vw;
overflow-y: auto;
z-index: 0;
background-color: hsl(0,0%,100%);
}
.page:target {
left: 0vw;
z-index: 1;
}
```
HTML:
```
<ul>
<li>Click <a href="#one">here</a> for page 1</li>
<li>Click <a href="#two">here</a> for page 2</li>
</ul>
<div class="page" id="one">
Content of page 1 goes here.
<ul>
<li><a href="#">Back</a></li>
<li><a href="#two">Page 2</a></li>
</ul>
</div>
<div class="page" id="two">
Content of page 2 goes here.
<ul style="margin-bottom: 100vh;">
<li><a href="#">Back</a></li>
<li><a href="#one">Page 1</a></li>
</ul>
</div>
```
See a [JSFiddle](https://jsfiddle.net/w2eox90g/#&togetherjs=AGDoSdvmVR).
Added advantage: as your url changes along, you can use it to link to specific pages. This is something the method won't let you do.
Hope this helps! | ```html
<html>
<head>
<script>
function show(shown, hidden) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden).style.display='none';
return false;
}
</script>
</head>
<body>
<a href="#" onclick="return show('Page1','Page2');">Show page 1</a>
<a href="#" onclick="return show('Page2','Page1');">Show page 2</a>
<div id="Page1">
Content of page 1
</div>
<div id="Page2" style="display:none">
Content of page 2
</div>
</body>
</html>
``` |
8,211,128 | Is there any way to have multiple distinct HTML pages contained within a single HTML file? For example, suppose I have a website with two pages:
```
Page 1 : click here for page 2
```
and
```
Page 2 : click here for page 1
```
Can I create a single HTML file that embeds simple static HTML for both pages but only displays one at a time? My actual pages are of course more complicated with images, tables and javascript to expand table rows. I would prefer to avoid too much script code. Thanks! | 2011/11/21 | [
"https://Stackoverflow.com/questions/8211128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/674683/"
]
| [Twine](https://twinery.org/) is an open-source tool for telling interactive, nonlinear stories.
It generates a single html with multiples pages.
Maybe it is not the right tool for you but it could be useful for someone else looking for something similar. | It is, in theory, possible using `data:` scheme URIs and frames, but that is rather a long way from practical.
You can fake it by hiding some content with JS and then revealing it when something is clicked (in the style of [tabtastic](http://phrogz.net/js/tabtastic/index.html)). |
8,211,128 | Is there any way to have multiple distinct HTML pages contained within a single HTML file? For example, suppose I have a website with two pages:
```
Page 1 : click here for page 2
```
and
```
Page 2 : click here for page 1
```
Can I create a single HTML file that embeds simple static HTML for both pages but only displays one at a time? My actual pages are of course more complicated with images, tables and javascript to expand table rows. I would prefer to avoid too much script code. Thanks! | 2011/11/21 | [
"https://Stackoverflow.com/questions/8211128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/674683/"
]
| Well, you *could*, but you probably just want to have two sets of content in the same page, and switch between them. Example:
```html
<html>
<head>
<script>
function show(shown, hidden) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden).style.display='none';
return false;
}
</script>
</head>
<body>
<div id="Page1">
Content of page 1
<a href="#" onclick="return show('Page2','Page1');">Show page 2</a>
</div>
<div id="Page2" style="display:none">
Content of page 2
<a href="#" onclick="return show('Page1','Page2');">Show page 1</a>
</div>
</body>
</html>
```
(Simplified HTML code, should of course have doctype, etc.) | I used the following trick for the same problem. The good thing is it doesn't require any javascript.
CSS:
```
.body {
margin: 0em;
}
.page {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: -100vw;
overflow-y: auto;
z-index: 0;
background-color: hsl(0,0%,100%);
}
.page:target {
left: 0vw;
z-index: 1;
}
```
HTML:
```
<ul>
<li>Click <a href="#one">here</a> for page 1</li>
<li>Click <a href="#two">here</a> for page 2</li>
</ul>
<div class="page" id="one">
Content of page 1 goes here.
<ul>
<li><a href="#">Back</a></li>
<li><a href="#two">Page 2</a></li>
</ul>
</div>
<div class="page" id="two">
Content of page 2 goes here.
<ul style="margin-bottom: 100vh;">
<li><a href="#">Back</a></li>
<li><a href="#one">Page 1</a></li>
</ul>
</div>
```
See a [JSFiddle](https://jsfiddle.net/w2eox90g/#&togetherjs=AGDoSdvmVR).
Added advantage: as your url changes along, you can use it to link to specific pages. This is something the method won't let you do.
Hope this helps! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.