qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
643,662
I'm fairly newbie to these concepts, so please try to give a simply answer. Electric energy is often compared to gravitational energy. This analogy helps to understand the concept of voltage. With gravitation, there is a *potential difference* between two points (given that they're not in the same height), and this potential difference is the *potential energy difference* per unit of mass. With electricity, the *potential difference* is potential energy difference per one Coulomb of charge. My question is: With gravitation, the mere arrangement of having 2 points with potential difference between them doesn't mean having a flow of mass between them. We need to bring some mass to the higher point in order to have *potential energy*. But with electricity, it seems that if you only have two points with potential difference between them, meaning that you already have *potential energy*, and all you have to do is to connect this two points with a conductive material. Another question related to this: The difference in gravitational potential difference is rooted in the difference of the height between the points. What is the root cause of the electrical potential difference between two points?
2021/06/06
[ "https://physics.stackexchange.com/questions/643662", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/299695/" ]
Ever since the discovery of calculus mathematics, mathematical functions are used in order to model observations and special axioms are introduced in order to connect the pure numbers of mathematics with observable numbers. Waves in water, the first waves to be observed are defined by their height and frequency in time and motion in time and space, and can be fitted with the solutions of what is called a ["wave equation"](http://hyperphysics.phy-astr.gsu.edu/hbase/Waves/waveq.html) > > The wave equation for a plane wave traveling in the x direction is $$\frac{\partial^2y}{\partial x^2}=\frac1{v^2}\frac{\partial^2y}{\partial t^2}$$ where $v$ is the phase velocity of the wave and $y$ represents the variable which is changing as the wave passes. > > > The solutions are in terms of sines and cosines which have the frequency of the repetition inherent. When [Maxwell brilliantly](https://en.wikipedia.org/wiki/Maxwell%27s_equations#Formulation_in_SI_units_convention) united what were disparate laws and equation in the study of electricity and magnetism into one set of interdependent differential equations, to everybody's surprise, a wave equation resulted. The solutions of this fitted light and the rest of electromagnetic phenomena to very great accuracy. [Here is](https://en.wikipedia.org/wiki/Electromagnetic_radiation#Properties) a polarized electromagnetic wave showing that it depends on Electric and B magnetic fields changing in time. [![enter image description here](https://i.stack.imgur.com/JB2NP.gif)](https://i.stack.imgur.com/JB2NP.gif) > > Electromagnetic waves can be imagined as a self-propagating transverse oscillating wave of electric and magnetic fields. This 3D animation shows a plane linearly polarized wave propagating from left to right. The electric and magnetic fields in such a wave are in-phase with each other, reaching minima and maxima together. > > > From infrared radiation to visible light to radioto gamma rays, this model is always validated . > > even worse when I read about the double slit experiment and particle wave duality. > > > The waves in particle wave duality are **probability waves** [as seen here](http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/qm.html). The wave function postulate is in the third page of the link. This means one must accumulate events in order to see the interference patterns predicted by the wave nature of the probability of interaction See this [answer of mine o](https://physics.stackexchange.com/questions/238855/is-it-wrong-to-say-that-an-electron-can-be-a-wave/238866#238866)n this..
For the layman: The defining characteristic of a wave is that it takes time for an influence to travel from place to place. E.g. Throw a stone in the water, and the influence (ripples) takes time to travel across the pond. Physics deals with abstract entities where the medium is not always physical, from water waves (medium = water) to light and radio waves (medium = Electromagnetic field) to probability waves in Quantum Mechanics (where the medium may only exist in an observer's head) Fun Fact: Newton's original formulation of Gravity had gravity affecting objects instantaneously (no time delay) so was not a wave theory
643,662
I'm fairly newbie to these concepts, so please try to give a simply answer. Electric energy is often compared to gravitational energy. This analogy helps to understand the concept of voltage. With gravitation, there is a *potential difference* between two points (given that they're not in the same height), and this potential difference is the *potential energy difference* per unit of mass. With electricity, the *potential difference* is potential energy difference per one Coulomb of charge. My question is: With gravitation, the mere arrangement of having 2 points with potential difference between them doesn't mean having a flow of mass between them. We need to bring some mass to the higher point in order to have *potential energy*. But with electricity, it seems that if you only have two points with potential difference between them, meaning that you already have *potential energy*, and all you have to do is to connect this two points with a conductive material. Another question related to this: The difference in gravitational potential difference is rooted in the difference of the height between the points. What is the root cause of the electrical potential difference between two points?
2021/06/06
[ "https://physics.stackexchange.com/questions/643662", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/299695/" ]
A wave is simply a function of space and time $F(\vec r, t)$ such that the value of $F$ at any point $\vec r$ and time $t$ depends on its values at nearby points and times in a deterministic way that is described mathematical by an equation called the [wave equation](https://en.wikipedia.org/wiki/Wave_equation). What does the function $F$ represent ? Well, that depends on the type of wave. For waves on the surface of a pond, $F$ represents the height of the water. For sound waves, $F$ represents the pressure at a particular point and time. For electromagnetic waves, $F$ represents the values of the electric and magnetic fields - in this case, $F$ is not just a single value at each point in space and time, but is actually a pair of vectors $\vec E(\vec r,t)$ and $\vec B(\vec r, t)$. And for a quantum wave function in position space $F$ is a complex number that is related to the probability of observing a particle at that point and time (there are other types of quantum wave functions where $\vec r$ is not a position in physical space, but is a position in a more abstract space such as momentum space). Although these waves are models of very different physical phenomena, they are all based on the same underlying mathematical structure.
Broadly, a wave is simply a quantity that changes in a periodic way over space and/or time. In the case of a water wave, the changing quantity is the distance through which the surface is displaced- or, if you like, just the height of the surface. With a wave on a string, the changing quantity is the displacement of the string from its resting position. With a sound wave, the changing quantity is air pressure. The frequency of a wave is the number of times per second that the changing quantity oscillates. The wavelength is the distance between successive occurrences of maximum or minimum values of the changing quantity. With electromagnetic waves, the changing quantity is the strength of the electric and magnetic fields that permeate space. If you are happy with the idea of an electric field, for example, then you can think of the wave as being a periodic fluctuation in the strength of the field at every point. All particles seem to have a wave-like aspect (the particle wave duality you mentioned). In the case of those waves, the changing quantity, very loosely speaking, is a measure of the probability that the particle will be found at a particular point. Strictly speaking, the idea of a pure wave with a precise frequency and wavelength everywhere in space is a bit of a fiction. In reality waves tend to be less uniform than that, and their properties can become very difficult to model precisely.
643,662
I'm fairly newbie to these concepts, so please try to give a simply answer. Electric energy is often compared to gravitational energy. This analogy helps to understand the concept of voltage. With gravitation, there is a *potential difference* between two points (given that they're not in the same height), and this potential difference is the *potential energy difference* per unit of mass. With electricity, the *potential difference* is potential energy difference per one Coulomb of charge. My question is: With gravitation, the mere arrangement of having 2 points with potential difference between them doesn't mean having a flow of mass between them. We need to bring some mass to the higher point in order to have *potential energy*. But with electricity, it seems that if you only have two points with potential difference between them, meaning that you already have *potential energy*, and all you have to do is to connect this two points with a conductive material. Another question related to this: The difference in gravitational potential difference is rooted in the difference of the height between the points. What is the root cause of the electrical potential difference between two points?
2021/06/06
[ "https://physics.stackexchange.com/questions/643662", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/299695/" ]
A wave is simply a function of space and time $F(\vec r, t)$ such that the value of $F$ at any point $\vec r$ and time $t$ depends on its values at nearby points and times in a deterministic way that is described mathematical by an equation called the [wave equation](https://en.wikipedia.org/wiki/Wave_equation). What does the function $F$ represent ? Well, that depends on the type of wave. For waves on the surface of a pond, $F$ represents the height of the water. For sound waves, $F$ represents the pressure at a particular point and time. For electromagnetic waves, $F$ represents the values of the electric and magnetic fields - in this case, $F$ is not just a single value at each point in space and time, but is actually a pair of vectors $\vec E(\vec r,t)$ and $\vec B(\vec r, t)$. And for a quantum wave function in position space $F$ is a complex number that is related to the probability of observing a particle at that point and time (there are other types of quantum wave functions where $\vec r$ is not a position in physical space, but is a position in a more abstract space such as momentum space). Although these waves are models of very different physical phenomena, they are all based on the same underlying mathematical structure.
For the layman: The defining characteristic of a wave is that it takes time for an influence to travel from place to place. E.g. Throw a stone in the water, and the influence (ripples) takes time to travel across the pond. Physics deals with abstract entities where the medium is not always physical, from water waves (medium = water) to light and radio waves (medium = Electromagnetic field) to probability waves in Quantum Mechanics (where the medium may only exist in an observer's head) Fun Fact: Newton's original formulation of Gravity had gravity affecting objects instantaneously (no time delay) so was not a wave theory
643,662
I'm fairly newbie to these concepts, so please try to give a simply answer. Electric energy is often compared to gravitational energy. This analogy helps to understand the concept of voltage. With gravitation, there is a *potential difference* between two points (given that they're not in the same height), and this potential difference is the *potential energy difference* per unit of mass. With electricity, the *potential difference* is potential energy difference per one Coulomb of charge. My question is: With gravitation, the mere arrangement of having 2 points with potential difference between them doesn't mean having a flow of mass between them. We need to bring some mass to the higher point in order to have *potential energy*. But with electricity, it seems that if you only have two points with potential difference between them, meaning that you already have *potential energy*, and all you have to do is to connect this two points with a conductive material. Another question related to this: The difference in gravitational potential difference is rooted in the difference of the height between the points. What is the root cause of the electrical potential difference between two points?
2021/06/06
[ "https://physics.stackexchange.com/questions/643662", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/299695/" ]
I assume that your question is about electromagnetic waves and light. This the same question that Huygens asked himself about light in the 17th century. He noticed that sound does not travel through vacuum whereas light does. Newton's solution we was that light consists of particles. This however does not explain the wave behavior of light. The present main stream physics answer is that light consists of particles, photons, the behavior of which is governed by electromagnetic waves. These waves are believed to have no medium.
Broadly, a wave is simply a quantity that changes in a periodic way over space and/or time. In the case of a water wave, the changing quantity is the distance through which the surface is displaced- or, if you like, just the height of the surface. With a wave on a string, the changing quantity is the displacement of the string from its resting position. With a sound wave, the changing quantity is air pressure. The frequency of a wave is the number of times per second that the changing quantity oscillates. The wavelength is the distance between successive occurrences of maximum or minimum values of the changing quantity. With electromagnetic waves, the changing quantity is the strength of the electric and magnetic fields that permeate space. If you are happy with the idea of an electric field, for example, then you can think of the wave as being a periodic fluctuation in the strength of the field at every point. All particles seem to have a wave-like aspect (the particle wave duality you mentioned). In the case of those waves, the changing quantity, very loosely speaking, is a measure of the probability that the particle will be found at a particular point. Strictly speaking, the idea of a pure wave with a precise frequency and wavelength everywhere in space is a bit of a fiction. In reality waves tend to be less uniform than that, and their properties can become very difficult to model precisely.
643,662
I'm fairly newbie to these concepts, so please try to give a simply answer. Electric energy is often compared to gravitational energy. This analogy helps to understand the concept of voltage. With gravitation, there is a *potential difference* between two points (given that they're not in the same height), and this potential difference is the *potential energy difference* per unit of mass. With electricity, the *potential difference* is potential energy difference per one Coulomb of charge. My question is: With gravitation, the mere arrangement of having 2 points with potential difference between them doesn't mean having a flow of mass between them. We need to bring some mass to the higher point in order to have *potential energy*. But with electricity, it seems that if you only have two points with potential difference between them, meaning that you already have *potential energy*, and all you have to do is to connect this two points with a conductive material. Another question related to this: The difference in gravitational potential difference is rooted in the difference of the height between the points. What is the root cause of the electrical potential difference between two points?
2021/06/06
[ "https://physics.stackexchange.com/questions/643662", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/299695/" ]
I assume that your question is about electromagnetic waves and light. This the same question that Huygens asked himself about light in the 17th century. He noticed that sound does not travel through vacuum whereas light does. Newton's solution we was that light consists of particles. This however does not explain the wave behavior of light. The present main stream physics answer is that light consists of particles, photons, the behavior of which is governed by electromagnetic waves. These waves are believed to have no medium.
For the layman: The defining characteristic of a wave is that it takes time for an influence to travel from place to place. E.g. Throw a stone in the water, and the influence (ripples) takes time to travel across the pond. Physics deals with abstract entities where the medium is not always physical, from water waves (medium = water) to light and radio waves (medium = Electromagnetic field) to probability waves in Quantum Mechanics (where the medium may only exist in an observer's head) Fun Fact: Newton's original formulation of Gravity had gravity affecting objects instantaneously (no time delay) so was not a wave theory
16,429,089
I have 2 buttons. Button A: A button. Button B: Submit button. What I am trying to do is, when user clicks on button A, it will send him a link. But he won't be able to submit using button B until 8 seconds has passed since when he clicked on button A. I am not to sure if its possible to do with PHP, is it? If not, how would I do this with jQuery? Maybe set a date on click using jQuery like var futureTime = time+8sec. if (!futureTime) { echo this }
2013/05/07
[ "https://Stackoverflow.com/questions/16429089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2352485/" ]
I managed to solve it by changing the default schema for the user name to dbo, in SQL Server Management Studio
What is the value set as DB objects schema in Site Manager -> Settings - > System? This setting should match the DB schema and also, all the object should have it the same. I would recommend to unify the tables and views schema to have one and the same name.
16,429,089
I have 2 buttons. Button A: A button. Button B: Submit button. What I am trying to do is, when user clicks on button A, it will send him a link. But he won't be able to submit using button B until 8 seconds has passed since when he clicked on button A. I am not to sure if its possible to do with PHP, is it? If not, how would I do this with jQuery? Maybe set a date on click using jQuery like var futureTime = time+8sec. if (!futureTime) { echo this }
2013/05/07
[ "https://Stackoverflow.com/questions/16429089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2352485/" ]
What is the value set as DB objects schema in Site Manager -> Settings - > System? This setting should match the DB schema and also, all the object should have it the same. I would recommend to unify the tables and views schema to have one and the same name.
Have you same installation on both machines? This issue occur when you don't have installed all modules as on origin machine (even if you don't use them). Try to exlude all Ecommerce object of System tables when you configure Import.
16,429,089
I have 2 buttons. Button A: A button. Button B: Submit button. What I am trying to do is, when user clicks on button A, it will send him a link. But he won't be able to submit using button B until 8 seconds has passed since when he clicked on button A. I am not to sure if its possible to do with PHP, is it? If not, how would I do this with jQuery? Maybe set a date on click using jQuery like var futureTime = time+8sec. if (!futureTime) { echo this }
2013/05/07
[ "https://Stackoverflow.com/questions/16429089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2352485/" ]
I managed to solve it by changing the default schema for the user name to dbo, in SQL Server Management Studio
Have you same installation on both machines? This issue occur when you don't have installed all modules as on origin machine (even if you don't use them). Try to exlude all Ecommerce object of System tables when you configure Import.
17,356
I have a limited amount of data included in my internet plan. If I exceed that limit I get charged extra. So, before signing up for Bitcoin, I'd like to know whether Bitcoin mining causes a lot of internet traffic. Does it involve a lot of downloading and uploading throughout the day?
2013/11/27
[ "https://bitcoin.stackexchange.com/questions/17356", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/9417/" ]
If you mine with a pool, your actual internet activity will be fairly small. I just took a look at my network statistics and BFGMiner used 9MBytes down and 11 MBytes up over the previous 24-hour period. The Bitcoin-Qt application on the other hand maxes out my upload bandwidth since I always seem to get 2-3 peers who want to download the entire 12 GB blockchain from me. Other than that, the main Bitcoin-Qt network usage occurs when you are receiving or relaying the latest block (blocks are typically 100-400 KBytes). Since you have limited internet bandwidth, your best bet would be to run a lightweight client such as Electrum or Multibit. If you are mining in a pool, you don't need a local Bitcoin-Qt.
If you use a light wallet like Electrum, definitely not. But even if you run a full node, it is unlikely. You could also use a web-based wallet like blockchain.info which would mean that nothing at all is running on your local computer and you can access it from anywhere.
30,050,777
I have a section of code as follows: ``` var percentageTemp =((parseInt(score)/parseInt(guesses))*100); var percentage= percentageTemp.toFixed(2); ``` `score` and `guesses` are both set to *0* at the start of the code, and are altered as the user plays the game. The code works as it should, exept if I leave `score` variable 0, I get a *NaN* output. Why am I getting the *NaN* output when `score` *= 0*?
2015/05/05
[ "https://Stackoverflow.com/questions/30050777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4129463/" ]
> > The code works as it should, exept if I leave score variable 0, I get a NaN output. > > > You shouldn't do (examples from the Node.JS REPL): > > > ``` > > var score = 0; var guesses = 1; var percentageTemp =((parseInt(score)/parseInt(guesses))*100); var percentage= percentageTemp.toFixed(2); console.log(percentage) > 0.00 > > ``` > > If, on the other hand, you leave `guesses` at `0` then: > > > ``` > > var score = 0; var guesses = 0; var percentageTemp =((parseInt(score)/parseInt(guesses))*100); var percentage= percentageTemp.toFixed(2); console.log(percentage) > NaN > > ``` > > … because [it isn't possible to divide by zero](http://en.wikipedia.org/wiki/Division_by_zero).
I'd advise using a radix. parseInt(score, 10) to ensure the value doesn't get converted to hexadecimal. Also, note that javascripts handling of decimal numbers is not accurate. Try putting this in your console - (0.1 + 0.2) and see an unusual value returned - 0.30000000000000004
54,405,955
I want add a script code function in my html page, i'm tried using $(element).append('my script') but, this method has add like a text, no like code. How i can do this? I executed this code in my page console: ``` document.querySelector("body").append('<script> function validarValorElemento(e){ var xpathWay = "xpath=//"+e.target.tagName+"[@class=\'" + e.target.className+"\']" var elementValue = e.target.textContent alert(xpathWay) alert(elementValue)}</script>'); ``` [This is the result.](https://i.stack.imgur.com/cfn6O.png)
2019/01/28
[ "https://Stackoverflow.com/questions/54405955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10802446/" ]
***IF*** I understand your question correctly -- that is, if you want to inject code into an existing webpage where you don't have access to the source code -- then: The simplest way to do this is with a browser extension called [TamperMonkey](https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en) - it allows you to inject javascript into any webpage, based on the URL. TamperMonkey scripts are installed (or written) in each person's browser, individually, and they only effect the webpage on that one computer. So, if your friend also wants to see the same effect, he also needs to install the TamperMonkey extension and add your script - which is why there are now millions of TamperMonkey users around the world. Hugely amazing product - many thanks to [Jan Biniok](https://tampermonkey.net/imprint.php?ext=dhdg). There are also tons of pre-existing Tampermonkey scripts at the [GreasyFork](https://greasyfork.org/en/scripts/by-site/youtube.com?sort=total_installs) script repository. TamperMonkey comes out of a previous extension called GreaseMonkey, so anywhere you see variations of that name, it probably also relates to TamperMonkey. The documentation for TamperMonkey is here: <https://tampermonkey.net/documentation.php>
Why don't you just add it inside the HTML directly? However, you can insert any tag with content into your HTML via JavaScript like this: ```js var htmlToInsert = '<div class="inserted">I am added dynamically</div>'; var target = document.querySelector('#container'); target.innerHTML += htmlToInsert; ``` ```css #container { padding: 10px; background: #000; color: #fff; } .inserted { margin: 20px 0; width: 200px; height: 200px; background: #c00; } ``` ```html <div id="container">I've been here all the time</div> ```
738,377
My English may not be perfect since I'm not a native speaker, so please do point out the grammar mistakes if there are any. I've been reading Conway's "Functions of One Complex Variable", and encountered following exercise in the book (p. 17). $X$ here is a metric space and $d$ is the metric of it. Show that if $F\subset X$ is closed and connected then for every pair of points $a,b$ in $F$ and each $\epsilon>0$ there are points $z\_{0},z\_{1},\dots,z\_{n}$ in $F$ with $z\_{0}=a, z\_{n}=b$ and $d(z\_{k-1},z\_{k})<\epsilon$ for $1\leq k\leq n$. Is the hypothesis that $F$ be closed needed? If $F$ is a set which satisfies this property then $F$ is not necessarily connected, even if $F$ is closed. Give an example to illustrate this. Now, I guess the right way to solve this problem is to first fix a point $a$ and consider the subset $S$ of $F$ definded by $$S=\{b\in X;\ for\ all\ \epsilon>0,\ there\ are\ points \ z\_{0},z\_{1},\dots,z\_{n}\ in \ F\ with\ z\_{0}=a, z\_{n}=b\ and \ d(z\_{k-1},z\_{k})<\epsilon\ for \ 1\leq k\leq n\}$$and show that this set is nonempty, open and closed, but I'm currently stuck. I'm not sure where I should use the condition that $F$ is closed. Moreover, the rest of the problem is also challenging, and I can't think of any possible way to get started. Am I going in the right direction? Please give me a clear motivation on this problem and possibly the solution!! :D
2014/04/03
[ "https://math.stackexchange.com/questions/738377", "https://math.stackexchange.com", "https://math.stackexchange.com/users/92456/" ]
Here is an long alternative to Stefan's succinct proof: If $a,b \in F$ and $\epsilon>0$, let an $\epsilon$-path be a finite sequence of points satisfying the condition in the question. Suppose $F$ is connected. Let $a \in F$ and $\epsilon>0$. Let $U\_a(0) = B(a,\epsilon) \cap F$, and $U\_a(n+1) = \cup\_{x \in U\_a(n)} B(x,\epsilon) \cap F$. Note that $U\_a(n) \subset U\_a(n+1) \subset F$, and each set is open relative to $F$. Let $U\_a = \cup\_{n} U\_a(n)$, and again note that $U\_a$ is open relative to $F$. Note that if $b \in U\_a$, then there is an $\epsilon$-path joining $a$ and $b$. It is straightforward to see that if $a \neq b$, then either $U\_a=U\_b$ or $U\_a \cap U\_b = \emptyset $, and since $a \in U\_a$ for all $a$, we see that $ { \cal P} = \{ U\_a \}\_{a \in F}$ forms a partition of $F$. Suppose ${ \cal P}$ has more than one element, then let $V \in { \cal P}$, $W = \cup\_{O \in { \cal P}, O \neq V } O$. Then $V,W$ are open (relative to $F$), disjoint, non-empty and $F=V \cup W$, which contradicts $F$ being connected. Hence ${ \cal P}$ consists of one element and hence any two points of $F$ can be connected by an $\epsilon$-path. Counterexample: You need two closed sets that are not connected but are arbitrarily close to each other. Look for an example in $\mathbb{R}^2$. If either set was bounded, then one would be compact, and the hypotheses would imply that their union was connected. Hence both sets need to be unbounded, and the points at which they get closer and closer must get further and further away. Example: > > Let $C\_1 = \{ (x, {1 \over x} ) \}\_{ x >0 }$, $C\_2 = \{ (x,0) \}\_{x \ge 0 }$ and $F = C\_1 \cup C\_2$. > > >
Your approach seems correct. Your set contains the point $a$, so it's nonempty. For the openness pick any point and show that an open ball of radius $\varepsilon$ is contained in the set too. For the closedness pick a point in the closure and show there's a point from the set that is $\varepsilon$ close to it. So your set is a nonempty clopen subset of $F$ and must be the whole $F$ because of connectedness. You didn't need that $F$ is closed in $X$ anywhere. As for an example of a closed set which satisfies the property, but is not connected consider the graph of $f(x)=\dfrac1{x^2}$.
738,377
My English may not be perfect since I'm not a native speaker, so please do point out the grammar mistakes if there are any. I've been reading Conway's "Functions of One Complex Variable", and encountered following exercise in the book (p. 17). $X$ here is a metric space and $d$ is the metric of it. Show that if $F\subset X$ is closed and connected then for every pair of points $a,b$ in $F$ and each $\epsilon>0$ there are points $z\_{0},z\_{1},\dots,z\_{n}$ in $F$ with $z\_{0}=a, z\_{n}=b$ and $d(z\_{k-1},z\_{k})<\epsilon$ for $1\leq k\leq n$. Is the hypothesis that $F$ be closed needed? If $F$ is a set which satisfies this property then $F$ is not necessarily connected, even if $F$ is closed. Give an example to illustrate this. Now, I guess the right way to solve this problem is to first fix a point $a$ and consider the subset $S$ of $F$ definded by $$S=\{b\in X;\ for\ all\ \epsilon>0,\ there\ are\ points \ z\_{0},z\_{1},\dots,z\_{n}\ in \ F\ with\ z\_{0}=a, z\_{n}=b\ and \ d(z\_{k-1},z\_{k})<\epsilon\ for \ 1\leq k\leq n\}$$and show that this set is nonempty, open and closed, but I'm currently stuck. I'm not sure where I should use the condition that $F$ is closed. Moreover, the rest of the problem is also challenging, and I can't think of any possible way to get started. Am I going in the right direction? Please give me a clear motivation on this problem and possibly the solution!! :D
2014/04/03
[ "https://math.stackexchange.com/questions/738377", "https://math.stackexchange.com", "https://math.stackexchange.com/users/92456/" ]
The set $S$ should depend on a particular $ϵ$, so $$S\_ϵ=\{b\in F\mid \exists\{z\_o,...,z\_n\}\subseteq F,\ z\_0=a,\ z\_n=b,\ d(z\_n,z\_{m+1})<ϵ\}$$ You can show that $S\_ϵ$ is open in $F$: If $b\in S\_ϵ$, and $(z\_0,...,z\_n)$ is the sequence from $a$ to $b$ in $F$, then the ball $B\_{ϵ-d(z\_n,z\_{n-1})}(b)$ is contained in $S\_ϵ$. $S\_ϵ$ is also closed in $F$: If $x\in\overline S\_ϵ\cap F$, then the $B\_ϵ(x)$ intersects $S\_ϵ$, and the sequence to some point in this intersection can be extended to $z\_{n+1}=x$. So $S\_ϵ$ is open and closed in $F$, and since $F$ is connected, we have $F=S\_ϵ$. But this works for any $ϵ$, so the claim follows. The closedness of $F$ is not needed here.
Your approach seems correct. Your set contains the point $a$, so it's nonempty. For the openness pick any point and show that an open ball of radius $\varepsilon$ is contained in the set too. For the closedness pick a point in the closure and show there's a point from the set that is $\varepsilon$ close to it. So your set is a nonempty clopen subset of $F$ and must be the whole $F$ because of connectedness. You didn't need that $F$ is closed in $X$ anywhere. As for an example of a closed set which satisfies the property, but is not connected consider the graph of $f(x)=\dfrac1{x^2}$.
73,273,777
List all the ways that 1, 2, and 3 can add up to 4, the order matters. For example, `[1, 1, 1, 1]` is one way. `[1,1,2]` is different from `[1,2,1]` I have figured out one way it works on paper. But I still cannot write the code for it. Please help and Please check out this picture of [My Idea](https://i.stack.imgur.com/Qonb7.jpg) for clarity. This code I wrote failed. But this is how far I've got. ```js function theseAddToSum(steps = [], sum) { let results = []; if (steps.length < 1) return 'error' for (let i = 0; i < steps.length; i++) { let cur = steps[i]; let remaining = sum - cur; if (remaining >= 0) { console.log('sum', sum, 'step', cur) let c = theseAddToSum(steps, remaining) } } return results } console.log(theseAddToSum([1, 2, 3], 4)) ``` As I `console.log('sum', sum, 'step', cur)`, I get the desired results: ``` sum 4 step 1 sum 3 step 1 sum 2 step 1 sum 1 step 1 sum 2 step 2 sum 3 step 2 sum 1 step 1 sum 3 step 3 sum 4 step 2 sum 2 step 1 sum 1 step 1 sum 2 step 2 sum 4 step 3 sum 1 step 1 ``` My problem is that I don't know how to push the result to `results` array. It should look like `[[1,1,1,1], [1,1,2], [1,2,1], [1,3], [2,1,1], and on]`
2022/08/08
[ "https://Stackoverflow.com/questions/73273777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17173084/" ]
You have three issues in the method: 1. `;` after declaration 2. method's arguments should not be *redeclared* 3. you should *return* `List<int>` from the method Code: ``` static List<int> Merge(List<int> list_a, List<int> list_b) // no ; here { // You should not redclare list_a and list_b List<int> combined = new List<int>(); foreach (int i in list_a) { combined.Add(i); } foreach (int i in list_b) { combined.Add(i); } combined.Sort(); combined.ForEach(Console.WriteLine); // you should return List<int> from you function return combined; } ``` You can simplify the method with a help of *Linq*: ``` using System.Linq; ... static List<int> Merge(List<int> list_a, List<int> list_b) => list_a .Concat(list_b) .OrderBy(item => item) .ToList(); ```
Your method should return a List value. Your method never returns anything. Add `return combined;` at the end of your method or make your method a `void`
19,938
I'm currently trying to implement a simple file-upload form with CraftCMS. However, even though there are no errors on submitting the form, no file actually seems to get uploaded. This is the form: ``` <form action="" method="post" accept-charset="UTF-8" enctype="multipart/form-data"> <input type="hidden" name="action" value="entries/saveEntry"/> <input type="hidden" name="sectionId" value="29"> <input type="hidden" name="enabled" value="1"> <input type="file" name="useruploads" style="margin-bottom: 30px"/> <select class="form-control" id="sel1" style="margin-bottom: 30px"> <option>x-challenge auswählen</option> {% for entry in craft.entries.section('challenges') %} {% for ch in entry.allOverChallenge %} %} <option>( Tirol ) {{ch.allOverName}}</option> {% endfor %} {% endfor %} {% for entry in craft.entries.section('xSpots') %} {% for ch in entry.standaloneChallenges %} %} <option>( {{entry.title}} ) {{ch.standaloneName}}</option> {% endfor %} {% endfor %} </select> <input type="text" class="form-control" id="challenge_select" placeholder="Titel eingeben" style="margin-bottom: 30px"> <textarea class="form-control" rows="5" id="challenge_description" placeholder="Beschreibung eingeben" style="margin-bottom: 30px"></textarea> <input type="text" class="form-control" id="challenge_customtags" placeholder="Hashtags ( max. 3 )" style="margin-bottom: 30px"> <div style="margin-bottom: 30px"> <input type="reset" value="abbrechen"> <input type="submit" value="hochladen"> </div> </form> ``` I'm attaching two screenshots that show both the actual field and the section: [![enter image description here](https://i.stack.imgur.com/awKln.jpg)](https://i.stack.imgur.com/awKln.jpg) [![enter image description here](https://i.stack.imgur.com/YMpZz.jpg)](https://i.stack.imgur.com/YMpZz.jpg) When submitting the form in it's current state, no entries actually get added to the field as shown in the image below. Am I doing something wrong here? I'd appreciate some help on the topic. [![enter image description here](https://i.stack.imgur.com/bojKe.jpg)](https://i.stack.imgur.com/bojKe.jpg)
2017/04/13
[ "https://craftcms.stackexchange.com/questions/19938", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/5798/" ]
Have you tried enabling devMode in the craft/config/general.php file? You can do this by adding `'devMode' => true` to the array. You should then be able to see an error on submission. If this fails to output anything then it could be that your input requires square brackets adding to the name, e.g. `name="useruploads[]"` Even though you have limited the field to 1 upload, it may still be expecting an array to be posted to it.
Doesn't look like the field name is correct - you should be using the `fields` namespace for all the actual Entry fields. For the upload, for example, you should be using `fields[useruploads]`. You can find more information about Asset uploads specifically [here](https://craftcms.com/docs/assets-fields#uploading-files-from-front-end-entry-forms)
3,003,271
Please tell me if there is a duplicate; I can't find any question that does answer me; If you find one, I'll remove my question. Thank you :) --- > > Prove that $2\cos36° = 2\sin18° +1$. > > > I saw people proving it by identities [here](https://www.quora.com/How-can-I-solve-cos-36-sin-18-1-2), or I can also prove it by finding the exact value [here](http://www.cut-the-knot.org/pythagoras/cos36.shtml) and [here](https://www.quora.com/How-can-I-find-the-value-of-sin18%C2%B0-1), but what I'm trying to find is a way that (I hope) can be proven from this diagram, since both $\cos36°$ and $\sin18°$ have a close relationship with the golden ratio. Any help will be appreciated. [![This diagram](https://i.stack.imgur.com/t2nNV.gif)](https://i.stack.imgur.com/t2nNV.gif)
2018/11/18
[ "https://math.stackexchange.com/questions/3003271", "https://math.stackexchange.com", "https://math.stackexchange.com/users/515374/" ]
You can pull it off with your diagram, but you will also need $\color{blue}{\Phi^2=\Phi+1}$ (which is already implied in your diagram). Take one of the isoceles triangles with sides $\Phi$, $\Phi$ and $1$; split it in half to obtain a right-angled triangle with sides $\Phi$, "something" and $1/2$; then you can compute $$\sin 18^\circ =\frac{1/2}{\Phi}$$ so that $$2\sin 18^\circ +1 =\frac{1}{\Phi} +1 =\frac{\color{blue}{1+\Phi}}{\Phi} =\frac{\color{blue}{\Phi^2}}{\Phi} =\Phi.$$ For $\cos 36^\circ$, take an isoceles triangle of sides $\Phi$, $\Phi$ and $\Phi^2$; split it in half to obtain a right-angled triangle with sides $\Phi$, "something" and $\Phi^2/2$; then you can compute $$\cos 36^\circ =\frac{\Phi^2/2}{\Phi} =\frac{\Phi}{2}.$$
Let the top vertex be called $A$, the left arm vertex be called $B$, the next line intersection on that very horizontal line be called $C$ the center point be called $D$, the next line intersection there be called $E$ and the right arm point be called $F$. Then you already displayed that $AB=\Phi^2$. Thus from the triangle $ABD$ you get $$2\cos(36°)=2\frac{BD}{AB}=\frac{BF}{AB}=\frac{\Phi^3}{\Phi^2}=\Phi$$ On the other hand you have displayed that $AC=\Phi$. Thus $$2\sin(18°)=2\cos(72°)=2\frac{CD}{AC}=\frac{CE}{AC}=\frac1{\Phi}$$ And of course you know that $\Phi=1+1/\Phi$ or (multiplied by $\Phi$): $\Phi^2=\Phi+1$. In fact this can be also read off from the isoceles triangle $ABE$, because $AB=\Phi^2$ and $AB=BE=BC+CE=\Phi+1$. --- rk
36,761,091
I am not able to access function b(). How can I call function b() outside? ``` function a() { function b() { alert("I am in b function"); } } ```
2016/04/21
[ "https://Stackoverflow.com/questions/36761091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917166/" ]
You can't, unless you modify `a` to make `b` available outside of `a`. As it stands now, `b` is completely private to `a`. There are lots of ways `a` could make `b` available outside of itself: 1. Return it 2. Return an object that has `b` on one of its properties 3. Assign it to a variable `a` closes over 4. Assign it to a property on an object referenced by a variable `a` closes over ...but as `a` is now, you can't access `b`. Here are examples of the above: ### 1 - Return it ``` function a() { return function b() { alert("I am in b function"); }; } var x = a(); x(); ``` ### 2 - Return an object with `b` as a property: ``` function a() { return { foo: function b() { alert("I am in b function"); } }; } var x = a(); x.foo(); ``` ### 3 - Assign it to a variable `a` closes over ``` var x; function a() { x = function b() { alert("I am in b function"); }; } x(); ``` ### 4 - Assign it to a property of an object referenced by a variable `a` closes over ``` var x = {}; function a() { x.foo = function b() { alert("I am in b function"); }; } x.foo(); ```
Can't you do the below thing ``` function a() { b(); } function b() { alert("I am in b function"); } ```
36,761,091
I am not able to access function b(). How can I call function b() outside? ``` function a() { function b() { alert("I am in b function"); } } ```
2016/04/21
[ "https://Stackoverflow.com/questions/36761091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917166/" ]
You can't, unless you modify `a` to make `b` available outside of `a`. As it stands now, `b` is completely private to `a`. There are lots of ways `a` could make `b` available outside of itself: 1. Return it 2. Return an object that has `b` on one of its properties 3. Assign it to a variable `a` closes over 4. Assign it to a property on an object referenced by a variable `a` closes over ...but as `a` is now, you can't access `b`. Here are examples of the above: ### 1 - Return it ``` function a() { return function b() { alert("I am in b function"); }; } var x = a(); x(); ``` ### 2 - Return an object with `b` as a property: ``` function a() { return { foo: function b() { alert("I am in b function"); } }; } var x = a(); x.foo(); ``` ### 3 - Assign it to a variable `a` closes over ``` var x; function a() { x = function b() { alert("I am in b function"); }; } x(); ``` ### 4 - Assign it to a property of an object referenced by a variable `a` closes over ``` var x = {}; function a() { x.foo = function b() { alert("I am in b function"); }; } x.foo(); ```
Following @ArunPJohny's comment, you can do something like this: ```js var a = (function a() { function b() { alert("I am in b function"); } return { b: b } })(); a.b(); ``` The above is called the [revealing module pattern](https://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript).
59,610,380
Is there a way to deserialize GenericRecord (which I just got from Kafka message) to nested POJO? I am actually tying to deserialize it to Scala's case class but I realize that's even harder. I searched through the internet and it seems everyone was doing it manually. Are you aware of any library which is able to do this?
2020/01/06
[ "https://Stackoverflow.com/questions/59610380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045201/" ]
``` Chart.helpers.each(Chart.instances, function(instance){ console.log(instance); }); ``` Update: <https://jsfiddle.net/furd1L27/14/>
I would recommend to store all data sent to chart in arrays. Once the array is updated you can send: > > HTTP/AJAX/SOCKET.IO > > > indication to the client, and update the chart.
59,610,380
Is there a way to deserialize GenericRecord (which I just got from Kafka message) to nested POJO? I am actually tying to deserialize it to Scala's case class but I realize that's even harder. I searched through the internet and it seems everyone was doing it manually. Are you aware of any library which is able to do this?
2020/01/06
[ "https://Stackoverflow.com/questions/59610380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045201/" ]
ChartJS API actually offers the [`getChart`](https://www.chartjs.org/docs/latest/developers/api.html#static-getchart-key) method to do what you want: ```js let chart = Chart.getChart('chart-2'); // Select by canvas ID // OR let canvas = document.querySelector('#chart-2') let chart = Chart.getChart(canvas); // Select using the canvas element // You can now update your chart chart.data.datasets[0].data = newData; chart.data.labels = newLabels; chart.update(); ```
I would recommend to store all data sent to chart in arrays. Once the array is updated you can send: > > HTTP/AJAX/SOCKET.IO > > > indication to the client, and update the chart.
45,456,182
``` typedef enum {my_false, my_true = 5, my_maybe = 3} my_bool; my_bool f(){return 2;} int g(){return my_true;} int main (){ my_bool mb = f(); int i = f(); printf("%d--%d\n", mb==i, mb); mb = g(); i = g(); printf("%d--%d\n", mb==i, mb); return 0; } ``` What is happening when a function returns `enum`? As I see it, in my code, `f()` can return any number, even if it's not defined inside the `my_bool enum`, but it seems that no matter what I return (like `2` in my example, the value stored inside `my_bool mb = f();` would `1` unless I return `0`or`my_false`. 1. Is this what should happen? does `enum` decays immediately to `int` and thus has no problem with numbers that aren't defined in it? 2. Why gcc generates warning: `comparison between signed and unsigned integer expressions [-Wsign-compare]... printf("%d--%d\n", mb==i, mb);`? isn't `enum` a `signed int`? 3. why defining the same value with different identifiers ok? (i.e. `typedef enum {xx = 1, yy = 1} zz;`)
2017/08/02
[ "https://Stackoverflow.com/questions/45456182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3512538/" ]
Enums can take any value in their range. The range is defined by the bits needed to represent all enumerators. In your case, you need 3 bits for `my_true`, which gives a range 0-7. Enumerators are essentially named constants, and there's no reason why you can't have two constants that happen to have the same value. Plenty of constants are in fact zero.
enums can be implemented as `char` ,`int` or `unsigned int` and it is left for the implementation. From the warning you get the information that your gcc compiler implements the `unsigned int`.
311,836
A charged particle $q$ enters a uniform magnetic field $\vec{B}$ with velocity $\vec{v}$ making an angle $\theta$ with it. Since the Lorentz force is perpendicular to the velocity, the particle will move along a circular path of radius $r$, which *my textbook* derives as follows: $$\frac{mv^2}{r}=qvB \sin\theta$$ $$r=\frac{mv}{qB\sin\theta}.$$ But I think the correct formula for $r$ should be derived as follows: $$\frac{m(v\sin\theta)^2}{r}=qvB \sin\theta$$ $$r=\frac{mv\sin\theta}{qB}.$$ This should be because we only consider the perpendicular component of velocity when we calculate magnetic force and therefore the velocity to which the force is perpendicular is the component of velocity perpendicular to $\vec{B}$ and not $\vec{v}$. Which is the correct formula?
2017/02/13
[ "https://physics.stackexchange.com/questions/311836", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/112205/" ]
Your derivation is correct and your book is incorrect unless the $v$ in their equation is the component of velocity perpendicular to the magnetic field? The diagram below assumes a positive charge. [![enter image description here](https://i.stack.imgur.com/6GYqt.jpg)](https://i.stack.imgur.com/6GYqt.jpg) The radius of the circular motion is given by the equation $r=\dfrac{mv\sin\theta}{qB}$ and the pitch of the helix is $p = \dfrac{2\pi mv\cos \theta}{qB}$
![enter image description here](https://i.stack.imgur.com/umooF.jpg).this is the ans for the question
311,836
A charged particle $q$ enters a uniform magnetic field $\vec{B}$ with velocity $\vec{v}$ making an angle $\theta$ with it. Since the Lorentz force is perpendicular to the velocity, the particle will move along a circular path of radius $r$, which *my textbook* derives as follows: $$\frac{mv^2}{r}=qvB \sin\theta$$ $$r=\frac{mv}{qB\sin\theta}.$$ But I think the correct formula for $r$ should be derived as follows: $$\frac{m(v\sin\theta)^2}{r}=qvB \sin\theta$$ $$r=\frac{mv\sin\theta}{qB}.$$ This should be because we only consider the perpendicular component of velocity when we calculate magnetic force and therefore the velocity to which the force is perpendicular is the component of velocity perpendicular to $\vec{B}$ and not $\vec{v}$. Which is the correct formula?
2017/02/13
[ "https://physics.stackexchange.com/questions/311836", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/112205/" ]
Your derivation is correct and your book is incorrect unless the $v$ in their equation is the component of velocity perpendicular to the magnetic field? The diagram below assumes a positive charge. [![enter image description here](https://i.stack.imgur.com/6GYqt.jpg)](https://i.stack.imgur.com/6GYqt.jpg) The radius of the circular motion is given by the equation $r=\dfrac{mv\sin\theta}{qB}$ and the pitch of the helix is $p = \dfrac{2\pi mv\cos \theta}{qB}$
It is easy to see that the book answer r = mv/qBsin θ is correct. Ask yourself what happens to the radius as the strength of the magnetic field decreases. Since the component of the magnetic field producing a force on the charge is smaller than 1.0 for any θ less than 90 degrees the book's formula correctly describes what happens for angles other than 90 degrees. The error in multiplying the velocity by sin θ, rather than the magnetic field is that you are only considering the component of the velocity that is perpendicular to the field. You have erroneously ignored the effect that the total velocity has on the circumference of the circle. Also the sin θ factor only applies to the force on a charge that is moving perpendicular to a magnetic field. It does not apply to the force required to change the direction of a moving mass that happens to have a charge.
311,836
A charged particle $q$ enters a uniform magnetic field $\vec{B}$ with velocity $\vec{v}$ making an angle $\theta$ with it. Since the Lorentz force is perpendicular to the velocity, the particle will move along a circular path of radius $r$, which *my textbook* derives as follows: $$\frac{mv^2}{r}=qvB \sin\theta$$ $$r=\frac{mv}{qB\sin\theta}.$$ But I think the correct formula for $r$ should be derived as follows: $$\frac{m(v\sin\theta)^2}{r}=qvB \sin\theta$$ $$r=\frac{mv\sin\theta}{qB}.$$ This should be because we only consider the perpendicular component of velocity when we calculate magnetic force and therefore the velocity to which the force is perpendicular is the component of velocity perpendicular to $\vec{B}$ and not $\vec{v}$. Which is the correct formula?
2017/02/13
[ "https://physics.stackexchange.com/questions/311836", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/112205/" ]
It is easy to see that the book answer r = mv/qBsin θ is correct. Ask yourself what happens to the radius as the strength of the magnetic field decreases. Since the component of the magnetic field producing a force on the charge is smaller than 1.0 for any θ less than 90 degrees the book's formula correctly describes what happens for angles other than 90 degrees. The error in multiplying the velocity by sin θ, rather than the magnetic field is that you are only considering the component of the velocity that is perpendicular to the field. You have erroneously ignored the effect that the total velocity has on the circumference of the circle. Also the sin θ factor only applies to the force on a charge that is moving perpendicular to a magnetic field. It does not apply to the force required to change the direction of a moving mass that happens to have a charge.
![enter image description here](https://i.stack.imgur.com/umooF.jpg).this is the ans for the question
26,607,435
I want to upload users into lync by an xml file. is there any lync api or c# code to do it?? I have xml file like below ``` <ns1:LyncOnlineAcpUsers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns1="http://schemas.microsoft.com/online/mco/2011/02/acp">-<ns1:ACPUser><ns1:Username>first.last@test.com</ns1:Username>-<ns1:UserAudioConferencingInfo>-<ns1:Provider><ns1:Identity>BT Conferencing</ns1:Identity></ns1:Provider><ns1:TollNumber>17209882090</ns1:TollNumber><ns1:TollFreeNumber>18666708282</ns1:TollFreeNumber><ns1:Passcode>99999999</ns1:Passcode></ns1:UserAudioConferencingInfo></ns1:ACPUser></ns1:LyncOnlineAcpUsers> ```
2014/10/28
[ "https://Stackoverflow.com/questions/26607435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2369697/" ]
Hope so this will help you ``` public class RangingActivity extends Activity implements BeaconConsumer { protected static final String TAG = "RangingActivity"; private static final String UUID = "XXXXXXXXXXXXXXXXXXXX"; private BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ranging); beaconManager.bind(this); } @Override protected void onDestroy() { super.onDestroy(); beaconManager.unbind(this); } @Override public void onBeaconServiceConnect() { beaconManager.setRangeNotifier(new RangeNotifier() { @Override public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) { if (beacons.size() > 0) { Log.i(TAG, "The first beacon I see is about "+beacons.iterator().next().getDistance()+" meters away."); } } }); try { beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", Identifier.parse(UUID), null, null)); } catch (RemoteException e) { } beaconManager.getBeaconParsers().add(new BeaconParser() .setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")); } } ``` in AndroidManifest.xml permissions ``` <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> ``` Register ``` <service android:name="org.altbeacon.beacon.service.BeaconService" android:enabled="true" android:exported="true" android:isolatedProcess="false" android:label="beacon" > </service> <service android:name="org.altbeacon.beacon.BeaconIntentProcessor" android:enabled="true" > </service> <receiver android:name="org.altbeacon.beacon.startup.StartupBroadcastReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.ACTION_POWER_CONNECTED" /> <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" /> </intent-filter> </receiver> ```
pass major and minor in place of null ``` Region region = new Region("myRangingUniqueId", uUID, major, minor); ```
2,339,560
DTF does not call the second action if the custom action assembly has more than one action. It always calls only the first action. As a workaround, I am using one action in one assembly. It works perfectly always. Do you have any idea on this issue? ``` public class CustomActions { [CustomAction] public static ActionResult CustomAction1(Session session) { [some code] } [CustomAction] public static ActionResult CustomAction2(Session session) { [some code] } } ```
2010/02/26
[ "https://Stackoverflow.com/questions/2339560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281321/" ]
I've never seen this problem as I group custom actions together in a single assembly all the time. Each method will be exported as type 1 entry points and then you write a custom action for each exported function. Windows Installer calls the CA which calls the function which fires up the CLR and invokes the static method that the custom action points to.
It might seem an obvious thing, but still. When you define a custom actions in your wxs file, do you specify different values in "DllEntry" attribute? This attribute points out a method, which is actually your CA. If you copy/paste custom action definitions, you might just forget to change the DllEntry...
2,339,560
DTF does not call the second action if the custom action assembly has more than one action. It always calls only the first action. As a workaround, I am using one action in one assembly. It works perfectly always. Do you have any idea on this issue? ``` public class CustomActions { [CustomAction] public static ActionResult CustomAction1(Session session) { [some code] } [CustomAction] public static ActionResult CustomAction2(Session session) { [some code] } } ```
2010/02/26
[ "https://Stackoverflow.com/questions/2339560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281321/" ]
I've never seen this problem as I group custom actions together in a single assembly all the time. Each method will be exported as type 1 entry points and then you write a custom action for each exported function. Windows Installer calls the CA which calls the function which fires up the CLR and invokes the static method that the custom action points to.
Probably, it will be helpful for some searchers, especially for .Net novices: double check that class and static method of custom action entry is public!
2,339,560
DTF does not call the second action if the custom action assembly has more than one action. It always calls only the first action. As a workaround, I am using one action in one assembly. It works perfectly always. Do you have any idea on this issue? ``` public class CustomActions { [CustomAction] public static ActionResult CustomAction1(Session session) { [some code] } [CustomAction] public static ActionResult CustomAction2(Session session) { [some code] } } ```
2010/02/26
[ "https://Stackoverflow.com/questions/2339560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281321/" ]
Probably, it will be helpful for some searchers, especially for .Net novices: double check that class and static method of custom action entry is public!
It might seem an obvious thing, but still. When you define a custom actions in your wxs file, do you specify different values in "DllEntry" attribute? This attribute points out a method, which is actually your CA. If you copy/paste custom action definitions, you might just forget to change the DllEntry...
1,310,843
I use cron jobs to execute shell scripts which are very simple invocations of wget. Here's one such example: ``` #!/bin/sh fileName="WRTI-"$(date +"%m-%d-%Y-%H%M") directory=/volume1/multimedia/Internet\ Radio\ Recordings/WRTI/$1/ wget http://playerservices.streamtheworld.com/api/livestream-redirect/WRTI_JAZZ.mp3 -O "$directory$fileName.mp3" -q& nWgetPID=$! sleep 3600 kill $nWgetPID echo "Done." ``` This is an internet radio stream. My problem is that while this works fine, there are times very frequently where the stream gets "interrupted" (as best as i can tell) and I end up with a truncated copy of the stream. If there was a switch I could throw at WGET to say "resume automatically after the interruption", I would be much, much, much, (MUCH!) happier. Any ideas?
2018/04/04
[ "https://superuser.com/questions/1310843", "https://superuser.com", "https://superuser.com/users/366999/" ]
As C0deDaedalus wrote, `wget -c` means to resume downloading a partially downloaded file by sending the "Range" header. Since you're dealing with a live internet stream, this flag won't work as intended. At best, it may enable you to continue appending the stream into the same downloaded file, ignoring the fact that you lost a chunk when the stream got interrupted, and at best, the missing chunk won't cause trouble for your MP3 player. Regardless, you seem to have a different problem as well: Your script needs to actually *detect* when the `wget` process ends too soon, so that it can even try to resume the download. [Here is a way to detect whether a process has ended, using the exit status of `kill -0`.](https://unix.stackexchange.com/questions/76717/bash-launch-background-process-and-check-when-it-ends) This means you can't just use `sleep 3600` either, so you'll need [a different way to end after 1 hour](https://stackoverflow.com/questions/11176284/time-condition-loop-in-shell). So you'd have something like this: ``` #!/usr/bin/bash directory=/volume1/multimedia/Internet\ Radio\ Recordings/WRTI/$1/ endSeconds=$((SECONDS + 3600)) while [ $SECONDS -lt $endSeconds ]; do fileName="WRTI-"$(date +"%m-%d-%Y-%H%M%S") wget http://playerservices.streamtheworld.com/api/livestream-redirect/WRTI_JAZZ.mp3 -O "$directory$fileName.mp3" -q& nWgetPID=$! while kill -0 "$nWgetPID" >/dev/null 2>&1; do if [ $SECONDS -gt $endSeconds ] then kill "$nWgetPID" fi sleep 1 done done echo "Done." ``` As written, this starts a new file after every interruption. You could also probably incorporate `wget -c` to put everything into the same file, but then you won't be able to easily diagnose how many interruptions there were and when they happened.
Well, To continue interrupted downloads with `wget` you can use **`-c`** option that means to continue. ``` wget -c http://playerservices.streamtheworld.com/api/livestream-redirect/WRTI_JAZZ.mp3 -O "$directory$fileName.mp3" -q ``` Some points here : * It assumes that you have partial downloaded file on your local system. * If the download file with earlier invocation is empty, It will refuse to continue. In that case you need to remove empty file first. * While using `-c` , Any file that's bigger on the server than locally will be considered as an incomplete download and only ``` (length(remote) - length(local)) bytes ``` will be downloaded and tacked onto the end of the local file. * **`Important`** `-c` only [works](https://linux.die.net/man/1/wget) (See last line under -c option) with FTP servers and with `HTTP servers that support the Range header` and in your case It's HTTP. ``` http://playerservices.streamtheworld.com/api/livestream-redirect/WRTI_JAZZ.mp3 ``` So, Goodluck with that ! Feel free to add-in more details.
11,968,860
Is this possible? It shouldn't be but sometimes its behavior is quite against ordinary programming sense.
2012/08/15
[ "https://Stackoverflow.com/questions/11968860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
No, Matlab isn't affected by indentation. They do have editors that will automatically indent the code for you, but it is for readability purposes only. Keeping your code readable with [smart-indenting](http://blogs.mathworks.com/community/2009/05/11/keep-your-code-readable-with-smart-indenting/) is always a good idea not only for yourself, but for others who may have to read through your code. Note: ***Warnings can*** occur (depending on the IDE) if the indentation isn't consistent, but even sporadic indentation won't affect how your code executes in Matlab.
It'll give you warnings if you don't indent properly. If you make a if or for loop or something like that and the end block isn't inline with it you'll get a possible warning that says the statement might not be aligned with its end block. CRTL+A CTRL+I is easy enough though.
11,947,858
I am just starting out with Windows 8 development using HTML/JS. I've spent the last few months immersed in jQuery development for apps targeting vehicle head-units and televisions. Jumping into this, I thought the transition would be simple. I have the design and structure of my site all figured out for the most part and was hoping to follow some of the practices I had been using for my previous work. That is, I want to essentially create a single page app. The main default.html file will house the top navigation/title and one other div. The other div will be used to load in all the other pages, all separate HTML files within the project. All of the global functions and major functionality will reside in a javascript file, application.js. Then any page-specific javascript will reside at the top of each HTML file. I'm quickly realizing that this is a problem. Using jQuery.load() to load in my pages causes security errors in my app. > > JavaScript runtime error: Unable to add dynamic content. A script attempted to inject dynamic content, or elements previously modified dynamically, that might be unsafe. For example, using the innerHTML property to add script or malformed HTML will generate this exception. Use the toStaticHTML method to filter dynamic content, or explicitly create elements and attributes with a method such as createElement. > > > I was really hoping to avoid having to learn a bunch of Microsoft-specific stuff. I think it's great that they've provided a lot of tools and what not, and maybe I just haven't used them enough, but everything just feels too rigid for me and for what I'm trying to do or can already be accomplished with jQuery. I'm one who likes to know EXACTLY what is happening and have full control over it. Also looking through the templates and sample projects, I really don't like all the repeated code. For instance, every single HTML file declaring all the same references. I want to write my references and sections like my title bar just once, and not have to copy/paste that code all over my project. Is there a way to do things the way I was hoping, and create a single page app? Do they have their own substitute for jQuery's .load()? Any help pointing me in the right direction would be much appreciated! EDIT 8/14/2012: I have tried using the fix from this question: [Using jQuery with Windows 8 Metro JavaScript App causes security error](https://stackoverflow.com/questions/10859523/using-jquery-with-windows-8-metro-javascript-app-causes-security-error) This gets rid of the security warning and I can load in HTML using jQuery.load(). However, looking at DOM explorer, my HTML is being stripped of my scripts. I have also tried wrapping my .load() call inside of MSApp.execUnsafeLocalFunction(), but yet again my file still gets stripped of all scripts. What gives?
2012/08/14
[ "https://Stackoverflow.com/questions/11947858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/711596/" ]
I fixed by simply changing the line of jQuery that was causing the error. jQuery-1.8.0, line 5566: ``` append: function () { return this.domManip(arguments, true, function (elem) { if (this.nodeType === 1 || this.nodeType === 11) { self.appendChild(elem); // problem line } }); }, ``` Changed to: ``` append: function () { return this.domManip(arguments, true, function (elem) { if (this.nodeType === 1 || this.nodeType === 11) { var self = this; MSApp.execUnsafeLocalFunction(function () { self.appendChild(elem); }); } }); }, ```
Depending on your app, if you are not intending to access any WinRT components, you can navigate your page to ms-appx-web which will change the security policy around the page, but you can't specify this from start up. You would have to do a navigate, and leverage that new securyt context. The other option you have it to wrap the calls to JQuery with msWWA.execUnsafeLocalFunction function, which will enable all that unsafe code be pushed into the DOM
11,947,858
I am just starting out with Windows 8 development using HTML/JS. I've spent the last few months immersed in jQuery development for apps targeting vehicle head-units and televisions. Jumping into this, I thought the transition would be simple. I have the design and structure of my site all figured out for the most part and was hoping to follow some of the practices I had been using for my previous work. That is, I want to essentially create a single page app. The main default.html file will house the top navigation/title and one other div. The other div will be used to load in all the other pages, all separate HTML files within the project. All of the global functions and major functionality will reside in a javascript file, application.js. Then any page-specific javascript will reside at the top of each HTML file. I'm quickly realizing that this is a problem. Using jQuery.load() to load in my pages causes security errors in my app. > > JavaScript runtime error: Unable to add dynamic content. A script attempted to inject dynamic content, or elements previously modified dynamically, that might be unsafe. For example, using the innerHTML property to add script or malformed HTML will generate this exception. Use the toStaticHTML method to filter dynamic content, or explicitly create elements and attributes with a method such as createElement. > > > I was really hoping to avoid having to learn a bunch of Microsoft-specific stuff. I think it's great that they've provided a lot of tools and what not, and maybe I just haven't used them enough, but everything just feels too rigid for me and for what I'm trying to do or can already be accomplished with jQuery. I'm one who likes to know EXACTLY what is happening and have full control over it. Also looking through the templates and sample projects, I really don't like all the repeated code. For instance, every single HTML file declaring all the same references. I want to write my references and sections like my title bar just once, and not have to copy/paste that code all over my project. Is there a way to do things the way I was hoping, and create a single page app? Do they have their own substitute for jQuery's .load()? Any help pointing me in the right direction would be much appreciated! EDIT 8/14/2012: I have tried using the fix from this question: [Using jQuery with Windows 8 Metro JavaScript App causes security error](https://stackoverflow.com/questions/10859523/using-jquery-with-windows-8-metro-javascript-app-causes-security-error) This gets rid of the security warning and I can load in HTML using jQuery.load(). However, looking at DOM explorer, my HTML is being stripped of my scripts. I have also tried wrapping my .load() call inside of MSApp.execUnsafeLocalFunction(), but yet again my file still gets stripped of all scripts. What gives?
2012/08/14
[ "https://Stackoverflow.com/questions/11947858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/711596/" ]
There is a "formal" way to do what you are seeking. WinJS.Navigation is provided to support "single page apps". For example, the `default.html` would contain a markup that would represent where the dynamically loaded page content would go: ``` <div id="contenthost" data-win-control="Application.PageControlNavigator" data-win-options="{home: '/pages/home/home.html'}"> </div> ``` In the example above, the actual content page loaded is at `/pages/home/home.html` In event handlers, you can simply do the following to `load` or navigate to another page: ``` WinJS.Navigation.nav("/pages/other/page.html"); ``` True, it is not jQuery, but it works great :)
Depending on your app, if you are not intending to access any WinRT components, you can navigate your page to ms-appx-web which will change the security policy around the page, but you can't specify this from start up. You would have to do a navigate, and leverage that new securyt context. The other option you have it to wrap the calls to JQuery with msWWA.execUnsafeLocalFunction function, which will enable all that unsafe code be pushed into the DOM
66,780
I'm trying to categorize my knowledge. Can I place block ciphers and stream ciphers under *symmetric* with RSA/DH under *asymmetric*?
2019/01/25
[ "https://crypto.stackexchange.com/questions/66780", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/61031/" ]
This is almost correct and in general these two classes of algorithms are distinct. However, Simon Shepherd published a paper called **Public Key Stream Ciphers** in the *IEE Colloquium on Security & Cryptography Applications to Radio Systems, London, 3 June 1994*. It proposes to essentially use the RSA setup and initial random seed $x\_0$ from $\mathbb{Z}\_{pq}$ and Blum Blum Shub type of squaring $$ x\_{k+1}:=x\_k^2~~in~~\mathbb{Z}\_{pq} $$ with the keystream being $z\_k=LSB(x\_k).$ This can be used to (presumably transmit to the holder of the private key $(p,q,d)$ first the initial value $x\_k$ encrypted with RSA, and then) the keystream $$ a\_k\oplus x\_k,\quad k\geq 1. $$ Of course BBS pseudorandom sequence generation is older than this.
> > Can I place block ciphers and stream ciphers under symmetric with RSA/DH under asymmetric? > > > This sounds like you are trying to categorize RSA/DH as block/stream ciphers, which is not accurate. It is possible to model RSA encryption as a block cipher, but that's an uncommon notion. "Public-key encryption" and "block cipher" indicate different concepts, even if the public-key encryption operation in question happens to be a permutation of blocks it would still create confusion to talk of it as a "block cipher". Diffie-Hellman is key agreement algorithm rather than an encryption algorithm, and as such is not any kind of cipher. A better way to rephrase your statement might be: > > Can I place block ciphers and stream ciphers under symmetric cryptography, with RSA/DH under asymmetric cryptography? > > > To which the answer would be "yes". > > Are all block and stream ciphers symmetric? > > > Conventionally, yes. It is conceivably possible to define an asymmetric operation to combine the key stream. But this would be abnormal.
3,175,194
Is it possible to use "tabs"(indenting) in textarea using javascript. When tab button is clicked, the next form element is focused. But, i need to indent the text in textarea. I am currently working in a project and any code with javascript or jquery will help me.
2010/07/04
[ "https://Stackoverflow.com/questions/3175194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306961/" ]
What about something like this: ``` <input onkeypress="if(event.keyCode == 9) { this.value += ' '; return false; }"> ``` Basically, when you press the keyCode 9 (which is the Tab key) I return false. This prevents from focusing another element on the page. To mimic the Tab spaces I just add the spaces myself to the value of the input itself.
Try this: capture the tab key in keypress events and stop propagation. I m not sure if this will work consistently across browsers; give it a try!
3,175,194
Is it possible to use "tabs"(indenting) in textarea using javascript. When tab button is clicked, the next form element is focused. But, i need to indent the text in textarea. I am currently working in a project and any code with javascript or jquery will help me.
2010/07/04
[ "https://Stackoverflow.com/questions/3175194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306961/" ]
The best plugin I've seen for this is the [Tabs in Textarea plugin](http://teddevito.com/demos/textarea.html). You can try a demo [on its page](http://teddevito.com/demos/textarea.html). The setup is fairly simple, since it has a simple *effect*: ``` $("textarea").tabby(); ``` The thing that annoyed me most about other plugins was lack of `shift`+`tab`, which this handles. You *can* do this without a plugin, but I wouldn't in this case...it's be quite a bit of code yourself, depending on the functionality you're after. TextRange operations in a cross-browser way are still a bit hairy under the covers, this is one of the times that a plugin is a better approach, IMO.
Try this: capture the tab key in keypress events and stop propagation. I m not sure if this will work consistently across browsers; give it a try!
3,175,194
Is it possible to use "tabs"(indenting) in textarea using javascript. When tab button is clicked, the next form element is focused. But, i need to indent the text in textarea. I am currently working in a project and any code with javascript or jquery will help me.
2010/07/04
[ "https://Stackoverflow.com/questions/3175194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306961/" ]
The best plugin I've seen for this is the [Tabs in Textarea plugin](http://teddevito.com/demos/textarea.html). You can try a demo [on its page](http://teddevito.com/demos/textarea.html). The setup is fairly simple, since it has a simple *effect*: ``` $("textarea").tabby(); ``` The thing that annoyed me most about other plugins was lack of `shift`+`tab`, which this handles. You *can* do this without a plugin, but I wouldn't in this case...it's be quite a bit of code yourself, depending on the functionality you're after. TextRange operations in a cross-browser way are still a bit hairy under the covers, this is one of the times that a plugin is a better approach, IMO.
What about something like this: ``` <input onkeypress="if(event.keyCode == 9) { this.value += ' '; return false; }"> ``` Basically, when you press the keyCode 9 (which is the Tab key) I return false. This prevents from focusing another element on the page. To mimic the Tab spaces I just add the spaces myself to the value of the input itself.
22,847,351
I'm wanting to filter the list of registered users based on their roles. I've managed to do it so that it shows users of one certain role but what I want to achieve is the complete opposite and show only the users who are *not* in that user group This is the code I have: ``` var users = UserManager.Users.ToListAsync(); var roleUsers = RoleManager.Roles.Single(a => a.Name.Equals("Super Admin")).Users; var list = (from r in roleUsers join u in users on r.UserId equals u.Id select u); ``` **Update** Thanks to @sjkm I've been able to filter out the super admins with this ``` var users = UserManager.Users.ToList(); var roles = RoleManager.Roles.Where(a => a.Name != "Super Admin").ToList(); var userList = new List<IdentityUserRole>(); foreach (var role in roles) { userList.AddRange(role.Users.ToList()); } var list = (from r in userList join u in users on r.UserId equals u.Id select u).Distinct(); return View(list); ``` My problem now is a user who is both an super admin and another role, is shown in this list so I now need to further filter down this list to remove any super admins who may be in another role I also forgot to mention this is using asp.net identity 2
2014/04/03
[ "https://Stackoverflow.com/questions/22847351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2287870/" ]
I've managed to filter out the super admins who have secondary roles, fairly simple really, just get a list of user ids of super admins and remove them from the list of non-super admin users to find and remove those with the secondary role ``` var users = UserManager.Users.ToList(); var roles = RoleManager.Roles.Where(a => a.Name != "Super Admin").ToList(); var superAdmins = RoleManager.Roles.Single(b => b.Name == "Super Admin").Users; var userList = new List<IdentityUserRole>(); foreach (var role in roles) { userList.AddRange(role.Users.ToList()); } foreach (var superAdmin in superAdmins) { userList.RemoveAll(x => x.UserId == superAdmin.UserId); } var list = (from r in userList join u in users on r.UserId equals u.Id orderby u.FirstName ascending orderby u.LastName ascending select u).Distinct(); return View(list); ``` No doubts this is a really rubbish and inefficient way of doing it but it does the job nonetheless but if anyone can streamline it then please be my guest Hope this will be of some use to somebody else out there! **Update** Managed to streamline this by just getting the user list and removing those whose user Ids match those who appear in the Super Admin user list ``` var users = UserManager.Users.ToList(); var superAdmins = RoleManager.Roles.Single(b => b.Name == "Super Admin").Users; foreach (var superAdmin in superAdmins) { users.RemoveAll(c => c.Id == superAdmin.UserId); } return View(users.ToList()); ```
``` var roles = RoleManager.Roles.Where(r => r.Name != "Super Admin").ToList(); var users = new List<User>(); foreach(var role in roles) { users.AddRange(role.Users.ToList()); } // 'users'-List contains all the users which do not have the 'Super Admin' role ``` (For a better perfomance get all ids of the roles and select the users with a single query `Users.Where(u => rolesIds.Contains(u.Role_IDFS))`)
116,747
I generally do my own electrical work but needed to upgrade my service from 100A to 200A so I hired someone. I had them add some outlets to my garage while they were at it because I was feeling lazy. Today I decided to add more outlets and noticed they used low voltage brackets rather than the enclosed junction boxes I always use. I am assuming this is a code violation, but before I complain I wanted to ask here. I live in California if that matters. ![115V outlet through low voltage frame](https://i.stack.imgur.com/n8M3N.jpg)
2017/06/18
[ "https://diy.stackexchange.com/questions/116747", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/70992/" ]
What sort of joker did *that*? ------------------------------ Clearly, whichever joker did that needs to be sent back to their apprentice electrician's training, because line voltage connections need to be in a box! If you see them around again, be sure to thwap them upside the head with NEC 300.15 for me, OK? (P.S. none of the exceptions in 300.15(A) through (L) apply to this situation.) > > **300.15 Boxes, Conduit Bodies, or Fittings - Where Required.** A box shall be installed at each outlet and switch > point for concealed knob-and-tube wiring. > > > Fittings and connectors shall be used only with the specific wiring methods for which they are designed and listed. > > > Where the wiring method is conduit, tubing, Type AC > cable, Type MC cable, Type MI cable, nonmetallic-sheathed > cable, or other cables, a box or conduit body shall be installed > at each conductor splice point, outlet point, switch point, junction point, termination point, or pull point, unless otherwise > permitted in 300.15(A) through (L). > > >
Honestly, I would make a beeline to the town office. (After discreetly removing my extension if unpermitted). Because the electrical inspector/permit issuer needs to know about this. First, they need to know that this guy out there making messes, so to watch out for him. And second, you have to ask *if he filed for a permit for the work he did to your house.* If he *did* pull a permit, then the inspector really dropped the ball on the inspection, and he needs to know that. If he did not pull a permit, you're in a bad spot because you now have unpermitted work in your house. That could blow up in your face when you go to sell the house, at which point it will be much too late to seek recourse from the "electrician", and you will be left holding the bag. That is why I would *make* this thing blow up *now*, while he can be held responsible for doing the job right. You want the job done right and you want the inspector to sign off on it. Honestly I think the inspector has the best chance of putting leverage on him.
38,990,356
I am working on creating an Android app and I am facing a problem while enabling location directly from my app. On the first launch, when location permission is allowed, the app works correctly, but when it is reopened, the app crashes. Here is the source code for my app: ``` public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private GoogleMap mMap; GoogleApiClient mGoogleApiClient; Location mLastLocation; Marker mCurrLocationMarker; LocationRequest mLocationRequest; protected static final int REQUEST_CHECK_SETTINGS = 0x1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission(); } // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); settingsrequest(); } private void settingsrequest() { if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext()) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this).build(); mGoogleApiClient.connect(); LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(30 * 1000); locationRequest.setFastestInterval(5 * 1000); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); builder.setAlwaysShow(true); //this is the key ingredient PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); result.setResultCallback(new ResultCallback<LocationSettingsResult>() { @Override public void onResult(LocationSettingsResult result) { final Status status = result.getStatus(); final LocationSettingsStates state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the user // a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult(MapsActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { // Ignore the error. } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way to fix the // settings so we won't show the dialog. break; } } }); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: startLocationUpdates(); break; case Activity.RESULT_CANCELED: settingsrequest();//keep asking if imp or do whatever break; } break; } } private void startLocationUpdates() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this); } public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; public boolean checkLocationPermission() { if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){ if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); }else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } return false; }else{ return true; } } @Override public void onConnected(Bundle bundle) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(1000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){ LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this); } } @Override public void onConnectionSuspended(int i) { } @Override public void onLocationChanged(Location location) { mLastLocation = location; if(mCurrLocationMarker != null){ mCurrLocationMarker.remove(); } LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude()); MarkerOptions markerOption = new MarkerOptions(); markerOption.position(latLng); markerOption.title("Current Position"); markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); mCurrLocationMarker = mMap.addMarker(markerOption); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(14).build(); mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); if(mGoogleApiClient != null){ LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this); } } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==PackageManager.PERMISSION_GRANTED){ buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } } else { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResult){ switch (requestCode){ case MY_PERMISSIONS_REQUEST_LOCATION: { if(grantResult.length > 0 && grantResult[0] == PackageManager.PERMISSION_GRANTED){ if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if(mGoogleApiClient == null){ buildGoogleApiClient(); } mMap.setMyLocationEnabled(true); } }else { Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show(); } return; } } } } ``` Posting the trace from user: ``` FATAL EXCEPTION: main Process: com.gprs, PID: 31433 java.lang.IllegalStateException: GoogleApiClient is not connected yet. at com.google.android.gms.internal.zzod.zzd(Unknown Source) at com.google.android.gms.internal.zzoh.zzd(Unknown Source) at com.google.android.gms.internal.zzof.zzd(Unknown Source) at com.google.android.gms.location.internal.zzd.requestLocationUpdates(Unknown Source) at com.gprs.MapsActivity.onConnected(MapsActivity.java:185) at com.google.android.gms.common.internal.zzl.zzm(Unknown Source) at com.google.android.gms.internal.zzof.zzk(Unknown Source) at com.google.android.gms.internal.zzod.zzsb(Unknown Source) at com.google.android.gms.internal.zzod.onConnected(Unknown Source) at com.google.android.gms.internal.zzoh.onConnected(Unknown Source) at com.google.android.gms.internal.zznw.onConnected(Unknown Source) at com.google.android.gms.common.internal.zzk$1.onConnected(Unknown Source) at com.google.android.gms.common.internal.zzd$zzj.zztp(Unknown Source) at com.google.android.gms.common.internal.zzd$zza.zzc(Unknown Source) at com.google.android.gms.common.internal.zzd$zza.zzw(Unknown Source) at com.google.android.gms.common.internal.zzd$zze.zztr(Unknown Source) at com.google.android.gms.common.internal.zzd$zzd.handleMessage(Unknown Source) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:168) at android.app.ActivityThread.main(ActivityThread.java:5885) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687) ```
2016/08/17
[ "https://Stackoverflow.com/questions/38990356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6518328/" ]
Don't use `String(format:...)`. Use `NSNumberFormatter`: ``` let f = NSNumberFormatter() f.maximumFractionDigits = 0 let s = f.stringFromNumber(-27790.00)! print(s) // Output "-27790" ```
Swift 4.0 iOS 11.x Converting an NSNumber into a string ... ``` let temp:NSNumber = 5 let tempString = temp.stringValue ```
3,507,993
> > Evaluate $$\int \_0^1\:\frac{2-x^2}{(1+x)\sqrt{1-x^2}}dx$$ > > > $$ \int \_0^1\:\frac{2-x^2}{(1+x)\sqrt{1-x^2}} \, dx = \int\_0^1 \bigg[\sqrt{\frac{1+x}{1-x}}+\frac{1}{(1-x)^{3/2}\sqrt{1+x}}\bigg] \, dx=\int\_0^1[f(x)+f'(x)]\,dx $$ Does making it into the above final form helps somehow solve the given definite integral ? **Note:** The solution given is $\pi/2$
2020/01/13
[ "https://math.stackexchange.com/questions/3507993", "https://math.stackexchange.com", "https://math.stackexchange.com/users/223599/" ]
Let $x=\sin t$. Then, $$\int \_0^1 \frac{2-x^2}{\left(1+x\right)\sqrt{1-x^2}}dx =\int \_0^1\left(\frac{1}{\left(1+x\right)\sqrt{1-x^2}} +\frac{\sqrt{1-x^2}}{1+x}\right)dx$$ $$=\int\_0^{\pi/2} \left( \frac{dt}{1+\sin t}+1-\sin t\right)dt$$ $$=\left(-\frac{\cos t}{1+\sin t} + t + \cos t\right)\_0^{\pi/2}=\frac\pi2$$
$$x=:\sin u\implies dx=\cos u\,du\implies\int\_0^1\frac{2-x^2}{(1+x)\sqrt{1-x^2}}dx=\int\_0^{\pi/2}\frac{2-\sin^2u}{(1+\sin u)}\,du=$$ $$=\int\_0^{\pi/2}\left(\frac1{1+\sin u}+1-\sin u\right)du=\int\_0^{\pi/2}\frac{1-\sin u}{\cos^2u}+\left.\frac\pi2+\cos u\right|\_0^{\pi/2}=$$ $$=\left.\left(\tan u-\frac1{\cos u}\right)\right|\_0^{\pi/2}+\frac\pi2-1=\frac\pi2$$ since $$\lim\_{u\to\frac\pi2^-}\left(\tan u-\frac1{\cos u}\right)=\lim\_{u\to\frac\pi2^-}\frac{\sin u-1}{\cos u}\stackrel{\text{L'Hospital}}=0$$
21,374,599
Office timings: `10:00 am to 18:00` pm. Office Policy: Actually, our office policy is to pay employees stipend for overtime so they calculate overtime only above than `18:00 pm` clock time, even if the person arrives at office at `17:00 pm` and has worked upto `18:54 pm` even then he would be paid for `54mins overtime`, apart from the time he hasn't worked would result in deducations from pay but still applicable for overtime stipend. Issue: I have written this query to calculate total time a person has worked per day, the duration of his work I mean. Now I am trying to calculate a new column `OVERTIME` which should show the duration of overtime a person has done if and only if a person has worked above than `18:00 pm` that time should come under overtime column other wise `00:00` so help me in this please ``` WITH Times AS ( SELECT emp.EmplID, emp.EmplName, InTime = MIN(atd.RecTime), OutTime = MAX(atd.RecTime), TimeWorked = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)), [DateVisited] = atd.RecDate FROM AtdRecord atd INNER JOIN HrEmployee emp ON atd.EmplID = emp.EmplID GROUP BY emp.EmplID, emp.EmplName, atd.RecDate HAVING COUNT(atd.RecTime) > 1 ) SELECT t.EmplID, t.EmplName, t.InTime, t.OutTime, t.DateVisited, TimeWorked = CONVERT(CHAR(5), DATEADD(MINUTE, t.TimeWorked, 0), 8) FROM Times t ``` Output: ![Image](https://i.stack.imgur.com/K9yvM.png) Output of Vignesh Kumar's solution: ![enter image description here](https://i.stack.imgur.com/IbDWl.png)
2014/01/27
[ "https://Stackoverflow.com/questions/21374599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3207757/" ]
Your question says that you are working on client side then use ``` OnClientClick="course(); return false;" ``` .
asp.net web forms will always do a postback on a runat="server" button click. that is how it reaches the code behind (.cs file). for client side clicks you can either use aspx ajax or jQuery click or javascript onclick functions to prevent postbacks. For this very reason more and more asp.net developers are moving to asp.net mvc. Try just creating a simple html button and doing and onclick to run you javascript function: ``` <button onclick="javascript:some_js_function();">Click Me</button> ``` or jQuery: ``` <button id="btn">Click Me</button> ``` in you document.ready: ``` $('form').on('click', '#btn', function(evt) { evt.preventDefault(); some_js_function(); }); ```
21,374,599
Office timings: `10:00 am to 18:00` pm. Office Policy: Actually, our office policy is to pay employees stipend for overtime so they calculate overtime only above than `18:00 pm` clock time, even if the person arrives at office at `17:00 pm` and has worked upto `18:54 pm` even then he would be paid for `54mins overtime`, apart from the time he hasn't worked would result in deducations from pay but still applicable for overtime stipend. Issue: I have written this query to calculate total time a person has worked per day, the duration of his work I mean. Now I am trying to calculate a new column `OVERTIME` which should show the duration of overtime a person has done if and only if a person has worked above than `18:00 pm` that time should come under overtime column other wise `00:00` so help me in this please ``` WITH Times AS ( SELECT emp.EmplID, emp.EmplName, InTime = MIN(atd.RecTime), OutTime = MAX(atd.RecTime), TimeWorked = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)), [DateVisited] = atd.RecDate FROM AtdRecord atd INNER JOIN HrEmployee emp ON atd.EmplID = emp.EmplID GROUP BY emp.EmplID, emp.EmplName, atd.RecDate HAVING COUNT(atd.RecTime) > 1 ) SELECT t.EmplID, t.EmplName, t.InTime, t.OutTime, t.DateVisited, TimeWorked = CONVERT(CHAR(5), DATEADD(MINUTE, t.TimeWorked, 0), 8) FROM Times t ``` Output: ![Image](https://i.stack.imgur.com/K9yvM.png) Output of Vignesh Kumar's solution: ![enter image description here](https://i.stack.imgur.com/IbDWl.png)
2014/01/27
[ "https://Stackoverflow.com/questions/21374599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3207757/" ]
if you want to call javascript method use OnClientclick() and if you want call both the methods use onclick event to call the code behind method i.e method in aspx.cs and inside use this code ``` ClientScript.RegisterStartupScript(this.GetType(), "JSScript", course()); ```
If you don't want to call any server side event on button click its better to use normal `html` `button` control. Replace ``` <asp:Button id="b1" Text="Submit" runat="server" /> ``` With ``` <input type="button" value="Submit">Submit</input> ```
21,374,599
Office timings: `10:00 am to 18:00` pm. Office Policy: Actually, our office policy is to pay employees stipend for overtime so they calculate overtime only above than `18:00 pm` clock time, even if the person arrives at office at `17:00 pm` and has worked upto `18:54 pm` even then he would be paid for `54mins overtime`, apart from the time he hasn't worked would result in deducations from pay but still applicable for overtime stipend. Issue: I have written this query to calculate total time a person has worked per day, the duration of his work I mean. Now I am trying to calculate a new column `OVERTIME` which should show the duration of overtime a person has done if and only if a person has worked above than `18:00 pm` that time should come under overtime column other wise `00:00` so help me in this please ``` WITH Times AS ( SELECT emp.EmplID, emp.EmplName, InTime = MIN(atd.RecTime), OutTime = MAX(atd.RecTime), TimeWorked = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)), [DateVisited] = atd.RecDate FROM AtdRecord atd INNER JOIN HrEmployee emp ON atd.EmplID = emp.EmplID GROUP BY emp.EmplID, emp.EmplName, atd.RecDate HAVING COUNT(atd.RecTime) > 1 ) SELECT t.EmplID, t.EmplName, t.InTime, t.OutTime, t.DateVisited, TimeWorked = CONVERT(CHAR(5), DATEADD(MINUTE, t.TimeWorked, 0), 8) FROM Times t ``` Output: ![Image](https://i.stack.imgur.com/K9yvM.png) Output of Vignesh Kumar's solution: ![enter image description here](https://i.stack.imgur.com/IbDWl.png)
2014/01/27
[ "https://Stackoverflow.com/questions/21374599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3207757/" ]
asp.net web forms will always do a postback on a runat="server" button click. that is how it reaches the code behind (.cs file). for client side clicks you can either use aspx ajax or jQuery click or javascript onclick functions to prevent postbacks. For this very reason more and more asp.net developers are moving to asp.net mvc. Try just creating a simple html button and doing and onclick to run you javascript function: ``` <button onclick="javascript:some_js_function();">Click Me</button> ``` or jQuery: ``` <button id="btn">Click Me</button> ``` in you document.ready: ``` $('form').on('click', '#btn', function(evt) { evt.preventDefault(); some_js_function(); }); ```
In your addcourse javascript function always return false and asp:button OnClientClick="return addcourse();" \*\* Example \*\* ``` <asp:button id="Add" runat="Server" OnClientClick="return addcourse();"/> ``` \*\* JQuery \*\* ``` function addcourse() { //your code here return false; } ```
21,374,599
Office timings: `10:00 am to 18:00` pm. Office Policy: Actually, our office policy is to pay employees stipend for overtime so they calculate overtime only above than `18:00 pm` clock time, even if the person arrives at office at `17:00 pm` and has worked upto `18:54 pm` even then he would be paid for `54mins overtime`, apart from the time he hasn't worked would result in deducations from pay but still applicable for overtime stipend. Issue: I have written this query to calculate total time a person has worked per day, the duration of his work I mean. Now I am trying to calculate a new column `OVERTIME` which should show the duration of overtime a person has done if and only if a person has worked above than `18:00 pm` that time should come under overtime column other wise `00:00` so help me in this please ``` WITH Times AS ( SELECT emp.EmplID, emp.EmplName, InTime = MIN(atd.RecTime), OutTime = MAX(atd.RecTime), TimeWorked = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)), [DateVisited] = atd.RecDate FROM AtdRecord atd INNER JOIN HrEmployee emp ON atd.EmplID = emp.EmplID GROUP BY emp.EmplID, emp.EmplName, atd.RecDate HAVING COUNT(atd.RecTime) > 1 ) SELECT t.EmplID, t.EmplName, t.InTime, t.OutTime, t.DateVisited, TimeWorked = CONVERT(CHAR(5), DATEADD(MINUTE, t.TimeWorked, 0), 8) FROM Times t ``` Output: ![Image](https://i.stack.imgur.com/K9yvM.png) Output of Vignesh Kumar's solution: ![enter image description here](https://i.stack.imgur.com/IbDWl.png)
2014/01/27
[ "https://Stackoverflow.com/questions/21374599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3207757/" ]
if you want to call javascript method use OnClientclick() and if you want call both the methods use onclick event to call the code behind method i.e method in aspx.cs and inside use this code ``` ClientScript.RegisterStartupScript(this.GetType(), "JSScript", course()); ```
In your addcourse javascript function always return false and asp:button OnClientClick="return addcourse();" \*\* Example \*\* ``` <asp:button id="Add" runat="Server" OnClientClick="return addcourse();"/> ``` \*\* JQuery \*\* ``` function addcourse() { //your code here return false; } ```
21,374,599
Office timings: `10:00 am to 18:00` pm. Office Policy: Actually, our office policy is to pay employees stipend for overtime so they calculate overtime only above than `18:00 pm` clock time, even if the person arrives at office at `17:00 pm` and has worked upto `18:54 pm` even then he would be paid for `54mins overtime`, apart from the time he hasn't worked would result in deducations from pay but still applicable for overtime stipend. Issue: I have written this query to calculate total time a person has worked per day, the duration of his work I mean. Now I am trying to calculate a new column `OVERTIME` which should show the duration of overtime a person has done if and only if a person has worked above than `18:00 pm` that time should come under overtime column other wise `00:00` so help me in this please ``` WITH Times AS ( SELECT emp.EmplID, emp.EmplName, InTime = MIN(atd.RecTime), OutTime = MAX(atd.RecTime), TimeWorked = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)), [DateVisited] = atd.RecDate FROM AtdRecord atd INNER JOIN HrEmployee emp ON atd.EmplID = emp.EmplID GROUP BY emp.EmplID, emp.EmplName, atd.RecDate HAVING COUNT(atd.RecTime) > 1 ) SELECT t.EmplID, t.EmplName, t.InTime, t.OutTime, t.DateVisited, TimeWorked = CONVERT(CHAR(5), DATEADD(MINUTE, t.TimeWorked, 0), 8) FROM Times t ``` Output: ![Image](https://i.stack.imgur.com/K9yvM.png) Output of Vignesh Kumar's solution: ![enter image description here](https://i.stack.imgur.com/IbDWl.png)
2014/01/27
[ "https://Stackoverflow.com/questions/21374599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3207757/" ]
Your question says that you are working on client side then use ``` OnClientClick="course(); return false;" ``` .
In your addcourse javascript function always return false and asp:button OnClientClick="return addcourse();" \*\* Example \*\* ``` <asp:button id="Add" runat="Server" OnClientClick="return addcourse();"/> ``` \*\* JQuery \*\* ``` function addcourse() { //your code here return false; } ```
21,374,599
Office timings: `10:00 am to 18:00` pm. Office Policy: Actually, our office policy is to pay employees stipend for overtime so they calculate overtime only above than `18:00 pm` clock time, even if the person arrives at office at `17:00 pm` and has worked upto `18:54 pm` even then he would be paid for `54mins overtime`, apart from the time he hasn't worked would result in deducations from pay but still applicable for overtime stipend. Issue: I have written this query to calculate total time a person has worked per day, the duration of his work I mean. Now I am trying to calculate a new column `OVERTIME` which should show the duration of overtime a person has done if and only if a person has worked above than `18:00 pm` that time should come under overtime column other wise `00:00` so help me in this please ``` WITH Times AS ( SELECT emp.EmplID, emp.EmplName, InTime = MIN(atd.RecTime), OutTime = MAX(atd.RecTime), TimeWorked = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)), [DateVisited] = atd.RecDate FROM AtdRecord atd INNER JOIN HrEmployee emp ON atd.EmplID = emp.EmplID GROUP BY emp.EmplID, emp.EmplName, atd.RecDate HAVING COUNT(atd.RecTime) > 1 ) SELECT t.EmplID, t.EmplName, t.InTime, t.OutTime, t.DateVisited, TimeWorked = CONVERT(CHAR(5), DATEADD(MINUTE, t.TimeWorked, 0), 8) FROM Times t ``` Output: ![Image](https://i.stack.imgur.com/K9yvM.png) Output of Vignesh Kumar's solution: ![enter image description here](https://i.stack.imgur.com/IbDWl.png)
2014/01/27
[ "https://Stackoverflow.com/questions/21374599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3207757/" ]
asp.net web forms will always do a postback on a runat="server" button click. that is how it reaches the code behind (.cs file). for client side clicks you can either use aspx ajax or jQuery click or javascript onclick functions to prevent postbacks. For this very reason more and more asp.net developers are moving to asp.net mvc. Try just creating a simple html button and doing and onclick to run you javascript function: ``` <button onclick="javascript:some_js_function();">Click Me</button> ``` or jQuery: ``` <button id="btn">Click Me</button> ``` in you document.ready: ``` $('form').on('click', '#btn', function(evt) { evt.preventDefault(); some_js_function(); }); ```
If you don't want to call any server side event on button click its better to use normal `html` `button` control. Replace ``` <asp:Button id="b1" Text="Submit" runat="server" /> ``` With ``` <input type="button" value="Submit">Submit</input> ```
21,374,599
Office timings: `10:00 am to 18:00` pm. Office Policy: Actually, our office policy is to pay employees stipend for overtime so they calculate overtime only above than `18:00 pm` clock time, even if the person arrives at office at `17:00 pm` and has worked upto `18:54 pm` even then he would be paid for `54mins overtime`, apart from the time he hasn't worked would result in deducations from pay but still applicable for overtime stipend. Issue: I have written this query to calculate total time a person has worked per day, the duration of his work I mean. Now I am trying to calculate a new column `OVERTIME` which should show the duration of overtime a person has done if and only if a person has worked above than `18:00 pm` that time should come under overtime column other wise `00:00` so help me in this please ``` WITH Times AS ( SELECT emp.EmplID, emp.EmplName, InTime = MIN(atd.RecTime), OutTime = MAX(atd.RecTime), TimeWorked = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)), [DateVisited] = atd.RecDate FROM AtdRecord atd INNER JOIN HrEmployee emp ON atd.EmplID = emp.EmplID GROUP BY emp.EmplID, emp.EmplName, atd.RecDate HAVING COUNT(atd.RecTime) > 1 ) SELECT t.EmplID, t.EmplName, t.InTime, t.OutTime, t.DateVisited, TimeWorked = CONVERT(CHAR(5), DATEADD(MINUTE, t.TimeWorked, 0), 8) FROM Times t ``` Output: ![Image](https://i.stack.imgur.com/K9yvM.png) Output of Vignesh Kumar's solution: ![enter image description here](https://i.stack.imgur.com/IbDWl.png)
2014/01/27
[ "https://Stackoverflow.com/questions/21374599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3207757/" ]
asp.net web forms will always do a postback on a runat="server" button click. that is how it reaches the code behind (.cs file). for client side clicks you can either use aspx ajax or jQuery click or javascript onclick functions to prevent postbacks. For this very reason more and more asp.net developers are moving to asp.net mvc. Try just creating a simple html button and doing and onclick to run you javascript function: ``` <button onclick="javascript:some_js_function();">Click Me</button> ``` or jQuery: ``` <button id="btn">Click Me</button> ``` in you document.ready: ``` $('form').on('click', '#btn', function(evt) { evt.preventDefault(); some_js_function(); }); ```
Your button on Edit.aspx have a property **runat="server"** remove it and your post back stops
21,374,599
Office timings: `10:00 am to 18:00` pm. Office Policy: Actually, our office policy is to pay employees stipend for overtime so they calculate overtime only above than `18:00 pm` clock time, even if the person arrives at office at `17:00 pm` and has worked upto `18:54 pm` even then he would be paid for `54mins overtime`, apart from the time he hasn't worked would result in deducations from pay but still applicable for overtime stipend. Issue: I have written this query to calculate total time a person has worked per day, the duration of his work I mean. Now I am trying to calculate a new column `OVERTIME` which should show the duration of overtime a person has done if and only if a person has worked above than `18:00 pm` that time should come under overtime column other wise `00:00` so help me in this please ``` WITH Times AS ( SELECT emp.EmplID, emp.EmplName, InTime = MIN(atd.RecTime), OutTime = MAX(atd.RecTime), TimeWorked = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)), [DateVisited] = atd.RecDate FROM AtdRecord atd INNER JOIN HrEmployee emp ON atd.EmplID = emp.EmplID GROUP BY emp.EmplID, emp.EmplName, atd.RecDate HAVING COUNT(atd.RecTime) > 1 ) SELECT t.EmplID, t.EmplName, t.InTime, t.OutTime, t.DateVisited, TimeWorked = CONVERT(CHAR(5), DATEADD(MINUTE, t.TimeWorked, 0), 8) FROM Times t ``` Output: ![Image](https://i.stack.imgur.com/K9yvM.png) Output of Vignesh Kumar's solution: ![enter image description here](https://i.stack.imgur.com/IbDWl.png)
2014/01/27
[ "https://Stackoverflow.com/questions/21374599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3207757/" ]
If you don't want to call any server side event on button click its better to use normal `html` `button` control. Replace ``` <asp:Button id="b1" Text="Submit" runat="server" /> ``` With ``` <input type="button" value="Submit">Submit</input> ```
Your button on Edit.aspx have a property **runat="server"** remove it and your post back stops
21,374,599
Office timings: `10:00 am to 18:00` pm. Office Policy: Actually, our office policy is to pay employees stipend for overtime so they calculate overtime only above than `18:00 pm` clock time, even if the person arrives at office at `17:00 pm` and has worked upto `18:54 pm` even then he would be paid for `54mins overtime`, apart from the time he hasn't worked would result in deducations from pay but still applicable for overtime stipend. Issue: I have written this query to calculate total time a person has worked per day, the duration of his work I mean. Now I am trying to calculate a new column `OVERTIME` which should show the duration of overtime a person has done if and only if a person has worked above than `18:00 pm` that time should come under overtime column other wise `00:00` so help me in this please ``` WITH Times AS ( SELECT emp.EmplID, emp.EmplName, InTime = MIN(atd.RecTime), OutTime = MAX(atd.RecTime), TimeWorked = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)), [DateVisited] = atd.RecDate FROM AtdRecord atd INNER JOIN HrEmployee emp ON atd.EmplID = emp.EmplID GROUP BY emp.EmplID, emp.EmplName, atd.RecDate HAVING COUNT(atd.RecTime) > 1 ) SELECT t.EmplID, t.EmplName, t.InTime, t.OutTime, t.DateVisited, TimeWorked = CONVERT(CHAR(5), DATEADD(MINUTE, t.TimeWorked, 0), 8) FROM Times t ``` Output: ![Image](https://i.stack.imgur.com/K9yvM.png) Output of Vignesh Kumar's solution: ![enter image description here](https://i.stack.imgur.com/IbDWl.png)
2014/01/27
[ "https://Stackoverflow.com/questions/21374599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3207757/" ]
if you want to call javascript method use OnClientclick() and if you want call both the methods use onclick event to call the code behind method i.e method in aspx.cs and inside use this code ``` ClientScript.RegisterStartupScript(this.GetType(), "JSScript", course()); ```
Your button on Edit.aspx have a property **runat="server"** remove it and your post back stops
21,374,599
Office timings: `10:00 am to 18:00` pm. Office Policy: Actually, our office policy is to pay employees stipend for overtime so they calculate overtime only above than `18:00 pm` clock time, even if the person arrives at office at `17:00 pm` and has worked upto `18:54 pm` even then he would be paid for `54mins overtime`, apart from the time he hasn't worked would result in deducations from pay but still applicable for overtime stipend. Issue: I have written this query to calculate total time a person has worked per day, the duration of his work I mean. Now I am trying to calculate a new column `OVERTIME` which should show the duration of overtime a person has done if and only if a person has worked above than `18:00 pm` that time should come under overtime column other wise `00:00` so help me in this please ``` WITH Times AS ( SELECT emp.EmplID, emp.EmplName, InTime = MIN(atd.RecTime), OutTime = MAX(atd.RecTime), TimeWorked = DATEDIFF(MINUTE, MIN(atd.RecTime), MAX(atd.RecTime)), [DateVisited] = atd.RecDate FROM AtdRecord atd INNER JOIN HrEmployee emp ON atd.EmplID = emp.EmplID GROUP BY emp.EmplID, emp.EmplName, atd.RecDate HAVING COUNT(atd.RecTime) > 1 ) SELECT t.EmplID, t.EmplName, t.InTime, t.OutTime, t.DateVisited, TimeWorked = CONVERT(CHAR(5), DATEADD(MINUTE, t.TimeWorked, 0), 8) FROM Times t ``` Output: ![Image](https://i.stack.imgur.com/K9yvM.png) Output of Vignesh Kumar's solution: ![enter image description here](https://i.stack.imgur.com/IbDWl.png)
2014/01/27
[ "https://Stackoverflow.com/questions/21374599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3207757/" ]
Your question says that you are working on client side then use ``` OnClientClick="course(); return false;" ``` .
If you don't want to call any server side event on button click its better to use normal `html` `button` control. Replace ``` <asp:Button id="b1" Text="Submit" runat="server" /> ``` With ``` <input type="button" value="Submit">Submit</input> ```
443,708
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
2009/01/14
[ "https://Stackoverflow.com/questions/443708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
yet i see there is most preferred way which was what i was looking for.. it's basically derived from these answers but i had to manipulate it to more more redundant and efficient.. **and i think everybody looking for what i come up with** ### To the point:: first make an Interface *that simple* ```java public interface myCallback { void onSuccess(); void onError(String err); } ``` now to make this callback run when ever you wish to do to handle the results - ***more likely after async call and you wanna run some stuff which depends on these reuslts*** ```java // import the Interface class here public class App { public static void main(String[] args) { // call your method doSomething("list your Params", new myCallback(){ @Override public void onSuccess() { // no errors System.out.println("Done"); } @Override public void onError(String err) { // error happen System.out.println(err); } }); } private void doSomething(String param, // some params.. myCallback callback) { // now call onSuccess whenever you want if results are ready if(results_success) callback.onSuccess(); else callback.onError(someError); } } ``` `doSomething` is the function that takes some time you wanna add a callback to it to notify you when the results came, add the call back interface as a parameter to this method ### hope my point is clear, enjoy ;)
This is very easy in Java 8 with lambdas. ``` public interface Callback { void callback(); } public class Main { public static void main(String[] args) { methodThatExpectsACallback(() -> System.out.println("I am the callback.")); } private static void methodThatExpectsACallback(Callback callback){ System.out.println("I am the method."); callback.callback(); } } ```
443,708
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
2009/01/14
[ "https://Stackoverflow.com/questions/443708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
When I need this kind of functionality in Java, I usually use the [Observer pattern](http://en.wikipedia.org/wiki/Observer_pattern). It does imply an extra object, but I think it's a clean way to go, and is a widely understood pattern, which helps with code readability.
Create an Interface, and Create the Same Interface Property in Callback Class. ``` interface dataFetchDelegate { void didFetchdata(String data); } //callback class public class BackendManager{ public dataFetchDelegate Delegate; public void getData() { //Do something, Http calls/ Any other work Delegate.didFetchdata("this is callbackdata"); } } ``` Now in the class where you want to get called back implement the above Created Interface. and Also Pass "this" Object/Reference of your class to be called back. ``` public class Main implements dataFetchDelegate { public static void main( String[] args ) { new Main().getDatafromBackend(); } public void getDatafromBackend() { BackendManager inc = new BackendManager(); //Pass this object as reference.in this Scenario this is Main Object inc.Delegate = this; //make call inc.getData(); } //This method is called after task/Code Completion public void didFetchdata(String callbackData) { // TODO Auto-generated method stub System.out.println(callbackData); } } ```
443,708
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
2009/01/14
[ "https://Stackoverflow.com/questions/443708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
A method is not (yet) a first-class object in Java; you can't pass a function pointer as a callback. Instead, create an object (which usually implements an interface) that contains the method you need and pass that. Proposals for closures in Java—which would provide the behavior you are looking for—have been made, but none will be included in the upcoming Java 7 release.
Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates: <http://code.google.com/p/lambdaj/wiki/Closures>
443,708
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
2009/01/14
[ "https://Stackoverflow.com/questions/443708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
it's a bit old, but nevertheless... I found the answer of Peter Wilkinson nice except for the fact that it does not work for primitive types like int/Integer. The problem is the `.getClass()` for the `parameters[i]`, which returns for instance `java.lang.Integer`, which on the other hand will not be correctly interpreted by `getMethod(methodName,parameters[])` (Java's fault) ... I combined it with the suggestion of Daniel Spiewak ([in his answer to this](https://stackoverflow.com/questions/180097/dynamically-find-the-class-that-represents-a-primitive-java-type)); steps to success included: catching `NoSuchMethodException` -> `getMethods()` -> looking for the matching one by `method.getName()` -> and then explicitly looping through the list of parameters and applying Daniels solution, such identifying the type matches and the signature matches.
``` public class HelloWorldAnonymousClasses { //this is an interface with only one method interface HelloWorld { public void printSomething(String something); } //this is a simple function called from main() public void sayHello() { //this is an object with interface reference followed by the definition of the interface itself new HelloWorld() { public void printSomething(String something) { System.out.println("Hello " + something); } }.printSomething("Abhi"); //imagine this as an object which is calling the function'printSomething()" } public static void main(String... args) { HelloWorldAnonymousClasses myApp = new HelloWorldAnonymousClasses(); myApp.sayHello(); } } //Output is "Hello Abhi" ``` Basically if you want to make the object of an interface it is not possible, because interface cannot have objects. The option is to let some class implement the interface and then call that function using the object of that class. But this approach is really verbose. Alternatively, write new HelloWorld() (\*oberserve this is an interface not a class) and then follow it up with the defination of the interface methods itself. (\*This defination is in reality the anonymous class). Then you get the object reference through which you can call the method itself.
443,708
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
2009/01/14
[ "https://Stackoverflow.com/questions/443708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates: <http://code.google.com/p/lambdaj/wiki/Closures>
Simpliest and easiest way is by creating a reusable model and trigger.... <https://onecompiler.com/java/3wejrcby2?fbclid=IwAR0dHbGDChRUJoCZ3CIDW-JQu7Dz3iYGNGYjxYVCPCWfEqQDogFGTwuOuO8>
443,708
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
2009/01/14
[ "https://Stackoverflow.com/questions/443708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
Since Java 8, there are lambda and method references: * [Oracle Docs: Lambda Expressions](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) * [Oracle Docs: Method References](http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html) For example, if you want a functional interface `A -> B`, you can use: ``` import java.util.function.Function; public MyClass { public static String applyFunction(String name, Function<String,String> function){ return function.apply(name); } } ``` And here is how you can call it: ``` MyClass.applyFunction("42", str -> "the answer is: " + str); // returns "the answer is: 42" ``` Also you can pass class method. For example: ``` @Value // lombok public class PrefixAppender { private String prefix; public String addPrefix(String suffix){ return prefix +":"+suffix; } } ``` Then you can do: ``` PrefixAppender prefixAppender= new PrefixAppender("prefix"); MyClass.applyFunction("some text", prefixAppender::addPrefix); // returns "prefix:some text" ``` **Note**: Here I used the functional interface `Function<A,B>`, but there are many others in the package `java.util.function`. Most notable ones are * `Supplier`: `void -> A` * `Consumer`: `A -> void` * `BiConsumer`: `(A,B) -> void` * `Function`: `A -> B` * `BiFunction`: `(A,B) -> C` and many others that specialize on some of the input/output type. Then, if it doesn't provide the one you need, you can create your own `FunctionalInterface`: ``` @FunctionalInterface interface Function3<In1, In2, In3, Out> { // (In1,In2,In3) -> Out public Out apply(In1 in1, In2 in2, In3 in3); } ``` Example of use: ``` String computeAnswer(Function3<String, Integer, Integer, String> f){ return f.apply("6x9=", 6, 9); } computeAnswer((question, a, b) -> question + "42"); // "6*9=42" ``` And you can also do that with thrown exception: ``` @FunctionalInterface interface FallibleFunction<In, Out, Ex extends Exception> { Out get(In input) throws Ex; } public <Ex extends IOException> String yo(FallibleFunction<Integer, String, Ex> f) throws Ex { return f.get(42); } ```
I found the idea of implementing using the reflect library interesting and came up with this which I think works quite well. The only down side is losing the compile time check that you are passing valid parameters. ``` public class CallBack { private String methodName; private Object scope; public CallBack(Object scope, String methodName) { this.methodName = methodName; this.scope = scope; } public Object invoke(Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { Method method = scope.getClass().getMethod(methodName, getParameterClasses(parameters)); return method.invoke(scope, parameters); } private Class[] getParameterClasses(Object... parameters) { Class[] classes = new Class[parameters.length]; for (int i=0; i < classes.length; i++) { classes[i] = parameters[i].getClass(); } return classes; } } ``` You use it like this ``` public class CallBackTest { @Test public void testCallBack() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { TestClass testClass = new TestClass(); CallBack callBack = new CallBack(testClass, "hello"); callBack.invoke(); callBack.invoke("Fred"); } public class TestClass { public void hello() { System.out.println("Hello World"); } public void hello(String name) { System.out.println("Hello " + name); } } } ```
443,708
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
2009/01/14
[ "https://Stackoverflow.com/questions/443708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
This is very easy in Java 8 with lambdas. ``` public interface Callback { void callback(); } public class Main { public static void main(String[] args) { methodThatExpectsACallback(() -> System.out.println("I am the callback.")); } private static void methodThatExpectsACallback(Callback callback){ System.out.println("I am the method."); callback.callback(); } } ```
I've recently started doing something like this: ``` public class Main { @FunctionalInterface public interface NotDotNetDelegate { int doSomething(int a, int b); } public static void main(String[] args) { // in java 8 (lambdas): System.out.println(functionThatTakesDelegate((a, b) -> {return a*b;} , 10, 20)); } public static int functionThatTakesDelegate(NotDotNetDelegate del, int a, int b) { // ... return del.doSomething(a, b); } } ```
443,708
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
2009/01/14
[ "https://Stackoverflow.com/questions/443708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well. ``` public class Main { public interface Visitor{ int doJob(int a, int b); } public static void main(String[] args) { Visitor adder = new Visitor(){ public int doJob(int a, int b) { return a + b; } }; Visitor multiplier = new Visitor(){ public int doJob(int a, int b) { return a*b; } }; System.out.println(adder.doJob(10, 20)); System.out.println(multiplier.doJob(10, 20)); } } ```
I've recently started doing something like this: ``` public class Main { @FunctionalInterface public interface NotDotNetDelegate { int doSomething(int a, int b); } public static void main(String[] args) { // in java 8 (lambdas): System.out.println(functionThatTakesDelegate((a, b) -> {return a*b;} , 10, 20)); } public static int functionThatTakesDelegate(NotDotNetDelegate del, int a, int b) { // ... return del.doSomething(a, b); } } ```
443,708
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
2009/01/14
[ "https://Stackoverflow.com/questions/443708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
You also can do the`Callback` using the `Delegate` pattern: Callback.java ``` public interface Callback { void onItemSelected(int position); } ``` PagerActivity.java ``` public class PagerActivity implements Callback { CustomPagerAdapter mPagerAdapter; public PagerActivity() { mPagerAdapter = new CustomPagerAdapter(this); } @Override public void onItemSelected(int position) { // Do something System.out.println("Item " + postion + " selected") } } ``` CustomPagerAdapter.java ``` public class CustomPagerAdapter { private static final int DEFAULT_POSITION = 1; public CustomPagerAdapter(Callback callback) { callback.onItemSelected(DEFAULT_POSITION); } } ```
Simpliest and easiest way is by creating a reusable model and trigger.... <https://onecompiler.com/java/3wejrcby2?fbclid=IwAR0dHbGDChRUJoCZ3CIDW-JQu7Dz3iYGNGYjxYVCPCWfEqQDogFGTwuOuO8>
443,708
Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
2009/01/14
[ "https://Stackoverflow.com/questions/443708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
Since Java 8, there are lambda and method references: * [Oracle Docs: Lambda Expressions](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) * [Oracle Docs: Method References](http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html) For example, if you want a functional interface `A -> B`, you can use: ``` import java.util.function.Function; public MyClass { public static String applyFunction(String name, Function<String,String> function){ return function.apply(name); } } ``` And here is how you can call it: ``` MyClass.applyFunction("42", str -> "the answer is: " + str); // returns "the answer is: 42" ``` Also you can pass class method. For example: ``` @Value // lombok public class PrefixAppender { private String prefix; public String addPrefix(String suffix){ return prefix +":"+suffix; } } ``` Then you can do: ``` PrefixAppender prefixAppender= new PrefixAppender("prefix"); MyClass.applyFunction("some text", prefixAppender::addPrefix); // returns "prefix:some text" ``` **Note**: Here I used the functional interface `Function<A,B>`, but there are many others in the package `java.util.function`. Most notable ones are * `Supplier`: `void -> A` * `Consumer`: `A -> void` * `BiConsumer`: `(A,B) -> void` * `Function`: `A -> B` * `BiFunction`: `(A,B) -> C` and many others that specialize on some of the input/output type. Then, if it doesn't provide the one you need, you can create your own `FunctionalInterface`: ``` @FunctionalInterface interface Function3<In1, In2, In3, Out> { // (In1,In2,In3) -> Out public Out apply(In1 in1, In2 in2, In3 in3); } ``` Example of use: ``` String computeAnswer(Function3<String, Integer, Integer, String> f){ return f.apply("6x9=", 6, 9); } computeAnswer((question, a, b) -> question + "42"); // "6*9=42" ``` And you can also do that with thrown exception: ``` @FunctionalInterface interface FallibleFunction<In, Out, Ex extends Exception> { Out get(In input) throws Ex; } public <Ex extends IOException> String yo(FallibleFunction<Integer, String, Ex> f) throws Ex { return f.get(42); } ```
For simplicity, you can use a **Runnable**: ``` private void runCallback(Runnable callback) { // Run callback callback.run(); } ``` Usage: ``` runCallback(new Runnable() { @Override public void run() { // Running callback } }); ``` or with Java8 lambdas ``` runCallback(() -> { // Running callback }); ```
15,429,854
So I have a `UITableView`. Its dataSource is an `NSArray` of custom objects beeing loaded after a search. When I scroll to bottom, everything works fine, the `scrollIndicator` scrolls to bottom as desired. Now when I scroll back to top the scrollIndicator stops about 50pixel below my UINavigationbar. I have no idea why this behaviour occurs only in this `tableViewController`, since my `UITabBarController` consists of 5 `UITableViewcontrollers` each inheriting from the same super class. Any help is appreciated, thanks in advance :) **EDIT:** Putting the following code in `viewWillAppear:` ``` self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, 0); ``` Solved the issue. Although I still don't know why this issue only occurs in one of the five tableViewControllers...
2013/03/15
[ "https://Stackoverflow.com/questions/15429854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067062/" ]
It looks like you might have set the `scrollIndicatorInsets` property of the scroll view wrongly. It might be the same for both bottom and top. Set it so that that you only have the margin for bottom. i.e use `UIEdgeInsetMake( <top> , <left>,<bottom>,<right>);` for this. i.e for your case ``` yourScrollView.scrollIndicatorInsets = UIEdgeInsetMake(0, 0,bottomInset,0); //Here bottom inset would be the value you have right now . ```
As `UITableView's` superclass is `UIScrollView`, its better to set `UIScrollView's` `scrollIndicatorInsets` property to required position.
11,065,853
I want to toggle element that id's *pg* when click link. header: ``` <title>Example</title> <script type="text/javascript" src="jquery-1.3.2.js"></script> <script type="text/javascript"> $(function() { $("#link").click(function() { $("#pg").toggle(); }); </script> ``` Elements: ``` <p id="pg">deneme deneme 123 deneme</p> <a href="#" id="link">toggle</a> ```
2012/06/16
[ "https://Stackoverflow.com/questions/11065853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291078/" ]
You're missing the final `});` for the statement ``` <title>Example</title> <script type="text/javascript" src="jquery-1.3.2.js"></script> <script type="text/javascript"> $(function() { $("#link").click(function() { $("#pg").toggle(); }); )}; //<-- Missing close bracket </script> ``` Also, if you're using Firefox, check out [Firebug](http://getfirebug.com/). Its an invaluable debugger tool and will show you where errors are happening. Chrome has a Developer Tools enabled, not sure about IE.
close click function by adding `});`: ``` $(function() { $("#link").click(function() { $("#pg").toggle(); }); }); ```
46,257,648
I'm using AWS API Gateway and its HTTP Proxy. I need to pass the `CloudFront-Viewer-Country` header to my endpoint. I tried following the same setup outlined in the following question [Access headers in AWS API Gateway using HTTP Proxy?](https://stackoverflow.com/questions/35017297/access-headers-in-aws-api-gateway-using-http-proxy) and I'm getting the following headers on my endpoint server. ```html Array ( [host] => example.com [Accept] => application/json [User-Agent] => AmazonAPIGateway_c8752844lh [x-amzn-apigateway-api-id] => c8752844lh [X-Amzn-Trace-Id] => Root=1-59bd7a5e-003ef07b3c4c3680299801f1 [X-Forwarded-For] => xx.xxx.xx.xxx [X-Forwarded-Port] => 443 [X-Forwarded-Proto] => https [Connection] => keep-alive ) ``` However, the `CloudFront-Viewer-Country` is not among them. If I used a lambda function instead of HTTP Proxy, I can see a lot more headers (including the `CloudFront-Viewer-Country`). Could anyone please tell me how to access the required header on my endpoint using HTTP Proxy ?
2017/09/16
[ "https://Stackoverflow.com/questions/46257648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3970440/" ]
For the resource and method where you want the header, go to Method Request → HTTP Request Headers → Add Header and set the Name as `CloudFront-Viewer-Country`. Click the circled checkmark to add. This exposed the header to the remainder of the execution flow. Then, in Integration Request → HTTP Headers → Add Header. Set the Name to `CloudFront-Viewer-Country` and set Mapped from `method.request.header.CloudFront-Viewer-Country` and click the circled checkmark to add. This picks up the exposed header and adds it to the request that is forwarded to your back-end. Deploy the API.
I solved the problem by simply creating a new integration header named `Accept-Encoding` with value equal to `'identity'` And all the missing headers appeared !!
53,327,745
I'm trying to read a timeStamp from Firebase and append it to an array. I have made some progress: ``` var orderDateHistoryArray = [String:Int]() func getOrderDates() { let uid = Auth.auth().currentUser!.uid let orderDateHistoryRef = Database.database().reference().child("users/\(uid)/Orders/") orderDateHistoryRef.observeSingleEvent(of: .value, with: { (snapshot) in // Get dates let value = snapshot.value as? NSDictionary if let orderDate = value?["Date"] as? [String:Int] { self.orderDateHistoryArray += Array(orderDate.values)//This does not conform print(orderDate) } self.tableView.reloadData() // ... }) { (error) in print(error.localizedDescription) } } ``` The `print(orderDate)`statement prints: > > ["-LQYspEghK3KE27MlFNE": 1541421618601, > > "-LQsYbhf-vl-NnRLTHhK": 1541768379422, > > "-LQYDWAKlzTrlTtO1Qiz": 1541410526186, > > "-LQsILjpNqKwLl9XBcQm": 1541764115618] > > > This is `childByAutoID` : `timeInMilliseconds` So, I want to read out the `timeInMilliseconds`, convert it to a readable `timestamp`and append it to the `orderDateHistoryArray`
2018/11/15
[ "https://Stackoverflow.com/questions/53327745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7860375/" ]
Your code as it is will run into negative numbers with months as well. Using the datetime library that was suggested you can do the following: ``` from datetime import datetime, timedelta list_of_spendings = [] # Month number for day in [(datetime.now()-timedelta(x)) for x in range(7)]: print('How many liters did you spend on the day {} of {}'.format(day.day, day.month)) #Rest of your code ``` OR ``` # Month name for day in [(datetime.now()-timedelta(x)) for x in range(7)]: print('How many liters did you spend on the day {} of {}'.format(day.day, day.strftime('%B'))) #Rest of your code ``` OR ``` # Short month name for day in [(datetime.now()-timedelta(x)) for x in range(7)]: print('How many liters did you spend on the day {} of {}'.format(day.day, day.strftime('%b'))) #Rest of your code ```
This is how I figured it out. "Dia" and "mes" are previously defined. Translations: ``` listaGastos = listOfSpendings gastos = spendings dia = day mes = month DuracMes = monthlenght diaC = currentDay mesC = currentMonth ``` Code: ``` DuracMes = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] listaGastos = [] x = 0 diaC = dia mesC = mes while x < 7: dia = diaC - x if dia <= 0: mes = mesC - 1 diaDif = diaC - 1 dia = DuracMes [mes - 1] + dia print("Quantos litros de soro fisiologico foram gastos no dia", dia, "de", mes) gastos = input() while True: try: gastos = int (gastos) if gastos < 0: gastos = input ("Introduza um valor diferente de 0: ") else: break except ValueError: gastos = input ("Nao inseriu um valor adequado, quantos litros de soro fisiologico foram gastos nos ultimos sete dias? ") x += 1 listaGastos.append(gastos) sumGastos = sum (listaGastos) ```
9,027,521
Here is a sample of what I am trying to accomplish: ``` public class BaseClass<T> { public static T GetByID(int ID) { // Need database name here that is determined at design time in the derived class. var databaseName = ""; // do some stuff involving database name that gets me object by ID here. return default(T); } } public class DerivedClass : BaseClass<DerivedClass> { private string DatabaseName { get; set; } } ``` Basically, how would I access the derived "DatabaseName" in the base class static GetByID method? EDIT: After I posted this, I tried one more thing. I played with attributes earlier, and failed, but I think my brain was mushy. Just tried again and ran a test, and it is working. Here is the updated sample. ``` public class BaseClass<T> { public static T GetByID(int ID) { // Need database name here that is determined at design time in the derived class. var databaseName = ((DatabaseAttribute)typeof(T).GetCustomAttributes(typeof(DatabaseAttribute), true).First()).DatabaseName; // do some stuff involving database name that gets me object by ID here. return default(T); } } [Database("MyDatabase")] public class DerivedClass : BaseClass<DerivedClass> { } public class DatabaseAttribute : Attribute { public DatabaseAttribute(string databaseName) { DatabaseName = databaseName; } public string DatabaseName { get; set; } } ```
2012/01/27
[ "https://Stackoverflow.com/questions/9027521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1172518/" ]
it renders the view's in the controller spec. If you don't put render\_views, the views won't render, that means the controller is called but after it returns the views are not rendered. Controller tests will run faster, as they won't have to render the view, but you might miss bugs in the view.
It's about [isolation](http://www.rubydoc.info/gems/rspec-rails/file/README.md#Controller_Specs). The idea is that you don't want your controller specs failing because there is a syntax error in the view, which should cause a request spec or a view spec to fail. If you're not writing request specs or view specs, or Cucumber features, then `render_views` can help you from a test-coverage perspective.
252,483
In my writing, I find that although the level of detail in something I am writing is a spectrum, there are two distinct categories for which most instances fall into only one of the two. The first category is what I call "close-up" (by analogy with cinematography) or "zoomed in" writing. For example: > > He opened the desk's sole drawer and looked inside; nothing. Next, he ran his fingers along all of the edges, looking for catches that might open hidden compartments. His fingers brushed over a slightly raised area on the desk's underside; he applied a little pressure, and a hidden drawer sprung out from the side of the desk. > > > The second category I call "zoomed out" narrative; I think about it as analogous to a cinematic "long shot" or "distance shot". The same example as above: > > He searched the desk and found a secret compartment. > > > Of course, these categories are somewhat relative and you could "zoom out" even further (eg. "A comprehensive search of every minister's office turned up only one hidden compartment in Minister Charles' desk, which held..."), but I think the meaning is clear. My question: **Is there a single word or phrase to describe:** a) **A "zoomed-in" narrative or narrative style?** b) **A "zoomed-out" narrative or narrative style?** c) **The dichotomy of the two?** Please note that there's no shortage of words to adequately *describe* the above; I'm interested in a word or phrase which specifically refers to them, for use in referring to them in an academic context.
2015/06/14
[ "https://english.stackexchange.com/questions/252483", "https://english.stackexchange.com", "https://english.stackexchange.com/users/77160/" ]
Easily the best question ever posted on the site, and I adore your conception and description of prose as zoomed-in and zoomed-out, close-up v. wide shots. I and I'm sure all writers constantly think about this fundamental tension - should I write most fundamental tension - in writing, and you're very insightful to concretize it - and it's amazing there's no specific word for this. Just a thought on your question c > > c) The dichotomy of the two? > > > Regarding writing that is highly aware of and uses well the dichotomy between the two, I would use the word from painting > > chiaroscuro > > > (Go see some Caravaggio {perhaps a better phrase there is *go get kicked in the face by the Caravaggio horse*} if not fully gut-familiar with this.) Of course, you can use chiaroscuro to talk about or emphasize the dichotomy between any two "values", it's the word you use when you want to describe that an artist recognises and clarifies two extremes of some quality (of course, in painting, "lighting".) I suggest that chiaroscuro works very well when describing prose with, well, a chiaroscuro of close-upness .. perhaps the phrase "a chiaroscuro of scale" almost captures what you mean. If there was a SWR "X" for what you're saying, "X chiaroscuro" works well.
So many good words! a) *Pedantic*, *florid*. b) *Prosaic*, *straightforward*, *hemingwayesque*... etc. Anyways, since you're uninterested in all that, you might be looking for ***purple prose*** and ***beige prose***. They specifically describe prose that is too blahblahblah and too blah, respectively.
252,483
In my writing, I find that although the level of detail in something I am writing is a spectrum, there are two distinct categories for which most instances fall into only one of the two. The first category is what I call "close-up" (by analogy with cinematography) or "zoomed in" writing. For example: > > He opened the desk's sole drawer and looked inside; nothing. Next, he ran his fingers along all of the edges, looking for catches that might open hidden compartments. His fingers brushed over a slightly raised area on the desk's underside; he applied a little pressure, and a hidden drawer sprung out from the side of the desk. > > > The second category I call "zoomed out" narrative; I think about it as analogous to a cinematic "long shot" or "distance shot". The same example as above: > > He searched the desk and found a secret compartment. > > > Of course, these categories are somewhat relative and you could "zoom out" even further (eg. "A comprehensive search of every minister's office turned up only one hidden compartment in Minister Charles' desk, which held..."), but I think the meaning is clear. My question: **Is there a single word or phrase to describe:** a) **A "zoomed-in" narrative or narrative style?** b) **A "zoomed-out" narrative or narrative style?** c) **The dichotomy of the two?** Please note that there's no shortage of words to adequately *describe* the above; I'm interested in a word or phrase which specifically refers to them, for use in referring to them in an academic context.
2015/06/14
[ "https://english.stackexchange.com/questions/252483", "https://english.stackexchange.com", "https://english.stackexchange.com/users/77160/" ]
So many good words! a) *Pedantic*, *florid*. b) *Prosaic*, *straightforward*, *hemingwayesque*... etc. Anyways, since you're uninterested in all that, you might be looking for ***purple prose*** and ***beige prose***. They specifically describe prose that is too blahblahblah and too blah, respectively.
The `close voice` and `distant voice` terminology comes somewhere near to what you are describing. People talk about `close first person` narrative, when the words are apparently written from inside the character's head, whereas the distant voice would be words spoken by an imaginary narrator who may know things individual characters do not.
252,483
In my writing, I find that although the level of detail in something I am writing is a spectrum, there are two distinct categories for which most instances fall into only one of the two. The first category is what I call "close-up" (by analogy with cinematography) or "zoomed in" writing. For example: > > He opened the desk's sole drawer and looked inside; nothing. Next, he ran his fingers along all of the edges, looking for catches that might open hidden compartments. His fingers brushed over a slightly raised area on the desk's underside; he applied a little pressure, and a hidden drawer sprung out from the side of the desk. > > > The second category I call "zoomed out" narrative; I think about it as analogous to a cinematic "long shot" or "distance shot". The same example as above: > > He searched the desk and found a secret compartment. > > > Of course, these categories are somewhat relative and you could "zoom out" even further (eg. "A comprehensive search of every minister's office turned up only one hidden compartment in Minister Charles' desk, which held..."), but I think the meaning is clear. My question: **Is there a single word or phrase to describe:** a) **A "zoomed-in" narrative or narrative style?** b) **A "zoomed-out" narrative or narrative style?** c) **The dichotomy of the two?** Please note that there's no shortage of words to adequately *describe* the above; I'm interested in a word or phrase which specifically refers to them, for use in referring to them in an academic context.
2015/06/14
[ "https://english.stackexchange.com/questions/252483", "https://english.stackexchange.com", "https://english.stackexchange.com/users/77160/" ]
Easily the best question ever posted on the site, and I adore your conception and description of prose as zoomed-in and zoomed-out, close-up v. wide shots. I and I'm sure all writers constantly think about this fundamental tension - should I write most fundamental tension - in writing, and you're very insightful to concretize it - and it's amazing there's no specific word for this. Just a thought on your question c > > c) The dichotomy of the two? > > > Regarding writing that is highly aware of and uses well the dichotomy between the two, I would use the word from painting > > chiaroscuro > > > (Go see some Caravaggio {perhaps a better phrase there is *go get kicked in the face by the Caravaggio horse*} if not fully gut-familiar with this.) Of course, you can use chiaroscuro to talk about or emphasize the dichotomy between any two "values", it's the word you use when you want to describe that an artist recognises and clarifies two extremes of some quality (of course, in painting, "lighting".) I suggest that chiaroscuro works very well when describing prose with, well, a chiaroscuro of close-upness .. perhaps the phrase "a chiaroscuro of scale" almost captures what you mean. If there was a SWR "X" for what you're saying, "X chiaroscuro" works well.
The `close voice` and `distant voice` terminology comes somewhere near to what you are describing. People talk about `close first person` narrative, when the words are apparently written from inside the character's head, whereas the distant voice would be words spoken by an imaginary narrator who may know things individual characters do not.
38,362,230
I wonder why Scala compiler couldn't infer a type of my combiner function. Here is the code ``` object WordsCount extends App { import java.io.File import scala.io.Source.fromFile type CombinerType = (((String, Int), (String, Int)) => ((String, Int))) val src = fromFile(new File("/Users/finkel/test/src/main/resources/words.txt")) var mapped: Iterator[(String, Int)] = src getLines() flatMap { _.split(" ") } map { (_,1) } val combiner: CombinerType = { case ((a, b), (c, d)) => ("_", b + d) } val wordsAmount = mapped.reduce(combiner)._2 println(wordsAmount) } ``` As you can see I need to tell the compiler that the type of combiner is a function. If I don't do that compiler say ``` Error:(16, 18) missing parameter type for expanded function The argument types of an anonymous function must be fully known. (SLS 8.5) Expected type was: ? val combiner = { ^ ``` But I don't understand here one moment. Is it so hard to infer Combiner type?
2016/07/13
[ "https://Stackoverflow.com/questions/38362230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552363/" ]
I haven't written Access queries in years and do not have it to try now, but if I remember correctly DateTime values in the query need to be surrounded with hash marks (#). ``` Dim qHrsWorked As String = _ "SELECT SUM(Hrs_worked) FROM Work WHERE IdEmployee = " & idEmptxt.Text & _ " AND Date >= #" & firstDayDTP.Value & "# AND Date <= #" & LastDayDTP.Value & "#" ```
I suspect this is because you use Textbox.Text for your datepickers. You can only use that property when the control has focus. Try replacing those with .Value ?
38,362,230
I wonder why Scala compiler couldn't infer a type of my combiner function. Here is the code ``` object WordsCount extends App { import java.io.File import scala.io.Source.fromFile type CombinerType = (((String, Int), (String, Int)) => ((String, Int))) val src = fromFile(new File("/Users/finkel/test/src/main/resources/words.txt")) var mapped: Iterator[(String, Int)] = src getLines() flatMap { _.split(" ") } map { (_,1) } val combiner: CombinerType = { case ((a, b), (c, d)) => ("_", b + d) } val wordsAmount = mapped.reduce(combiner)._2 println(wordsAmount) } ``` As you can see I need to tell the compiler that the type of combiner is a function. If I don't do that compiler say ``` Error:(16, 18) missing parameter type for expanded function The argument types of an anonymous function must be fully known. (SLS 8.5) Expected type was: ? val combiner = { ^ ``` But I don't understand here one moment. Is it so hard to infer Combiner type?
2016/07/13
[ "https://Stackoverflow.com/questions/38362230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552363/" ]
In SQL you must use a formatted string expression for the date values: ``` Dim qHrsWorked As String = "SELECT SUM(Hrs_worked) FROM Work WHERE IdEmployee = " & idEmptxt.Text & " AND Date >= #" & firstDayDTP.Value.ToString("yyyy'/'MM'/'dd") & "# AND Date <= #" & lastDayDTP.Value.ToString("yyyy'/'MM'/'dd") & "#" ```
I suspect this is because you use Textbox.Text for your datepickers. You can only use that property when the control has focus. Try replacing those with .Value ?
14,095,495
I wanted to plot the coordinates on a Google Map in the presence of point id: Sample of data: ``` coordinates id 1 (7.1735, 45.8688) 2 2 (7.17254, 45.8689) 3 3 (7.17164, 45.8692) 4 4 (7.18018, 45.8716) 5 5 (7.17807, 45.8701) 6 6 (7.17723, 45.8692) 7 7 (7.17524, 45.8681) 8 8 (7.18141, 45.8718) 9 9 (7.1793, 45.8702) 10 10 (7.17836, 45.8707) 11 11 (7.17519, 45.8697) 12 12 (7.17938, 45.8708) 13 13 (7.17551, 45.8693) 14 14 (7.17684, 45.8694) 15 15 (7.18099, 45.8726) 17 16 (7.18015, 45.8725) 18 17 (7.18122, 45.8736) 19 18 (7.17491, 45.8692) 20 19 (7.15497, 45.8706) 25 20 (7.1534, 45.8695) 28 21 (7.15265, 45.8699) 29 22 (7.15442, 45.87) 31 23 (7.1561, 45.8698) 32 24 (7.184, 45.896) GSBi_1 25 (7.36, 45.901) GSBi__1 26 (7.268, 45.961) GSBj__1 27 (7.276, 45.836) GSBj_1 28 (7.272, 45.899) GSB 29 (7.16667, 45.8667) GSB_r ```
2012/12/30
[ "https://Stackoverflow.com/questions/14095495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1678285/" ]
Rather than request a map of 'Switzerland' from google, you should request a map of a specific location by specifying a longitude/latitude and desired zoom (and maybe scale). Then you won't have to use `coord_map()` and blur your image. Here are the basics, you can play around with colors and sizes as in any ggplot: ``` library(ggplot2) library(ggmap) # copying text off screen # since the OP did not use dput() data<-read.table("clipboard") # reformat data=data[,-1] names(data)=c("lon","lat","id") data$lon <- as.numeric(gsub('[\\(\\)\\,]', '', data$lon)) data$lat <- as.numeric(gsub('[\\(\\)\\,]', '', data$lat)) head(data) # lon lat id # 1 7.17350 45.8688 2 # 2 7.17254 45.8689 3 # 3 7.17164 45.8692 4 # etc # determine a reasonable center for map, # this could fail in some places (near poles, 180th meridian) # also google appears to shift things slightly center = paste(min(data$lat)+(max(data$lat)-min(data$lat))/2, min(data$lon)+(max(data$lon)-min(data$lon))/2, sep=" ") # get map image from google map <- get_map(location = center, zoom = 11, maptype = "terrain", source = "google") # start a ggplot. it won't plot til we type p p <- ggmap(map) # add text labels, these will overlap p <- p + geom_text(data=data,aes(x = lon, y = lat, label = id), colour="white",size=4,hjust=0, vjust=0)+ theme(legend.position = "none") # add points last so they are on top p <- p + geom_point(data=data,aes(x=lon, y=lat),colour="white",size=2) # display plot p ``` ![enter image description here](https://i.stack.imgur.com/daC2L.jpg) This naturally is described in `?get_map` and `?get_googlemap`.
One of the problems with plotting of your points is that if you use `zoom=10` in function `get_map()` then your points are outside the map and they want be plotted, so I used `zoom=5` instead. ``` library(ggmap) map <- get_map(location = 'Switzerland', zoom = 5, maptype = "terrain", source = "google") ``` For the plotting of map I used function `ggmap()`. To add points `geom_point()` can be used. For this purpose your sample data were saved as data frame `df` with columns `x`, `y` and `id`. To zoom closer to points `coord_map()` can be used. ``` p <- ggmap(map) p <- p +geom_point(data=df,aes(x=x,y=y))+ coord_map(xlim=c(7,8),ylim=c(45.5,46)) print(p) ``` If you need to add labels to each point then add this line to map `p` ``` annotate("text",x=df$x,y=df$y,label=df$id) ``` ![enter image description here](https://i.stack.imgur.com/ToI7x.jpg)
15,182,445
I'm trying to get a simple PHP service to produce XML for an iPhone application, sourcing from an SQL database. The database has a variety of text sources and characters, some of which seem to be throwing off the script and producing the following encoding error: error on line 1 at column 6232: Encoding error The php is as follows: ``` <?php //database configuration $config['mysql_host'] = "XXX.XXX.XXX.XXX"; $config['mysql_user'] = "XXXX"; $config['mysql_pass'] = "XXXX"; $config['db_name'] = "XXXX"; $config['table_name'] = "articles"; //connect to host mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']); //select database @mysql_select_db($config['db_name']) or die( "Unable to select database"); $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; $root_element = $config['table_name']."s"; $xml .= "<$root_element>"; $sql = "SELECT * FROM ".$config['table_name']; $result = mysql_query($sql); if (!$result) { die('Invalid query: ' . mysql_error()); } if(mysql_num_rows($result)>0) { while($result_array = mysql_fetch_assoc($result)) { $xml .= "<".$config['table_name'].">"; //loop foreach($result_array as $key => $value) { $xml .= "<$key>"; $xml .= "<![CDATA[$value]]>"; //and close the element $xml .= "</$key>"; } $xml.="</".$config['table_name'].">"; } } $xml .= "</$root_element>"; //send xml header ("Content-Type:text/xml"); echo $xml; ?> ``` Some articles cause the entire page to fail, some don't. Any help would be greatly appreciated.
2013/03/03
[ "https://Stackoverflow.com/questions/15182445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1923903/" ]
``` mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']); mysql_set_charset('utf8'); mysql_select_db($config['db_name']); ```
As you have described the XML format as utf8 thus all the character in the XML File must be utf8 characters. You are getting the error as there are non UTF8 Characters. You have to change the Character to UFT8 format and there are two ways for checking UTF8 characters Way 1 ===== ``` if (mb_check_encoding(file_get_contents($file), 'UTF-8')) { // yup, all UTF-8 } ``` This way it make sure that all the characters are UTF8 compatible and if any row is not according to utf8 then left out. Way 2 ===== ``` mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']); mysql_set_charset('utf8'); mysql_select_db($config['db_name']); ``` Way 3 ===== ``` <xml> <![CDATA[ ///Enter the Test here ]]> </xml> ```
15,182,445
I'm trying to get a simple PHP service to produce XML for an iPhone application, sourcing from an SQL database. The database has a variety of text sources and characters, some of which seem to be throwing off the script and producing the following encoding error: error on line 1 at column 6232: Encoding error The php is as follows: ``` <?php //database configuration $config['mysql_host'] = "XXX.XXX.XXX.XXX"; $config['mysql_user'] = "XXXX"; $config['mysql_pass'] = "XXXX"; $config['db_name'] = "XXXX"; $config['table_name'] = "articles"; //connect to host mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']); //select database @mysql_select_db($config['db_name']) or die( "Unable to select database"); $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; $root_element = $config['table_name']."s"; $xml .= "<$root_element>"; $sql = "SELECT * FROM ".$config['table_name']; $result = mysql_query($sql); if (!$result) { die('Invalid query: ' . mysql_error()); } if(mysql_num_rows($result)>0) { while($result_array = mysql_fetch_assoc($result)) { $xml .= "<".$config['table_name'].">"; //loop foreach($result_array as $key => $value) { $xml .= "<$key>"; $xml .= "<![CDATA[$value]]>"; //and close the element $xml .= "</$key>"; } $xml.="</".$config['table_name'].">"; } } $xml .= "</$root_element>"; //send xml header ("Content-Type:text/xml"); echo $xml; ?> ``` Some articles cause the entire page to fail, some don't. Any help would be greatly appreciated.
2013/03/03
[ "https://Stackoverflow.com/questions/15182445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1923903/" ]
Your question is really broad, the best answer I can give is that you should use some existing library to encode the XML instead of writing your own one (as you obviously fail with the job hence the XML encoding error reported by the XML consument). Using an existing library would also allow you to point out problems earlier. E.g. for the following code ensure all you get back from your database are UTF-8 encoded strings. Also using a more modern database client class will also help you to greatly just write down the code. Here is an example with [`PDO`](http://php.net/PDO) and [`DOMDocument`](http://php.net/DomDocument): ``` ### configuration values $config = array( 'Database' => array( 'dsn' => 'mysql:dbname=test;host=localhost;charset=utf8', 'user' => 'testuser', 'pass' => 'test', ), 'table_name' => 'config', 'table_fields' => '*', ); ### implement database access class Database extends PDO { public function __construct(array $config = null) { $config = $config ? : $GLOBALS['config'][__CLASS__]; parent::__construct($config['dsn'], $config['user'], $config['pass']); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); } } ### setup the datasource ($rows) $db = new Database(); $rows = $db->query("SELECT $config[table_fields] FROM $config[table_name]"); ### setup the XML encoder ($doc) $doc = new DOMDocument(); $doc->formatOutput = true; $doc->loadXML("<$config[table_name]s/>"); $doc->encoding = 'utf-8'; ### fetch data from the datasource and encode the XML foreach ($rows as $row) { $child = $doc->createElement($config['table_name']); $child = $doc->documentElement->appendChild($child); foreach ($row as $key => $value) { $child->appendChild($doc->createElement($key, $value)); } } ### output XML header("Content-Type:text/xml"); echo $doc->saveXML(); ``` See that `DomDocument` is taking care here of properly encoding the UTF-8 strings that are returned from the database. There is (normally) no need for `<![CDATA[...]]>` here any longer. As you can imagine you likely put something in there that broke your XML encoding. Also for the database interaction, most of your code is not necessary either, you can just iterate over the rows, if there ain't no rows, there would be no iteration. This is normally best expressed with an `Iterator` the `foreach` language construct can operate on which is provided by modern database interfaces. Technically you can replace `$rows` here with many other things, like an iterator that goes over multiple tables one after the other. Additionally using the exception error mode does spare you to place checks and `die`s all over your codebase. An exemplary output is: ``` <?xml version="1.0" encoding="utf-8"?> <configs> <config> <id>1</id> <option>value for option with ID1</option> </config> <config> <id>2</id> <option>value for option with ID2</option> </config> ... </configs> ``` If you then still need to create CDATA elements, it works similarly (I show only a part of the script here, which only contains a slight modification adding CDATA sections instead of a child value): ``` ### fetch data from the datasource and encode the XML foreach ($rows as $row) { $child = $doc->createElement($config['table_name']); $child = $doc->documentElement->appendChild($child); foreach ($row as $key => $value) { $child->appendChild($doc->createElement($key)) ->appendChild($doc->createCDATASection($value)) ; } } ``` Here as well, `DOMDocument` takes care of properly encoding the CDATA section. Something likely you didn't do. Potential problems you still might run into are with table or row names that are [invalid XML names](https://stackoverflow.com/questions/2519845/how-to-check-if-string-is-a-valid-xml-element-name). But then `DOMDocument` will actually tell you so you know while generating the XML, not only afterwards with an encoding error.
``` mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']); mysql_set_charset('utf8'); mysql_select_db($config['db_name']); ```
15,182,445
I'm trying to get a simple PHP service to produce XML for an iPhone application, sourcing from an SQL database. The database has a variety of text sources and characters, some of which seem to be throwing off the script and producing the following encoding error: error on line 1 at column 6232: Encoding error The php is as follows: ``` <?php //database configuration $config['mysql_host'] = "XXX.XXX.XXX.XXX"; $config['mysql_user'] = "XXXX"; $config['mysql_pass'] = "XXXX"; $config['db_name'] = "XXXX"; $config['table_name'] = "articles"; //connect to host mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']); //select database @mysql_select_db($config['db_name']) or die( "Unable to select database"); $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; $root_element = $config['table_name']."s"; $xml .= "<$root_element>"; $sql = "SELECT * FROM ".$config['table_name']; $result = mysql_query($sql); if (!$result) { die('Invalid query: ' . mysql_error()); } if(mysql_num_rows($result)>0) { while($result_array = mysql_fetch_assoc($result)) { $xml .= "<".$config['table_name'].">"; //loop foreach($result_array as $key => $value) { $xml .= "<$key>"; $xml .= "<![CDATA[$value]]>"; //and close the element $xml .= "</$key>"; } $xml.="</".$config['table_name'].">"; } } $xml .= "</$root_element>"; //send xml header ("Content-Type:text/xml"); echo $xml; ?> ``` Some articles cause the entire page to fail, some don't. Any help would be greatly appreciated.
2013/03/03
[ "https://Stackoverflow.com/questions/15182445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1923903/" ]
Your question is really broad, the best answer I can give is that you should use some existing library to encode the XML instead of writing your own one (as you obviously fail with the job hence the XML encoding error reported by the XML consument). Using an existing library would also allow you to point out problems earlier. E.g. for the following code ensure all you get back from your database are UTF-8 encoded strings. Also using a more modern database client class will also help you to greatly just write down the code. Here is an example with [`PDO`](http://php.net/PDO) and [`DOMDocument`](http://php.net/DomDocument): ``` ### configuration values $config = array( 'Database' => array( 'dsn' => 'mysql:dbname=test;host=localhost;charset=utf8', 'user' => 'testuser', 'pass' => 'test', ), 'table_name' => 'config', 'table_fields' => '*', ); ### implement database access class Database extends PDO { public function __construct(array $config = null) { $config = $config ? : $GLOBALS['config'][__CLASS__]; parent::__construct($config['dsn'], $config['user'], $config['pass']); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); } } ### setup the datasource ($rows) $db = new Database(); $rows = $db->query("SELECT $config[table_fields] FROM $config[table_name]"); ### setup the XML encoder ($doc) $doc = new DOMDocument(); $doc->formatOutput = true; $doc->loadXML("<$config[table_name]s/>"); $doc->encoding = 'utf-8'; ### fetch data from the datasource and encode the XML foreach ($rows as $row) { $child = $doc->createElement($config['table_name']); $child = $doc->documentElement->appendChild($child); foreach ($row as $key => $value) { $child->appendChild($doc->createElement($key, $value)); } } ### output XML header("Content-Type:text/xml"); echo $doc->saveXML(); ``` See that `DomDocument` is taking care here of properly encoding the UTF-8 strings that are returned from the database. There is (normally) no need for `<![CDATA[...]]>` here any longer. As you can imagine you likely put something in there that broke your XML encoding. Also for the database interaction, most of your code is not necessary either, you can just iterate over the rows, if there ain't no rows, there would be no iteration. This is normally best expressed with an `Iterator` the `foreach` language construct can operate on which is provided by modern database interfaces. Technically you can replace `$rows` here with many other things, like an iterator that goes over multiple tables one after the other. Additionally using the exception error mode does spare you to place checks and `die`s all over your codebase. An exemplary output is: ``` <?xml version="1.0" encoding="utf-8"?> <configs> <config> <id>1</id> <option>value for option with ID1</option> </config> <config> <id>2</id> <option>value for option with ID2</option> </config> ... </configs> ``` If you then still need to create CDATA elements, it works similarly (I show only a part of the script here, which only contains a slight modification adding CDATA sections instead of a child value): ``` ### fetch data from the datasource and encode the XML foreach ($rows as $row) { $child = $doc->createElement($config['table_name']); $child = $doc->documentElement->appendChild($child); foreach ($row as $key => $value) { $child->appendChild($doc->createElement($key)) ->appendChild($doc->createCDATASection($value)) ; } } ``` Here as well, `DOMDocument` takes care of properly encoding the CDATA section. Something likely you didn't do. Potential problems you still might run into are with table or row names that are [invalid XML names](https://stackoverflow.com/questions/2519845/how-to-check-if-string-is-a-valid-xml-element-name). But then `DOMDocument` will actually tell you so you know while generating the XML, not only afterwards with an encoding error.
As you have described the XML format as utf8 thus all the character in the XML File must be utf8 characters. You are getting the error as there are non UTF8 Characters. You have to change the Character to UFT8 format and there are two ways for checking UTF8 characters Way 1 ===== ``` if (mb_check_encoding(file_get_contents($file), 'UTF-8')) { // yup, all UTF-8 } ``` This way it make sure that all the characters are UTF8 compatible and if any row is not according to utf8 then left out. Way 2 ===== ``` mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']); mysql_set_charset('utf8'); mysql_select_db($config['db_name']); ``` Way 3 ===== ``` <xml> <![CDATA[ ///Enter the Test here ]]> </xml> ```
994,168
If I know that: •$f(x)$ is an increasing function •$x<x+a$ •$\lim\_{x\to +\infty}f(x)=\lim\_{x\to +\infty}f(x+a)$ Can I conclude that $\lim\_{x\to +\infty}f(x)=\infty$ ? Sorry if the question is silly.
2014/10/27
[ "https://math.stackexchange.com/questions/994168", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Hint. If $\sqrt[3]{2}+\sqrt[3]{4}$ rational, so is $1+\sqrt[3]{2}+\sqrt[3]{4}$, and so is $$ \frac{1}{1+\sqrt[3]{2}+\sqrt[3]{4}}=\frac{(\sqrt[3]{2})^3-1}{(\sqrt[3]{2})^2+\sqrt[3]{2}+1}=\sqrt[3]{2}-1 $$ and hence so is $\sqrt[3]{2}$.
Hint: Find a polynomial with integer coefficients for which $\alpha = \sqrt[3]{2} + \sqrt[3]{4}$ is a root. Then you can use the Rational Roots Theorem.
994,168
If I know that: •$f(x)$ is an increasing function •$x<x+a$ •$\lim\_{x\to +\infty}f(x)=\lim\_{x\to +\infty}f(x+a)$ Can I conclude that $\lim\_{x\to +\infty}f(x)=\infty$ ? Sorry if the question is silly.
2014/10/27
[ "https://math.stackexchange.com/questions/994168", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let us rewrite $$\sqrt[3]2+\sqrt[3]4=\color{blue}{1+\sqrt[3]2+\sqrt[3]4}-1=\color{blue}{\frac{\left(\sqrt[3]2\right)^3-1}{\sqrt[3]2-1}}-1=\frac{1}{\sqrt[3]2-1}-1.$$ If the left side were rational, what could we say about $\sqrt[3]2$ ?
Hint: Find a polynomial with integer coefficients for which $\alpha = \sqrt[3]{2} + \sqrt[3]{4}$ is a root. Then you can use the Rational Roots Theorem.
994,168
If I know that: •$f(x)$ is an increasing function •$x<x+a$ •$\lim\_{x\to +\infty}f(x)=\lim\_{x\to +\infty}f(x+a)$ Can I conclude that $\lim\_{x\to +\infty}f(x)=\infty$ ? Sorry if the question is silly.
2014/10/27
[ "https://math.stackexchange.com/questions/994168", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Hint: Find a polynomial with integer coefficients for which $\alpha = \sqrt[3]{2} + \sqrt[3]{4}$ is a root. Then you can use the Rational Roots Theorem.
Suppose the sum is a rational number $r$, then $\sqrt[3]{4} = -\sqrt[3]{2} + r$, and cubing both sides: $4 = r^3 - 3r^2a + 3ra^2 - 2$, with $a = \sqrt[3]{2}$. Thus: $6 - r^3 = -3r^2a + 3r(r-a) \to a = \dfrac{6-r^3-3r^2}{-3r^2-3r} \in \mathbb{Q}$. But it can be proved that $a = \sqrt[3]{2} \notin \mathbb{Q}$, a contradiction, and we are done.
994,168
If I know that: •$f(x)$ is an increasing function •$x<x+a$ •$\lim\_{x\to +\infty}f(x)=\lim\_{x\to +\infty}f(x+a)$ Can I conclude that $\lim\_{x\to +\infty}f(x)=\infty$ ? Sorry if the question is silly.
2014/10/27
[ "https://math.stackexchange.com/questions/994168", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Hint: Find a polynomial with integer coefficients for which $\alpha = \sqrt[3]{2} + \sqrt[3]{4}$ is a root. Then you can use the Rational Roots Theorem.
Write $\sqrt[3]{2} + \sqrt[3]{4} = \alpha + \alpha^2$, with $\alpha=\sqrt[3]{2}$. Suppose $\alpha + \alpha^2 = q \in \Bbb Q$. Then $\alpha^2 + \alpha^3 = q \alpha$. Since $\alpha^3=2$, we get $\quad\alpha + \alpha^2 = q$ $\quad\alpha^2 + 2= q \alpha$ Subtracting these, we get $\alpha-2=q-q \alpha$, and so $\alpha=\frac{q+2}{q+1}\in \Bbb Q$, a contradiction since $\alpha$ is irrational. This argument is essentially dividing the polynomial $x^3-2$ by $x^2+x-q$, getting remainder $(q+1)x-(q+2)$.
994,168
If I know that: •$f(x)$ is an increasing function •$x<x+a$ •$\lim\_{x\to +\infty}f(x)=\lim\_{x\to +\infty}f(x+a)$ Can I conclude that $\lim\_{x\to +\infty}f(x)=\infty$ ? Sorry if the question is silly.
2014/10/27
[ "https://math.stackexchange.com/questions/994168", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let us rewrite $$\sqrt[3]2+\sqrt[3]4=\color{blue}{1+\sqrt[3]2+\sqrt[3]4}-1=\color{blue}{\frac{\left(\sqrt[3]2\right)^3-1}{\sqrt[3]2-1}}-1=\frac{1}{\sqrt[3]2-1}-1.$$ If the left side were rational, what could we say about $\sqrt[3]2$ ?
Hint. If $\sqrt[3]{2}+\sqrt[3]{4}$ rational, so is $1+\sqrt[3]{2}+\sqrt[3]{4}$, and so is $$ \frac{1}{1+\sqrt[3]{2}+\sqrt[3]{4}}=\frac{(\sqrt[3]{2})^3-1}{(\sqrt[3]{2})^2+\sqrt[3]{2}+1}=\sqrt[3]{2}-1 $$ and hence so is $\sqrt[3]{2}$.
994,168
If I know that: •$f(x)$ is an increasing function •$x<x+a$ •$\lim\_{x\to +\infty}f(x)=\lim\_{x\to +\infty}f(x+a)$ Can I conclude that $\lim\_{x\to +\infty}f(x)=\infty$ ? Sorry if the question is silly.
2014/10/27
[ "https://math.stackexchange.com/questions/994168", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Hint. If $\sqrt[3]{2}+\sqrt[3]{4}$ rational, so is $1+\sqrt[3]{2}+\sqrt[3]{4}$, and so is $$ \frac{1}{1+\sqrt[3]{2}+\sqrt[3]{4}}=\frac{(\sqrt[3]{2})^3-1}{(\sqrt[3]{2})^2+\sqrt[3]{2}+1}=\sqrt[3]{2}-1 $$ and hence so is $\sqrt[3]{2}$.
Suppose the sum is a rational number $r$, then $\sqrt[3]{4} = -\sqrt[3]{2} + r$, and cubing both sides: $4 = r^3 - 3r^2a + 3ra^2 - 2$, with $a = \sqrt[3]{2}$. Thus: $6 - r^3 = -3r^2a + 3r(r-a) \to a = \dfrac{6-r^3-3r^2}{-3r^2-3r} \in \mathbb{Q}$. But it can be proved that $a = \sqrt[3]{2} \notin \mathbb{Q}$, a contradiction, and we are done.
994,168
If I know that: •$f(x)$ is an increasing function •$x<x+a$ •$\lim\_{x\to +\infty}f(x)=\lim\_{x\to +\infty}f(x+a)$ Can I conclude that $\lim\_{x\to +\infty}f(x)=\infty$ ? Sorry if the question is silly.
2014/10/27
[ "https://math.stackexchange.com/questions/994168", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Hint. If $\sqrt[3]{2}+\sqrt[3]{4}$ rational, so is $1+\sqrt[3]{2}+\sqrt[3]{4}$, and so is $$ \frac{1}{1+\sqrt[3]{2}+\sqrt[3]{4}}=\frac{(\sqrt[3]{2})^3-1}{(\sqrt[3]{2})^2+\sqrt[3]{2}+1}=\sqrt[3]{2}-1 $$ and hence so is $\sqrt[3]{2}$.
Write $\sqrt[3]{2} + \sqrt[3]{4} = \alpha + \alpha^2$, with $\alpha=\sqrt[3]{2}$. Suppose $\alpha + \alpha^2 = q \in \Bbb Q$. Then $\alpha^2 + \alpha^3 = q \alpha$. Since $\alpha^3=2$, we get $\quad\alpha + \alpha^2 = q$ $\quad\alpha^2 + 2= q \alpha$ Subtracting these, we get $\alpha-2=q-q \alpha$, and so $\alpha=\frac{q+2}{q+1}\in \Bbb Q$, a contradiction since $\alpha$ is irrational. This argument is essentially dividing the polynomial $x^3-2$ by $x^2+x-q$, getting remainder $(q+1)x-(q+2)$.
994,168
If I know that: •$f(x)$ is an increasing function •$x<x+a$ •$\lim\_{x\to +\infty}f(x)=\lim\_{x\to +\infty}f(x+a)$ Can I conclude that $\lim\_{x\to +\infty}f(x)=\infty$ ? Sorry if the question is silly.
2014/10/27
[ "https://math.stackexchange.com/questions/994168", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let us rewrite $$\sqrt[3]2+\sqrt[3]4=\color{blue}{1+\sqrt[3]2+\sqrt[3]4}-1=\color{blue}{\frac{\left(\sqrt[3]2\right)^3-1}{\sqrt[3]2-1}}-1=\frac{1}{\sqrt[3]2-1}-1.$$ If the left side were rational, what could we say about $\sqrt[3]2$ ?
Suppose the sum is a rational number $r$, then $\sqrt[3]{4} = -\sqrt[3]{2} + r$, and cubing both sides: $4 = r^3 - 3r^2a + 3ra^2 - 2$, with $a = \sqrt[3]{2}$. Thus: $6 - r^3 = -3r^2a + 3r(r-a) \to a = \dfrac{6-r^3-3r^2}{-3r^2-3r} \in \mathbb{Q}$. But it can be proved that $a = \sqrt[3]{2} \notin \mathbb{Q}$, a contradiction, and we are done.
994,168
If I know that: •$f(x)$ is an increasing function •$x<x+a$ •$\lim\_{x\to +\infty}f(x)=\lim\_{x\to +\infty}f(x+a)$ Can I conclude that $\lim\_{x\to +\infty}f(x)=\infty$ ? Sorry if the question is silly.
2014/10/27
[ "https://math.stackexchange.com/questions/994168", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let us rewrite $$\sqrt[3]2+\sqrt[3]4=\color{blue}{1+\sqrt[3]2+\sqrt[3]4}-1=\color{blue}{\frac{\left(\sqrt[3]2\right)^3-1}{\sqrt[3]2-1}}-1=\frac{1}{\sqrt[3]2-1}-1.$$ If the left side were rational, what could we say about $\sqrt[3]2$ ?
Write $\sqrt[3]{2} + \sqrt[3]{4} = \alpha + \alpha^2$, with $\alpha=\sqrt[3]{2}$. Suppose $\alpha + \alpha^2 = q \in \Bbb Q$. Then $\alpha^2 + \alpha^3 = q \alpha$. Since $\alpha^3=2$, we get $\quad\alpha + \alpha^2 = q$ $\quad\alpha^2 + 2= q \alpha$ Subtracting these, we get $\alpha-2=q-q \alpha$, and so $\alpha=\frac{q+2}{q+1}\in \Bbb Q$, a contradiction since $\alpha$ is irrational. This argument is essentially dividing the polynomial $x^3-2$ by $x^2+x-q$, getting remainder $(q+1)x-(q+2)$.
164,853
I know what `chgrp` and `chown` do. My question is since `chown` does the same thing as `chgrp` (and even more), what is the point of `chgrp`?
2014/10/29
[ "https://unix.stackexchange.com/questions/164853", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/89629/" ]
When you use `chgrp` you are using a simple tool to change one thing... group permissions. For many people this is preferred over using `chown`, especially when you run the risk of mistyping a character while using the `chown` command and completely breaking permissions to whatever files/folder you specified. So instead of doing one of the following: ``` chown user:group [file/dir] chown :group [file/dir] ``` You just do: ``` chgrp group [file/dir] ``` This keeps the risks of changing file permissions in a production grade environment down. Which is always good for SysAdmins.
Remember: * A file is owned by exactly one group and one user. That file may have varying permissions depending on the user and/or group attempting to use it. * `chown` changes ownership of files to specified user/group * `chmod` changes permissions of files to specified user/group * `chgrp` changes ownership of files to specified group
31,440,774
I have the following data frame: ``` > head(newdat2) i42 i35 i32 i31 i30 i29 i28 i27 i26 1 5 5 5 5 5 5 5 5 5 5 3 3 2 2 4 4 4 3 2 6 5 5 5 2 5 5 5 5 5 7 5 5 5 5 5 5 5 5 5 8 4 5 4 3 5 4 4 3 4 11 3 2 2 6 2 4 2 2 2 ``` I would like to convert any values that are not 1,2,3,4, or 5 to NAs. How could I go about doing this? I have tried the following: ``` newdat2[(newdat2!=1)|(newdat2!=2)|(newdat2!=3)|(newdat2!=4)|(newdat2!=5)]<-NA ``` But this just makes all the values NA I also also tried some combos of sapply and ifelse, but nothing is working. Any thoughts? Thank you!
2015/07/15
[ "https://Stackoverflow.com/questions/31440774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4941925/" ]
Here's a possible implementation of the `is.na<-` replacement function ``` df[] <- lapply(df, function(x) `is.na<-`(x, !x %in% 1:5)) # i42 i35 i32 i31 i30 i29 i28 i27 i26 # 1 5 5 5 5 5 5 5 5 5 # 5 3 3 2 2 4 4 4 3 2 # 6 5 5 5 2 5 5 5 5 5 # 7 5 5 5 5 5 5 5 5 5 # 8 4 5 4 3 5 4 4 3 4 # 11 3 2 2 NA 2 4 2 2 2 ```
Your approach can be made to work, you just need to get the boolean logic right. David Arenburg's answer offers a cleaner approach anyway, but you may find it useful to understand "what went wrong" with your attempt. Note that `(x!=1)|(x!=2)` will evaluate to true for both 1 and 2 (as well as any other number): when `x` is 1 the `x!=2` clause is true, and when `x` is 2 the `x!=1` clause is true. To get all numbers that are neither 1 nor 2 you want to use the `&` connective: `(x!=1)&(x!=2)`. This is an application of one of two extremely useful principles known as [DeMorgan's laws](https://en.wikipedia.org/wiki/De_Morgan%27s_laws), which state that, for any boolean expressions `P` and `Q`, `!(P or Q) == (!P) and (!Q)`, and `!(P and Q) == (!P) or (!Q)`. It is not too hard to show that this extends to arbitrarily many expressions, so in your case the correct code would be ``` newdat2[(newdat2!=1)&(newdat2!=2)&(newdat2!=3)&(newdat2!=4)&(newdat2!=5)]<-NA ```
16,798,450
i have the following rules and when implementing them with bison i get 5 shift/reduce warnings. a part of the Rules are: ``` Type----> BOOL | INT | CHAR | DOUBLE | ID | INT '['']' ; rule: VarDec rule | VarDec ; VarDec: Type ID ';' ; ``` and the `Parser.output` give me the warning in this state: `**state 25**` ``` 4 rule: VarDec . rule 5 | VarDec . BOOL shift, and go to state 3 INT shift, and go to state 4 CHAR shift, and go to state 5 DOUBLE shift, and go to state 6 ID shift, and go to state 7 BOOL [reduce using rule 5 (rule)] INT [reduce using rule 5 (rule)] CHAR [reduce using rule 5 (rule)] DOUBLE [reduce using rule 5 (rule)] ID [reduce using rule 5 (rule)] $default reduce using rule 5 (rule) rule go to state 28 VarDec go to state 25 Type go to state 27 ``` can anyone help me how to solve this, i have read many articles but i wasn't able to figure out what's wrong, and thanks in advance to every one... :)
2013/05/28
[ "https://Stackoverflow.com/questions/16798450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1436099/" ]
The above example is not enough to reproduce the shift/reduce conflicts. You probably have an instance of `rule` somewhere else that is followed by `VarDec` or the tokens it starts with. If I add the following rule, I can reproduce the conflicts: ``` decl : rule VarDec; ``` That rule is causing your problems.
The conflict occurs in a state where there is a VarDec on top of the parse stack, and the next token is a BOOL, INT, CHAR, DOUBLE, or ID. The parser would then need to look at least two tokens ahead to determine whether it's looking at another VarDec -- in which case the correct action right now is to shift in anticipation of later reducing the following tokens to a 'rule' -- or whether it's looking at something else -- in which case the correct action is to reduce the VarDec currently on top of the stack to a 'rule'. It should be possible to resolve this particular conflict by changing your 'rule' rule like so: ``` rule: rule VarDec | VarDec ; ``` to use left recursion instead of right recursion. That's well, too, because you should **always** use left recursion instead of right recursion in Bison rules. That ensures you can parse any input with bounded stack space. The actual states identified by Bison might differ a bit with that change, but in the likely event that there were still one having a VarDec on top of the stack and one of BOOL, INT, CHAR, DOUBLE, or ID as the next token, there will be only one possible action (with only the rules presented): reduce the VarDec on the stack to a 'rule'. There's no other possible parse, even if the upcoming tokens later turn out not to reduce to a VarDec.
18,095,144
I took the following code from another webpage "<http://www.javascriptkit.com/script/cut10.shtml>". ``` <SCRIPT> function passWord() { var testV = 1; var pass1 = prompt('Please Enter Your Password',' '); while (testV < 3) { if (!pass1) history.go(-1); if (pass1.toLowerCase() == "letmein") { alert('You Got it Right!'); window.open('protectpage.html'); break; } testV+=1; var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password'); } if (pass1.toLowerCase()!="password" & testV ==3) history.go(-1); return " "; } </SCRIPT> <CENTER> <FORM> <input type="button" value="Enter Protected Area" onClick="passWord()"> </FORM> </CENTER> ``` It works only in case the password is entered second time, but not when it is entered first time. When you enter password it says wrong password prompting you to enter the password again and then it goes through.I need a script that shall prompt me of the correct password, in case I enter the wrong password. Can any one help me with the code as i am a beginner in JavaScript.
2013/08/07
[ "https://Stackoverflow.com/questions/18095144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2659279/" ]
Your code appears to *work* when visiting the link. I know you're learning. Still, you shouldn't be doing authentication like this though as you're not really protecting anything. Anyone can read the source code by using the "View Page Code" option in any browser (typically right click on the page). This means **anyone can easily get your password**. For true authentication you should be using either a server side language (like PHP), or [HTTP Digest authentication](http://en.wikipedia.org/wiki/Digest_access_authentication) configured by your web server. Digest is a bit out of date as it uses MD5, but it's a million times better than what you're doing. For more information about setting up HTTP Digest with Apache web server see: <http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html> For doing the same with Nginx: <http://wiki.nginx.org/HttpAuthDigestModule> The [HTTP Basic authentication](http://en.wikipedia.org/wiki/Basic_access_authentication) works too, but it transmits the password from the user's browser in plain text. With HTTP digest the password is [hashed](http://en.wikipedia.org/wiki/Cryptographic_hash_function). Knowing that you're learning JavaScript, your best bet is to configure the web server you're using. Since most web hosting services use Apache, you can most likely use an [.htaccess file](http://httpd.apache.org/docs/2.2/howto/htaccess.html). You can search [".htaccess http digest"](https://www.google.com/search?q=.htaccess%20auth%20digest) for tutorials on how to set this up. Some web hosting services have control panels that have a feature to protect directories using Digest/Basic auth. In cPanel, which is quite common, it's called ["Password Protect Directories"](http://docs.cpanel.net/twiki/bin/view/AllDocumentation/CpanelDocs/PasswordProtectDirectories). If you were more advanced I would suggest doing it in PHP, but thats a rather complicated subject.
Try this.. Just add access denied prompt inside the false case... ``` function passWord() { var testV = 1; var pass1 = prompt('Please Enter Your Password',' '); while (testV < 3) { if (!pass1) { history.go(-1); var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password'); } else if (pass1.toLowerCase() == "letmein") { alert('You Got it Right!'); window.open('protectpage.html'); break; } testV+=1; } if (pass1.toLowerCase()!="password" & testV ==3) history.go(-1); return " "; } ```
18,095,144
I took the following code from another webpage "<http://www.javascriptkit.com/script/cut10.shtml>". ``` <SCRIPT> function passWord() { var testV = 1; var pass1 = prompt('Please Enter Your Password',' '); while (testV < 3) { if (!pass1) history.go(-1); if (pass1.toLowerCase() == "letmein") { alert('You Got it Right!'); window.open('protectpage.html'); break; } testV+=1; var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password'); } if (pass1.toLowerCase()!="password" & testV ==3) history.go(-1); return " "; } </SCRIPT> <CENTER> <FORM> <input type="button" value="Enter Protected Area" onClick="passWord()"> </FORM> </CENTER> ``` It works only in case the password is entered second time, but not when it is entered first time. When you enter password it says wrong password prompting you to enter the password again and then it goes through.I need a script that shall prompt me of the correct password, in case I enter the wrong password. Can any one help me with the code as i am a beginner in JavaScript.
2013/08/07
[ "https://Stackoverflow.com/questions/18095144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2659279/" ]
``` //Add this to you script function run(){ var password = prompt("Password Please"); //Change to your own Password if(password != 'Sameer'){ document.body.innerHTML = ''; document.body.innerHTML = 'Password Failed! Reload to Renter Password'; }else{ alert('Success'); } } run(); ```
Try this.. Just add access denied prompt inside the false case... ``` function passWord() { var testV = 1; var pass1 = prompt('Please Enter Your Password',' '); while (testV < 3) { if (!pass1) { history.go(-1); var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password'); } else if (pass1.toLowerCase() == "letmein") { alert('You Got it Right!'); window.open('protectpage.html'); break; } testV+=1; } if (pass1.toLowerCase()!="password" & testV ==3) history.go(-1); return " "; } ```
18,095,144
I took the following code from another webpage "<http://www.javascriptkit.com/script/cut10.shtml>". ``` <SCRIPT> function passWord() { var testV = 1; var pass1 = prompt('Please Enter Your Password',' '); while (testV < 3) { if (!pass1) history.go(-1); if (pass1.toLowerCase() == "letmein") { alert('You Got it Right!'); window.open('protectpage.html'); break; } testV+=1; var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password'); } if (pass1.toLowerCase()!="password" & testV ==3) history.go(-1); return " "; } </SCRIPT> <CENTER> <FORM> <input type="button" value="Enter Protected Area" onClick="passWord()"> </FORM> </CENTER> ``` It works only in case the password is entered second time, but not when it is entered first time. When you enter password it says wrong password prompting you to enter the password again and then it goes through.I need a script that shall prompt me of the correct password, in case I enter the wrong password. Can any one help me with the code as i am a beginner in JavaScript.
2013/08/07
[ "https://Stackoverflow.com/questions/18095144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2659279/" ]
Your code appears to *work* when visiting the link. I know you're learning. Still, you shouldn't be doing authentication like this though as you're not really protecting anything. Anyone can read the source code by using the "View Page Code" option in any browser (typically right click on the page). This means **anyone can easily get your password**. For true authentication you should be using either a server side language (like PHP), or [HTTP Digest authentication](http://en.wikipedia.org/wiki/Digest_access_authentication) configured by your web server. Digest is a bit out of date as it uses MD5, but it's a million times better than what you're doing. For more information about setting up HTTP Digest with Apache web server see: <http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html> For doing the same with Nginx: <http://wiki.nginx.org/HttpAuthDigestModule> The [HTTP Basic authentication](http://en.wikipedia.org/wiki/Basic_access_authentication) works too, but it transmits the password from the user's browser in plain text. With HTTP digest the password is [hashed](http://en.wikipedia.org/wiki/Cryptographic_hash_function). Knowing that you're learning JavaScript, your best bet is to configure the web server you're using. Since most web hosting services use Apache, you can most likely use an [.htaccess file](http://httpd.apache.org/docs/2.2/howto/htaccess.html). You can search [".htaccess http digest"](https://www.google.com/search?q=.htaccess%20auth%20digest) for tutorials on how to set this up. Some web hosting services have control panels that have a feature to protect directories using Digest/Basic auth. In cPanel, which is quite common, it's called ["Password Protect Directories"](http://docs.cpanel.net/twiki/bin/view/AllDocumentation/CpanelDocs/PasswordProtectDirectories). If you were more advanced I would suggest doing it in PHP, but thats a rather complicated subject.
I used the same exact code that you have and the problem is the the first time for don't know what reason it added one space in front of the input. Just make sure that you don't have that and it will be fine.
18,095,144
I took the following code from another webpage "<http://www.javascriptkit.com/script/cut10.shtml>". ``` <SCRIPT> function passWord() { var testV = 1; var pass1 = prompt('Please Enter Your Password',' '); while (testV < 3) { if (!pass1) history.go(-1); if (pass1.toLowerCase() == "letmein") { alert('You Got it Right!'); window.open('protectpage.html'); break; } testV+=1; var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password'); } if (pass1.toLowerCase()!="password" & testV ==3) history.go(-1); return " "; } </SCRIPT> <CENTER> <FORM> <input type="button" value="Enter Protected Area" onClick="passWord()"> </FORM> </CENTER> ``` It works only in case the password is entered second time, but not when it is entered first time. When you enter password it says wrong password prompting you to enter the password again and then it goes through.I need a script that shall prompt me of the correct password, in case I enter the wrong password. Can any one help me with the code as i am a beginner in JavaScript.
2013/08/07
[ "https://Stackoverflow.com/questions/18095144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2659279/" ]
Your code appears to *work* when visiting the link. I know you're learning. Still, you shouldn't be doing authentication like this though as you're not really protecting anything. Anyone can read the source code by using the "View Page Code" option in any browser (typically right click on the page). This means **anyone can easily get your password**. For true authentication you should be using either a server side language (like PHP), or [HTTP Digest authentication](http://en.wikipedia.org/wiki/Digest_access_authentication) configured by your web server. Digest is a bit out of date as it uses MD5, but it's a million times better than what you're doing. For more information about setting up HTTP Digest with Apache web server see: <http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html> For doing the same with Nginx: <http://wiki.nginx.org/HttpAuthDigestModule> The [HTTP Basic authentication](http://en.wikipedia.org/wiki/Basic_access_authentication) works too, but it transmits the password from the user's browser in plain text. With HTTP digest the password is [hashed](http://en.wikipedia.org/wiki/Cryptographic_hash_function). Knowing that you're learning JavaScript, your best bet is to configure the web server you're using. Since most web hosting services use Apache, you can most likely use an [.htaccess file](http://httpd.apache.org/docs/2.2/howto/htaccess.html). You can search [".htaccess http digest"](https://www.google.com/search?q=.htaccess%20auth%20digest) for tutorials on how to set this up. Some web hosting services have control panels that have a feature to protect directories using Digest/Basic auth. In cPanel, which is quite common, it's called ["Password Protect Directories"](http://docs.cpanel.net/twiki/bin/view/AllDocumentation/CpanelDocs/PasswordProtectDirectories). If you were more advanced I would suggest doing it in PHP, but thats a rather complicated subject.
If you use a library to render the UI, you can use this function: ```js export function setPasswordToEnter({ password, localStorageKey, errorMessage, }) { if ( !password || (localStorageKey && localStorage.getItem(localStorageKey) === password) ) { return; } const input = prompt('Enter the password to continue:'); if (input !== password) { alert(errorMessage || 'Incorrect password'); throw new Error(errorMessage || 'Incorrect password'); } if (localStorageKey) { localStorage.setItem(localStorageKey, input); } } ``` Run before the render function: ```js setPasswordToEnter({ password: 'password', localStorageKey: '[myapp] password to enter' }); ``` React Example: <https://stackblitz.com/edit/password-to-enter-react?file=src/index.js> P.S. You should definitely get your password from env variable if possible.
18,095,144
I took the following code from another webpage "<http://www.javascriptkit.com/script/cut10.shtml>". ``` <SCRIPT> function passWord() { var testV = 1; var pass1 = prompt('Please Enter Your Password',' '); while (testV < 3) { if (!pass1) history.go(-1); if (pass1.toLowerCase() == "letmein") { alert('You Got it Right!'); window.open('protectpage.html'); break; } testV+=1; var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password'); } if (pass1.toLowerCase()!="password" & testV ==3) history.go(-1); return " "; } </SCRIPT> <CENTER> <FORM> <input type="button" value="Enter Protected Area" onClick="passWord()"> </FORM> </CENTER> ``` It works only in case the password is entered second time, but not when it is entered first time. When you enter password it says wrong password prompting you to enter the password again and then it goes through.I need a script that shall prompt me of the correct password, in case I enter the wrong password. Can any one help me with the code as i am a beginner in JavaScript.
2013/08/07
[ "https://Stackoverflow.com/questions/18095144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2659279/" ]
``` //Add this to you script function run(){ var password = prompt("Password Please"); //Change to your own Password if(password != 'Sameer'){ document.body.innerHTML = ''; document.body.innerHTML = 'Password Failed! Reload to Renter Password'; }else{ alert('Success'); } } run(); ```
I used the same exact code that you have and the problem is the the first time for don't know what reason it added one space in front of the input. Just make sure that you don't have that and it will be fine.
18,095,144
I took the following code from another webpage "<http://www.javascriptkit.com/script/cut10.shtml>". ``` <SCRIPT> function passWord() { var testV = 1; var pass1 = prompt('Please Enter Your Password',' '); while (testV < 3) { if (!pass1) history.go(-1); if (pass1.toLowerCase() == "letmein") { alert('You Got it Right!'); window.open('protectpage.html'); break; } testV+=1; var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password'); } if (pass1.toLowerCase()!="password" & testV ==3) history.go(-1); return " "; } </SCRIPT> <CENTER> <FORM> <input type="button" value="Enter Protected Area" onClick="passWord()"> </FORM> </CENTER> ``` It works only in case the password is entered second time, but not when it is entered first time. When you enter password it says wrong password prompting you to enter the password again and then it goes through.I need a script that shall prompt me of the correct password, in case I enter the wrong password. Can any one help me with the code as i am a beginner in JavaScript.
2013/08/07
[ "https://Stackoverflow.com/questions/18095144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2659279/" ]
``` //Add this to you script function run(){ var password = prompt("Password Please"); //Change to your own Password if(password != 'Sameer'){ document.body.innerHTML = ''; document.body.innerHTML = 'Password Failed! Reload to Renter Password'; }else{ alert('Success'); } } run(); ```
If you use a library to render the UI, you can use this function: ```js export function setPasswordToEnter({ password, localStorageKey, errorMessage, }) { if ( !password || (localStorageKey && localStorage.getItem(localStorageKey) === password) ) { return; } const input = prompt('Enter the password to continue:'); if (input !== password) { alert(errorMessage || 'Incorrect password'); throw new Error(errorMessage || 'Incorrect password'); } if (localStorageKey) { localStorage.setItem(localStorageKey, input); } } ``` Run before the render function: ```js setPasswordToEnter({ password: 'password', localStorageKey: '[myapp] password to enter' }); ``` React Example: <https://stackblitz.com/edit/password-to-enter-react?file=src/index.js> P.S. You should definitely get your password from env variable if possible.
40,725,691
I am doing a project in college which we are to create a java program to add golfers to a list of members. I am having trouble getting them added to the list! This is my code so far: ``` *import java.util.*; public class GolfClubTester { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("Please enter number for:"); System.out.println("1: Joining Member:"); System.out.println("2: Remove an old Member:"); System.out.println("3: Search for a Member:"); System.out.println("4: View all"); //Ask User for input Scanner input = new Scanner(System.in); int i = input.nextInt(); if(i == 1){ //Clear scanner input buffer input.nextLine(); System.out.println("Please enter Members name:"); String name = input.nextLine(); System.out.println("Please enter day:"); int day = input.nextInt(); System.out.println("Please enter month"); int month = input.nextInt(); System.out.println("Please enter year:"); int year = input.nextInt(); System.out.println("Please enter Handicap:"); int Handicap = input.nextInt(); System.out.println("Please enter Id:"); int MemId = input.nextInt(); //Clear scanner input buffer input.nextLine(); //Ask user type of Member System.out.println("Please enter type of Member:"); System.out.println("1 - Senior:"); System.out.println("2 - Junior:"); int i1 = input.nextInt(); if (i1 == 1){ //Create member object Date join1 = new Date(day,month,year); SeniorMembers s1 = new SeniorMembers(name,join1,Handicap,MemId); //Display member details System.out.println("**Senior Member has joined**"); System.out.println(s1); return; } else if (i1 == 2){ Date join1 = new Date(day,month,year); JuniorMembers j1 = new JuniorMembers(name,join1,Handicap,MemId); //Display member details System.out.println("**Junior Member has joined**"); System.out.println(j1); } else{ throw new IllegalArgumentException("Invalid input:"); } }* ``` So I can get it to say the member has joined but it doesn't actually save the member. Can anyone help and tell me what I am missing?
2016/11/21
[ "https://Stackoverflow.com/questions/40725691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7019953/" ]
It seems that Sense plugin isn’t necessary because Kibana (for sure 5.0.1) is shipped with console available from DevTools menu. If Kibana is installed locally open <http://localhost:5601> and choose “DevTools” from the left menu.
Seems, when you are installing locally by downloading complete file was not downloaded. plz check on that.
40,725,691
I am doing a project in college which we are to create a java program to add golfers to a list of members. I am having trouble getting them added to the list! This is my code so far: ``` *import java.util.*; public class GolfClubTester { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("Please enter number for:"); System.out.println("1: Joining Member:"); System.out.println("2: Remove an old Member:"); System.out.println("3: Search for a Member:"); System.out.println("4: View all"); //Ask User for input Scanner input = new Scanner(System.in); int i = input.nextInt(); if(i == 1){ //Clear scanner input buffer input.nextLine(); System.out.println("Please enter Members name:"); String name = input.nextLine(); System.out.println("Please enter day:"); int day = input.nextInt(); System.out.println("Please enter month"); int month = input.nextInt(); System.out.println("Please enter year:"); int year = input.nextInt(); System.out.println("Please enter Handicap:"); int Handicap = input.nextInt(); System.out.println("Please enter Id:"); int MemId = input.nextInt(); //Clear scanner input buffer input.nextLine(); //Ask user type of Member System.out.println("Please enter type of Member:"); System.out.println("1 - Senior:"); System.out.println("2 - Junior:"); int i1 = input.nextInt(); if (i1 == 1){ //Create member object Date join1 = new Date(day,month,year); SeniorMembers s1 = new SeniorMembers(name,join1,Handicap,MemId); //Display member details System.out.println("**Senior Member has joined**"); System.out.println(s1); return; } else if (i1 == 2){ Date join1 = new Date(day,month,year); JuniorMembers j1 = new JuniorMembers(name,join1,Handicap,MemId); //Display member details System.out.println("**Junior Member has joined**"); System.out.println(j1); } else{ throw new IllegalArgumentException("Invalid input:"); } }* ``` So I can get it to say the member has joined but it doesn't actually save the member. Can anyone help and tell me what I am missing?
2016/11/21
[ "https://Stackoverflow.com/questions/40725691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7019953/" ]
``` bin/kibana plugin --install sense --url file:///<path of sense plugin>/sense-2.0.0-beta7.tar.gz ``` Above command works for me with out issues.
Seems, when you are installing locally by downloading complete file was not downloaded. plz check on that.
40,725,691
I am doing a project in college which we are to create a java program to add golfers to a list of members. I am having trouble getting them added to the list! This is my code so far: ``` *import java.util.*; public class GolfClubTester { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("Please enter number for:"); System.out.println("1: Joining Member:"); System.out.println("2: Remove an old Member:"); System.out.println("3: Search for a Member:"); System.out.println("4: View all"); //Ask User for input Scanner input = new Scanner(System.in); int i = input.nextInt(); if(i == 1){ //Clear scanner input buffer input.nextLine(); System.out.println("Please enter Members name:"); String name = input.nextLine(); System.out.println("Please enter day:"); int day = input.nextInt(); System.out.println("Please enter month"); int month = input.nextInt(); System.out.println("Please enter year:"); int year = input.nextInt(); System.out.println("Please enter Handicap:"); int Handicap = input.nextInt(); System.out.println("Please enter Id:"); int MemId = input.nextInt(); //Clear scanner input buffer input.nextLine(); //Ask user type of Member System.out.println("Please enter type of Member:"); System.out.println("1 - Senior:"); System.out.println("2 - Junior:"); int i1 = input.nextInt(); if (i1 == 1){ //Create member object Date join1 = new Date(day,month,year); SeniorMembers s1 = new SeniorMembers(name,join1,Handicap,MemId); //Display member details System.out.println("**Senior Member has joined**"); System.out.println(s1); return; } else if (i1 == 2){ Date join1 = new Date(day,month,year); JuniorMembers j1 = new JuniorMembers(name,join1,Handicap,MemId); //Display member details System.out.println("**Junior Member has joined**"); System.out.println(j1); } else{ throw new IllegalArgumentException("Invalid input:"); } }* ``` So I can get it to say the member has joined but it doesn't actually save the member. Can anyone help and tell me what I am missing?
2016/11/21
[ "https://Stackoverflow.com/questions/40725691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7019953/" ]
It seems that Sense plugin isn’t necessary because Kibana (for sure 5.0.1) is shipped with console available from DevTools menu. If Kibana is installed locally open <http://localhost:5601> and choose “DevTools” from the left menu.
The second floor is correct . I also have this problem. There are many huge differents among different versions . Under the version 5.4.1 even the ``` kibana plugin --install elastic/sense ``` is deprecated. If you want install a plugin for kibana, need use the following command ``` ./bin/kibana-plugin install "plugin name " ``` And the sense plugin has integrated in kibana dev tools
40,725,691
I am doing a project in college which we are to create a java program to add golfers to a list of members. I am having trouble getting them added to the list! This is my code so far: ``` *import java.util.*; public class GolfClubTester { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("Please enter number for:"); System.out.println("1: Joining Member:"); System.out.println("2: Remove an old Member:"); System.out.println("3: Search for a Member:"); System.out.println("4: View all"); //Ask User for input Scanner input = new Scanner(System.in); int i = input.nextInt(); if(i == 1){ //Clear scanner input buffer input.nextLine(); System.out.println("Please enter Members name:"); String name = input.nextLine(); System.out.println("Please enter day:"); int day = input.nextInt(); System.out.println("Please enter month"); int month = input.nextInt(); System.out.println("Please enter year:"); int year = input.nextInt(); System.out.println("Please enter Handicap:"); int Handicap = input.nextInt(); System.out.println("Please enter Id:"); int MemId = input.nextInt(); //Clear scanner input buffer input.nextLine(); //Ask user type of Member System.out.println("Please enter type of Member:"); System.out.println("1 - Senior:"); System.out.println("2 - Junior:"); int i1 = input.nextInt(); if (i1 == 1){ //Create member object Date join1 = new Date(day,month,year); SeniorMembers s1 = new SeniorMembers(name,join1,Handicap,MemId); //Display member details System.out.println("**Senior Member has joined**"); System.out.println(s1); return; } else if (i1 == 2){ Date join1 = new Date(day,month,year); JuniorMembers j1 = new JuniorMembers(name,join1,Handicap,MemId); //Display member details System.out.println("**Junior Member has joined**"); System.out.println(j1); } else{ throw new IllegalArgumentException("Invalid input:"); } }* ``` So I can get it to say the member has joined but it doesn't actually save the member. Can anyone help and tell me what I am missing?
2016/11/21
[ "https://Stackoverflow.com/questions/40725691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7019953/" ]
It seems that Sense plugin isn’t necessary because Kibana (for sure 5.0.1) is shipped with console available from DevTools menu. If Kibana is installed locally open <http://localhost:5601> and choose “DevTools” from the left menu.
``` bin/kibana plugin --install sense --url file:///<path of sense plugin>/sense-2.0.0-beta7.tar.gz ``` Above command works for me with out issues.
40,725,691
I am doing a project in college which we are to create a java program to add golfers to a list of members. I am having trouble getting them added to the list! This is my code so far: ``` *import java.util.*; public class GolfClubTester { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("Please enter number for:"); System.out.println("1: Joining Member:"); System.out.println("2: Remove an old Member:"); System.out.println("3: Search for a Member:"); System.out.println("4: View all"); //Ask User for input Scanner input = new Scanner(System.in); int i = input.nextInt(); if(i == 1){ //Clear scanner input buffer input.nextLine(); System.out.println("Please enter Members name:"); String name = input.nextLine(); System.out.println("Please enter day:"); int day = input.nextInt(); System.out.println("Please enter month"); int month = input.nextInt(); System.out.println("Please enter year:"); int year = input.nextInt(); System.out.println("Please enter Handicap:"); int Handicap = input.nextInt(); System.out.println("Please enter Id:"); int MemId = input.nextInt(); //Clear scanner input buffer input.nextLine(); //Ask user type of Member System.out.println("Please enter type of Member:"); System.out.println("1 - Senior:"); System.out.println("2 - Junior:"); int i1 = input.nextInt(); if (i1 == 1){ //Create member object Date join1 = new Date(day,month,year); SeniorMembers s1 = new SeniorMembers(name,join1,Handicap,MemId); //Display member details System.out.println("**Senior Member has joined**"); System.out.println(s1); return; } else if (i1 == 2){ Date join1 = new Date(day,month,year); JuniorMembers j1 = new JuniorMembers(name,join1,Handicap,MemId); //Display member details System.out.println("**Junior Member has joined**"); System.out.println(j1); } else{ throw new IllegalArgumentException("Invalid input:"); } }* ``` So I can get it to say the member has joined but it doesn't actually save the member. Can anyone help and tell me what I am missing?
2016/11/21
[ "https://Stackoverflow.com/questions/40725691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7019953/" ]
``` bin/kibana plugin --install sense --url file:///<path of sense plugin>/sense-2.0.0-beta7.tar.gz ``` Above command works for me with out issues.
The second floor is correct . I also have this problem. There are many huge differents among different versions . Under the version 5.4.1 even the ``` kibana plugin --install elastic/sense ``` is deprecated. If you want install a plugin for kibana, need use the following command ``` ./bin/kibana-plugin install "plugin name " ``` And the sense plugin has integrated in kibana dev tools
17,720,594
I've tried searching for about an hour through all the Foreign Key / Collation Questions but I can't find something even remotely close to my question. I have 2 tables from two different software vendors sitting in the same database. One vendor hard codes their collations to Latin1\_General\_BIN while the other uses the Database Default (in this case Latin1\_General\_CI\_AS). Is it possible, without altering any of the columns, to create Foreign Keys between these two Collation Types? Typically you would simply change one but in this case the Tables are very sensitive and I'm not allowed to make such a change but I have to create a Foreign Key due to a piece of logic in a Trigger that reads data between these two tables only if it finds a Foreign Key: ``` SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME = ( SELECT name FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID( 'Table1' ) AND referenced_object_id = OBJECT_ID( 'Table2' ) ) ``` Any help would really be appreciate P.S. I just can't seem to figure out how this code thing works if anyone would help me out, I put in the 4 required spaces but it's still just displaying my code as text :(
2013/07/18
[ "https://Stackoverflow.com/questions/17720594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538480/" ]
Yes, either you use javascript, or you send the form to the server, where a new html page with all the inputs is generated (e.g. with PHP).
Here's the **[FIDDLE](http://jsfiddle.net/vonDy2791/h5RTG/)**. Hope it helps. :) html ``` <input type="text" size="3" maxlength="3" id="count" name="count" value="1"> <div id="container"></div> ``` script ``` $('#count').on('keyup', function () { var $this = $(this); var count = $this.val(); $('#container').empty(); for (var x = 1; x <= count; x++) { var newInput = '<input type="text" size="30" maxlength="30" id="input_' + x + '" name="input_' + x + '">'; $('#container').append(newInput); } }); ```
17,720,594
I've tried searching for about an hour through all the Foreign Key / Collation Questions but I can't find something even remotely close to my question. I have 2 tables from two different software vendors sitting in the same database. One vendor hard codes their collations to Latin1\_General\_BIN while the other uses the Database Default (in this case Latin1\_General\_CI\_AS). Is it possible, without altering any of the columns, to create Foreign Keys between these two Collation Types? Typically you would simply change one but in this case the Tables are very sensitive and I'm not allowed to make such a change but I have to create a Foreign Key due to a piece of logic in a Trigger that reads data between these two tables only if it finds a Foreign Key: ``` SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME = ( SELECT name FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID( 'Table1' ) AND referenced_object_id = OBJECT_ID( 'Table2' ) ) ``` Any help would really be appreciate P.S. I just can't seem to figure out how this code thing works if anyone would help me out, I put in the 4 required spaces but it's still just displaying my code as text :(
2013/07/18
[ "https://Stackoverflow.com/questions/17720594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538480/" ]
Here's a simple javascript snippet that doesn't make use of any frameworks: ``` function addInputs() { var count = parseInt(document.getElementById("count").value); for (var i = 2; i <= count; i++) { document.getElementById('moreinputs').innerHTML += '<input type="text" name="input_' + i + '" id="input_' + i + '" />'; } } ``` In this example you have to add a container (div) with id 'moreinputs'. However, when calling this function more than once, it will not work properly (e.g. it can only increase the number of input but not decrease)
Yes, either you use javascript, or you send the form to the server, where a new html page with all the inputs is generated (e.g. with PHP).
17,720,594
I've tried searching for about an hour through all the Foreign Key / Collation Questions but I can't find something even remotely close to my question. I have 2 tables from two different software vendors sitting in the same database. One vendor hard codes their collations to Latin1\_General\_BIN while the other uses the Database Default (in this case Latin1\_General\_CI\_AS). Is it possible, without altering any of the columns, to create Foreign Keys between these two Collation Types? Typically you would simply change one but in this case the Tables are very sensitive and I'm not allowed to make such a change but I have to create a Foreign Key due to a piece of logic in a Trigger that reads data between these two tables only if it finds a Foreign Key: ``` SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME = ( SELECT name FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID( 'Table1' ) AND referenced_object_id = OBJECT_ID( 'Table2' ) ) ``` Any help would really be appreciate P.S. I just can't seem to figure out how this code thing works if anyone would help me out, I put in the 4 required spaces but it's still just displaying my code as text :(
2013/07/18
[ "https://Stackoverflow.com/questions/17720594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538480/" ]
Yes, either you use javascript, or you send the form to the server, where a new html page with all the inputs is generated (e.g. with PHP).
This worked for me ``` function AddField() { var count = $("#countetfield").val(); var i = 1; var id = $("#container .testClass:last").attr('name'); var test = id.split("_"); id_name = test[1]; while (i <= count) { id_name++; var a = '<input type="text" class="testClass" size="30" maxlength="30" id="input_' + id_name + '" name="input_' + id_name + '"/>'; $("#container").append(a); i++; } } <input type="text" id="countetfield" value="1" /> <input type="button" value="Go" onclick="AddField();" /> <div id="container"> <input type="text" class="testClass" size="30" maxlength="30" id="input_1" name="input_1" /> </div> ```