conversations
sequence
source
string
length
int64
2
2
prompt_id
string
prompt
string
messages
list
meta
dict
text
string
[ "Can brain cells move? By movement I mean long distance migration (preferably within the brain only).", "The question is relatively broad and one should take into account that the brain not only consists of neurons, but also glial cells (supportive cells) and pre-mitotic neuronal stem cells. Furthermore, as critical fellow-scientists have indicated, developmental stage is very important, as the developing embryonic brain is very different from the adult brain.\nHowever, after sifting through various publications, the answer to the question is actually remarkably simple: Yes, brain cells migrate.\nIn the adult brain glial cells migrate in the brain (Klämbt, 2009). Glial cells are involved in a myriad of functions, but a notable example of migrating glial cells are the oligodendrocytes that migrate relative long distances to find their target axons onto which they wrap themselves to form the insulating myelin sheath (Tsai and Miller, 2002).\nNeuronal stem cells migrate over long distances in response to injury (Imitola et al., 2004) and they migrate from specific stem-cell locations (e.g., hippocampus and subventricular zone) to other regions (Clarke, 2003).\nPost-mitotic, but non-differentiated neurons have been shown to migrate in the adult brain in fish (Scott et al., 2012), and in mammals and non-human primates as well (Sawada et al., 2011).\nNot surprisingly, glial cells, stem cells and neurons also migrate during embryonic development. Most notably, post-mitotic neurons destined to fulfill peripheral functions have to migrate over relatively long distances from the neural crest to their target locations (Neuroscience, 2nd ed, Neuronal Migration)." ]
"stackexchange"
2
"4d2c9b7776dceda59c9a0500f9096c0639c82b695a42ea60a481a05db03fa8dd"
"Can brain cells move? By movement I mean long distance migration (preferably within the brain only)."
[ { "content": "Can brain cells move? By movement I mean long distance migration (preferably within the brain only).", "role": "user" }, { "content": "The question is relatively broad and one should take into account that the brain not only consists of neurons, but also glial cells (supportive cells) and pre-mitotic neuronal stem cells. Furthermore, as critical fellow-scientists have indicated, developmental stage is very important, as the developing embryonic brain is very different from the adult brain.\nHowever, after sifting through various publications, the answer to the question is actually remarkably simple: Yes, brain cells migrate.\nIn the adult brain glial cells migrate in the brain (Klämbt, 2009). Glial cells are involved in a myriad of functions, but a notable example of migrating glial cells are the oligodendrocytes that migrate relative long distances to find their target axons onto which they wrap themselves to form the insulating myelin sheath (Tsai and Miller, 2002).\nNeuronal stem cells migrate over long distances in response to injury (Imitola et al., 2004) and they migrate from specific stem-cell locations (e.g., hippocampus and subventricular zone) to other regions (Clarke, 2003).\nPost-mitotic, but non-differentiated neurons have been shown to migrate in the adult brain in fish (Scott et al., 2012), and in mammals and non-human primates as well (Sawada et al., 2011).\nNot surprisingly, glial cells, stem cells and neurons also migrate during embryonic development. Most notably, post-mitotic neurons destined to fulfill peripheral functions have to migrate over relatively long distances from the neural crest to their target locations (Neuroscience, 2nd ed, Neuronal Migration).", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Can brain cells move? By movement I mean long distance migration (preferably within the brain only). [/INST] The question is relatively broad and one should take into account that the brain not only consists of neurons, but also glial cells (supportive cells) and pre-mitotic neuronal stem cells. Furthermore, as critical fellow-scientists have indicated, developmental stage is very important, as the developing embryonic brain is very different from the adult brain. However, after sifting through various publications, the answer to the question is actually remarkably simple: Yes, brain cells migrate. In the adult brain glial cells migrate in the brain (Klämbt, 2009). Glial cells are involved in a myriad of functions, but a notable example of migrating glial cells are the oligodendrocytes that migrate relative long distances to find their target axons onto which they wrap themselves to form the insulating myelin sheath (Tsai and Miller, 2002). Neuronal stem cells migrate over long distances in response to injury (Imitola et al., 2004) and they migrate from specific stem-cell locations (e.g., hippocampus and subventricular zone) to other regions (Clarke, 2003). Post-mitotic, but non-differentiated neurons have been shown to migrate in the adult brain in fish (Scott et al., 2012), and in mammals and non-human primates as well (Sawada et al., 2011). Not surprisingly, glial cells, stem cells and neurons also migrate during embryonic development. Most notably, post-mitotic neurons destined to fulfill peripheral functions have to migrate over relatively long distances from the neural crest to their target locations (Neuroscience, 2nd ed, Neuronal Migration). </s>"
[ "In our computer systems lecture we were introduced to the MIPS processor. It was (re)developed over the course of the term and has in fact been quite easy to understand. It uses a RISC design, that is its elementary commands are regularly encoded and there are only few of them in order to keep the wires simple.\nIt was mentioned that CISC follows a different philosophy. I looked briefly at the x86 instruction set and was shocked. I can not image how anyone would want to build a processor that uses so complex a command set!\nSo I figure there have to be good arguments why large portions of the processor market use CISC architectures. What are they? ", "There is a general historical trend.\nIn the olden days, memories were small, and so programs were perforce small. Also, compilers were not very smart, and many programs were written in assembler, so it was considered a good thing to be able to write a program using few instructions. Instruction pipelines were simple, and processors grabbed one instruction at a time to execute it. The machinery inside the processor was quite complex anyway; decoding instructions was not felt to be much of a burden. \nIn the 1970s, CPU and compiler designers realized that having such complex instructions was not so helpful after all. It was difficult to design processors in which those instructions were really efficient, and it was difficult to design compilers that really took advantage of these instructions. Chip area and compiler complexity was better spent on more generic pursuits such as more general-purpose registers. The Wikipedia article on RISC explains this in more detail.\nMIPS is the ultimate RISC architecture, which is why it's taught so often.\nThe x86 family is a bit different. It was originally a CISC architecture meant for systems with very small memory (no room for large instructions), and has undergone many successive versions. Today's x86 instruction set is not only complicated because it's CISC, but because it's really a 8088 with a 80386 with a Pentium possibly with an x86_64 processor.\nIn today's world, RISC and CISC are no longer the black-and-white distinction they might have been once. Most CPU architectures have evolved to different shades of grey.\nOn the RISC side, some modern MIPS variants have added multiplication and division instructions, with a non-uniform encoding. ARM processors have become more complex: many of them have a 16-bit instruction set called Thumb in addition to the “original” 32-bit instructions, not to mention Jazelle to execute JVM instructions on the CPU. Modern ARM processors also have SIMD instructions for multimedia applications: some complex instructions do pay after all.\nOn the CISC side, all recent processors are to some extent RISC inside. They have microcode to define all these complex macro instructions. The sheer complexity of the processor makes the design of each model take several years, even with a RISC design, what with the large number of components, with pipelining and predictive execution and whatnot.\nSo why do the fastest processors remain CISC outside? Part of it, in the case of the x86 (32-bit and 64-bit) family, is historical compatibility. But that's not the whole of it. In the early 2000s, Intel tried pushing the Itanium architecture. Itanium is an extreme case of complex instructions (not really CISC, though: its design has been dubbed EPIC). It even does away with the old-fashioned idea of executing instructions in sequence: all instructions are executed in parallel until the next barrier. One of the reasons Itanium didn't take is that nobody, whether at Intel or elsewhere, could write a decent compiler for it. Now a good old mostly-sequential processor like x86_64, that's something we understand." ]
"stackexchange"
2
"6f69b0918029959fc32ccf50dcb75790d3de66722c9748902b4f43180b5a2863"
"In our computer systems lecture we were introduced to the MIPS processor. It was (re)developed over the course of the term and has in fact been quite easy to understand. It uses a RISC design, that is its elementary commands are regularly encoded and there are only few of them in order to keep the wires simple. It was mentioned that CISC follows a different philosophy. I looked briefly at the x86 instruction set and was shocked. I can not image how anyone would want to build a processor that uses so complex a command set! So I figure there have to be good arguments why large portions of the processor market use CISC architectures. What are they? "
[ { "content": "In our computer systems lecture we were introduced to the MIPS processor. It was (re)developed over the course of the term and has in fact been quite easy to understand. It uses a RISC design, that is its elementary commands are regularly encoded and there are only few of them in order to keep the wires simple.\nIt was mentioned that CISC follows a different philosophy. I looked briefly at the x86 instruction set and was shocked. I can not image how anyone would want to build a processor that uses so complex a command set!\nSo I figure there have to be good arguments why large portions of the processor market use CISC architectures. What are they? ", "role": "user" }, { "content": "There is a general historical trend.\nIn the olden days, memories were small, and so programs were perforce small. Also, compilers were not very smart, and many programs were written in assembler, so it was considered a good thing to be able to write a program using few instructions. Instruction pipelines were simple, and processors grabbed one instruction at a time to execute it. The machinery inside the processor was quite complex anyway; decoding instructions was not felt to be much of a burden. \nIn the 1970s, CPU and compiler designers realized that having such complex instructions was not so helpful after all. It was difficult to design processors in which those instructions were really efficient, and it was difficult to design compilers that really took advantage of these instructions. Chip area and compiler complexity was better spent on more generic pursuits such as more general-purpose registers. The Wikipedia article on RISC explains this in more detail.\nMIPS is the ultimate RISC architecture, which is why it's taught so often.\nThe x86 family is a bit different. It was originally a CISC architecture meant for systems with very small memory (no room for large instructions), and has undergone many successive versions. Today's x86 instruction set is not only complicated because it's CISC, but because it's really a 8088 with a 80386 with a Pentium possibly with an x86_64 processor.\nIn today's world, RISC and CISC are no longer the black-and-white distinction they might have been once. Most CPU architectures have evolved to different shades of grey.\nOn the RISC side, some modern MIPS variants have added multiplication and division instructions, with a non-uniform encoding. ARM processors have become more complex: many of them have a 16-bit instruction set called Thumb in addition to the “original” 32-bit instructions, not to mention Jazelle to execute JVM instructions on the CPU. Modern ARM processors also have SIMD instructions for multimedia applications: some complex instructions do pay after all.\nOn the CISC side, all recent processors are to some extent RISC inside. They have microcode to define all these complex macro instructions. The sheer complexity of the processor makes the design of each model take several years, even with a RISC design, what with the large number of components, with pipelining and predictive execution and whatnot.\nSo why do the fastest processors remain CISC outside? Part of it, in the case of the x86 (32-bit and 64-bit) family, is historical compatibility. But that's not the whole of it. In the early 2000s, Intel tried pushing the Itanium architecture. Itanium is an extreme case of complex instructions (not really CISC, though: its design has been dubbed EPIC). It even does away with the old-fashioned idea of executing instructions in sequence: all instructions are executed in parallel until the next barrier. One of the reasons Itanium didn't take is that nobody, whether at Intel or elsewhere, could write a decent compiler for it. Now a good old mostly-sequential processor like x86_64, that's something we understand.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] In our computer systems lecture we were introduced to the MIPS processor. It was (re)developed over the course of the term and has in fact been quite easy to understand. It uses a RISC design, that is its elementary commands are regularly encoded and there are only few of them in order to keep the wires simple. It was mentioned that CISC follows a different philosophy. I looked briefly at the x86 instruction set and was shocked. I can not image how anyone would want to build a processor that uses so complex a command set! So I figure there have to be good arguments why large portions of the processor market use CISC architectures. What are they? [/INST] There is a general historical trend. In the olden days, memories were small, and so programs were perforce small. Also, compilers were not very smart, and many programs were written in assembler, so it was considered a good thing to be able to write a program using few instructions. Instruction pipelines were simple, and processors grabbed one instruction at a time to execute it. The machinery inside the processor was quite complex anyway; decoding instructions was not felt to be much of a burden. In the 1970s, CPU and compiler designers realized that having such complex instructions was not so helpful after all. It was difficult to design processors in which those instructions were really efficient, and it was difficult to design compilers that really took advantage of these instructions. Chip area and compiler complexity was better spent on more generic pursuits such as more general-purpose registers. The Wikipedia article on RISC explains this in more detail. MIPS is the ultimate RISC architecture, which is why it's taught so often. The x86 family is a bit different. It was originally a CISC architecture meant for systems with very small memory (no room for large instructions), and has undergone many successive versions. Today's x86 instruction set is not only complicated because it's CISC, but because it's really a 8088 with a 80386 with a Pentium possibly with an x86_64 processor. In today's world, RISC and CISC are no longer the black-and-white distinction they might have been once. Most CPU architectures have evolved to different shades of grey. On the RISC side, some modern MIPS variants have added multiplication and division instructions, with a non-uniform encoding. ARM processors have become more complex: many of them have a 16-bit instruction set called Thumb in addition to the “original” 32-bit instructions, not to mention Jazelle to execute JVM instructions on the CPU. Modern ARM processors also have SIMD instructions for multimedia applications: some complex instructions do pay after all. On the CISC side, all recent processors are to some extent RISC inside. They have microcode to define all these complex macro instructions. The sheer complexity of the processor makes the design of each model take several years, even with a RISC design, what with the large number of components, with pipelining and predictive execution and whatnot. So why do the fastest processors remain CISC outside? Part of it, in the case of the x86 (32-bit and 64-bit) family, is historical compatibility. But that's not the whole of it. In the early 2000s, Intel tried pushing the Itanium architecture. Itanium is an extreme case of complex instructions (not really CISC, though: its design has been dubbed EPIC). It even does away with the old-fashioned idea of executing instructions in sequence: all instructions are executed in parallel until the next barrier. One of the reasons Itanium didn't take is that nobody, whether at Intel or elsewhere, could write a decent compiler for it. Now a good old mostly-sequential processor like x86_64, that's something we understand. </s>"
[ "View tabular file such as CSV from command line, having horizontal and vertical scrolling would be great.", "Sure, please take a look at csvkit. It provides a set of tools that adhere to the UNIX philosophy (meaning they are small, simple, single-purposed and can be combined). \n\nHere is an example that extracts the ten most populated cities in Germany from the free Maxmind World Cities database and displays the result in a console-readable format:\n```$ csvgrep -e iso-8859-1 -c 1 -m \"de\" worldcitiespop | csvgrep -c 5 -r \"\\d+\"\n | csvsort -r -c 5 -l | csvcut -c 1,2,4,6 | head -n 11 | csvlook\n-----------------------------------------------------\n| line_number | Country | AccentCity | Population |\n-----------------------------------------------------\n| 1 | de | Berlin | 3398362 |\n| 2 | de | Hamburg | 1733846 |\n| 3 | de | Munich | 1246133 |\n| 4 | de | Cologne | 968823 |\n| 5 | de | Frankfurt | 648034 |\n| 6 | de | Dortmund | 594255 |\n| 7 | de | Stuttgart | 591688 |\n| 8 | de | Düsseldorf | 577139 |\n| 9 | de | Essen | 576914 |\n| 10 | de | Bremen | 546429 |\n-----------------------------------------------------\n```\n\nCsvkit is platform independent because it is written in Python. " ]
"stackexchange"
2
"480644a1267b2fdd5e7bc347a17158121d59d62bac4b37ad38d6619bc58eb76b"
"View tabular file such as CSV from command line, having horizontal and vertical scrolling would be great."
[ { "content": "View tabular file such as CSV from command line, having horizontal and vertical scrolling would be great.", "role": "user" }, { "content": "Sure, please take a look at csvkit. It provides a set of tools that adhere to the UNIX philosophy (meaning they are small, simple, single-purposed and can be combined). \n\nHere is an example that extracts the ten most populated cities in Germany from the free Maxmind World Cities database and displays the result in a console-readable format:\n```$ csvgrep -e iso-8859-1 -c 1 -m \"de\" worldcitiespop | csvgrep -c 5 -r \"\\d+\"\n | csvsort -r -c 5 -l | csvcut -c 1,2,4,6 | head -n 11 | csvlook\n-----------------------------------------------------\n| line_number | Country | AccentCity | Population |\n-----------------------------------------------------\n| 1 | de | Berlin | 3398362 |\n| 2 | de | Hamburg | 1733846 |\n| 3 | de | Munich | 1246133 |\n| 4 | de | Cologne | 968823 |\n| 5 | de | Frankfurt | 648034 |\n| 6 | de | Dortmund | 594255 |\n| 7 | de | Stuttgart | 591688 |\n| 8 | de | Düsseldorf | 577139 |\n| 9 | de | Essen | 576914 |\n| 10 | de | Bremen | 546429 |\n-----------------------------------------------------\n```\n\nCsvkit is platform independent because it is written in Python. ", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] View tabular file such as CSV from command line, having horizontal and vertical scrolling would be great. [/INST] Sure, please take a look at csvkit. It provides a set of tools that adhere to the UNIX philosophy (meaning they are small, simple, single-purposed and can be combined). Here is an example that extracts the ten most populated cities in Germany from the free Maxmind World Cities database and displays the result in a console-readable format: ```$ csvgrep -e iso-8859-1 -c 1 -m "de" worldcitiespop | csvgrep -c 5 -r "\d+" | csvsort -r -c 5 -l | csvcut -c 1,2,4,6 | head -n 11 | csvlook ----------------------------------------------------- | line_number | Country | AccentCity | Population | ----------------------------------------------------- | 1 | de | Berlin | 3398362 | | 2 | de | Hamburg | 1733846 | | 3 | de | Munich | 1246133 | | 4 | de | Cologne | 968823 | | 5 | de | Frankfurt | 648034 | | 6 | de | Dortmund | 594255 | | 7 | de | Stuttgart | 591688 | | 8 | de | Düsseldorf | 577139 | | 9 | de | Essen | 576914 | | 10 | de | Bremen | 546429 | ----------------------------------------------------- ``` Csvkit is platform independent because it is written in Python. </s>"
[ "Slater type orbitals (STO) are considered to be more accurate than gaussian type orbitals (GTO) for atomic and molecular QM calculations because - among other reasons - they decay with $e^{-\\alpha r}$ as $r \\to \\infty$. But GTOs are more popular because they are easier to calculate with. GTOs decay with $e^{-\\alpha r^2}$, so its adequate to sometimes add diffuse functions to the GTO basis set to compensate for gaussian decay behaviour.\nAlso, exact hydrogen wavefunctions decay exponentially, so the motivation for STOs.\nI understand that the only boundary requirement for solving the Schrödinger equation for atoms and molecules in free space is that the wavefunction goes zero as $r \\to \\infty$, but there are no a priori requirements for the way it decays as it does so.\nMy question is: do we have theoretical (ab initio) and/or experimental reasons to believe that all atomic and molecular wavefunctions decay like $e^{-\\alpha r}$ as $r \\to \\infty$.", "I'll answer this question from the theoretical side. The exponential behavior follows simply from the Schrödinger equation. Consider the one-electron Schrödinger equation:\n$$\n(-\\frac{1}{2}\\nabla^2 + V(\\mathbf{r}))\\psi(\\mathbf{r}) = \\epsilon\\psi(\\mathbf{r}), \\epsilon < 0\n$$\nAt spatial points that are very far away from the nucleus, $V(\\mathbf{r})\\approx 0$, so that the asymptotic solution is given by\n$$\n-\\frac{1}{2}\\nabla^2\\psi(\\mathbf{r}) = \\epsilon\\psi(\\mathbf{r}), \\epsilon < 0\n$$\nThis differential equation has basic solutions of the form\n$$\n\\psi(\\mathbf{r}) = Ce^{-\\sqrt{-2\\epsilon}\\mathbf{k}\\cdot\\mathbf{r}}\n$$\nfor some unit vector $\\mathbf{k}$. The real asymptotic behavior of $\\psi(\\mathbf{r})$ is thus a linear combination of these basic solutions. The linear combination may bring a polynomial prefactor to the exponential, but will never alter the exponent. Thus we have not only proved the exponential behavior, but also derived the correct exponent $\\alpha = \\sqrt{-2\\epsilon}$. For a multi-electronic, non-interacting system, the overall decay rate is governed by the slowest decaying orbital, i.e. the HOMO.\nOf course, the real wavefunction can only be described by a multi-electron Schrödinger equation. But we can work on the equivalent Kohn-Sham system and show that the Kohn-Sham wavefunction decays at a rate given by the Kohn-Sham HOMO energy. By Janak's theorem, the Kohn-Sham HOMO energy is just the negative of the ionization potential of the exact system. To see this, consider a huge ensemble of $N$ identical, non-interacting molecules. If we remove one electron from the ensemble and let the hole delocalize evenly between all the molecules, then as $N\\to +\\infty$, the electron removal has a negligible impact on the electron density of any molecule (and therefore the Kohn-Sham potential of each molecule). Therefore under the Kohn-Sham framework we see that removing such an electron costs an energy of $-\\epsilon_{\\mathrm{HOMO}}$ (it does not matter whether the HOMO refers to that of the ensemble or that of a molecule, since their orbital energies are equal), since the electron is taken from an energy level whose energy is $\\epsilon_{\\mathrm{HOMO}}$ and the Hamiltonian is not changed in this process. On the other hand, from the perspective of the real system it is clear that the energy cost is equal to the first ionization energy of one of the molecules, $I$. Therefore we have $\\epsilon_{\\mathrm{HOMO}} = -I$, which means that the Kohn-Sham wavefunction decays like (again up to a possible polynomial prefactor; the precise determination of this polynomial prefactor is a much more difficult question)\n$$\n\\psi(\\mathbf{r}) = Ce^{-\\sqrt{2I}\\mathbf{k}\\cdot\\mathbf{r}}\n$$\nAlthough the Kohn-Sham wavefunction is fictional, its density is equal to the true multielectronic density, and in order for the true density to have the same asymptotic behavior as the Kohn-Sham density, the true wavefunction must have the same asymptotic behavior as the Kohn-Sham wavefunction. Q.E.D." ]
"stackexchange"
2
"1929df3d795fdc053850e1ed7e3ec849927bf87f954ea6c92799b0670b8b373f"
"Slater type orbitals (STO) are considered to be more accurate than gaussian type orbitals (GTO) for atomic and molecular QM calculations because - among other reasons - they decay with $e^{-\alpha r}$ as $r \to \infty$. But GTOs are more popular because they are easier to calculate with. GTOs decay with $e^{-\alpha r^2}$, so its adequate to sometimes add diffuse functions to the GTO basis set to compensate for gaussian decay behaviour. Also, exact hydrogen wavefunctions decay exponentially, so the motivation for STOs. I understand that the only boundary requirement for solving the Schrödinger equation for atoms and molecules in free space is that the wavefunction goes zero as $r \to \infty$, but there are no a priori requirements for the way it decays as it does so. My question is: do we have theoretical (ab initio) and/or experimental reasons to believe that all atomic and molecular wavefunctions decay like $e^{-\alpha r}$ as $r \to \infty$."
[ { "content": "Slater type orbitals (STO) are considered to be more accurate than gaussian type orbitals (GTO) for atomic and molecular QM calculations because - among other reasons - they decay with $e^{-\\alpha r}$ as $r \\to \\infty$. But GTOs are more popular because they are easier to calculate with. GTOs decay with $e^{-\\alpha r^2}$, so its adequate to sometimes add diffuse functions to the GTO basis set to compensate for gaussian decay behaviour.\nAlso, exact hydrogen wavefunctions decay exponentially, so the motivation for STOs.\nI understand that the only boundary requirement for solving the Schrödinger equation for atoms and molecules in free space is that the wavefunction goes zero as $r \\to \\infty$, but there are no a priori requirements for the way it decays as it does so.\nMy question is: do we have theoretical (ab initio) and/or experimental reasons to believe that all atomic and molecular wavefunctions decay like $e^{-\\alpha r}$ as $r \\to \\infty$.", "role": "user" }, { "content": "I'll answer this question from the theoretical side. The exponential behavior follows simply from the Schrödinger equation. Consider the one-electron Schrödinger equation:\n$$\n(-\\frac{1}{2}\\nabla^2 + V(\\mathbf{r}))\\psi(\\mathbf{r}) = \\epsilon\\psi(\\mathbf{r}), \\epsilon < 0\n$$\nAt spatial points that are very far away from the nucleus, $V(\\mathbf{r})\\approx 0$, so that the asymptotic solution is given by\n$$\n-\\frac{1}{2}\\nabla^2\\psi(\\mathbf{r}) = \\epsilon\\psi(\\mathbf{r}), \\epsilon < 0\n$$\nThis differential equation has basic solutions of the form\n$$\n\\psi(\\mathbf{r}) = Ce^{-\\sqrt{-2\\epsilon}\\mathbf{k}\\cdot\\mathbf{r}}\n$$\nfor some unit vector $\\mathbf{k}$. The real asymptotic behavior of $\\psi(\\mathbf{r})$ is thus a linear combination of these basic solutions. The linear combination may bring a polynomial prefactor to the exponential, but will never alter the exponent. Thus we have not only proved the exponential behavior, but also derived the correct exponent $\\alpha = \\sqrt{-2\\epsilon}$. For a multi-electronic, non-interacting system, the overall decay rate is governed by the slowest decaying orbital, i.e. the HOMO.\nOf course, the real wavefunction can only be described by a multi-electron Schrödinger equation. But we can work on the equivalent Kohn-Sham system and show that the Kohn-Sham wavefunction decays at a rate given by the Kohn-Sham HOMO energy. By Janak's theorem, the Kohn-Sham HOMO energy is just the negative of the ionization potential of the exact system. To see this, consider a huge ensemble of $N$ identical, non-interacting molecules. If we remove one electron from the ensemble and let the hole delocalize evenly between all the molecules, then as $N\\to +\\infty$, the electron removal has a negligible impact on the electron density of any molecule (and therefore the Kohn-Sham potential of each molecule). Therefore under the Kohn-Sham framework we see that removing such an electron costs an energy of $-\\epsilon_{\\mathrm{HOMO}}$ (it does not matter whether the HOMO refers to that of the ensemble or that of a molecule, since their orbital energies are equal), since the electron is taken from an energy level whose energy is $\\epsilon_{\\mathrm{HOMO}}$ and the Hamiltonian is not changed in this process. On the other hand, from the perspective of the real system it is clear that the energy cost is equal to the first ionization energy of one of the molecules, $I$. Therefore we have $\\epsilon_{\\mathrm{HOMO}} = -I$, which means that the Kohn-Sham wavefunction decays like (again up to a possible polynomial prefactor; the precise determination of this polynomial prefactor is a much more difficult question)\n$$\n\\psi(\\mathbf{r}) = Ce^{-\\sqrt{2I}\\mathbf{k}\\cdot\\mathbf{r}}\n$$\nAlthough the Kohn-Sham wavefunction is fictional, its density is equal to the true multielectronic density, and in order for the true density to have the same asymptotic behavior as the Kohn-Sham density, the true wavefunction must have the same asymptotic behavior as the Kohn-Sham wavefunction. Q.E.D.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Slater type orbitals (STO) are considered to be more accurate than gaussian type orbitals (GTO) for atomic and molecular QM calculations because - among other reasons - they decay with $e^{-\alpha r}$ as $r \to \infty$. But GTOs are more popular because they are easier to calculate with. GTOs decay with $e^{-\alpha r^2}$, so its adequate to sometimes add diffuse functions to the GTO basis set to compensate for gaussian decay behaviour. Also, exact hydrogen wavefunctions decay exponentially, so the motivation for STOs. I understand that the only boundary requirement for solving the Schrödinger equation for atoms and molecules in free space is that the wavefunction goes zero as $r \to \infty$, but there are no a priori requirements for the way it decays as it does so. My question is: do we have theoretical (ab initio) and/or experimental reasons to believe that all atomic and molecular wavefunctions decay like $e^{-\alpha r}$ as $r \to \infty$. [/INST] I'll answer this question from the theoretical side. The exponential behavior follows simply from the Schrödinger equation. Consider the one-electron Schrödinger equation: $$ (-\frac{1}{2}\nabla^2 + V(\mathbf{r}))\psi(\mathbf{r}) = \epsilon\psi(\mathbf{r}), \epsilon < 0 $$ At spatial points that are very far away from the nucleus, $V(\mathbf{r})\approx 0$, so that the asymptotic solution is given by $$ -\frac{1}{2}\nabla^2\psi(\mathbf{r}) = \epsilon\psi(\mathbf{r}), \epsilon < 0 $$ This differential equation has basic solutions of the form $$ \psi(\mathbf{r}) = Ce^{-\sqrt{-2\epsilon}\mathbf{k}\cdot\mathbf{r}} $$ for some unit vector $\mathbf{k}$. The real asymptotic behavior of $\psi(\mathbf{r})$ is thus a linear combination of these basic solutions. The linear combination may bring a polynomial prefactor to the exponential, but will never alter the exponent. Thus we have not only proved the exponential behavior, but also derived the correct exponent $\alpha = \sqrt{-2\epsilon}$. For a multi-electronic, non-interacting system, the overall decay rate is governed by the slowest decaying orbital, i.e. the HOMO. Of course, the real wavefunction can only be described by a multi-electron Schrödinger equation. But we can work on the equivalent Kohn-Sham system and show that the Kohn-Sham wavefunction decays at a rate given by the Kohn-Sham HOMO energy. By Janak's theorem, the Kohn-Sham HOMO energy is just the negative of the ionization potential of the exact system. To see this, consider a huge ensemble of $N$ identical, non-interacting molecules. If we remove one electron from the ensemble and let the hole delocalize evenly between all the molecules, then as $N\to +\infty$, the electron removal has a negligible impact on the electron density of any molecule (and therefore the Kohn-Sham potential of each molecule). Therefore under the Kohn-Sham framework we see that removing such an electron costs an energy of $-\epsilon_{\mathrm{HOMO}}$ (it does not matter whether the HOMO refers to that of the ensemble or that of a molecule, since their orbital energies are equal), since the electron is taken from an energy level whose energy is $\epsilon_{\mathrm{HOMO}}$ and the Hamiltonian is not changed in this process. On the other hand, from the perspective of the real system it is clear that the energy cost is equal to the first ionization energy of one of the molecules, $I$. Therefore we have $\epsilon_{\mathrm{HOMO}} = -I$, which means that the Kohn-Sham wavefunction decays like (again up to a possible polynomial prefactor; the precise determination of this polynomial prefactor is a much more difficult question) $$ \psi(\mathbf{r}) = Ce^{-\sqrt{2I}\mathbf{k}\cdot\mathbf{r}} $$ Although the Kohn-Sham wavefunction is fictional, its density is equal to the true multielectronic density, and in order for the true density to have the same asymptotic behavior as the Kohn-Sham density, the true wavefunction must have the same asymptotic behavior as the Kohn-Sham wavefunction. Q.E.D. </s>"
[ "Explain what \"git reset\" does. I come from a SVN background and Git is a whole new paradigm. I got mercurial easily, but Git is much more technical.\nI think ```git reset``` is close to ```hg revert```, but it seems there are differences. Please include detailed explanations about:\n\n* the options ```--hard```, ```--soft``` and ```--merge```;\n* the strange notation you use with ```HEAD``` such as ```HEAD^``` and ```HEAD~1```;\n* concrete use cases and work flows;\n* consequences on the working copy, the ```HEAD``` and your global stress level.", "Remember that in ```git``` you have:\n\n* the ```HEAD``` pointer, which tells you what commit you're working on\n* the working tree, which represents the state of the files on your system\n* the staging area (also called the index), which \"stages\" changes so that they can later be committed together\n\n\n> Please include detailed explanations about:\n ```--hard```, ```--soft``` and ```--merge```;\n\nIn increasing order of dangerous-ness:\n\n* ```--soft``` moves ```HEAD``` but doesn't touch the staging area or the working tree.\n* ```--mixed``` moves ```HEAD``` and updates the staging area, but not the working tree.\n* ```--merge``` moves ```HEAD```, resets the staging area, and tries to move all the changes in your working tree into the new working tree.\n* ```--hard``` moves ```HEAD``` and adjusts your staging area and working tree to the new ```HEAD```, throwing away everything.\n\n\n> concrete use cases and workflows;\n\n\n* Use ```--soft``` when you want to move to another commit and patch things up without \"losing your place\". It's pretty rare that you need this.\n\n```\n# git reset --soft example\ntouch foo // Add a file, make some changes.\ngit add foo //\ngit commit -m \"bad commit message\" // Commit... D'oh, that was a mistake!\ngit reset --soft HEAD^ // Go back one commit and fix things.\ngit commit -m \"good commit\" // There, now it's right.\n```\n--\n\n* Use ```--mixed``` (which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have.\n* Use ```--merge``` when you want to move to a new spot but incorporate the changes you already have into that the working tree.\n* Use ```--hard``` to wipe everything out and start a fresh slate at the new commit." ]
"stackexchange"
2
"49e554a16d5d5384c9cc654399ba8ed79dc6e54791fb4f827c4a5201fa6c5ec1"
"Explain what "git reset" does. I come from a SVN background and Git is a whole new paradigm. I got mercurial easily, but Git is much more technical. I think ```git reset``` is close to ```hg revert```, but it seems there are differences. Please include detailed explanations about: * the options ```--hard```, ```--soft``` and ```--merge```; * the strange notation you use with ```HEAD``` such as ```HEAD^``` and ```HEAD~1```; * concrete use cases and work flows; * consequences on the working copy, the ```HEAD``` and your global stress level."
[ { "content": "Explain what \"git reset\" does. I come from a SVN background and Git is a whole new paradigm. I got mercurial easily, but Git is much more technical.\nI think ```git reset``` is close to ```hg revert```, but it seems there are differences. Please include detailed explanations about:\n\n* the options ```--hard```, ```--soft``` and ```--merge```;\n* the strange notation you use with ```HEAD``` such as ```HEAD^``` and ```HEAD~1```;\n* concrete use cases and work flows;\n* consequences on the working copy, the ```HEAD``` and your global stress level.", "role": "user" }, { "content": "Remember that in ```git``` you have:\n\n* the ```HEAD``` pointer, which tells you what commit you're working on\n* the working tree, which represents the state of the files on your system\n* the staging area (also called the index), which \"stages\" changes so that they can later be committed together\n\n\n> Please include detailed explanations about:\n ```--hard```, ```--soft``` and ```--merge```;\n\nIn increasing order of dangerous-ness:\n\n* ```--soft``` moves ```HEAD``` but doesn't touch the staging area or the working tree.\n* ```--mixed``` moves ```HEAD``` and updates the staging area, but not the working tree.\n* ```--merge``` moves ```HEAD```, resets the staging area, and tries to move all the changes in your working tree into the new working tree.\n* ```--hard``` moves ```HEAD``` and adjusts your staging area and working tree to the new ```HEAD```, throwing away everything.\n\n\n> concrete use cases and workflows;\n\n\n* Use ```--soft``` when you want to move to another commit and patch things up without \"losing your place\". It's pretty rare that you need this.\n\n```\n# git reset --soft example\ntouch foo // Add a file, make some changes.\ngit add foo //\ngit commit -m \"bad commit message\" // Commit... D'oh, that was a mistake!\ngit reset --soft HEAD^ // Go back one commit and fix things.\ngit commit -m \"good commit\" // There, now it's right.\n```\n--\n\n* Use ```--mixed``` (which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have.\n* Use ```--merge``` when you want to move to a new spot but incorporate the changes you already have into that the working tree.\n* Use ```--hard``` to wipe everything out and start a fresh slate at the new commit.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Explain what "git reset" does. I come from a SVN background and Git is a whole new paradigm. I got mercurial easily, but Git is much more technical. I think ```git reset``` is close to ```hg revert```, but it seems there are differences. Please include detailed explanations about: * the options ```--hard```, ```--soft``` and ```--merge```; * the strange notation you use with ```HEAD``` such as ```HEAD^``` and ```HEAD~1```; * concrete use cases and work flows; * consequences on the working copy, the ```HEAD``` and your global stress level. [/INST] Remember that in ```git``` you have: * the ```HEAD``` pointer, which tells you what commit you're working on * the working tree, which represents the state of the files on your system * the staging area (also called the index), which "stages" changes so that they can later be committed together > Please include detailed explanations about: ```--hard```, ```--soft``` and ```--merge```; In increasing order of dangerous-ness: * ```--soft``` moves ```HEAD``` but doesn't touch the staging area or the working tree. * ```--mixed``` moves ```HEAD``` and updates the staging area, but not the working tree. * ```--merge``` moves ```HEAD```, resets the staging area, and tries to move all the changes in your working tree into the new working tree. * ```--hard``` moves ```HEAD``` and adjusts your staging area and working tree to the new ```HEAD```, throwing away everything. > concrete use cases and workflows; * Use ```--soft``` when you want to move to another commit and patch things up without "losing your place". It's pretty rare that you need this. ``` # git reset --soft example touch foo // Add a file, make some changes. git add foo // git commit -m "bad commit message" // Commit... D'oh, that was a mistake! git reset --soft HEAD^ // Go back one commit and fix things. git commit -m "good commit" // There, now it's right. ``` -- * Use ```--mixed``` (which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have. * Use ```--merge``` when you want to move to a new spot but incorporate the changes you already have into that the working tree. * Use ```--hard``` to wipe everything out and start a fresh slate at the new commit. </s>"
[ "I am looking to use Java to get the MD5 checksum of a file.\nHow is it done?", "The com.google.common.hash API offers:\n\n* A unified user-friendly API for all hash functions\n* Seedable 32- and 128-bit implementations of murmur3\n* md5(), sha1(), sha256(), sha512() adapters, change only one line of code to switch between these, and murmur.\n* goodFastHash(int bits), for when you don't care what algorithm you use\n* General utilities for HashCode instances, like combineOrdered / combineUnordered\n\nRead the User Guide (IO Explained, Hashing Explained). \nFor your use-case ```Files.hash()``` computes and returns the digest value for a file.\nFor example a sha-1 digest calculation (change SHA-1 to MD5 to get MD5 digest)\n```HashCode hc = Files.asByteSource(file).hash(Hashing.sha1());\n\"SHA-1: \" + hc.toString();\n```\nNote that crc32 is much faster than md5, so use crc32 if you do not need a cryptographically secure checksum. Note also that md5 should not be used to store passwords and the like since it is to easy to brute force, for passwords use bcrypt, scrypt or sha-256 instead. \nFor long term protection with hashes a Merkle signature scheme adds to the security and The Post Quantum Cryptography Study Group sponsored by the European Commission has recommended use of this cryptography for long term protection against quantum computers (ref).\nNote that crc32 has a higher collision rate than the others. \nWhat part of Files.hash as stated above does not cover Files.hash ?" ]
"stackexchange"
2
"2f7680d642a4f08ee6b030f8db2a8da9070a35b2bdbb658bdd064840bae7ac0a"
"I am looking to use Java to get the MD5 checksum of a file. How is it done?"
[ { "content": "I am looking to use Java to get the MD5 checksum of a file.\nHow is it done?", "role": "user" }, { "content": "The com.google.common.hash API offers:\n\n* A unified user-friendly API for all hash functions\n* Seedable 32- and 128-bit implementations of murmur3\n* md5(), sha1(), sha256(), sha512() adapters, change only one line of code to switch between these, and murmur.\n* goodFastHash(int bits), for when you don't care what algorithm you use\n* General utilities for HashCode instances, like combineOrdered / combineUnordered\n\nRead the User Guide (IO Explained, Hashing Explained). \nFor your use-case ```Files.hash()``` computes and returns the digest value for a file.\nFor example a sha-1 digest calculation (change SHA-1 to MD5 to get MD5 digest)\n```HashCode hc = Files.asByteSource(file).hash(Hashing.sha1());\n\"SHA-1: \" + hc.toString();\n```\nNote that crc32 is much faster than md5, so use crc32 if you do not need a cryptographically secure checksum. Note also that md5 should not be used to store passwords and the like since it is to easy to brute force, for passwords use bcrypt, scrypt or sha-256 instead. \nFor long term protection with hashes a Merkle signature scheme adds to the security and The Post Quantum Cryptography Study Group sponsored by the European Commission has recommended use of this cryptography for long term protection against quantum computers (ref).\nNote that crc32 has a higher collision rate than the others. \nWhat part of Files.hash as stated above does not cover Files.hash ?", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] I am looking to use Java to get the MD5 checksum of a file. How is it done? [/INST] The com.google.common.hash API offers: * A unified user-friendly API for all hash functions * Seedable 32- and 128-bit implementations of murmur3 * md5(), sha1(), sha256(), sha512() adapters, change only one line of code to switch between these, and murmur. * goodFastHash(int bits), for when you don't care what algorithm you use * General utilities for HashCode instances, like combineOrdered / combineUnordered Read the User Guide (IO Explained, Hashing Explained). For your use-case ```Files.hash()``` computes and returns the digest value for a file. For example a sha-1 digest calculation (change SHA-1 to MD5 to get MD5 digest) ```HashCode hc = Files.asByteSource(file).hash(Hashing.sha1()); "SHA-1: " + hc.toString(); ``` Note that crc32 is much faster than md5, so use crc32 if you do not need a cryptographically secure checksum. Note also that md5 should not be used to store passwords and the like since it is to easy to brute force, for passwords use bcrypt, scrypt or sha-256 instead. For long term protection with hashes a Merkle signature scheme adds to the security and The Post Quantum Cryptography Study Group sponsored by the European Commission has recommended use of this cryptography for long term protection against quantum computers (ref). Note that crc32 has a higher collision rate than the others. What part of Files.hash as stated above does not cover Files.hash ? </s>"
[ "What are the primary objections Democrats have to a border wall?", "It's not clear to me that Democrats are opposed to border-wall construction (your one source suggests they are fine with border walls/fences where necessary), so much as they opposed to some of the plans for full-border walls that have been put forth so far.\nRecently, in response to reports that the spending bill would include funding for a border wall, 5 Democratic senators released a letter voicing concerns over the cost, the effectiveness, and the legal issues of constructing it.\n\nWe are also concerned with reports that there may be an effort to include funding for a very expensive new wall along the southern border with Mexico and a “deportation force.” According to non-partisan experts, the proposed new border wall could cost as much as $25 million per mile and raises considerable issues that have not been resolved by the Congress or the Department of Homeland Security. First, many experts believe that such a border wall will not work. Second, there is real concern that the Administration, put simply, has no plan to build the border wall. For example, the Administration has not detailed how to 1) use eminent domain and other procedures to acquire land from private landowners and Native American tribes, 2) design the wall, 3) locate the wall, 4) construct the wall, and 5) require Mexico to pay for the wall given the President’s clear and repeated promises that he would force Mexico to do so. Finally, there are objections to the construction of a wall from Democratic and Republican members of Congress that represent border states. Given these and other concerns, we believe it would be inappropriate to insist on the inclusion of such funding in a must-pass appropriations bill that is needed for the Republican majority in control of the Congress to avert a government shutdown so early in President Trump’s Administration.\n[...]\nSenator Charles Schumer\nSenator Richard Durbin\nSenator Patty Murray\nSenator Debbie Stabenow\nSenator Patrick Leahy\n\nBased on this letter, it appears their main objections to a full border wall are currently the cost-benefit ratio and the legal issues of taking land from Americans to build it on; objections that may not be unique to Democrats." ]
"stackexchange"
2
"2599610086034abb2a3c11bcb2045955cd9836440a44d6c795dd479c3d2b1edb"
"What are the primary objections Democrats have to a border wall?"
[ { "content": "What are the primary objections Democrats have to a border wall?", "role": "user" }, { "content": "It's not clear to me that Democrats are opposed to border-wall construction (your one source suggests they are fine with border walls/fences where necessary), so much as they opposed to some of the plans for full-border walls that have been put forth so far.\nRecently, in response to reports that the spending bill would include funding for a border wall, 5 Democratic senators released a letter voicing concerns over the cost, the effectiveness, and the legal issues of constructing it.\n\nWe are also concerned with reports that there may be an effort to include funding for a very expensive new wall along the southern border with Mexico and a “deportation force.” According to non-partisan experts, the proposed new border wall could cost as much as $25 million per mile and raises considerable issues that have not been resolved by the Congress or the Department of Homeland Security. First, many experts believe that such a border wall will not work. Second, there is real concern that the Administration, put simply, has no plan to build the border wall. For example, the Administration has not detailed how to 1) use eminent domain and other procedures to acquire land from private landowners and Native American tribes, 2) design the wall, 3) locate the wall, 4) construct the wall, and 5) require Mexico to pay for the wall given the President’s clear and repeated promises that he would force Mexico to do so. Finally, there are objections to the construction of a wall from Democratic and Republican members of Congress that represent border states. Given these and other concerns, we believe it would be inappropriate to insist on the inclusion of such funding in a must-pass appropriations bill that is needed for the Republican majority in control of the Congress to avert a government shutdown so early in President Trump’s Administration.\n[...]\nSenator Charles Schumer\nSenator Richard Durbin\nSenator Patty Murray\nSenator Debbie Stabenow\nSenator Patrick Leahy\n\nBased on this letter, it appears their main objections to a full border wall are currently the cost-benefit ratio and the legal issues of taking land from Americans to build it on; objections that may not be unique to Democrats.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] What are the primary objections Democrats have to a border wall? [/INST] It's not clear to me that Democrats are opposed to border-wall construction (your one source suggests they are fine with border walls/fences where necessary), so much as they opposed to some of the plans for full-border walls that have been put forth so far. Recently, in response to reports that the spending bill would include funding for a border wall, 5 Democratic senators released a letter voicing concerns over the cost, the effectiveness, and the legal issues of constructing it. We are also concerned with reports that there may be an effort to include funding for a very expensive new wall along the southern border with Mexico and a “deportation force.” According to non-partisan experts, the proposed new border wall could cost as much as $25 million per mile and raises considerable issues that have not been resolved by the Congress or the Department of Homeland Security. First, many experts believe that such a border wall will not work. Second, there is real concern that the Administration, put simply, has no plan to build the border wall. For example, the Administration has not detailed how to 1) use eminent domain and other procedures to acquire land from private landowners and Native American tribes, 2) design the wall, 3) locate the wall, 4) construct the wall, and 5) require Mexico to pay for the wall given the President’s clear and repeated promises that he would force Mexico to do so. Finally, there are objections to the construction of a wall from Democratic and Republican members of Congress that represent border states. Given these and other concerns, we believe it would be inappropriate to insist on the inclusion of such funding in a must-pass appropriations bill that is needed for the Republican majority in control of the Congress to avert a government shutdown so early in President Trump’s Administration. [...] Senator Charles Schumer Senator Richard Durbin Senator Patty Murray Senator Debbie Stabenow Senator Patrick Leahy Based on this letter, it appears their main objections to a full border wall are currently the cost-benefit ratio and the legal issues of taking land from Americans to build it on; objections that may not be unique to Democrats. </s>"
[ "I'm converting a video to GIF file with ```ffmpeg```:\n```ffmpeg \\\n -i input.flv \\\n -ss 00:00:00.000 \\\n -pix_fmt rgb24 \\\n -r 10 \\\n -s 320x240 \\\n -t 00:00:10.000 \\\n output.gif\n```\nIt works great, but output gif file has a very low quality.\nAny ideas how can I improve quality of converted gif?", "If you would prefer to avoid intermediate image files, the commands provided by LordNeckBeard can be piped between ```ffmpeg``` and ImageMagick's ```convert``` so that no intermediate files are required:\n```ffmpeg -i input.flv -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 10 -loop 0 - output.gif\n```\nThe ```-f image2pipe``` tells ffmpeg to split the video into images and make it suitable to be piped out, and ```-vcodec ppm``` specifies the output format to be ppm (for some reason if the format is png, either ```convert``` does not read all the images from the pipe, or ffmpeg does not output them all). The ```-``` for both commands specifies that a pipe will be used for output and input respectively.\nTo optimize the result without saving a file, you can pipe the output from ```convert``` to a second ```convert``` command:\n```ffmpeg -i input.flv -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 10 -loop 0 - gif:- | convert -layers Optimize - output.gif\n```\nThe ```gif:-``` tells ```convert``` to pipe its output as gif formatted data and ```-layers Optimize``` tells the second ```convert``` to perform ```optimize-frame``` and ```optimize-transparancy``` methods (see the ImageMagick Introduction to Animation Optimization). Note that the output from the ```-layers Optimize``` may not always provide a smaller file size, so you may want to try converting to a gif without optimization first to be sure.\nRemember that during this whole process everything is in memory so you may need sufficient memory if the images are quite large." ]
"stackexchange"
2
"34f86027b6fc3a8a299a5b724f4768b2f2c36947ce55cfe9295a53b0dd313a41"
"I'm converting a video to GIF file with ```ffmpeg```: ```ffmpeg \ -i input.flv \ -ss 00:00:00.000 \ -pix_fmt rgb24 \ -r 10 \ -s 320x240 \ -t 00:00:10.000 \ output.gif ``` It works great, but output gif file has a very low quality. Any ideas how can I improve quality of converted gif?"
[ { "content": "I'm converting a video to GIF file with ```ffmpeg```:\n```ffmpeg \\\n -i input.flv \\\n -ss 00:00:00.000 \\\n -pix_fmt rgb24 \\\n -r 10 \\\n -s 320x240 \\\n -t 00:00:10.000 \\\n output.gif\n```\nIt works great, but output gif file has a very low quality.\nAny ideas how can I improve quality of converted gif?", "role": "user" }, { "content": "If you would prefer to avoid intermediate image files, the commands provided by LordNeckBeard can be piped between ```ffmpeg``` and ImageMagick's ```convert``` so that no intermediate files are required:\n```ffmpeg -i input.flv -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 10 -loop 0 - output.gif\n```\nThe ```-f image2pipe``` tells ffmpeg to split the video into images and make it suitable to be piped out, and ```-vcodec ppm``` specifies the output format to be ppm (for some reason if the format is png, either ```convert``` does not read all the images from the pipe, or ffmpeg does not output them all). The ```-``` for both commands specifies that a pipe will be used for output and input respectively.\nTo optimize the result without saving a file, you can pipe the output from ```convert``` to a second ```convert``` command:\n```ffmpeg -i input.flv -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 10 -loop 0 - gif:- | convert -layers Optimize - output.gif\n```\nThe ```gif:-``` tells ```convert``` to pipe its output as gif formatted data and ```-layers Optimize``` tells the second ```convert``` to perform ```optimize-frame``` and ```optimize-transparancy``` methods (see the ImageMagick Introduction to Animation Optimization). Note that the output from the ```-layers Optimize``` may not always provide a smaller file size, so you may want to try converting to a gif without optimization first to be sure.\nRemember that during this whole process everything is in memory so you may need sufficient memory if the images are quite large.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] I'm converting a video to GIF file with ```ffmpeg```: ```ffmpeg \ -i input.flv \ -ss 00:00:00.000 \ -pix_fmt rgb24 \ -r 10 \ -s 320x240 \ -t 00:00:10.000 \ output.gif ``` It works great, but output gif file has a very low quality. Any ideas how can I improve quality of converted gif? [/INST] If you would prefer to avoid intermediate image files, the commands provided by LordNeckBeard can be piped between ```ffmpeg``` and ImageMagick's ```convert``` so that no intermediate files are required: ```ffmpeg -i input.flv -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 10 -loop 0 - output.gif ``` The ```-f image2pipe``` tells ffmpeg to split the video into images and make it suitable to be piped out, and ```-vcodec ppm``` specifies the output format to be ppm (for some reason if the format is png, either ```convert``` does not read all the images from the pipe, or ffmpeg does not output them all). The ```-``` for both commands specifies that a pipe will be used for output and input respectively. To optimize the result without saving a file, you can pipe the output from ```convert``` to a second ```convert``` command: ```ffmpeg -i input.flv -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm - | convert -delay 10 -loop 0 - gif:- | convert -layers Optimize - output.gif ``` The ```gif:-``` tells ```convert``` to pipe its output as gif formatted data and ```-layers Optimize``` tells the second ```convert``` to perform ```optimize-frame``` and ```optimize-transparancy``` methods (see the ImageMagick Introduction to Animation Optimization). Note that the output from the ```-layers Optimize``` may not always provide a smaller file size, so you may want to try converting to a gif without optimization first to be sure. Remember that during this whole process everything is in memory so you may need sufficient memory if the images are quite large. </s>"
[ "Tor can only handle TCP connections, but DNS is a UDP protocol. How does Tor route DNS requests over its TCP based network? Why can the same approach not be used to route all UDP traffic over Tor?", "Tor clients do not, in general, directly do DNS requests. When you open a connection through the tor network you usually ask your client (on its socks ports) to connect you to a hostname and port, say www.example.com:80.\nYour tor client, once it has created a circuit, will send that hostname and port to the exit node in its RELAY_BEGIN cell.\nThe exit node will then do a DNS resolve and open a TCP connection to the target. Once that's established it will tell your client that the connection is open, and for informational purposes will also tell your client what address that hostname resolved to.\nTor, in addition to that, has some sort of \"remote DNS resolve\" protocol built in. This support allows clients to query for certain resource types, like IPv4 or IPv6 addresses. Here too, the exit node does the actual DNS packet sending and receiving and just relays the answer to the client.\nNo UDP packets are actually ever routed from the client.\nThere's also a proposal to add more full featured DNS support to Tor. So far it hasn't been implemented.\n\nTor Protocol Specification references\n\n* 6.2. Opening streams and transferring data\n* 6.4. Remote hostname lookup\n* Proposal 219 - Support for full DNS and DNSSEC resolution in Tor\n" ]
"stackexchange"
2
"dbc6e91be6beba4c59bfd8d02e9966d3755ba13cfcd52d74533396ead5bbe41e"
"Tor can only handle TCP connections, but DNS is a UDP protocol. How does Tor route DNS requests over its TCP based network? Why can the same approach not be used to route all UDP traffic over Tor?"
[ { "content": "Tor can only handle TCP connections, but DNS is a UDP protocol. How does Tor route DNS requests over its TCP based network? Why can the same approach not be used to route all UDP traffic over Tor?", "role": "user" }, { "content": "Tor clients do not, in general, directly do DNS requests. When you open a connection through the tor network you usually ask your client (on its socks ports) to connect you to a hostname and port, say www.example.com:80.\nYour tor client, once it has created a circuit, will send that hostname and port to the exit node in its RELAY_BEGIN cell.\nThe exit node will then do a DNS resolve and open a TCP connection to the target. Once that's established it will tell your client that the connection is open, and for informational purposes will also tell your client what address that hostname resolved to.\nTor, in addition to that, has some sort of \"remote DNS resolve\" protocol built in. This support allows clients to query for certain resource types, like IPv4 or IPv6 addresses. Here too, the exit node does the actual DNS packet sending and receiving and just relays the answer to the client.\nNo UDP packets are actually ever routed from the client.\nThere's also a proposal to add more full featured DNS support to Tor. So far it hasn't been implemented.\n\nTor Protocol Specification references\n\n* 6.2. Opening streams and transferring data\n* 6.4. Remote hostname lookup\n* Proposal 219 - Support for full DNS and DNSSEC resolution in Tor\n", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Tor can only handle TCP connections, but DNS is a UDP protocol. How does Tor route DNS requests over its TCP based network? Why can the same approach not be used to route all UDP traffic over Tor? [/INST] Tor clients do not, in general, directly do DNS requests. When you open a connection through the tor network you usually ask your client (on its socks ports) to connect you to a hostname and port, say www.example.com:80. Your tor client, once it has created a circuit, will send that hostname and port to the exit node in its RELAY_BEGIN cell. The exit node will then do a DNS resolve and open a TCP connection to the target. Once that's established it will tell your client that the connection is open, and for informational purposes will also tell your client what address that hostname resolved to. Tor, in addition to that, has some sort of "remote DNS resolve" protocol built in. This support allows clients to query for certain resource types, like IPv4 or IPv6 addresses. Here too, the exit node does the actual DNS packet sending and receiving and just relays the answer to the client. No UDP packets are actually ever routed from the client. There's also a proposal to add more full featured DNS support to Tor. So far it hasn't been implemented. Tor Protocol Specification references * 6.2. Opening streams and transferring data * 6.4. Remote hostname lookup * Proposal 219 - Support for full DNS and DNSSEC resolution in Tor </s>"
[ "Why does this throw ```NullPointerException```\n```public static void main(String[] args) throws Exception {\n Boolean b = true ? returnsNull() : false; // NPE on this line.\n System.out.println(b);\n}\npublic static Boolean returnsNull() {\n return null;\n}\n```\nwhile this doesn't\n```public static void main(String[] args) throws Exception {\n Boolean b = true ? null : false;\n System.out.println(b); // null\n}\n```\n?\nThe solution is by the way to replace ```false``` by ```Boolean.FALSE``` to avoid ```null``` being unboxed to ```boolean``` --which isn't possible. But that isn't the question. The question is why? Are there any references in JLS which confirms this behaviour, especially of the 2nd case?", "The difference is that the explicit type of the ```returnsNull()``` method affects the static typing of the expressions at compile time:\n```E1: `true ? returnsNull() : false` - boolean (auto-unboxing 2nd operand to boolean)\nE2: `true ? null : false` - Boolean (autoboxing of 3rd operand to Boolean)\n```\nSee Java Language Specification, section 15.25 Conditional Operator ? :\n\n* For E1, the types of the 2nd and 3rd operands are ```Boolean``` and ```boolean``` respectively, so this clause applies:\n\n If one of the second and third operands is of type boolean and the type of the other is of type Boolean, then the type of the conditional expression is boolean.\n\nSince the type of the expression is ```boolean```, the 2nd operand must be coerced to ```boolean```. The compiler inserts auto-unboxing code to the 2nd operand (return value of ```returnsNull()```) to make it type ```boolean```. This of course causes the NPE from the ```null``` returned at run-time.\n* For E2, types of the 2nd and 3rd operands are `````` (not ```Boolean``` as in E1!) and ```boolean``` respectively, so no specific typing clause applies (go read 'em!), so the final \"otherwise\" clause applies:\n\n Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).\n\n\n* S1 == `````` (see §4.1)\n* S2 == ```boolean```\n* T1 == box(S1) == `````` (see last item in list of boxing conversions in §5.1.7)\n* T2 == box(S2) == `Boolean\n* lub(T1, T2) == ```Boolean```\n\nSo the type of the conditional expression is ```Boolean``` and the 3rd operand must be coerced to ```Boolean```. The compiler inserts auto-boxing code for the 3rd operand (```false```). The 2nd operand doesn't need the auto-unboxing as in ```E1```, so no auto-unboxing NPE when ```null``` is returned.\n\n\nThis question needs a similar type analysis:\nJava conditional operator ?: result type" ]
"stackexchange"
2
"0d9130750ad9f59b2c451e727c90d3d51e365fc5c420f58f1d11bc07a443f15e"
"Why does this throw ```NullPointerException``` ```public static void main(String[] args) throws Exception { Boolean b = true ? returnsNull() : false; // NPE on this line. System.out.println(b); } public static Boolean returnsNull() { return null; } ``` while this doesn't ```public static void main(String[] args) throws Exception { Boolean b = true ? null : false; System.out.println(b); // null } ``` ? The solution is by the way to replace ```false``` by ```Boolean.FALSE``` to avoid ```null``` being unboxed to ```boolean``` --which isn't possible. But that isn't the question. The question is why? Are there any references in JLS which confirms this behaviour, especially of the 2nd case?"
[ { "content": "Why does this throw ```NullPointerException```\n```public static void main(String[] args) throws Exception {\n Boolean b = true ? returnsNull() : false; // NPE on this line.\n System.out.println(b);\n}\npublic static Boolean returnsNull() {\n return null;\n}\n```\nwhile this doesn't\n```public static void main(String[] args) throws Exception {\n Boolean b = true ? null : false;\n System.out.println(b); // null\n}\n```\n?\nThe solution is by the way to replace ```false``` by ```Boolean.FALSE``` to avoid ```null``` being unboxed to ```boolean``` --which isn't possible. But that isn't the question. The question is why? Are there any references in JLS which confirms this behaviour, especially of the 2nd case?", "role": "user" }, { "content": "The difference is that the explicit type of the ```returnsNull()``` method affects the static typing of the expressions at compile time:\n```E1: `true ? returnsNull() : false` - boolean (auto-unboxing 2nd operand to boolean)\nE2: `true ? null : false` - Boolean (autoboxing of 3rd operand to Boolean)\n```\nSee Java Language Specification, section 15.25 Conditional Operator ? :\n\n* For E1, the types of the 2nd and 3rd operands are ```Boolean``` and ```boolean``` respectively, so this clause applies:\n\n If one of the second and third operands is of type boolean and the type of the other is of type Boolean, then the type of the conditional expression is boolean.\n\nSince the type of the expression is ```boolean```, the 2nd operand must be coerced to ```boolean```. The compiler inserts auto-unboxing code to the 2nd operand (return value of ```returnsNull()```) to make it type ```boolean```. This of course causes the NPE from the ```null``` returned at run-time.\n* For E2, types of the 2nd and 3rd operands are `````` (not ```Boolean``` as in E1!) and ```boolean``` respectively, so no specific typing clause applies (go read 'em!), so the final \"otherwise\" clause applies:\n\n Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).\n\n\n* S1 == `````` (see §4.1)\n* S2 == ```boolean```\n* T1 == box(S1) == `````` (see last item in list of boxing conversions in §5.1.7)\n* T2 == box(S2) == `Boolean\n* lub(T1, T2) == ```Boolean```\n\nSo the type of the conditional expression is ```Boolean``` and the 3rd operand must be coerced to ```Boolean```. The compiler inserts auto-boxing code for the 3rd operand (```false```). The 2nd operand doesn't need the auto-unboxing as in ```E1```, so no auto-unboxing NPE when ```null``` is returned.\n\n\nThis question needs a similar type analysis:\nJava conditional operator ?: result type", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Why does this throw ```NullPointerException``` ```public static void main(String[] args) throws Exception { Boolean b = true ? returnsNull() : false; // NPE on this line. System.out.println(b); } public static Boolean returnsNull() { return null; } ``` while this doesn't ```public static void main(String[] args) throws Exception { Boolean b = true ? null : false; System.out.println(b); // null } ``` ? The solution is by the way to replace ```false``` by ```Boolean.FALSE``` to avoid ```null``` being unboxed to ```boolean``` --which isn't possible. But that isn't the question. The question is why? Are there any references in JLS which confirms this behaviour, especially of the 2nd case? [/INST] The difference is that the explicit type of the ```returnsNull()``` method affects the static typing of the expressions at compile time: ```E1: `true ? returnsNull() : false` - boolean (auto-unboxing 2nd operand to boolean) E2: `true ? null : false` - Boolean (autoboxing of 3rd operand to Boolean) ``` See Java Language Specification, section 15.25 Conditional Operator ? : * For E1, the types of the 2nd and 3rd operands are ```Boolean``` and ```boolean``` respectively, so this clause applies: If one of the second and third operands is of type boolean and the type of the other is of type Boolean, then the type of the conditional expression is boolean. Since the type of the expression is ```boolean```, the 2nd operand must be coerced to ```boolean```. The compiler inserts auto-unboxing code to the 2nd operand (return value of ```returnsNull()```) to make it type ```boolean```. This of course causes the NPE from the ```null``` returned at run-time. * For E2, types of the 2nd and 3rd operands are `````` (not ```Boolean``` as in E1!) and ```boolean``` respectively, so no specific typing clause applies (go read 'em!), so the final "otherwise" clause applies: Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7). * S1 == `````` (see §4.1) * S2 == ```boolean``` * T1 == box(S1) == `````` (see last item in list of boxing conversions in §5.1.7) * T2 == box(S2) == `Boolean * lub(T1, T2) == ```Boolean``` So the type of the conditional expression is ```Boolean``` and the 3rd operand must be coerced to ```Boolean```. The compiler inserts auto-boxing code for the 3rd operand (```false```). The 2nd operand doesn't need the auto-unboxing as in ```E1```, so no auto-unboxing NPE when ```null``` is returned. This question needs a similar type analysis: Java conditional operator ?: result type </s>"
[ "How do DOS games like DOOM benefit from a PCI graphics card?", "DOOM itself doesn’t do anything special to benefit from PCI graphics cards. It runs faster with PCI graphics cards (and VLB, AGP, and PCI Express cards) than with ISA graphics cards because the supporting bus is faster, so reads from and writes to video memory take less time.\nPCI goes to great lengths to preserve backwards compatibility with ISA-based VGA, providing support for “VGA compatible” adapters so that they can appear in memory at the same locations and use the same I/O ports as ISA VGA cards. So accesses to the VGA registers and to the VGA buffer (at 0xA0000) go directly to the main PCI VGA compatible adapter in the system, with no change required in the operating system or programs running on it. (This is the reason why there’s a specific “VGA compatible controller” device type in PCI. Such shenanigans are impossible for other device types in PCI, which is why PCI sound cards have so much trouble providing compatibility with programs written for ISA sound cards.)\nA faster bus and/or faster video memory immediately leads to higher performance in video-intensive programs because software doesn’t need to be careful about how it accesses video memory (except on CGA, and on all platforms with vertical blank synchronisation if it cares about tearing). So ```REP MOVSW``` or ```REP MOVSD``` with no waiting in software, once the program decides to write a frame, is perfectly fine, and will go faster and faster as the underlying hardware improves. On platforms where this can’t work in hardware (e.g. on an 8088 with a VGA card), the hardware takes care of specifics — for example on an 8088 the bus unit will split up 16-bit accesses.\nYour question is specific to DOOM but other DOS games are in a similar situation. Later games tended to rely on VBE (often using UniVBE) to access video modes beyond those provided by VGA, but they mostly didn’t use anything beyond video-mode setup and framebuffer configuration (see also Were any DOS games (or software) known to use VBE/AF?), so improved video speed came mostly from bus speed increases, faster video memory, and speed increases in the cards themselves (which was already a factor in the ISA era, compare most Trident cards to Tseng cards for example).\nFor an excellent explanation of the intricacies of VGA programming and its memory layout, see Fabien Sanglard’s Game Engine Black Book series. The DOOM update loop is shown on page 185 of the DOOM book; it doesn’t use any assembly language (unlike the renderer, see pp. 290 and following), but it does have one perhaps surprising feature given the 32-bit nature of the code: VGA updates are done 16 bits at a time. Section 2.3 of the same book, pp. 59 and following, describes some of the improvements to VGA adapters around the time DOOM was released, in particular the switch to the VESA Local Bus on 486s. The benchmark table on page 287 shows the importance of the bus." ]
"stackexchange"
2
"1df09377eb920fe027499b3390b1cf056b3a29c2ecf763cf7faa5b94e47e016a"
"How do DOS games like DOOM benefit from a PCI graphics card?"
[ { "content": "How do DOS games like DOOM benefit from a PCI graphics card?", "role": "user" }, { "content": "DOOM itself doesn’t do anything special to benefit from PCI graphics cards. It runs faster with PCI graphics cards (and VLB, AGP, and PCI Express cards) than with ISA graphics cards because the supporting bus is faster, so reads from and writes to video memory take less time.\nPCI goes to great lengths to preserve backwards compatibility with ISA-based VGA, providing support for “VGA compatible” adapters so that they can appear in memory at the same locations and use the same I/O ports as ISA VGA cards. So accesses to the VGA registers and to the VGA buffer (at 0xA0000) go directly to the main PCI VGA compatible adapter in the system, with no change required in the operating system or programs running on it. (This is the reason why there’s a specific “VGA compatible controller” device type in PCI. Such shenanigans are impossible for other device types in PCI, which is why PCI sound cards have so much trouble providing compatibility with programs written for ISA sound cards.)\nA faster bus and/or faster video memory immediately leads to higher performance in video-intensive programs because software doesn’t need to be careful about how it accesses video memory (except on CGA, and on all platforms with vertical blank synchronisation if it cares about tearing). So ```REP MOVSW``` or ```REP MOVSD``` with no waiting in software, once the program decides to write a frame, is perfectly fine, and will go faster and faster as the underlying hardware improves. On platforms where this can’t work in hardware (e.g. on an 8088 with a VGA card), the hardware takes care of specifics — for example on an 8088 the bus unit will split up 16-bit accesses.\nYour question is specific to DOOM but other DOS games are in a similar situation. Later games tended to rely on VBE (often using UniVBE) to access video modes beyond those provided by VGA, but they mostly didn’t use anything beyond video-mode setup and framebuffer configuration (see also Were any DOS games (or software) known to use VBE/AF?), so improved video speed came mostly from bus speed increases, faster video memory, and speed increases in the cards themselves (which was already a factor in the ISA era, compare most Trident cards to Tseng cards for example).\nFor an excellent explanation of the intricacies of VGA programming and its memory layout, see Fabien Sanglard’s Game Engine Black Book series. The DOOM update loop is shown on page 185 of the DOOM book; it doesn’t use any assembly language (unlike the renderer, see pp. 290 and following), but it does have one perhaps surprising feature given the 32-bit nature of the code: VGA updates are done 16 bits at a time. Section 2.3 of the same book, pp. 59 and following, describes some of the improvements to VGA adapters around the time DOOM was released, in particular the switch to the VESA Local Bus on 486s. The benchmark table on page 287 shows the importance of the bus.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] How do DOS games like DOOM benefit from a PCI graphics card? [/INST] DOOM itself doesn’t do anything special to benefit from PCI graphics cards. It runs faster with PCI graphics cards (and VLB, AGP, and PCI Express cards) than with ISA graphics cards because the supporting bus is faster, so reads from and writes to video memory take less time. PCI goes to great lengths to preserve backwards compatibility with ISA-based VGA, providing support for “VGA compatible” adapters so that they can appear in memory at the same locations and use the same I/O ports as ISA VGA cards. So accesses to the VGA registers and to the VGA buffer (at 0xA0000) go directly to the main PCI VGA compatible adapter in the system, with no change required in the operating system or programs running on it. (This is the reason why there’s a specific “VGA compatible controller” device type in PCI. Such shenanigans are impossible for other device types in PCI, which is why PCI sound cards have so much trouble providing compatibility with programs written for ISA sound cards.) A faster bus and/or faster video memory immediately leads to higher performance in video-intensive programs because software doesn’t need to be careful about how it accesses video memory (except on CGA, and on all platforms with vertical blank synchronisation if it cares about tearing). So ```REP MOVSW``` or ```REP MOVSD``` with no waiting in software, once the program decides to write a frame, is perfectly fine, and will go faster and faster as the underlying hardware improves. On platforms where this can’t work in hardware (e.g. on an 8088 with a VGA card), the hardware takes care of specifics — for example on an 8088 the bus unit will split up 16-bit accesses. Your question is specific to DOOM but other DOS games are in a similar situation. Later games tended to rely on VBE (often using UniVBE) to access video modes beyond those provided by VGA, but they mostly didn’t use anything beyond video-mode setup and framebuffer configuration (see also Were any DOS games (or software) known to use VBE/AF?), so improved video speed came mostly from bus speed increases, faster video memory, and speed increases in the cards themselves (which was already a factor in the ISA era, compare most Trident cards to Tseng cards for example). For an excellent explanation of the intricacies of VGA programming and its memory layout, see Fabien Sanglard’s Game Engine Black Book series. The DOOM update loop is shown on page 185 of the DOOM book; it doesn’t use any assembly language (unlike the renderer, see pp. 290 and following), but it does have one perhaps surprising feature given the 32-bit nature of the code: VGA updates are done 16 bits at a time. Section 2.3 of the same book, pp. 59 and following, describes some of the improvements to VGA adapters around the time DOOM was released, in particular the switch to the VESA Local Bus on 486s. The benchmark table on page 287 shows the importance of the bus. </s>"
[ "I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python?", "```open``` and ```start``` are command-interpreter things for Mac OS/X and Windows respectively, to do this.\nTo call them from Python, you can either use ```subprocess``` module or ```os.system()```. \nHere are considerations on which package to use:\n\n* You can call them via ```os.system```, which works, but...\nEscaping: ```os.system``` only works with filenames that don't have any spaces or other shell metacharacters in the pathname (e.g. ```A:\\abc\\def\\a.txt```), or else these need to be escaped. There is ```shlex.quote``` for Unix-like systems, but nothing really standard for Windows. Maybe see also python, windows : parsing command lines with shlex\n\n* MacOS/X: ```os.system(\"open \" + shlex.quote(filename))```\n* Windows: ```os.system(\"start \" + filename)``` where properly speaking ```filename``` should be escaped, too.\n\n* You can also call them via ```subprocess``` module, but...\nFor Python 2.7 and newer, simply use\n```subprocess.check_call(['open', filename])\n```\nIn Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile\n```subprocess.run(['open', filename], check=True)\n```\nIf you need to be compatible all the way back to Python 2.4, you can use ```subprocess.call()``` and implement your own error checking:\n```try:\n retcode = subprocess.call(\"open \" + filename, shell=True)\n if retcode < 0:\n print >>sys.stderr, \"Child was terminated by signal\", -retcode\n else:\n print >>sys.stderr, \"Child returned\", retcode\nexcept OSError, e:\n print >>sys.stderr, \"Execution failed:\", e\n```\nNow, what are the advantages of using ```subprocess```?\n\n* Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent \"but you can type ```'filename ; rm -rf /'```\" problem, and if the file name can be corrupted, using ```subprocess.call``` gives us little additional protection.\n* Error handling: It doesn't actually give us any more error detection, we're still depending on the ```retcode``` in either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error).\n* Spawns a (non-blocking) subprocess: We don't need to wait for the child process, since we're by problem statement starting a separate process.\n\nTo the objection \"But ```subprocess``` is preferred.\" However, ```os.system()``` is not deprecated, and it's in some sense the simplest tool for this particular job. Conclusion: using ```os.system()``` is therefore also a correct answer.\nA marked disadvantage is that the Windows ```start``` command requires you to pass in ```shell=True``` which negates most of the benefits of using ```subprocess```.\n" ]
"stackexchange"
2
"8319c941fe18ff94f78fc64b09017b0685711341a273a6b8e587fa8132c11e36"
"I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python?"
[ { "content": "I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python?", "role": "user" }, { "content": "```open``` and ```start``` are command-interpreter things for Mac OS/X and Windows respectively, to do this.\nTo call them from Python, you can either use ```subprocess``` module or ```os.system()```. \nHere are considerations on which package to use:\n\n* You can call them via ```os.system```, which works, but...\nEscaping: ```os.system``` only works with filenames that don't have any spaces or other shell metacharacters in the pathname (e.g. ```A:\\abc\\def\\a.txt```), or else these need to be escaped. There is ```shlex.quote``` for Unix-like systems, but nothing really standard for Windows. Maybe see also python, windows : parsing command lines with shlex\n\n* MacOS/X: ```os.system(\"open \" + shlex.quote(filename))```\n* Windows: ```os.system(\"start \" + filename)``` where properly speaking ```filename``` should be escaped, too.\n\n* You can also call them via ```subprocess``` module, but...\nFor Python 2.7 and newer, simply use\n```subprocess.check_call(['open', filename])\n```\nIn Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile\n```subprocess.run(['open', filename], check=True)\n```\nIf you need to be compatible all the way back to Python 2.4, you can use ```subprocess.call()``` and implement your own error checking:\n```try:\n retcode = subprocess.call(\"open \" + filename, shell=True)\n if retcode < 0:\n print >>sys.stderr, \"Child was terminated by signal\", -retcode\n else:\n print >>sys.stderr, \"Child returned\", retcode\nexcept OSError, e:\n print >>sys.stderr, \"Execution failed:\", e\n```\nNow, what are the advantages of using ```subprocess```?\n\n* Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent \"but you can type ```'filename ; rm -rf /'```\" problem, and if the file name can be corrupted, using ```subprocess.call``` gives us little additional protection.\n* Error handling: It doesn't actually give us any more error detection, we're still depending on the ```retcode``` in either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error).\n* Spawns a (non-blocking) subprocess: We don't need to wait for the child process, since we're by problem statement starting a separate process.\n\nTo the objection \"But ```subprocess``` is preferred.\" However, ```os.system()``` is not deprecated, and it's in some sense the simplest tool for this particular job. Conclusion: using ```os.system()``` is therefore also a correct answer.\nA marked disadvantage is that the Windows ```start``` command requires you to pass in ```shell=True``` which negates most of the benefits of using ```subprocess```.\n", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python? [/INST] ```open``` and ```start``` are command-interpreter things for Mac OS/X and Windows respectively, to do this. To call them from Python, you can either use ```subprocess``` module or ```os.system()```. Here are considerations on which package to use: * You can call them via ```os.system```, which works, but... Escaping: ```os.system``` only works with filenames that don't have any spaces or other shell metacharacters in the pathname (e.g. ```A:\abc\def\a.txt```), or else these need to be escaped. There is ```shlex.quote``` for Unix-like systems, but nothing really standard for Windows. Maybe see also python, windows : parsing command lines with shlex * MacOS/X: ```os.system("open " + shlex.quote(filename))``` * Windows: ```os.system("start " + filename)``` where properly speaking ```filename``` should be escaped, too. * You can also call them via ```subprocess``` module, but... For Python 2.7 and newer, simply use ```subprocess.check_call(['open', filename]) ``` In Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile ```subprocess.run(['open', filename], check=True) ``` If you need to be compatible all the way back to Python 2.4, you can use ```subprocess.call()``` and implement your own error checking: ```try: retcode = subprocess.call("open " + filename, shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e ``` Now, what are the advantages of using ```subprocess```? * Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type ```'filename ; rm -rf /'```" problem, and if the file name can be corrupted, using ```subprocess.call``` gives us little additional protection. * Error handling: It doesn't actually give us any more error detection, we're still depending on the ```retcode``` in either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error). * Spawns a (non-blocking) subprocess: We don't need to wait for the child process, since we're by problem statement starting a separate process. To the objection "But ```subprocess``` is preferred." However, ```os.system()``` is not deprecated, and it's in some sense the simplest tool for this particular job. Conclusion: using ```os.system()``` is therefore also a correct answer. A marked disadvantage is that the Windows ```start``` command requires you to pass in ```shell=True``` which negates most of the benefits of using ```subprocess```. </s>"
[ "Why does PRC devalue its currency on purpose, but Turkey is worried about the devaluation of its currency?", "Trade surplus/deficit\nDevaluing one's currency means mostly one thing: It becomes more expensive to import products from abroad, while one's own products become comparably cheaper to buy on the world market. That means a country which exports lots of goods wants to devalue their currency while a country which imports lots of goods does not.\nIn 2016, Turkey imported goods worth US $186 billion and exported goods worth US $156 billion. That means they had a trade deficit of 19%.\nHowever, China only imported goods worth US $1.23 trillion and exported goods worth US $2.27 trillion in 2016. That means they had a trade surplus of 84%.\nWhich is why China wants to devalue their currency while Turkey does not.\nDebt management\nAnother reason to devalue one's currency is that it reduces any debts denoted in that currency. If a country has a problem of too much public and private debt, then an easy way to get rid of it is to cause a hyperinflation. \nChina happens to have a debt-to-gdp ratio of 47.6% while Turkey only has one of 28.3%. When you look at the private debt (debt of private citizens and companies in the country), you see the same picture. Private debit in Turkey was 170% of GDP, while China's is rumored to be over 300%.\nWhich is why reducing debt through causing inflation seems more attractive to China than to Turkey.\nForeign investor relations\nSo why don't all countries get rid of their debt by adding a few zeroes to their bank notes? Because inflating your currency is a surefire way to drive away any foreign investors. Nobody will invest money into your country when that money might be worth nothing in a few years. Investors want stable currencies. Again, we observe the same difference in motivation between Turkey and China here. Turkey is actively inviting foreign investors, but China is quite reluctant to allow foreign economic influence in their country." ]
"stackexchange"
2
"5bbbf1bec394b515bf86ec1c1e0eb0246b26299632fcc024a08f96ce2fdbc2f4"
"Why does PRC devalue its currency on purpose, but Turkey is worried about the devaluation of its currency?"
[ { "content": "Why does PRC devalue its currency on purpose, but Turkey is worried about the devaluation of its currency?", "role": "user" }, { "content": "Trade surplus/deficit\nDevaluing one's currency means mostly one thing: It becomes more expensive to import products from abroad, while one's own products become comparably cheaper to buy on the world market. That means a country which exports lots of goods wants to devalue their currency while a country which imports lots of goods does not.\nIn 2016, Turkey imported goods worth US $186 billion and exported goods worth US $156 billion. That means they had a trade deficit of 19%.\nHowever, China only imported goods worth US $1.23 trillion and exported goods worth US $2.27 trillion in 2016. That means they had a trade surplus of 84%.\nWhich is why China wants to devalue their currency while Turkey does not.\nDebt management\nAnother reason to devalue one's currency is that it reduces any debts denoted in that currency. If a country has a problem of too much public and private debt, then an easy way to get rid of it is to cause a hyperinflation. \nChina happens to have a debt-to-gdp ratio of 47.6% while Turkey only has one of 28.3%. When you look at the private debt (debt of private citizens and companies in the country), you see the same picture. Private debit in Turkey was 170% of GDP, while China's is rumored to be over 300%.\nWhich is why reducing debt through causing inflation seems more attractive to China than to Turkey.\nForeign investor relations\nSo why don't all countries get rid of their debt by adding a few zeroes to their bank notes? Because inflating your currency is a surefire way to drive away any foreign investors. Nobody will invest money into your country when that money might be worth nothing in a few years. Investors want stable currencies. Again, we observe the same difference in motivation between Turkey and China here. Turkey is actively inviting foreign investors, but China is quite reluctant to allow foreign economic influence in their country.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Why does PRC devalue its currency on purpose, but Turkey is worried about the devaluation of its currency? [/INST] Trade surplus/deficit Devaluing one's currency means mostly one thing: It becomes more expensive to import products from abroad, while one's own products become comparably cheaper to buy on the world market. That means a country which exports lots of goods wants to devalue their currency while a country which imports lots of goods does not. In 2016, Turkey imported goods worth US $186 billion and exported goods worth US $156 billion. That means they had a trade deficit of 19%. However, China only imported goods worth US $1.23 trillion and exported goods worth US $2.27 trillion in 2016. That means they had a trade surplus of 84%. Which is why China wants to devalue their currency while Turkey does not. Debt management Another reason to devalue one's currency is that it reduces any debts denoted in that currency. If a country has a problem of too much public and private debt, then an easy way to get rid of it is to cause a hyperinflation. China happens to have a debt-to-gdp ratio of 47.6% while Turkey only has one of 28.3%. When you look at the private debt (debt of private citizens and companies in the country), you see the same picture. Private debit in Turkey was 170% of GDP, while China's is rumored to be over 300%. Which is why reducing debt through causing inflation seems more attractive to China than to Turkey. Foreign investor relations So why don't all countries get rid of their debt by adding a few zeroes to their bank notes? Because inflating your currency is a surefire way to drive away any foreign investors. Nobody will invest money into your country when that money might be worth nothing in a few years. Investors want stable currencies. Again, we observe the same difference in motivation between Turkey and China here. Turkey is actively inviting foreign investors, but China is quite reluctant to allow foreign economic influence in their country. </s>"
[ "Is it worth patenting an algorithm if I don't have the money to defend against infringements?", "This is a great question, with no one right answer.\nThe strength of a patent comes from the ability to enforce it. If the patent owner cannot enforce it for whatever reason (such as a lack of funding), the patent is effectively toothless.\nBut your competitors will likely not know that. They may therefore be dissuaded from infringing simply by the existence of a patent and the assumption that you would sue. Such a chilling effect on competition may be valuable to you.\nIn addition, if there is infringement, you may be able to get a licensing agreement without the need for litigation. This can be a very lucrative business model, and so may justify the cost of patenting.\nAnd if litigation seems likely, there is a nascent field of litigation funding. While your funders will take quite a great deal of the damages, you may at least get something out of the end of it.\nFinally, even if you can't sue, someone else could. You might therefore get quite some value from selling it off at some point. There are a number of tech businesses where most of their value comes from their IP portfolio.\nOn the whole therefore it depends how you see yourself proceeding. If you're unsure, it may pay to err on the side of patenting: once you disclose or use your invention publicly, you're generally barred from patenting it later (but for a short grace period in some countries), whereas it's easy to abandon a patent (or application) later down the track if you wish." ]
"stackexchange"
2
"0e901b0a1b8c86fd275b0c12ded35a08fdad4b461c589d9b1ceedf44f9a7a83e"
"Is it worth patenting an algorithm if I don't have the money to defend against infringements?"
[ { "content": "Is it worth patenting an algorithm if I don't have the money to defend against infringements?", "role": "user" }, { "content": "This is a great question, with no one right answer.\nThe strength of a patent comes from the ability to enforce it. If the patent owner cannot enforce it for whatever reason (such as a lack of funding), the patent is effectively toothless.\nBut your competitors will likely not know that. They may therefore be dissuaded from infringing simply by the existence of a patent and the assumption that you would sue. Such a chilling effect on competition may be valuable to you.\nIn addition, if there is infringement, you may be able to get a licensing agreement without the need for litigation. This can be a very lucrative business model, and so may justify the cost of patenting.\nAnd if litigation seems likely, there is a nascent field of litigation funding. While your funders will take quite a great deal of the damages, you may at least get something out of the end of it.\nFinally, even if you can't sue, someone else could. You might therefore get quite some value from selling it off at some point. There are a number of tech businesses where most of their value comes from their IP portfolio.\nOn the whole therefore it depends how you see yourself proceeding. If you're unsure, it may pay to err on the side of patenting: once you disclose or use your invention publicly, you're generally barred from patenting it later (but for a short grace period in some countries), whereas it's easy to abandon a patent (or application) later down the track if you wish.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Is it worth patenting an algorithm if I don't have the money to defend against infringements? [/INST] This is a great question, with no one right answer. The strength of a patent comes from the ability to enforce it. If the patent owner cannot enforce it for whatever reason (such as a lack of funding), the patent is effectively toothless. But your competitors will likely not know that. They may therefore be dissuaded from infringing simply by the existence of a patent and the assumption that you would sue. Such a chilling effect on competition may be valuable to you. In addition, if there is infringement, you may be able to get a licensing agreement without the need for litigation. This can be a very lucrative business model, and so may justify the cost of patenting. And if litigation seems likely, there is a nascent field of litigation funding. While your funders will take quite a great deal of the damages, you may at least get something out of the end of it. Finally, even if you can't sue, someone else could. You might therefore get quite some value from selling it off at some point. There are a number of tech businesses where most of their value comes from their IP portfolio. On the whole therefore it depends how you see yourself proceeding. If you're unsure, it may pay to err on the side of patenting: once you disclose or use your invention publicly, you're generally barred from patenting it later (but for a short grace period in some countries), whereas it's easy to abandon a patent (or application) later down the track if you wish. </s>"
[ "\"I have a ```String[]``` with values like so:\n```public static final String[] VALUES = new String[] {\"\"AB\"\",\"\"BC\"\",\"\"CD\"\",\"\"AE\"\"};\n```\nGiven ```String s```, is there a good way of testing whether ```VALUES``` contains ```s```?\" How do I determine whether an array contains a particular value in Java?", "Four Different Ways to Check If an Array Contains a Value:\n\n* Using ```List```:\n```public static boolean useList(String[] arr, String targetValue) {\n return Arrays.asList(arr).contains(targetValue);\n}\n```\n* Using ```Set```:\n```public static boolean useSet(String[] arr, String targetValue) {\n Set set = new HashSet(Arrays.asList(arr));\n return set.contains(targetValue);\n}\n```\n* Using a simple loop:\n```public static boolean useLoop(String[] arr, String targetValue) {\n for (String s: arr) {\n if (s.equals(targetValue))\n return true;\n }\n return false;\n}\n```\n* Using ```Arrays.binarySearch()```:\nThe code below is wrong, it is listed here for completeness. ```binarySearch()``` can ONLY be used on sorted arrays. You will find the result is weird below. This is the best option when array is sorted.\n```public static boolean binarySearch(String[] arr, String targetValue) {\n return Arrays.binarySearch(arr, targetValue) >= 0;\n}\n```\n\nQuick Example:\n```String testValue=\"test\";\nString newValueNotInList=\"newValue\";\nString[] valueArray = { \"this\", \"is\", \"java\" , \"test\" };\nArrays.asList(valueArray).contains(testValue); // returns true\nArrays.asList(valueArray).contains(newValueNotInList); // returns false\n```" ]
"stackexchange"
2
"8f2674a18e36c3ea08567ded7e90f4386b6dbed1d21db9fc8753a82e5741b36e"
""I have a ```String[]``` with values like so: ```public static final String[] VALUES = new String[] {""AB"",""BC"",""CD"",""AE""}; ``` Given ```String s```, is there a good way of testing whether ```VALUES``` contains ```s```?" How do I determine whether an array contains a particular value in Java?"
[ { "content": "\"I have a ```String[]``` with values like so:\n```public static final String[] VALUES = new String[] {\"\"AB\"\",\"\"BC\"\",\"\"CD\"\",\"\"AE\"\"};\n```\nGiven ```String s```, is there a good way of testing whether ```VALUES``` contains ```s```?\" How do I determine whether an array contains a particular value in Java?", "role": "user" }, { "content": "Four Different Ways to Check If an Array Contains a Value:\n\n* Using ```List```:\n```public static boolean useList(String[] arr, String targetValue) {\n return Arrays.asList(arr).contains(targetValue);\n}\n```\n* Using ```Set```:\n```public static boolean useSet(String[] arr, String targetValue) {\n Set set = new HashSet(Arrays.asList(arr));\n return set.contains(targetValue);\n}\n```\n* Using a simple loop:\n```public static boolean useLoop(String[] arr, String targetValue) {\n for (String s: arr) {\n if (s.equals(targetValue))\n return true;\n }\n return false;\n}\n```\n* Using ```Arrays.binarySearch()```:\nThe code below is wrong, it is listed here for completeness. ```binarySearch()``` can ONLY be used on sorted arrays. You will find the result is weird below. This is the best option when array is sorted.\n```public static boolean binarySearch(String[] arr, String targetValue) {\n return Arrays.binarySearch(arr, targetValue) >= 0;\n}\n```\n\nQuick Example:\n```String testValue=\"test\";\nString newValueNotInList=\"newValue\";\nString[] valueArray = { \"this\", \"is\", \"java\" , \"test\" };\nArrays.asList(valueArray).contains(testValue); // returns true\nArrays.asList(valueArray).contains(newValueNotInList); // returns false\n```", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] "I have a ```String[]``` with values like so: ```public static final String[] VALUES = new String[] {""AB"",""BC"",""CD"",""AE""}; ``` Given ```String s```, is there a good way of testing whether ```VALUES``` contains ```s```?" How do I determine whether an array contains a particular value in Java? [/INST] Four Different Ways to Check If an Array Contains a Value: * Using ```List```: ```public static boolean useList(String[] arr, String targetValue) { return Arrays.asList(arr).contains(targetValue); } ``` * Using ```Set```: ```public static boolean useSet(String[] arr, String targetValue) { Set set = new HashSet(Arrays.asList(arr)); return set.contains(targetValue); } ``` * Using a simple loop: ```public static boolean useLoop(String[] arr, String targetValue) { for (String s: arr) { if (s.equals(targetValue)) return true; } return false; } ``` * Using ```Arrays.binarySearch()```: The code below is wrong, it is listed here for completeness. ```binarySearch()``` can ONLY be used on sorted arrays. You will find the result is weird below. This is the best option when array is sorted. ```public static boolean binarySearch(String[] arr, String targetValue) { return Arrays.binarySearch(arr, targetValue) >= 0; } ``` Quick Example: ```String testValue="test"; String newValueNotInList="newValue"; String[] valueArray = { "this", "is", "java" , "test" }; Arrays.asList(valueArray).contains(testValue); // returns true Arrays.asList(valueArray).contains(newValueNotInList); // returns false ``` </s>"
[ "Does Java casting introduce overhead? Or the compiler just resolves everything and there is no cost at run time?\nIs this a general things, or there are different cases?", "There are 2 types of casting in Java:\n\nImplicit casting, when you cast from a type to a wider type, which is done automatically and there is no overhead:\n```String s = \"Cast\";\nObject o = s; // implicit casting\n```\nExplicit casting, when you go from a wider type to a more narrow one. For this case, you must explicitly use casting like that:\n```Object o = someObject;\nString s = (String) o; // explicit casting\n```\nIn this second case, there is overhead in runtime, because the two types must be checked and in case that casting is not feasible, JVM must throw a ClassCastException.\n\nTaken from JavaWorld: The cost of casting\n\n> Casting is used to convert between types -- between reference types in particular, for the type of casting operation in which we're interested here. Upcast operations (also called widening conversions in the Java Language Specification) convert a subclass reference to an ancestor class reference. This casting operation is normally automatic, since it's always safe and can be implemented directly by the compiler. Downcast operations (also called narrowing conversions in the Java Language Specification) convert an ancestor class reference to a subclass reference. This casting operation creates execution overhead, since Java requires that the cast be checked at runtime to make sure that it's valid. If the referenced object is not an instance of either the target type for the cast or a subclass of that type, the attempted cast is not permitted and must throw a java.lang.ClassCastException.\n" ]
"stackexchange"
2
"0fde3f5b46b90fa9bc56d6145bf3179fd344d0aa569515cf3f7940e2161782d4"
"Does Java casting introduce overhead? Or the compiler just resolves everything and there is no cost at run time? Is this a general things, or there are different cases?"
[ { "content": "Does Java casting introduce overhead? Or the compiler just resolves everything and there is no cost at run time?\nIs this a general things, or there are different cases?", "role": "user" }, { "content": "There are 2 types of casting in Java:\n\nImplicit casting, when you cast from a type to a wider type, which is done automatically and there is no overhead:\n```String s = \"Cast\";\nObject o = s; // implicit casting\n```\nExplicit casting, when you go from a wider type to a more narrow one. For this case, you must explicitly use casting like that:\n```Object o = someObject;\nString s = (String) o; // explicit casting\n```\nIn this second case, there is overhead in runtime, because the two types must be checked and in case that casting is not feasible, JVM must throw a ClassCastException.\n\nTaken from JavaWorld: The cost of casting\n\n> Casting is used to convert between types -- between reference types in particular, for the type of casting operation in which we're interested here. Upcast operations (also called widening conversions in the Java Language Specification) convert a subclass reference to an ancestor class reference. This casting operation is normally automatic, since it's always safe and can be implemented directly by the compiler. Downcast operations (also called narrowing conversions in the Java Language Specification) convert an ancestor class reference to a subclass reference. This casting operation creates execution overhead, since Java requires that the cast be checked at runtime to make sure that it's valid. If the referenced object is not an instance of either the target type for the cast or a subclass of that type, the attempted cast is not permitted and must throw a java.lang.ClassCastException.\n", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Does Java casting introduce overhead? Or the compiler just resolves everything and there is no cost at run time? Is this a general things, or there are different cases? [/INST] There are 2 types of casting in Java: Implicit casting, when you cast from a type to a wider type, which is done automatically and there is no overhead: ```String s = "Cast"; Object o = s; // implicit casting ``` Explicit casting, when you go from a wider type to a more narrow one. For this case, you must explicitly use casting like that: ```Object o = someObject; String s = (String) o; // explicit casting ``` In this second case, there is overhead in runtime, because the two types must be checked and in case that casting is not feasible, JVM must throw a ClassCastException. Taken from JavaWorld: The cost of casting > Casting is used to convert between types -- between reference types in particular, for the type of casting operation in which we're interested here. Upcast operations (also called widening conversions in the Java Language Specification) convert a subclass reference to an ancestor class reference. This casting operation is normally automatic, since it's always safe and can be implemented directly by the compiler. Downcast operations (also called narrowing conversions in the Java Language Specification) convert an ancestor class reference to a subclass reference. This casting operation creates execution overhead, since Java requires that the cast be checked at runtime to make sure that it's valid. If the referenced object is not an instance of either the target type for the cast or a subclass of that type, the attempted cast is not permitted and must throw a java.lang.ClassCastException. </s>"
[ "How can I copy a string (e.g \"hello\") to the System Clipboard in C#, so next time I press CTRL+V I'll get \"hello\"?", "There are two classes that lives in different assemblies and different namespaces.\n\n* WinForms: use following namespace declaration, make sure ```Main``` is marked with ```[STAThread]``` attribute:\n```using System.Windows.Forms;\n```\n* WPF: use following namespace declaration\n```using System.Windows;\n```\n* console: add reference to ```System.Windows.Forms```, use following namespace declaration, make sure ```Main``` is marked with ```[STAThread]``` attribute. Step-by-step guide in another answer\n```using System.Windows.Forms;\n```\n\nTo copy an exact string (literal in this case):\n```Clipboard.SetText(\"Hello, clipboard\");\n```\nTo copy the contents of a textbox either use TextBox.Copy() or get text first and then set clipboard value:\n```Clipboard.SetText(txtClipboard.Text);\n```\nSee here for an example.\nOr... Official MSDN documentation or Here for WPF.\n\nRemarks:\n\n* Clipboard is desktop UI concept, trying to set it in server side code like ASP.Net will only set value on the server and has no impact on what user can see in they browser. While linked answer lets one to run Clipboard access code server side with ```SetApartmentState``` it is unlikely what you want to achieve.\n* If after following information in this question code still gets an exception see &quot;Current thread must be set to single thread apartment (STA)&quot; error in copy string to clipboard\n* This question/answer covers regular .NET, for .NET Core see - .Net Core - copy to clipboard?\n" ]
"stackexchange"
2
"7f269a382ec8177e5b0088f1277f4adddad2e7925ede07f62d1dbc7f1d0f2a50"
"How can I copy a string (e.g "hello") to the System Clipboard in C#, so next time I press CTRL+V I'll get "hello"?"
[ { "content": "How can I copy a string (e.g \"hello\") to the System Clipboard in C#, so next time I press CTRL+V I'll get \"hello\"?", "role": "user" }, { "content": "There are two classes that lives in different assemblies and different namespaces.\n\n* WinForms: use following namespace declaration, make sure ```Main``` is marked with ```[STAThread]``` attribute:\n```using System.Windows.Forms;\n```\n* WPF: use following namespace declaration\n```using System.Windows;\n```\n* console: add reference to ```System.Windows.Forms```, use following namespace declaration, make sure ```Main``` is marked with ```[STAThread]``` attribute. Step-by-step guide in another answer\n```using System.Windows.Forms;\n```\n\nTo copy an exact string (literal in this case):\n```Clipboard.SetText(\"Hello, clipboard\");\n```\nTo copy the contents of a textbox either use TextBox.Copy() or get text first and then set clipboard value:\n```Clipboard.SetText(txtClipboard.Text);\n```\nSee here for an example.\nOr... Official MSDN documentation or Here for WPF.\n\nRemarks:\n\n* Clipboard is desktop UI concept, trying to set it in server side code like ASP.Net will only set value on the server and has no impact on what user can see in they browser. While linked answer lets one to run Clipboard access code server side with ```SetApartmentState``` it is unlikely what you want to achieve.\n* If after following information in this question code still gets an exception see &quot;Current thread must be set to single thread apartment (STA)&quot; error in copy string to clipboard\n* This question/answer covers regular .NET, for .NET Core see - .Net Core - copy to clipboard?\n", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] How can I copy a string (e.g "hello") to the System Clipboard in C#, so next time I press CTRL+V I'll get "hello"? [/INST] There are two classes that lives in different assemblies and different namespaces. * WinForms: use following namespace declaration, make sure ```Main``` is marked with ```[STAThread]``` attribute: ```using System.Windows.Forms; ``` * WPF: use following namespace declaration ```using System.Windows; ``` * console: add reference to ```System.Windows.Forms```, use following namespace declaration, make sure ```Main``` is marked with ```[STAThread]``` attribute. Step-by-step guide in another answer ```using System.Windows.Forms; ``` To copy an exact string (literal in this case): ```Clipboard.SetText("Hello, clipboard"); ``` To copy the contents of a textbox either use TextBox.Copy() or get text first and then set clipboard value: ```Clipboard.SetText(txtClipboard.Text); ``` See here for an example. Or... Official MSDN documentation or Here for WPF. Remarks: * Clipboard is desktop UI concept, trying to set it in server side code like ASP.Net will only set value on the server and has no impact on what user can see in they browser. While linked answer lets one to run Clipboard access code server side with ```SetApartmentState``` it is unlikely what you want to achieve. * If after following information in this question code still gets an exception see &quot;Current thread must be set to single thread apartment (STA)&quot; error in copy string to clipboard * This question/answer covers regular .NET, for .NET Core see - .Net Core - copy to clipboard? </s>"
[ "I want to put a draft watermark using the below script but the problem is that the watermark don't come over the images and I want it to come over it.\n```\\usepackage{draftwatermark}\n\\SetWatermarkText{DRAFT}\n\\SetWatermarkScale{1}\n```", "The problem is that the ```draftwatermark``` places the material in the background, so other elements (for example, figures and listings) might cover the included material; to prevent this, instead of using the ```draftwatermark``` package, you can use the ```xwatermark``` package; the starred variant of ```\\newwatermark``` places the material in the foreground which seems to be what you need. A little example:\nFirst, with the unstarred variant (material on the background, so a figure will be placed on top of it):\n```\\documentclass{article}\n\\usepackage[printwatermark]{xwatermark}\n\\usepackage{xcolor}\n\\usepackage{graphicx}\n\\usepackage{lipsum}\n\\newwatermark[allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRAFT}\n\\begin{document}\n\\lipsum[1-2]\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=3cm]{example-image-a}\n\\end{figure}\n\\lipsum[1-2]\n\\end{document}\n```\n\nAnd now, with the starred variant (material on the foreground, so it will appear on top of figures):\n```\\documentclass{article}\n\\usepackage[printwatermark]{xwatermark}\n\\usepackage{xcolor}\n\\usepackage{graphicx}\n\\usepackage{lipsum}\n\\newwatermark*[allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRAFT}\n\\begin{document}\n\\lipsum[1-2]\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=3cm]{example-image-a}\n\\end{figure}\n\\lipsum[1-2]\n\\end{document}\n```\n" ]
"stackexchange"
2
"f98ea5fb91d96688630160e630bcf603afba53951d6ceb7a973567bd9b2679f9"
"I want to put a draft watermark using the below script but the problem is that the watermark don't come over the images and I want it to come over it. ```\usepackage{draftwatermark} \SetWatermarkText{DRAFT} \SetWatermarkScale{1} ```"
[ { "content": "I want to put a draft watermark using the below script but the problem is that the watermark don't come over the images and I want it to come over it.\n```\\usepackage{draftwatermark}\n\\SetWatermarkText{DRAFT}\n\\SetWatermarkScale{1}\n```", "role": "user" }, { "content": "The problem is that the ```draftwatermark``` places the material in the background, so other elements (for example, figures and listings) might cover the included material; to prevent this, instead of using the ```draftwatermark``` package, you can use the ```xwatermark``` package; the starred variant of ```\\newwatermark``` places the material in the foreground which seems to be what you need. A little example:\nFirst, with the unstarred variant (material on the background, so a figure will be placed on top of it):\n```\\documentclass{article}\n\\usepackage[printwatermark]{xwatermark}\n\\usepackage{xcolor}\n\\usepackage{graphicx}\n\\usepackage{lipsum}\n\\newwatermark[allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRAFT}\n\\begin{document}\n\\lipsum[1-2]\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=3cm]{example-image-a}\n\\end{figure}\n\\lipsum[1-2]\n\\end{document}\n```\n\nAnd now, with the starred variant (material on the foreground, so it will appear on top of figures):\n```\\documentclass{article}\n\\usepackage[printwatermark]{xwatermark}\n\\usepackage{xcolor}\n\\usepackage{graphicx}\n\\usepackage{lipsum}\n\\newwatermark*[allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRAFT}\n\\begin{document}\n\\lipsum[1-2]\n\\begin{figure}[!ht]\n\\centering\n\\includegraphics[width=3cm]{example-image-a}\n\\end{figure}\n\\lipsum[1-2]\n\\end{document}\n```\n", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] I want to put a draft watermark using the below script but the problem is that the watermark don't come over the images and I want it to come over it. ```\usepackage{draftwatermark} \SetWatermarkText{DRAFT} \SetWatermarkScale{1} ``` [/INST] The problem is that the ```draftwatermark``` places the material in the background, so other elements (for example, figures and listings) might cover the included material; to prevent this, instead of using the ```draftwatermark``` package, you can use the ```xwatermark``` package; the starred variant of ```\newwatermark``` places the material in the foreground which seems to be what you need. A little example: First, with the unstarred variant (material on the background, so a figure will be placed on top of it): ```\documentclass{article} \usepackage[printwatermark]{xwatermark} \usepackage{xcolor} \usepackage{graphicx} \usepackage{lipsum} \newwatermark[allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRAFT} \begin{document} \lipsum[1-2] \begin{figure}[!ht] \centering \includegraphics[width=3cm]{example-image-a} \end{figure} \lipsum[1-2] \end{document} ``` And now, with the starred variant (material on the foreground, so it will appear on top of figures): ```\documentclass{article} \usepackage[printwatermark]{xwatermark} \usepackage{xcolor} \usepackage{graphicx} \usepackage{lipsum} \newwatermark*[allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRAFT} \begin{document} \lipsum[1-2] \begin{figure}[!ht] \centering \includegraphics[width=3cm]{example-image-a} \end{figure} \lipsum[1-2] \end{document} ``` </s>"
[ "Understanding the Rails Authenticity Token", "What is CSRF?\nThe Authenticity Token is a countermeasure to Cross-Site Request Forgery (CSRF). What is CSRF, you ask?\nIt's a way that an attacker can potentially hijack sessions without even knowing session tokens. \nScenario:\n\n* Visit your bank's site, log in.\n* Then visit the attacker's site (e.g. sponsored ad from an untrusted organization).\n* Attacker's page includes form with same fields as the bank's \"Transfer Funds\" form.\n* Attacker knows your account info, and has pre-filled form fields to transfer money from your account to attacker's account.\n* Attacker's page includes Javascript that submits form to your bank.\n* When form gets submitted, browser includes your cookies for the bank site, including the session token.\n* Bank transfers money to attacker's account.\n* The form can be in an iframe that is invisible, so you never know the attack occurred. \n* This is called Cross-Site Request Forgery (CSRF). \n\nCSRF solution:\n\n* Server can mark forms that came from the server itself\n* Every form must contain an additional authentication token as a hidden field.\n* Token must be unpredictable (attacker can't guess it).\n* Server provides valid token in forms in its pages.\n* Server checks token when form posted, rejects forms without proper token. \n* Example token: session identifier encrypted with server secret key.\n* Rails automatically generates such tokens: see the authenticity_token input field in every form. \n" ]
"stackexchange"
2
"446983cd7a189d4906b839f22203ceebf1c32125c40faaf6aca67e659be6683d"
"Understanding the Rails Authenticity Token"
[ { "content": "Understanding the Rails Authenticity Token", "role": "user" }, { "content": "What is CSRF?\nThe Authenticity Token is a countermeasure to Cross-Site Request Forgery (CSRF). What is CSRF, you ask?\nIt's a way that an attacker can potentially hijack sessions without even knowing session tokens. \nScenario:\n\n* Visit your bank's site, log in.\n* Then visit the attacker's site (e.g. sponsored ad from an untrusted organization).\n* Attacker's page includes form with same fields as the bank's \"Transfer Funds\" form.\n* Attacker knows your account info, and has pre-filled form fields to transfer money from your account to attacker's account.\n* Attacker's page includes Javascript that submits form to your bank.\n* When form gets submitted, browser includes your cookies for the bank site, including the session token.\n* Bank transfers money to attacker's account.\n* The form can be in an iframe that is invisible, so you never know the attack occurred. \n* This is called Cross-Site Request Forgery (CSRF). \n\nCSRF solution:\n\n* Server can mark forms that came from the server itself\n* Every form must contain an additional authentication token as a hidden field.\n* Token must be unpredictable (attacker can't guess it).\n* Server provides valid token in forms in its pages.\n* Server checks token when form posted, rejects forms without proper token. \n* Example token: session identifier encrypted with server secret key.\n* Rails automatically generates such tokens: see the authenticity_token input field in every form. \n", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Understanding the Rails Authenticity Token [/INST] What is CSRF? The Authenticity Token is a countermeasure to Cross-Site Request Forgery (CSRF). What is CSRF, you ask? It's a way that an attacker can potentially hijack sessions without even knowing session tokens. Scenario: * Visit your bank's site, log in. * Then visit the attacker's site (e.g. sponsored ad from an untrusted organization). * Attacker's page includes form with same fields as the bank's "Transfer Funds" form. * Attacker knows your account info, and has pre-filled form fields to transfer money from your account to attacker's account. * Attacker's page includes Javascript that submits form to your bank. * When form gets submitted, browser includes your cookies for the bank site, including the session token. * Bank transfers money to attacker's account. * The form can be in an iframe that is invisible, so you never know the attack occurred. * This is called Cross-Site Request Forgery (CSRF). CSRF solution: * Server can mark forms that came from the server itself * Every form must contain an additional authentication token as a hidden field. * Token must be unpredictable (attacker can't guess it). * Server provides valid token in forms in its pages. * Server checks token when form posted, rejects forms without proper token. * Example token: session identifier encrypted with server secret key. * Rails automatically generates such tokens: see the authenticity_token input field in every form. </s>"
[ "Why is FIFA against adding instant replay to the game?", "There are a few fundamental considerations:\n\n* Uncertainty is a part of the game. The referee and linesmen are the arbiters of the action. Instant replay would limit their authority.\n* Football is global. Many places do not have access to the technology necessary to implement instant replay.\n* Football is a fast-paced game with few opportunities for stoppage. Instant replay would unnecessarily slow the pace.\n\nIn 2008, FiFA President Sepp Blatter said:\n\n \"Let it be as it is and let's leave [football] with errors. The television companies will have the right to say [the referee] was right or wrong, but still the referee makes the decision – a man, not a machine.\"\n\nBlatter and others at FIFA have repeatedly argued against using instant replay. But lately, FIFA has begun to come around on the idea. At FIFA's Congress in São Paulo prior to the 2014 World Cup, Blatter proposed allowing managers 2 challenges per game, much like the NFL handles challenges today.\nAlthough it's not quite \"instant replay,\" in 2012 FIFA approved two different goal-line technologies to improve referee accuracy: \"Hawk-Eye\" -- which uses visual triangulation to determine ball location -- and \"GoalRef\" -- which uses a microchip in the ball and magnetic sensors within goalposts. (Many say FIFA approved the technologies in response to Frank Lampard's snubbed \"goal\" against Germany in the 2010 World Cup.) In 2013, FIFA announced it would use GoalControl, a German competitor to Hawk-Eye, at the Confederations Cup, basically a rehearsal for the World Cup. After a successful run at that tournament, FIFA announced it would implement GoalControl at the 2014 World Cup. The Guardian provides a pretty helpful FAQ on the technology.\nFIFA may choose to implement further changes to approved goal-line technology and referee rules when it meets again after the World Cup." ]
"stackexchange"
2
"9a7cbef8d771bf229122d66e5a704d3e89a3b8aad9dd67d0298f558dea9d5ea3"
"Why is FIFA against adding instant replay to the game?"
[ { "content": "Why is FIFA against adding instant replay to the game?", "role": "user" }, { "content": "There are a few fundamental considerations:\n\n* Uncertainty is a part of the game. The referee and linesmen are the arbiters of the action. Instant replay would limit their authority.\n* Football is global. Many places do not have access to the technology necessary to implement instant replay.\n* Football is a fast-paced game with few opportunities for stoppage. Instant replay would unnecessarily slow the pace.\n\nIn 2008, FiFA President Sepp Blatter said:\n\n \"Let it be as it is and let's leave [football] with errors. The television companies will have the right to say [the referee] was right or wrong, but still the referee makes the decision – a man, not a machine.\"\n\nBlatter and others at FIFA have repeatedly argued against using instant replay. But lately, FIFA has begun to come around on the idea. At FIFA's Congress in São Paulo prior to the 2014 World Cup, Blatter proposed allowing managers 2 challenges per game, much like the NFL handles challenges today.\nAlthough it's not quite \"instant replay,\" in 2012 FIFA approved two different goal-line technologies to improve referee accuracy: \"Hawk-Eye\" -- which uses visual triangulation to determine ball location -- and \"GoalRef\" -- which uses a microchip in the ball and magnetic sensors within goalposts. (Many say FIFA approved the technologies in response to Frank Lampard's snubbed \"goal\" against Germany in the 2010 World Cup.) In 2013, FIFA announced it would use GoalControl, a German competitor to Hawk-Eye, at the Confederations Cup, basically a rehearsal for the World Cup. After a successful run at that tournament, FIFA announced it would implement GoalControl at the 2014 World Cup. The Guardian provides a pretty helpful FAQ on the technology.\nFIFA may choose to implement further changes to approved goal-line technology and referee rules when it meets again after the World Cup.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Why is FIFA against adding instant replay to the game? [/INST] There are a few fundamental considerations: * Uncertainty is a part of the game. The referee and linesmen are the arbiters of the action. Instant replay would limit their authority. * Football is global. Many places do not have access to the technology necessary to implement instant replay. * Football is a fast-paced game with few opportunities for stoppage. Instant replay would unnecessarily slow the pace. In 2008, FiFA President Sepp Blatter said: "Let it be as it is and let's leave [football] with errors. The television companies will have the right to say [the referee] was right or wrong, but still the referee makes the decision – a man, not a machine." Blatter and others at FIFA have repeatedly argued against using instant replay. But lately, FIFA has begun to come around on the idea. At FIFA's Congress in São Paulo prior to the 2014 World Cup, Blatter proposed allowing managers 2 challenges per game, much like the NFL handles challenges today. Although it's not quite "instant replay," in 2012 FIFA approved two different goal-line technologies to improve referee accuracy: "Hawk-Eye" -- which uses visual triangulation to determine ball location -- and "GoalRef" -- which uses a microchip in the ball and magnetic sensors within goalposts. (Many say FIFA approved the technologies in response to Frank Lampard's snubbed "goal" against Germany in the 2010 World Cup.) In 2013, FIFA announced it would use GoalControl, a German competitor to Hawk-Eye, at the Confederations Cup, basically a rehearsal for the World Cup. After a successful run at that tournament, FIFA announced it would implement GoalControl at the 2014 World Cup. The Guardian provides a pretty helpful FAQ on the technology. FIFA may choose to implement further changes to approved goal-line technology and referee rules when it meets again after the World Cup. </s>"
[ "If we should encrypt the message rather than the method of transfer, why do we care about wifi security? Is this just security theatre?", "Network encryption protects against different set of threats than application layer encryption like TLS.\nIn particular, network encryption like Wifi encryption are primarily designed to protect from a local attacker from being able to watch network patterns (by recording who you're making connections with, and discovering what devices are on the local network), observing/tampering of low level messages like ARP/DNS, and protecting network broadcasts from devices that aren't supposed to be in the network, and from tampering or selective interference.\nTLS doesn't protect the low level TCP/IP packets, which leaks information like the IP address of the machine you're connecting with, and the TLS handshake also by design leaks a number of information about the connection like Server Name Indication (SNI) header.\nThe side effect of needing to do all this is that Wifi hardware already need to have enough code and processing power to handle encryption, so it becomes easier to just encrypt all wifi packets rather than selectively figuring out what needs protection or not. This come also with the side benefit that unsecured HTTP connection will still be at least marginally protected, even if at least to protect users of the infrastructure from each other, but not from the infrastructure provider.\nNetwork encryption is designed to protect the network, not the service. Application encryption is designed to protect the connection to the service, but it doesn't protect the network. They complement each other, but neither completely makes the other unnecessary." ]
"stackexchange"
2
"79e87dfd3e8878785e1f8e5625c1b3459354e21ab1bc5420c4cb15b15e381305"
"If we should encrypt the message rather than the method of transfer, why do we care about wifi security? Is this just security theatre?"
[ { "content": "If we should encrypt the message rather than the method of transfer, why do we care about wifi security? Is this just security theatre?", "role": "user" }, { "content": "Network encryption protects against different set of threats than application layer encryption like TLS.\nIn particular, network encryption like Wifi encryption are primarily designed to protect from a local attacker from being able to watch network patterns (by recording who you're making connections with, and discovering what devices are on the local network), observing/tampering of low level messages like ARP/DNS, and protecting network broadcasts from devices that aren't supposed to be in the network, and from tampering or selective interference.\nTLS doesn't protect the low level TCP/IP packets, which leaks information like the IP address of the machine you're connecting with, and the TLS handshake also by design leaks a number of information about the connection like Server Name Indication (SNI) header.\nThe side effect of needing to do all this is that Wifi hardware already need to have enough code and processing power to handle encryption, so it becomes easier to just encrypt all wifi packets rather than selectively figuring out what needs protection or not. This come also with the side benefit that unsecured HTTP connection will still be at least marginally protected, even if at least to protect users of the infrastructure from each other, but not from the infrastructure provider.\nNetwork encryption is designed to protect the network, not the service. Application encryption is designed to protect the connection to the service, but it doesn't protect the network. They complement each other, but neither completely makes the other unnecessary.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] If we should encrypt the message rather than the method of transfer, why do we care about wifi security? Is this just security theatre? [/INST] Network encryption protects against different set of threats than application layer encryption like TLS. In particular, network encryption like Wifi encryption are primarily designed to protect from a local attacker from being able to watch network patterns (by recording who you're making connections with, and discovering what devices are on the local network), observing/tampering of low level messages like ARP/DNS, and protecting network broadcasts from devices that aren't supposed to be in the network, and from tampering or selective interference. TLS doesn't protect the low level TCP/IP packets, which leaks information like the IP address of the machine you're connecting with, and the TLS handshake also by design leaks a number of information about the connection like Server Name Indication (SNI) header. The side effect of needing to do all this is that Wifi hardware already need to have enough code and processing power to handle encryption, so it becomes easier to just encrypt all wifi packets rather than selectively figuring out what needs protection or not. This come also with the side benefit that unsecured HTTP connection will still be at least marginally protected, even if at least to protect users of the infrastructure from each other, but not from the infrastructure provider. Network encryption is designed to protect the network, not the service. Application encryption is designed to protect the connection to the service, but it doesn't protect the network. They complement each other, but neither completely makes the other unnecessary. </s>"
[ "Applying filter in scipy.signal: Use lfilter or filtfilt?", "\n* ```filtfilt``` is zero-phase filtering, which doesn't shift the signal as it filters. Since the phase is zero at all frequencies, it is also linear-phase. Filtering backwards in time requires you to predict the future, so it can't be used in \"online\" real-life applications, only for offline processing of recordings of signals.\n* ```lfilter``` is causal forward-in-time filtering only, similar to a real-life electronic filter. It can't be zero-phase. It can be linear-phase (symmetrical FIR), but usually isn't. Usually it adds different amounts of delay at different frequencies.\n\nAn example and image should make it obvious. Although the magnitude of the frequency response of the filters is identical (top left and top right), the zero-phase lowpass lines up with the original signal, just without high frequency content, while the minimum phase filtering delays the signal in a causal way:\n\n```from __future__ import division, print_function\nimport numpy as np\nfrom numpy.random import randn\nfrom numpy.fft import rfft\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nb, a = signal.butter(4, 0.03, analog=False)\n# Show that frequency response is the same\nimpulse = np.zeros(1000)\nimpulse[500] = 1\n# Applies filter forward and backward in time\nimp_ff = signal.filtfilt(b, a, impulse)\n# Applies filter forward in time twice (for same frequency response)\nimp_lf = signal.lfilter(b, a, signal.lfilter(b, a, impulse))\nplt.subplot(2, 2, 1)\nplt.semilogx(20*np.log10(np.abs(rfft(imp_lf))))\nplt.ylim(-100, 20)\nplt.grid(True, which='both')\nplt.title('lfilter')\nplt.subplot(2, 2, 2)\nplt.semilogx(20*np.log10(np.abs(rfft(imp_ff))))\nplt.ylim(-100, 20)\nplt.grid(True, which='both')\nplt.title('filtfilt')\nsig = np.cumsum(randn(800)) # Brownian noise\nsig_ff = signal.filtfilt(b, a, sig)\nsig_lf = signal.lfilter(b, a, signal.lfilter(b, a, sig))\nplt.subplot(2, 1, 2)\nplt.plot(sig, color='silver', label='Original')\nplt.plot(sig_ff, color='#3465a4', label='filtfilt')\nplt.plot(sig_lf, color='#cc0000', label='lfilter')\nplt.grid(True, which='both')\nplt.legend(loc=\"best\")\n```" ]
"stackexchange"
2
"783c1ae41a662cf634dd4332f4db26dd02db9f862dc5ed2d59d873c422e5058c"
"Applying filter in scipy.signal: Use lfilter or filtfilt?"
[ { "content": "Applying filter in scipy.signal: Use lfilter or filtfilt?", "role": "user" }, { "content": "\n* ```filtfilt``` is zero-phase filtering, which doesn't shift the signal as it filters. Since the phase is zero at all frequencies, it is also linear-phase. Filtering backwards in time requires you to predict the future, so it can't be used in \"online\" real-life applications, only for offline processing of recordings of signals.\n* ```lfilter``` is causal forward-in-time filtering only, similar to a real-life electronic filter. It can't be zero-phase. It can be linear-phase (symmetrical FIR), but usually isn't. Usually it adds different amounts of delay at different frequencies.\n\nAn example and image should make it obvious. Although the magnitude of the frequency response of the filters is identical (top left and top right), the zero-phase lowpass lines up with the original signal, just without high frequency content, while the minimum phase filtering delays the signal in a causal way:\n\n```from __future__ import division, print_function\nimport numpy as np\nfrom numpy.random import randn\nfrom numpy.fft import rfft\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nb, a = signal.butter(4, 0.03, analog=False)\n# Show that frequency response is the same\nimpulse = np.zeros(1000)\nimpulse[500] = 1\n# Applies filter forward and backward in time\nimp_ff = signal.filtfilt(b, a, impulse)\n# Applies filter forward in time twice (for same frequency response)\nimp_lf = signal.lfilter(b, a, signal.lfilter(b, a, impulse))\nplt.subplot(2, 2, 1)\nplt.semilogx(20*np.log10(np.abs(rfft(imp_lf))))\nplt.ylim(-100, 20)\nplt.grid(True, which='both')\nplt.title('lfilter')\nplt.subplot(2, 2, 2)\nplt.semilogx(20*np.log10(np.abs(rfft(imp_ff))))\nplt.ylim(-100, 20)\nplt.grid(True, which='both')\nplt.title('filtfilt')\nsig = np.cumsum(randn(800)) # Brownian noise\nsig_ff = signal.filtfilt(b, a, sig)\nsig_lf = signal.lfilter(b, a, signal.lfilter(b, a, sig))\nplt.subplot(2, 1, 2)\nplt.plot(sig, color='silver', label='Original')\nplt.plot(sig_ff, color='#3465a4', label='filtfilt')\nplt.plot(sig_lf, color='#cc0000', label='lfilter')\nplt.grid(True, which='both')\nplt.legend(loc=\"best\")\n```", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Applying filter in scipy.signal: Use lfilter or filtfilt? [/INST] * ```filtfilt``` is zero-phase filtering, which doesn't shift the signal as it filters. Since the phase is zero at all frequencies, it is also linear-phase. Filtering backwards in time requires you to predict the future, so it can't be used in "online" real-life applications, only for offline processing of recordings of signals. * ```lfilter``` is causal forward-in-time filtering only, similar to a real-life electronic filter. It can't be zero-phase. It can be linear-phase (symmetrical FIR), but usually isn't. Usually it adds different amounts of delay at different frequencies. An example and image should make it obvious. Although the magnitude of the frequency response of the filters is identical (top left and top right), the zero-phase lowpass lines up with the original signal, just without high frequency content, while the minimum phase filtering delays the signal in a causal way: ```from __future__ import division, print_function import numpy as np from numpy.random import randn from numpy.fft import rfft from scipy import signal import matplotlib.pyplot as plt b, a = signal.butter(4, 0.03, analog=False) # Show that frequency response is the same impulse = np.zeros(1000) impulse[500] = 1 # Applies filter forward and backward in time imp_ff = signal.filtfilt(b, a, impulse) # Applies filter forward in time twice (for same frequency response) imp_lf = signal.lfilter(b, a, signal.lfilter(b, a, impulse)) plt.subplot(2, 2, 1) plt.semilogx(20*np.log10(np.abs(rfft(imp_lf)))) plt.ylim(-100, 20) plt.grid(True, which='both') plt.title('lfilter') plt.subplot(2, 2, 2) plt.semilogx(20*np.log10(np.abs(rfft(imp_ff)))) plt.ylim(-100, 20) plt.grid(True, which='both') plt.title('filtfilt') sig = np.cumsum(randn(800)) # Brownian noise sig_ff = signal.filtfilt(b, a, sig) sig_lf = signal.lfilter(b, a, signal.lfilter(b, a, sig)) plt.subplot(2, 1, 2) plt.plot(sig, color='silver', label='Original') plt.plot(sig_ff, color='#3465a4', label='filtfilt') plt.plot(sig_lf, color='#cc0000', label='lfilter') plt.grid(True, which='both') plt.legend(loc="best") ``` </s>"
[ "What do different people in the department expect from a postdoc?\nBy different people I mean the advisor, graduate students and PhD students.\nI know it mainly depends on the job description but there are few basic things that a postdoc must be expected to do. How aggressive (proactive) must one be? This question is important since a postdoc cannot just wait for the adviser to give him/her inputs. Rather the postdoc must take the project(s) as another PhD research of his own but be completely accountable to the adviser in terms of what he/she is doing and how is he/she doing that.\nThe above are my thoughts. My question is divided into the following sub-parts:\n\n* What would you as a professor expect from your postdoc? \n* What preparation one must do to rise to the expected level? \n* Is the preparation merely restricted to having sound academic record and experience?", "You'll very quickly learn that being an academic involves more than just writing research papers. Your time as a postdoc is when you can start learning about these other aspects, while building your own profile.\nA postdoc needs to do the following:\n\n* Build a publication record. This will involve both what you are paid to do and your own line of research.\n* Get involved with supervising students. Help with the PhDs in the lab, and get involved in supervising masters students.\n* Get involved with obtaining funding. This can either be by helping your employer or (ideally) obtaining your own funding. \n* Build an international reputation.\n* Start collaborating with external parties.\n* Gain some teaching experience. This is absolutely crucial if you want a faculty position.\n* Learn how to manage projects and a lab. This includes overseeing the progress of projects, allocating your time (and others), presenting results at meetings and writing deliverables. If you are in a lab setting, you will need to learn how to fix/calibrate/maintain critical equipment and software so that you can start your own lab some day, and you will need to become proficient in teaching more junior members on how to use that equipment.\n* Start to devise a strategic research plan. While it is fun to do opportunistic research, solving a problem that comes along or investigating any idea that pops into your head, a better long term strategy is to formulate an interesting long term research plan and follow it, building result upon result.\n\nBe as proactive as humanly possible, without being annoying. Talk to everyone in the department, especially people whose research interests are close to your. Go to conferences and sit down and work with interesting people (not necessarily the superstars)." ]
"stackexchange"
2
"967b7d3df886735543df43b8e8bdcb4024bb2349df1e472d0706114091e6296a"
"What do different people in the department expect from a postdoc? By different people I mean the advisor, graduate students and PhD students. I know it mainly depends on the job description but there are few basic things that a postdoc must be expected to do. How aggressive (proactive) must one be? This question is important since a postdoc cannot just wait for the adviser to give him/her inputs. Rather the postdoc must take the project(s) as another PhD research of his own but be completely accountable to the adviser in terms of what he/she is doing and how is he/she doing that. The above are my thoughts. My question is divided into the following sub-parts: * What would you as a professor expect from your postdoc? * What preparation one must do to rise to the expected level? * Is the preparation merely restricted to having sound academic record and experience?"
[ { "content": "What do different people in the department expect from a postdoc?\nBy different people I mean the advisor, graduate students and PhD students.\nI know it mainly depends on the job description but there are few basic things that a postdoc must be expected to do. How aggressive (proactive) must one be? This question is important since a postdoc cannot just wait for the adviser to give him/her inputs. Rather the postdoc must take the project(s) as another PhD research of his own but be completely accountable to the adviser in terms of what he/she is doing and how is he/she doing that.\nThe above are my thoughts. My question is divided into the following sub-parts:\n\n* What would you as a professor expect from your postdoc? \n* What preparation one must do to rise to the expected level? \n* Is the preparation merely restricted to having sound academic record and experience?", "role": "user" }, { "content": "You'll very quickly learn that being an academic involves more than just writing research papers. Your time as a postdoc is when you can start learning about these other aspects, while building your own profile.\nA postdoc needs to do the following:\n\n* Build a publication record. This will involve both what you are paid to do and your own line of research.\n* Get involved with supervising students. Help with the PhDs in the lab, and get involved in supervising masters students.\n* Get involved with obtaining funding. This can either be by helping your employer or (ideally) obtaining your own funding. \n* Build an international reputation.\n* Start collaborating with external parties.\n* Gain some teaching experience. This is absolutely crucial if you want a faculty position.\n* Learn how to manage projects and a lab. This includes overseeing the progress of projects, allocating your time (and others), presenting results at meetings and writing deliverables. If you are in a lab setting, you will need to learn how to fix/calibrate/maintain critical equipment and software so that you can start your own lab some day, and you will need to become proficient in teaching more junior members on how to use that equipment.\n* Start to devise a strategic research plan. While it is fun to do opportunistic research, solving a problem that comes along or investigating any idea that pops into your head, a better long term strategy is to formulate an interesting long term research plan and follow it, building result upon result.\n\nBe as proactive as humanly possible, without being annoying. Talk to everyone in the department, especially people whose research interests are close to your. Go to conferences and sit down and work with interesting people (not necessarily the superstars).", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] What do different people in the department expect from a postdoc? By different people I mean the advisor, graduate students and PhD students. I know it mainly depends on the job description but there are few basic things that a postdoc must be expected to do. How aggressive (proactive) must one be? This question is important since a postdoc cannot just wait for the adviser to give him/her inputs. Rather the postdoc must take the project(s) as another PhD research of his own but be completely accountable to the adviser in terms of what he/she is doing and how is he/she doing that. The above are my thoughts. My question is divided into the following sub-parts: * What would you as a professor expect from your postdoc? * What preparation one must do to rise to the expected level? * Is the preparation merely restricted to having sound academic record and experience? [/INST] You'll very quickly learn that being an academic involves more than just writing research papers. Your time as a postdoc is when you can start learning about these other aspects, while building your own profile. A postdoc needs to do the following: * Build a publication record. This will involve both what you are paid to do and your own line of research. * Get involved with supervising students. Help with the PhDs in the lab, and get involved in supervising masters students. * Get involved with obtaining funding. This can either be by helping your employer or (ideally) obtaining your own funding. * Build an international reputation. * Start collaborating with external parties. * Gain some teaching experience. This is absolutely crucial if you want a faculty position. * Learn how to manage projects and a lab. This includes overseeing the progress of projects, allocating your time (and others), presenting results at meetings and writing deliverables. If you are in a lab setting, you will need to learn how to fix/calibrate/maintain critical equipment and software so that you can start your own lab some day, and you will need to become proficient in teaching more junior members on how to use that equipment. * Start to devise a strategic research plan. While it is fun to do opportunistic research, solving a problem that comes along or investigating any idea that pops into your head, a better long term strategy is to formulate an interesting long term research plan and follow it, building result upon result. Be as proactive as humanly possible, without being annoying. Talk to everyone in the department, especially people whose research interests are close to your. Go to conferences and sit down and work with interesting people (not necessarily the superstars). </s>"
[ "Can someone explain to me what the ```contentInset``` property in a ```UIScrollView``` instance is used for? And maybe provide an example?", "While jball's answer is an excellent description of content insets, it doesn't answer the question of when to use it. I'll borrow from his diagrams:\n``` _|←_cW_→_|_↓_\n | |\n---------------\n |content| ↑\n ↑ |content| contentInset.top\ncH |content|\n ↓ |content| contentInset.bottom\n |content| ↓\n---------------\n |content|\n-------------↑-\n```\nThat's what you get when you do it, but the usefulness of it only shows when you scroll:\n``` _|←_cW_→_|_↓_\n |content| ← content is still visible\n---------------\n |content| ↑\n ↑ |content| contentInset.top\ncH |content|\n ↓ |content| contentInset.bottom\n |content| ↓\n---------------\n _|_______|___\n ↑\n```\nThat top row of content will still be visible because it's still inside the frame of the scroll view. One way to think of the top offset is \"how much to shift the content down the scroll view when we're scrolled all the way to the top\"\nTo see a place where this is actually used, look at the build-in Photos app on the iphone. The Navigation bar and status bar are transparent, and the contents of the scroll view are visible underneath. That's because the scroll view's frame extends out that far. But if it wasn't for the content inset, you would never be able to have the top of the content clear that transparent navigation bar when you go all the way to the top." ]
"stackexchange"
2
"f0e352256e0f2253424ee276df5fa4d5197445e4b97465874d0c983e1efc574a"
"Can someone explain to me what the ```contentInset``` property in a ```UIScrollView``` instance is used for? And maybe provide an example?"
[ { "content": "Can someone explain to me what the ```contentInset``` property in a ```UIScrollView``` instance is used for? And maybe provide an example?", "role": "user" }, { "content": "While jball's answer is an excellent description of content insets, it doesn't answer the question of when to use it. I'll borrow from his diagrams:\n``` _|←_cW_→_|_↓_\n | |\n---------------\n |content| ↑\n ↑ |content| contentInset.top\ncH |content|\n ↓ |content| contentInset.bottom\n |content| ↓\n---------------\n |content|\n-------------↑-\n```\nThat's what you get when you do it, but the usefulness of it only shows when you scroll:\n``` _|←_cW_→_|_↓_\n |content| ← content is still visible\n---------------\n |content| ↑\n ↑ |content| contentInset.top\ncH |content|\n ↓ |content| contentInset.bottom\n |content| ↓\n---------------\n _|_______|___\n ↑\n```\nThat top row of content will still be visible because it's still inside the frame of the scroll view. One way to think of the top offset is \"how much to shift the content down the scroll view when we're scrolled all the way to the top\"\nTo see a place where this is actually used, look at the build-in Photos app on the iphone. The Navigation bar and status bar are transparent, and the contents of the scroll view are visible underneath. That's because the scroll view's frame extends out that far. But if it wasn't for the content inset, you would never be able to have the top of the content clear that transparent navigation bar when you go all the way to the top.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Can someone explain to me what the ```contentInset``` property in a ```UIScrollView``` instance is used for? And maybe provide an example? [/INST] While jball's answer is an excellent description of content insets, it doesn't answer the question of when to use it. I'll borrow from his diagrams: ``` _|←_cW_→_|_↓_ | | --------------- |content| ↑ ↑ |content| contentInset.top cH |content| ↓ |content| contentInset.bottom |content| ↓ --------------- |content| -------------↑- ``` That's what you get when you do it, but the usefulness of it only shows when you scroll: ``` _|←_cW_→_|_↓_ |content| ← content is still visible --------------- |content| ↑ ↑ |content| contentInset.top cH |content| ↓ |content| contentInset.bottom |content| ↓ --------------- _|_______|___ ↑ ``` That top row of content will still be visible because it's still inside the frame of the scroll view. One way to think of the top offset is "how much to shift the content down the scroll view when we're scrolled all the way to the top" To see a place where this is actually used, look at the build-in Photos app on the iphone. The Navigation bar and status bar are transparent, and the contents of the scroll view are visible underneath. That's because the scroll view's frame extends out that far. But if it wasn't for the content inset, you would never be able to have the top of the content clear that transparent navigation bar when you go all the way to the top. </s>"
[ "How is arc defined in TikZ?", "```\\draw (x,y) arc (start:stop:radius);``` draws an arc\n\n* with radius ```radius```\n* starts from ```(x,y)```\n* with center ```(x-r*cos(start), y-r*sin(start))``` and\n* ends at ```(x-r*cos(start)+r*cos(stop), y-r*sin(start)+r*sin(stop))```.\n\nFor example,\n``` \\draw[red] (0,0) arc (30:60:3);\n```\ndraws an arc\n\n* of radius ```3```\n* starting from ```(0,0)```\n* with center ```(0-3*cos(30),0-3*sin(30))``` and\n* ending at ```(0-3*cos(30)+3*cos(60),0-3*sin(30)+3*sin(60))```.\n\n```\\draw[blue] (0,0) -- ++(30+180:3) -- +(60:3);\n```\ndraw a blue line to the arc to make a complete sector.\n\nMinimal Working Example\n```\\documentclass[tikz,border=12pt]{standalone}\n\\begin{document}\n\\foreach \\start/\\stop in {30/60,45/90,135/180,0/180,45/315}\n{\n \\begin{tikzpicture}\n \\draw[lightgray,ultra thin] (-6,-6) grid (6,6);\n \\draw[red] (0,0) arc (\\start:\\stop:3);\n \\draw[blue] (0,0) -- ++(\\start+180:3) -- +(\\stop:3);\n \\node[anchor=north] at (0,6) {$(\\start:\\stop:3)$};\n \\end{tikzpicture}\n}\n\\end{document}\n```\n\n\n\n" ]
"stackexchange"
2
"4814a0816ef9a66f47cdddbd2c7a61af884dba38dbbe98af8383249987237cf9"
"How is arc defined in TikZ?"
[ { "content": "How is arc defined in TikZ?", "role": "user" }, { "content": "```\\draw (x,y) arc (start:stop:radius);``` draws an arc\n\n* with radius ```radius```\n* starts from ```(x,y)```\n* with center ```(x-r*cos(start), y-r*sin(start))``` and\n* ends at ```(x-r*cos(start)+r*cos(stop), y-r*sin(start)+r*sin(stop))```.\n\nFor example,\n``` \\draw[red] (0,0) arc (30:60:3);\n```\ndraws an arc\n\n* of radius ```3```\n* starting from ```(0,0)```\n* with center ```(0-3*cos(30),0-3*sin(30))``` and\n* ending at ```(0-3*cos(30)+3*cos(60),0-3*sin(30)+3*sin(60))```.\n\n```\\draw[blue] (0,0) -- ++(30+180:3) -- +(60:3);\n```\ndraw a blue line to the arc to make a complete sector.\n\nMinimal Working Example\n```\\documentclass[tikz,border=12pt]{standalone}\n\\begin{document}\n\\foreach \\start/\\stop in {30/60,45/90,135/180,0/180,45/315}\n{\n \\begin{tikzpicture}\n \\draw[lightgray,ultra thin] (-6,-6) grid (6,6);\n \\draw[red] (0,0) arc (\\start:\\stop:3);\n \\draw[blue] (0,0) -- ++(\\start+180:3) -- +(\\stop:3);\n \\node[anchor=north] at (0,6) {$(\\start:\\stop:3)$};\n \\end{tikzpicture}\n}\n\\end{document}\n```\n\n\n\n", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] How is arc defined in TikZ? [/INST] ```\draw (x,y) arc (start:stop:radius);``` draws an arc * with radius ```radius``` * starts from ```(x,y)``` * with center ```(x-r*cos(start), y-r*sin(start))``` and * ends at ```(x-r*cos(start)+r*cos(stop), y-r*sin(start)+r*sin(stop))```. For example, ``` \draw[red] (0,0) arc (30:60:3); ``` draws an arc * of radius ```3``` * starting from ```(0,0)``` * with center ```(0-3*cos(30),0-3*sin(30))``` and * ending at ```(0-3*cos(30)+3*cos(60),0-3*sin(30)+3*sin(60))```. ```\draw[blue] (0,0) -- ++(30+180:3) -- +(60:3); ``` draw a blue line to the arc to make a complete sector. Minimal Working Example ```\documentclass[tikz,border=12pt]{standalone} \begin{document} \foreach \start/\stop in {30/60,45/90,135/180,0/180,45/315} { \begin{tikzpicture} \draw[lightgray,ultra thin] (-6,-6) grid (6,6); \draw[red] (0,0) arc (\start:\stop:3); \draw[blue] (0,0) -- ++(\start+180:3) -- +(\stop:3); \node[anchor=north] at (0,6) {$(\start:\stop:3)$}; \end{tikzpicture} } \end{document} ``` </s>"
[ "How to connect mysql workbench to running mysql inside docker?", "By default after deployment MySQL has following connection restrictions:\n```mysql> select host, user from mysql.user;\n+-----------+---------------+\n| host | user |\n+-----------+---------------+\n| localhost | healthchecker |\n| localhost | mysql.session |\n| localhost | mysql.sys |\n| localhost | root |\n+-----------+---------------+\n4 rows in set (0.00 sec)\n```\nApparently, for the security purposes you will not be able to connect to it outside of the docker image.\nIf you need to change that to allow root to connect from any host (say, for development purposes), do:\n\n* Start your mysql image with all port mappings required:\n```docker run -p 3306:3306 --name=mysql57 -d mysql/mysql-server:5.7```\n\nor, if the complete port mapping is required:\n```docker run -p 3306:3306 -p 33060:33060 --name=mysql57 -d mysql/mysql-server:5.7\n```\n\n* If this is the fresh installation - grab the default password:\n```docker logs mysql57 2>&1 | grep GENERATED```\n* Connect using ```mysql``` client directly to the mysqld in docker:\n```docker exec -it mysql57 mysql -uroot -p```\n* If this is the fresh installation you will be asked to change the password using ```ALTER USER``` command. Do it.\n* Run SQL:\n```update mysql.user set host = '%' where user='root';```\n* Quit the ```mysql``` client.\n* Restart the container:\n```docker restart mysql57```\n\nNow you will be able to connect from MySQL Workbench to\n```host: `0.0.0.0`\nport: `3306`\n```\nAfter all the changes the query will show:\n```select host, user from mysql.user;\n+-----------+---------------+\n| host | user |\n+-----------+---------------+\n| % | root |\n| localhost | healthchecker |\n| localhost | mysql.session |\n| localhost | mysql.sys |\n+-----------+---------------+\n```" ]
"stackexchange"
2
"a6f42594f984920e49f2918d045dcb01deb0f9267f8a1561761d8f68655de124"
"How to connect mysql workbench to running mysql inside docker?"
[ { "content": "How to connect mysql workbench to running mysql inside docker?", "role": "user" }, { "content": "By default after deployment MySQL has following connection restrictions:\n```mysql> select host, user from mysql.user;\n+-----------+---------------+\n| host | user |\n+-----------+---------------+\n| localhost | healthchecker |\n| localhost | mysql.session |\n| localhost | mysql.sys |\n| localhost | root |\n+-----------+---------------+\n4 rows in set (0.00 sec)\n```\nApparently, for the security purposes you will not be able to connect to it outside of the docker image.\nIf you need to change that to allow root to connect from any host (say, for development purposes), do:\n\n* Start your mysql image with all port mappings required:\n```docker run -p 3306:3306 --name=mysql57 -d mysql/mysql-server:5.7```\n\nor, if the complete port mapping is required:\n```docker run -p 3306:3306 -p 33060:33060 --name=mysql57 -d mysql/mysql-server:5.7\n```\n\n* If this is the fresh installation - grab the default password:\n```docker logs mysql57 2>&1 | grep GENERATED```\n* Connect using ```mysql``` client directly to the mysqld in docker:\n```docker exec -it mysql57 mysql -uroot -p```\n* If this is the fresh installation you will be asked to change the password using ```ALTER USER``` command. Do it.\n* Run SQL:\n```update mysql.user set host = '%' where user='root';```\n* Quit the ```mysql``` client.\n* Restart the container:\n```docker restart mysql57```\n\nNow you will be able to connect from MySQL Workbench to\n```host: `0.0.0.0`\nport: `3306`\n```\nAfter all the changes the query will show:\n```select host, user from mysql.user;\n+-----------+---------------+\n| host | user |\n+-----------+---------------+\n| % | root |\n| localhost | healthchecker |\n| localhost | mysql.session |\n| localhost | mysql.sys |\n+-----------+---------------+\n```", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] How to connect mysql workbench to running mysql inside docker? [/INST] By default after deployment MySQL has following connection restrictions: ```mysql> select host, user from mysql.user; +-----------+---------------+ | host | user | +-----------+---------------+ | localhost | healthchecker | | localhost | mysql.session | | localhost | mysql.sys | | localhost | root | +-----------+---------------+ 4 rows in set (0.00 sec) ``` Apparently, for the security purposes you will not be able to connect to it outside of the docker image. If you need to change that to allow root to connect from any host (say, for development purposes), do: * Start your mysql image with all port mappings required: ```docker run -p 3306:3306 --name=mysql57 -d mysql/mysql-server:5.7``` or, if the complete port mapping is required: ```docker run -p 3306:3306 -p 33060:33060 --name=mysql57 -d mysql/mysql-server:5.7 ``` * If this is the fresh installation - grab the default password: ```docker logs mysql57 2>&1 | grep GENERATED``` * Connect using ```mysql``` client directly to the mysqld in docker: ```docker exec -it mysql57 mysql -uroot -p``` * If this is the fresh installation you will be asked to change the password using ```ALTER USER``` command. Do it. * Run SQL: ```update mysql.user set host = '%' where user='root';``` * Quit the ```mysql``` client. * Restart the container: ```docker restart mysql57``` Now you will be able to connect from MySQL Workbench to ```host: `0.0.0.0` port: `3306` ``` After all the changes the query will show: ```select host, user from mysql.user; +-----------+---------------+ | host | user | +-----------+---------------+ | % | root | | localhost | healthchecker | | localhost | mysql.session | | localhost | mysql.sys | +-----------+---------------+ ``` </s>"
[ "Can meat spoil outside the fridge if it's baked into bread as a filling?", "There are two differences between your buns and a tin can.\nFirst, your buns were heated to a core temperature of under 100°C. Yes, your oven was probably set way higher, but the water content in your filling prevents it from getting hotter than boiling water. Commercial canning is done in the vicinity of 120-130°C, which is possible because the cans are cooked under pressure. So unlike in a can, most pathogens were destroyed, but not necessarily all of them. For human consumption, that’s perfectly fine as long as the remaining ones don’t get the time-temperature combo to regrow.\nSecond, a bread dough may be dense (although the aim is usually something different), but by no means airtight. Interestingly, wrapping meat in dense dough was used as preservation method in medieval times - the “ancestor” of today’s pork pies and pastries. But while the hard flour crust (not intended to be eaten originally) did form a protective layer and usually extended the shelf life more or less, it was by no means food safe judged by modern standards - although some pies were stored for months. But your fluffy buns are truly not a protective layer. Which means you should refrigerate your buns, but also that you get to enjoy the whole dish." ]
"stackexchange"
2
"bfe05eba882abde475a1e7769004d3a71e85a669187954ea99c72cb70a28eafc"
"Can meat spoil outside the fridge if it's baked into bread as a filling?"
[ { "content": "Can meat spoil outside the fridge if it's baked into bread as a filling?", "role": "user" }, { "content": "There are two differences between your buns and a tin can.\nFirst, your buns were heated to a core temperature of under 100°C. Yes, your oven was probably set way higher, but the water content in your filling prevents it from getting hotter than boiling water. Commercial canning is done in the vicinity of 120-130°C, which is possible because the cans are cooked under pressure. So unlike in a can, most pathogens were destroyed, but not necessarily all of them. For human consumption, that’s perfectly fine as long as the remaining ones don’t get the time-temperature combo to regrow.\nSecond, a bread dough may be dense (although the aim is usually something different), but by no means airtight. Interestingly, wrapping meat in dense dough was used as preservation method in medieval times - the “ancestor” of today’s pork pies and pastries. But while the hard flour crust (not intended to be eaten originally) did form a protective layer and usually extended the shelf life more or less, it was by no means food safe judged by modern standards - although some pies were stored for months. But your fluffy buns are truly not a protective layer. Which means you should refrigerate your buns, but also that you get to enjoy the whole dish.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Can meat spoil outside the fridge if it's baked into bread as a filling? [/INST] There are two differences between your buns and a tin can. First, your buns were heated to a core temperature of under 100°C. Yes, your oven was probably set way higher, but the water content in your filling prevents it from getting hotter than boiling water. Commercial canning is done in the vicinity of 120-130°C, which is possible because the cans are cooked under pressure. So unlike in a can, most pathogens were destroyed, but not necessarily all of them. For human consumption, that’s perfectly fine as long as the remaining ones don’t get the time-temperature combo to regrow. Second, a bread dough may be dense (although the aim is usually something different), but by no means airtight. Interestingly, wrapping meat in dense dough was used as preservation method in medieval times - the “ancestor” of today’s pork pies and pastries. But while the hard flour crust (not intended to be eaten originally) did form a protective layer and usually extended the shelf life more or less, it was by no means food safe judged by modern standards - although some pies were stored for months. But your fluffy buns are truly not a protective layer. Which means you should refrigerate your buns, but also that you get to enjoy the whole dish. </s>"
[ "I'm wondering how the XML Schema specification handles these cases:\n```\n```\nNo maxOccurs given -> Is this the cardinality [1..1]?\n```\n```\nI suppose this is simply invalid?\n```\n```\nIs this the cardinality [0..2] or [1..2]?\nIs there an \"official\" definition on how the XML Schema spec handles these cases?", "New, expanded answer to an old, commonly asked question...\nDefault Values\n\n* Occurrence constraints ```minOccurs``` and ```maxOccurs``` default to ```1```.\n\n\nCommon Cases Explained\n```\n```\nmeans ```A``` is required and must appear exactly once.\n\n```\n```\nmeans ```A``` is optional and may appear at most once.\n\n``` \n```\nmeans ```A``` is required and may repeat an unlimited number of times.\n\n``` \n```\nmeans ```A``` is optional and may repeat an unlimited number of times.\n\nSee Also\n\n* W3C XML Schema Part 0: Primer\n\n In general, an element is required to appear when the value of\n minOccurs is 1 or more. The maximum number of times an element may\n appear is determined by the value of a maxOccurs attribute in its\n declaration. This value may be a positive integer such as 41, or the\n term unbounded to indicate there is no maximum number of occurrences.\n The default value for both the minOccurs and the maxOccurs attributes\n is 1. Thus, when an element such as comment is declared without a\n maxOccurs attribute, the element may not occur more than once. Be sure\n that if you specify a value for only the minOccurs attribute, it is\n less than or equal to the default value of maxOccurs, i.e. it is 0 or 1.\n Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs,\n i.e. 1 or more. If both attributes are omitted, the element must\n appear exactly once.\n\n* W3C XML Schema Part 1: Structures Second Edition \n```<element\n maxOccurs = (nonNegativeInteger | unbounded) : 1\n minOccurs = nonNegativeInteger : 1\n >\n\n```\n" ]
"stackexchange"
2
"36940a1e139744d8515084320a3250f8801faf347b5b95649be4332a122b0545"
"I'm wondering how the XML Schema specification handles these cases: ``` ``` No maxOccurs given -> Is this the cardinality [1..1]? ``` ``` I suppose this is simply invalid? ``` ``` Is this the cardinality [0..2] or [1..2]? Is there an "official" definition on how the XML Schema spec handles these cases?"
[ { "content": "I'm wondering how the XML Schema specification handles these cases:\n```\n```\nNo maxOccurs given -> Is this the cardinality [1..1]?\n```\n```\nI suppose this is simply invalid?\n```\n```\nIs this the cardinality [0..2] or [1..2]?\nIs there an \"official\" definition on how the XML Schema spec handles these cases?", "role": "user" }, { "content": "New, expanded answer to an old, commonly asked question...\nDefault Values\n\n* Occurrence constraints ```minOccurs``` and ```maxOccurs``` default to ```1```.\n\n\nCommon Cases Explained\n```\n```\nmeans ```A``` is required and must appear exactly once.\n\n```\n```\nmeans ```A``` is optional and may appear at most once.\n\n``` \n```\nmeans ```A``` is required and may repeat an unlimited number of times.\n\n``` \n```\nmeans ```A``` is optional and may repeat an unlimited number of times.\n\nSee Also\n\n* W3C XML Schema Part 0: Primer\n\n In general, an element is required to appear when the value of\n minOccurs is 1 or more. The maximum number of times an element may\n appear is determined by the value of a maxOccurs attribute in its\n declaration. This value may be a positive integer such as 41, or the\n term unbounded to indicate there is no maximum number of occurrences.\n The default value for both the minOccurs and the maxOccurs attributes\n is 1. Thus, when an element such as comment is declared without a\n maxOccurs attribute, the element may not occur more than once. Be sure\n that if you specify a value for only the minOccurs attribute, it is\n less than or equal to the default value of maxOccurs, i.e. it is 0 or 1.\n Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs,\n i.e. 1 or more. If both attributes are omitted, the element must\n appear exactly once.\n\n* W3C XML Schema Part 1: Structures Second Edition \n```<element\n maxOccurs = (nonNegativeInteger | unbounded) : 1\n minOccurs = nonNegativeInteger : 1\n >\n\n```\n", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] I'm wondering how the XML Schema specification handles these cases: ``` ``` No maxOccurs given -> Is this the cardinality [1..1]? ``` ``` I suppose this is simply invalid? ``` ``` Is this the cardinality [0..2] or [1..2]? Is there an "official" definition on how the XML Schema spec handles these cases? [/INST] New, expanded answer to an old, commonly asked question... Default Values * Occurrence constraints ```minOccurs``` and ```maxOccurs``` default to ```1```. Common Cases Explained ``` ``` means ```A``` is required and must appear exactly once. ``` ``` means ```A``` is optional and may appear at most once. ``` ``` means ```A``` is required and may repeat an unlimited number of times. ``` ``` means ```A``` is optional and may repeat an unlimited number of times. See Also * W3C XML Schema Part 0: Primer In general, an element is required to appear when the value of minOccurs is 1 or more. The maximum number of times an element may appear is determined by the value of a maxOccurs attribute in its declaration. This value may be a positive integer such as 41, or the term unbounded to indicate there is no maximum number of occurrences. The default value for both the minOccurs and the maxOccurs attributes is 1. Thus, when an element such as comment is declared without a maxOccurs attribute, the element may not occur more than once. Be sure that if you specify a value for only the minOccurs attribute, it is less than or equal to the default value of maxOccurs, i.e. it is 0 or 1. Similarly, if you specify a value for only the maxOccurs attribute, it must be greater than or equal to the default value of minOccurs, i.e. 1 or more. If both attributes are omitted, the element must appear exactly once. * W3C XML Schema Part 1: Structures Second Edition ```<element maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 > ``` </s>"
[ "Were there any flying dinosaurs?", "Birds are both flying dinosaurs and flying reptiles. Yes, that's potentially confusing.\n\nTo understand the apparent contradiction, you have to understand how modern classification of organisms works (phylogenetic systematics). Under the old (Linnean) classification system, Reptilia (reptiles) was an order and Aves (birds) was a separate order. Phylogenetic systematics, which has completely replaced the Linnean system, views all organisms as interrelated in a nested set of monophyletic groups (clades). It's like a set of venn diagrams, where all organisms fall into a giant circle and then successively smaller circles classify more and more specific groups.\n\nThe clade Reptilia includes snakes, lizards, crocodiles, and lots of extinct groups, including dinosaurs. So all dinosaurs are reptiles. The clade Dinosauria includes all the extinct dinosaurs (Stegosaurus, Triceratops, sauropods, etc.), including theropod dinosaurs, which include well known dinosaurs like Tyrannosaurus and Allosaurus. Based on a mountain on anatomical evidence, including lots of transitional fossils, living birds are a sub-group of theropod dinosaurs.\n\nSo all birds (Aves) are theropod dinosaurs (Dinosauria: Theropoda). All dinosaurs are reptiles. Therefore, birds are dinosaurs and reptiles. They are just more closely related to dinosaurs than to other reptiles.\nThe tricky part is that most people have an intuitive idea of what \"reptiles\" and \"dinosaurs\" are. To a systematist, whose job it is to classify organisms, these terms don't mean the same thing as they do to most people. Systematists think about groups like Reptilia and Dinosauria and how those groups are related to one another. So they have no problem saying that birds are dinosaurs and reptiles, because birds are nested within both of those groups.\n\nA few words about pterosaurs\nAlong with birds and bats, pterosaurs are the other clade of vertebrates capable of powered, flapping flight. Pterosaurs fall within Reptilia (and Diapsida and Archosauria) along with Dinosauria, which includes birds. There are a lot of other extinct lineages in the tree that are not shown, e.g., ornithodirans that are not dinosaurs and not pterosaurs. Pterosaurs and birds share anatomical features that all reptiles, diapsids, archosaurs, and ornithodirans have, which is how we know that they are more closely related to each other than to other groups, like crocodiles. But their flight structures evolved independently and are anatomically distinct fro one another. So pterosaurs are flying reptiles but not flying dinosaurs.\nThese images might help you understand the above explanation." ]
"stackexchange"
2
"00d99cf862dd8a6b1b9136492efaebfae3ba5e0ded0ee58c1b13d6adfe00af6e"
"Were there any flying dinosaurs?"
[ { "content": "Were there any flying dinosaurs?", "role": "user" }, { "content": "Birds are both flying dinosaurs and flying reptiles. Yes, that's potentially confusing.\n\nTo understand the apparent contradiction, you have to understand how modern classification of organisms works (phylogenetic systematics). Under the old (Linnean) classification system, Reptilia (reptiles) was an order and Aves (birds) was a separate order. Phylogenetic systematics, which has completely replaced the Linnean system, views all organisms as interrelated in a nested set of monophyletic groups (clades). It's like a set of venn diagrams, where all organisms fall into a giant circle and then successively smaller circles classify more and more specific groups.\n\nThe clade Reptilia includes snakes, lizards, crocodiles, and lots of extinct groups, including dinosaurs. So all dinosaurs are reptiles. The clade Dinosauria includes all the extinct dinosaurs (Stegosaurus, Triceratops, sauropods, etc.), including theropod dinosaurs, which include well known dinosaurs like Tyrannosaurus and Allosaurus. Based on a mountain on anatomical evidence, including lots of transitional fossils, living birds are a sub-group of theropod dinosaurs.\n\nSo all birds (Aves) are theropod dinosaurs (Dinosauria: Theropoda). All dinosaurs are reptiles. Therefore, birds are dinosaurs and reptiles. They are just more closely related to dinosaurs than to other reptiles.\nThe tricky part is that most people have an intuitive idea of what \"reptiles\" and \"dinosaurs\" are. To a systematist, whose job it is to classify organisms, these terms don't mean the same thing as they do to most people. Systematists think about groups like Reptilia and Dinosauria and how those groups are related to one another. So they have no problem saying that birds are dinosaurs and reptiles, because birds are nested within both of those groups.\n\nA few words about pterosaurs\nAlong with birds and bats, pterosaurs are the other clade of vertebrates capable of powered, flapping flight. Pterosaurs fall within Reptilia (and Diapsida and Archosauria) along with Dinosauria, which includes birds. There are a lot of other extinct lineages in the tree that are not shown, e.g., ornithodirans that are not dinosaurs and not pterosaurs. Pterosaurs and birds share anatomical features that all reptiles, diapsids, archosaurs, and ornithodirans have, which is how we know that they are more closely related to each other than to other groups, like crocodiles. But their flight structures evolved independently and are anatomically distinct fro one another. So pterosaurs are flying reptiles but not flying dinosaurs.\nThese images might help you understand the above explanation.", "role": "assistant" } ]
{ "category": "stackexchange", "source": "lima" }
"<s> [INST] Were there any flying dinosaurs? [/INST] Birds are both flying dinosaurs and flying reptiles. Yes, that's potentially confusing. To understand the apparent contradiction, you have to understand how modern classification of organisms works (phylogenetic systematics). Under the old (Linnean) classification system, Reptilia (reptiles) was an order and Aves (birds) was a separate order. Phylogenetic systematics, which has completely replaced the Linnean system, views all organisms as interrelated in a nested set of monophyletic groups (clades). It's like a set of venn diagrams, where all organisms fall into a giant circle and then successively smaller circles classify more and more specific groups. The clade Reptilia includes snakes, lizards, crocodiles, and lots of extinct groups, including dinosaurs. So all dinosaurs are reptiles. The clade Dinosauria includes all the extinct dinosaurs (Stegosaurus, Triceratops, sauropods, etc.), including theropod dinosaurs, which include well known dinosaurs like Tyrannosaurus and Allosaurus. Based on a mountain on anatomical evidence, including lots of transitional fossils, living birds are a sub-group of theropod dinosaurs. So all birds (Aves) are theropod dinosaurs (Dinosauria: Theropoda). All dinosaurs are reptiles. Therefore, birds are dinosaurs and reptiles. They are just more closely related to dinosaurs than to other reptiles. The tricky part is that most people have an intuitive idea of what "reptiles" and "dinosaurs" are. To a systematist, whose job it is to classify organisms, these terms don't mean the same thing as they do to most people. Systematists think about groups like Reptilia and Dinosauria and how those groups are related to one another. So they have no problem saying that birds are dinosaurs and reptiles, because birds are nested within both of those groups. A few words about pterosaurs Along with birds and bats, pterosaurs are the other clade of vertebrates capable of powered, flapping flight. Pterosaurs fall within Reptilia (and Diapsida and Archosauria) along with Dinosauria, which includes birds. There are a lot of other extinct lineages in the tree that are not shown, e.g., ornithodirans that are not dinosaurs and not pterosaurs. Pterosaurs and birds share anatomical features that all reptiles, diapsids, archosaurs, and ornithodirans have, which is how we know that they are more closely related to each other than to other groups, like crocodiles. But their flight structures evolved independently and are anatomically distinct fro one another. So pterosaurs are flying reptiles but not flying dinosaurs. These images might help you understand the above explanation. </s>"

Dataset Card for "lima_llama2"

More Information needed

Downloads last month
0
Edit dataset card
Evaluate models HF Leaderboard