qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
143,735 |
I find it difficult to understand as to why current behaves differently in an RL and an RC circuit. At time $t=0$, in an RC circuit the current is maximum, whereas in an RL circuit its $0$. Why is it so? The current should rise from $0$ to some value in both the circuits, so where am I going wrong?
|
2014/10/29
|
['https://physics.stackexchange.com/questions/143735', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/46325/']
|
[@Floris' answer](https://physics.stackexchange.com/a/143737/44176) being good, i'll give another view on the matter.
A **capacitor is equivalent to an open circuit** (since simply put, a capacitor is an element consisting of two plates which do not actually touch but through another medium, the *dielectric*, the circuit is **not connected** at that point where the capacitor is located), whereas an **inductor is equivalent to a short circuit** (since simply put, an inductor is an element which is a wire folded around a magnetic material, the circuit is **connected** at that point)
**For Direct current (DC):**
In DC how would these behave (as a first approximation)?
The capacitor would be an open circuit while the inductor would be a closed circuit.
Now a capacitor (and an inductor) **are not immediately open or closed circuits**, for example the capacitor needs to be charged first, then it acts as an open circuit. Similarly the inductor needs to overcome any magnetic effects before acting as a closed circuit.
**For Alternating current (AC):**
So lets assume a frequency of operation where the capacitor does not have time to charge completely, then it will **not act as an open circuit** but maybe close to it (depending on frequency of operation)
Similarly an inductor will not act as closed circuit (depending on frequency of operation), but close to it.
The above provide basic explanation (and mnemonic rules) to infer the behaviour of capacitors/inductors in AC circuits
The images are from different sites (just for illustration), represent the resistor voltage in RC and RL circuits:
**RC in series (Resistor voltage in time):**

**RL in series (Resistor voltage in time):**

|
Circuits with inductors are sensitive to changes in the signal - think of them as differentiators. Circuits with capacitors are responding to the integral of the signal over time.
When you first turn on a circuit, the current wants to make a step change - which the capacitor doesn't care about, but the inductor resists vigorously. Thus the current will flow through the capacitor without any problem (there is no built up charge so no potential resisting the current flow), but the inductor will not permit the instantaneous change in current (back emf given by $-L\frac{dI}{dt}$).
So current in the capacitor starts big, then drops off; in the inductor, it starts small, then builds up (at some point the current in the inductor is only limited by the series resistance; while current through the capacitor goes to zero once enough charge is built up to get a potential equal to the applied potential).
|
143,735 |
I find it difficult to understand as to why current behaves differently in an RL and an RC circuit. At time $t=0$, in an RC circuit the current is maximum, whereas in an RL circuit its $0$. Why is it so? The current should rise from $0$ to some value in both the circuits, so where am I going wrong?
|
2014/10/29
|
['https://physics.stackexchange.com/questions/143735', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/46325/']
|
Circuits with inductors are sensitive to changes in the signal - think of them as differentiators. Circuits with capacitors are responding to the integral of the signal over time.
When you first turn on a circuit, the current wants to make a step change - which the capacitor doesn't care about, but the inductor resists vigorously. Thus the current will flow through the capacitor without any problem (there is no built up charge so no potential resisting the current flow), but the inductor will not permit the instantaneous change in current (back emf given by $-L\frac{dI}{dt}$).
So current in the capacitor starts big, then drops off; in the inductor, it starts small, then builds up (at some point the current in the inductor is only limited by the series resistance; while current through the capacitor goes to zero once enough charge is built up to get a potential equal to the applied potential).
|
1. Charge on the capacitor does not change instantaneously or suddenly if there if a resistance in the path(series) of the capacitor.
2. When an uncharged capacitor is connected with battery then its charge is zero initally hence potential difference across it is zero. At this time the capacitor can be treated as a conducting wire.
3. The current will become zero finally(that means in steady state)in the branch which contains capacitor.
|
143,735 |
I find it difficult to understand as to why current behaves differently in an RL and an RC circuit. At time $t=0$, in an RC circuit the current is maximum, whereas in an RL circuit its $0$. Why is it so? The current should rise from $0$ to some value in both the circuits, so where am I going wrong?
|
2014/10/29
|
['https://physics.stackexchange.com/questions/143735', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/46325/']
|
[@Floris' answer](https://physics.stackexchange.com/a/143737/44176) being good, i'll give another view on the matter.
A **capacitor is equivalent to an open circuit** (since simply put, a capacitor is an element consisting of two plates which do not actually touch but through another medium, the *dielectric*, the circuit is **not connected** at that point where the capacitor is located), whereas an **inductor is equivalent to a short circuit** (since simply put, an inductor is an element which is a wire folded around a magnetic material, the circuit is **connected** at that point)
**For Direct current (DC):**
In DC how would these behave (as a first approximation)?
The capacitor would be an open circuit while the inductor would be a closed circuit.
Now a capacitor (and an inductor) **are not immediately open or closed circuits**, for example the capacitor needs to be charged first, then it acts as an open circuit. Similarly the inductor needs to overcome any magnetic effects before acting as a closed circuit.
**For Alternating current (AC):**
So lets assume a frequency of operation where the capacitor does not have time to charge completely, then it will **not act as an open circuit** but maybe close to it (depending on frequency of operation)
Similarly an inductor will not act as closed circuit (depending on frequency of operation), but close to it.
The above provide basic explanation (and mnemonic rules) to infer the behaviour of capacitors/inductors in AC circuits
The images are from different sites (just for illustration), represent the resistor voltage in RC and RL circuits:
**RC in series (Resistor voltage in time):**

**RL in series (Resistor voltage in time):**

|
>
> Why is it so?
>
>
>
Well, it isn't actually *always* so. It will depend on the actual circuit configuration and whether the switch opens or closes when $t=0$.
But first, here are a couple of *crucial* results to *always* keep in mind when solving these type of switched circuits:
* the current through an inductor must be continuous
* the voltage across a capacitor must be continuous
In this context, this means that the current through the inductor the instant *after* the switch changes position must be the same as the current through the inductor *before* the switch changes position.
Similarly, the voltage across the capacitor the instant *after* the switch changes position must be the same as the voltage across the capacitor *before* the switch changes position.
So, for example, if we have a resistor $R$, inductor $L$, and switch in series with a voltage source $V$ and the switch is *closed* at $t=0$, it is indeed true that the inductor current is initially zero and asymptotically approaches a constant value
$$i\_L(0-) = i\_L(0+) = 0$$
$$i\_L(t) \rightarrow \frac{V}{R}\,,\quad t\rightarrow \infty $$
This must be the case since the inductor current is zero before the switch is closed and so, must be zero the instant after the switch is closed.
If the inductor is replaced with a capacitor, the voltage across the capacitor $C$ is initially zero and so, must be zero the instant after the switch is closed.
This means that the entire voltage $V$ is across the resistor and so, the series current must 'jump' from zero to $\frac{V}{R}$ at $t=0$ and then decay asymptotically to zero.
$$v\_C(0-) =v\_C(0+) = 0 \Rightarrow i\_C(0+) = \frac{V}{R}$$
$$i\_C(t) \rightarrow 0\,,\quad t \rightarrow \infty $$
|
143,735 |
I find it difficult to understand as to why current behaves differently in an RL and an RC circuit. At time $t=0$, in an RC circuit the current is maximum, whereas in an RL circuit its $0$. Why is it so? The current should rise from $0$ to some value in both the circuits, so where am I going wrong?
|
2014/10/29
|
['https://physics.stackexchange.com/questions/143735', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/46325/']
|
[@Floris' answer](https://physics.stackexchange.com/a/143737/44176) being good, i'll give another view on the matter.
A **capacitor is equivalent to an open circuit** (since simply put, a capacitor is an element consisting of two plates which do not actually touch but through another medium, the *dielectric*, the circuit is **not connected** at that point where the capacitor is located), whereas an **inductor is equivalent to a short circuit** (since simply put, an inductor is an element which is a wire folded around a magnetic material, the circuit is **connected** at that point)
**For Direct current (DC):**
In DC how would these behave (as a first approximation)?
The capacitor would be an open circuit while the inductor would be a closed circuit.
Now a capacitor (and an inductor) **are not immediately open or closed circuits**, for example the capacitor needs to be charged first, then it acts as an open circuit. Similarly the inductor needs to overcome any magnetic effects before acting as a closed circuit.
**For Alternating current (AC):**
So lets assume a frequency of operation where the capacitor does not have time to charge completely, then it will **not act as an open circuit** but maybe close to it (depending on frequency of operation)
Similarly an inductor will not act as closed circuit (depending on frequency of operation), but close to it.
The above provide basic explanation (and mnemonic rules) to infer the behaviour of capacitors/inductors in AC circuits
The images are from different sites (just for illustration), represent the resistor voltage in RC and RL circuits:
**RC in series (Resistor voltage in time):**

**RL in series (Resistor voltage in time):**

|
1. Charge on the capacitor does not change instantaneously or suddenly if there if a resistance in the path(series) of the capacitor.
2. When an uncharged capacitor is connected with battery then its charge is zero initally hence potential difference across it is zero. At this time the capacitor can be treated as a conducting wire.
3. The current will become zero finally(that means in steady state)in the branch which contains capacitor.
|
143,735 |
I find it difficult to understand as to why current behaves differently in an RL and an RC circuit. At time $t=0$, in an RC circuit the current is maximum, whereas in an RL circuit its $0$. Why is it so? The current should rise from $0$ to some value in both the circuits, so where am I going wrong?
|
2014/10/29
|
['https://physics.stackexchange.com/questions/143735', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/46325/']
|
>
> Why is it so?
>
>
>
Well, it isn't actually *always* so. It will depend on the actual circuit configuration and whether the switch opens or closes when $t=0$.
But first, here are a couple of *crucial* results to *always* keep in mind when solving these type of switched circuits:
* the current through an inductor must be continuous
* the voltage across a capacitor must be continuous
In this context, this means that the current through the inductor the instant *after* the switch changes position must be the same as the current through the inductor *before* the switch changes position.
Similarly, the voltage across the capacitor the instant *after* the switch changes position must be the same as the voltage across the capacitor *before* the switch changes position.
So, for example, if we have a resistor $R$, inductor $L$, and switch in series with a voltage source $V$ and the switch is *closed* at $t=0$, it is indeed true that the inductor current is initially zero and asymptotically approaches a constant value
$$i\_L(0-) = i\_L(0+) = 0$$
$$i\_L(t) \rightarrow \frac{V}{R}\,,\quad t\rightarrow \infty $$
This must be the case since the inductor current is zero before the switch is closed and so, must be zero the instant after the switch is closed.
If the inductor is replaced with a capacitor, the voltage across the capacitor $C$ is initially zero and so, must be zero the instant after the switch is closed.
This means that the entire voltage $V$ is across the resistor and so, the series current must 'jump' from zero to $\frac{V}{R}$ at $t=0$ and then decay asymptotically to zero.
$$v\_C(0-) =v\_C(0+) = 0 \Rightarrow i\_C(0+) = \frac{V}{R}$$
$$i\_C(t) \rightarrow 0\,,\quad t \rightarrow \infty $$
|
1. Charge on the capacitor does not change instantaneously or suddenly if there if a resistance in the path(series) of the capacitor.
2. When an uncharged capacitor is connected with battery then its charge is zero initally hence potential difference across it is zero. At this time the capacitor can be treated as a conducting wire.
3. The current will become zero finally(that means in steady state)in the branch which contains capacitor.
|
23,020,571 |
I am trying to import data from a db via pdo and output the results to a csv file. I am able to output to a screen correctly but the formatting in the csv is wild, double names and no '\n'
```
<?php
require_once('auth.php');
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $pw);
if (($handle = fopen("nameList2.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, " ")) !== FALSE) {
$firstname = $data[0];
$lastname = $data[1];
$stmt = $conn->prepare("SELECT * FROM list WHERE FName = :firstname AND LName = :lastname");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->execute();
$result = $stmt->fetchAll();
//var_dump($firstname);
//var_dump($lastname);
//var_dump($result);
$fp = fopen('file.csv', 'w');
foreach($result as $chunk){
echo $chunk[4]." ".$chunk[6]." ".$chunk[7]." ".$chunk[10]." ".$chunk[11]."".$chunk[12]." ".$chunk[13]." ".$chunk[18]." ".$chunk[19]." ".$chunk[20]."<br />";
fputcsv($fp, $chunk);
}
fclose($fp);
}
fclose($handle);
//fclose($fp);
}
?>
```

|
2014/04/11
|
['https://Stackoverflow.com/questions/23020571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2528910/']
|
I've [updated your fiddle](http://jsfiddle.net/8s9ss/4) and below code as well. I hope that will help.
Regards
```
var app = angular.module('app', ['ui.bootstrap']);
app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, customer)
{
$scope.customer = customer;
});
app.controller('CustomerController', function($scope, $timeout, $modal, $log) {
$scope.customers = [
{
name: 'Ricky',
details: 'Some Details for Ricky',
},
{
name: 'Dicky',
details: 'Some Dicky Details',
},
{
name: 'Nicky',
details: 'Some Nicky Details',
}
];
// MODAL WINDOW
$scope.open = function (_customer) {
var modalInstance = $modal.open({
controller: "ModalInstanceCtrl",
templateUrl: 'myModalContent.html',
resolve: {
customer: function()
{
return _customer;
}
}
});
};
});
```
|
This is how I setup my modals for handleing items that I ng-repeat over and want to edit. I suggest setting it up to work with a different controller, because then you can use DI to inject the resolved item to the child scope.
```
$scope.openModal = function(item)
// This sets up some of the options I want the modal to open with
var options = {}
angular.extend(options, {
templateUrl: '/views/userItems/form.html',
controller: 'ItemEditController',
resolve: {
// I resolve a copy of the so it dont mess up the original if they cancel
item: function() { return angular.copy(item); }
}
});
$modal.open(options).result.then(function(updatedItem) {
// after the user saves the edits to the item it gets passed back in the then function
if(updatedItem) {
// this is a service i have to deal with talking to my db
modelService.editItem(updatedItem).then(function(result) {
// get the result back, error check then update the scope
if(result.reason) {
$scope.addAlert({type: 'error', title: 'Application Error', msg: result.reason});
} else {
angular.extend(vital, result);
$scope.addAlert({type: 'success', msg: 'Successfully updated Item!'});
}
});
}
});
};
```
|
46,065 |
And in what sense could he be called wise?
Can you please help me in this essay assignment?
|
2017/09/16
|
['https://philosophy.stackexchange.com/questions/46065', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/28693/']
|
There's a lot of interesting features to the question.
First, you need to consider how serious Socrates is being vs. how much of a joke he's making of the whole thing. Second, it's important to realize "Socrates" is a character Plato is using and the *Apology* is largely agreed to not be a factual representation of what's going on (See [What did Socrates mean by " there is no more fitting reward than maintenance in the prytaneum"?](https://philosophy.stackexchange.com/questions/28527/what-did-socrates-mean-by-there-is-no-more-fitting-reward-than-maintenance-in) and [Did Plato record actual conversations in his dialogues?](https://philosophy.stackexchange.com/questions/30278/did-plato-record-actual-conversations-in-his-dialogues)).
Building on these two considerations, we can trace the narrative form of Socrates' claim and then ask whether he's being a jerk to the people of Athens or he's just that genuinely inquisitive and naturally trusting of what others tell him. So here's the narrative as Plato writes it (at least on my reading):
1. Socrates is told that he's the smartest
2. Socrates denies this based on a "principle of charity" argument that merges these three features:
* Socrates does not claim to be wise
* Other people do claim to be wise.
* Socrates accepts the claims of others at face value.
3. But this breaks down, because Socrates seeks out to prove the oracle wrong by proving others smart.
4. Socrates interrogates all of the people who claim to be wise and discovers they don't have any idea what they are talking about.
5. Ergo, Socrates is forced to conclude he is the wisest *because* he has the advantage over them of knowing that he does not know anything (whereas they claim to know things).
The face-value reading sounds plausible in a certain way, but it's also quite plausible to view him as never holding the naive belief that the people who said they were smart are not.
If we want to restructure the argument in the terms of modern logic, we would state that he's doing a reductio against the assumption that they are wise and this forces him to recognize them as fools and thus himself as wise insofar as he doesn't make the foolish claim to know things.
|
He could be called wise in starting from the position he knows nothing, and pursuing knowledge as something of worth he does not "own" already - instead of treating knowledge like property, as a kind of status symbol through the appearance of knowing "something", he treated knowledge as something to be gained through rigorous inquiry - and so treated knowledge as something of worth, instead of cheapening it through treating it like some kind of a status object, which, perhaps, was how the sophists treated knowledge, as my understanding is they were hired to train citizens in their art - cheapening knowledge to the position of a status object, instead of as something to be pursued at personal cost because of its inherent value to the individual person. In this sense, Socrates had wisdom, because he knew that knowledge could only be pursued at great personal cost, it could not be bought like property, but rather changed the individual person in his or her pursuit of it. In summary he could be called wise in relation to his approach to the question of knowledge, and in his appreciation of his own ignorance at the beginning of inquiry - he had an appreciation of his own "irrelevance" before the object of knowledge ... in other words, perhaps we could simply say he had an attitude of humility in inquiry (which could easily have been mistaken by others as arrogance, or simply being a nuisance!)
|
46,065 |
And in what sense could he be called wise?
Can you please help me in this essay assignment?
|
2017/09/16
|
['https://philosophy.stackexchange.com/questions/46065', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/28693/']
|
He could be called wise in starting from the position he knows nothing, and pursuing knowledge as something of worth he does not "own" already - instead of treating knowledge like property, as a kind of status symbol through the appearance of knowing "something", he treated knowledge as something to be gained through rigorous inquiry - and so treated knowledge as something of worth, instead of cheapening it through treating it like some kind of a status object, which, perhaps, was how the sophists treated knowledge, as my understanding is they were hired to train citizens in their art - cheapening knowledge to the position of a status object, instead of as something to be pursued at personal cost because of its inherent value to the individual person. In this sense, Socrates had wisdom, because he knew that knowledge could only be pursued at great personal cost, it could not be bought like property, but rather changed the individual person in his or her pursuit of it. In summary he could be called wise in relation to his approach to the question of knowledge, and in his appreciation of his own ignorance at the beginning of inquiry - he had an appreciation of his own "irrelevance" before the object of knowledge ... in other words, perhaps we could simply say he had an attitude of humility in inquiry (which could easily have been mistaken by others as arrogance, or simply being a nuisance!)
|
Socrates did not understand the situation surrounding Chaerephon's visit to Delphi. Chaerephon went to ask the oracle at Delphi, "Of all the Greeks, who is wisest?" (Από όλους τους Έλληνες, ποιος είναι πιο σοφός;) The Pythia replied, “Socrates”, perplexing even Socrates.
Clarity comes when we understand the full circumstance of the Delphic interrogation. Whether it was the Pythia inspiring fumes or a swallowed stray fly, something caused Chaerephon to end his question with a strangled cough swallow that sounded somewhat like kolos. Thus leading the Pythia to hear Chaerephon ask,"Από όλους τους Έλληνες, ποιος είναι ο σοφότερος κώλος;" (Of all the Greeks, who is wisest ass?).
|
46,065 |
And in what sense could he be called wise?
Can you please help me in this essay assignment?
|
2017/09/16
|
['https://philosophy.stackexchange.com/questions/46065', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/28693/']
|
He could be called wise in starting from the position he knows nothing, and pursuing knowledge as something of worth he does not "own" already - instead of treating knowledge like property, as a kind of status symbol through the appearance of knowing "something", he treated knowledge as something to be gained through rigorous inquiry - and so treated knowledge as something of worth, instead of cheapening it through treating it like some kind of a status object, which, perhaps, was how the sophists treated knowledge, as my understanding is they were hired to train citizens in their art - cheapening knowledge to the position of a status object, instead of as something to be pursued at personal cost because of its inherent value to the individual person. In this sense, Socrates had wisdom, because he knew that knowledge could only be pursued at great personal cost, it could not be bought like property, but rather changed the individual person in his or her pursuit of it. In summary he could be called wise in relation to his approach to the question of knowledge, and in his appreciation of his own ignorance at the beginning of inquiry - he had an appreciation of his own "irrelevance" before the object of knowledge ... in other words, perhaps we could simply say he had an attitude of humility in inquiry (which could easily have been mistaken by others as arrogance, or simply being a nuisance!)
|
He changed his mind when he discovered that the wise were not wise but did not know that they were not wise . Socrates was wise only in the sense that he knew that he was not wise .
|
46,065 |
And in what sense could he be called wise?
Can you please help me in this essay assignment?
|
2017/09/16
|
['https://philosophy.stackexchange.com/questions/46065', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/28693/']
|
There's a lot of interesting features to the question.
First, you need to consider how serious Socrates is being vs. how much of a joke he's making of the whole thing. Second, it's important to realize "Socrates" is a character Plato is using and the *Apology* is largely agreed to not be a factual representation of what's going on (See [What did Socrates mean by " there is no more fitting reward than maintenance in the prytaneum"?](https://philosophy.stackexchange.com/questions/28527/what-did-socrates-mean-by-there-is-no-more-fitting-reward-than-maintenance-in) and [Did Plato record actual conversations in his dialogues?](https://philosophy.stackexchange.com/questions/30278/did-plato-record-actual-conversations-in-his-dialogues)).
Building on these two considerations, we can trace the narrative form of Socrates' claim and then ask whether he's being a jerk to the people of Athens or he's just that genuinely inquisitive and naturally trusting of what others tell him. So here's the narrative as Plato writes it (at least on my reading):
1. Socrates is told that he's the smartest
2. Socrates denies this based on a "principle of charity" argument that merges these three features:
* Socrates does not claim to be wise
* Other people do claim to be wise.
* Socrates accepts the claims of others at face value.
3. But this breaks down, because Socrates seeks out to prove the oracle wrong by proving others smart.
4. Socrates interrogates all of the people who claim to be wise and discovers they don't have any idea what they are talking about.
5. Ergo, Socrates is forced to conclude he is the wisest *because* he has the advantage over them of knowing that he does not know anything (whereas they claim to know things).
The face-value reading sounds plausible in a certain way, but it's also quite plausible to view him as never holding the naive belief that the people who said they were smart are not.
If we want to restructure the argument in the terms of modern logic, we would state that he's doing a reductio against the assumption that they are wise and this forces him to recognize them as fools and thus himself as wise insofar as he doesn't make the foolish claim to know things.
|
I am just going to quote wikipedia:
>
> According to Plato's Apology, Socrates' life as the "gadfly" of Athens began when his friend Chaerephon asked the oracle at Delphi if anyone were wiser than Socrates; the Oracle responded that no-one was wiser. Socrates believed the Oracle's response was not correct, because he believed he possessed no wisdom whatsoever. He proceeded to test the riddle by approaching men considered wise by the people of Athens—statesmen, poets, and artisans—in order to refute the Oracle's pronouncement. Questioning them, however, Socrates concluded: while each man thought he knew a great deal and was wise, in fact they knew very little and were not wise at all. Socrates realized the Oracle was correct; while so-called wise men thought themselves wise and yet were not, he himself knew he was not wise at all, which, paradoxically, made him the wiser one since he was the only person aware of his own ignorance. Socrates' paradoxical wisdom made the prominent Athenians he publicly questioned look foolish, turning them against him and leading to accusations of wrongdoing.
> <https://en.wikipedia.org/wiki/Socrates>
>
>
>
|
46,065 |
And in what sense could he be called wise?
Can you please help me in this essay assignment?
|
2017/09/16
|
['https://philosophy.stackexchange.com/questions/46065', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/28693/']
|
I am just going to quote wikipedia:
>
> According to Plato's Apology, Socrates' life as the "gadfly" of Athens began when his friend Chaerephon asked the oracle at Delphi if anyone were wiser than Socrates; the Oracle responded that no-one was wiser. Socrates believed the Oracle's response was not correct, because he believed he possessed no wisdom whatsoever. He proceeded to test the riddle by approaching men considered wise by the people of Athens—statesmen, poets, and artisans—in order to refute the Oracle's pronouncement. Questioning them, however, Socrates concluded: while each man thought he knew a great deal and was wise, in fact they knew very little and were not wise at all. Socrates realized the Oracle was correct; while so-called wise men thought themselves wise and yet were not, he himself knew he was not wise at all, which, paradoxically, made him the wiser one since he was the only person aware of his own ignorance. Socrates' paradoxical wisdom made the prominent Athenians he publicly questioned look foolish, turning them against him and leading to accusations of wrongdoing.
> <https://en.wikipedia.org/wiki/Socrates>
>
>
>
|
Socrates did not understand the situation surrounding Chaerephon's visit to Delphi. Chaerephon went to ask the oracle at Delphi, "Of all the Greeks, who is wisest?" (Από όλους τους Έλληνες, ποιος είναι πιο σοφός;) The Pythia replied, “Socrates”, perplexing even Socrates.
Clarity comes when we understand the full circumstance of the Delphic interrogation. Whether it was the Pythia inspiring fumes or a swallowed stray fly, something caused Chaerephon to end his question with a strangled cough swallow that sounded somewhat like kolos. Thus leading the Pythia to hear Chaerephon ask,"Από όλους τους Έλληνες, ποιος είναι ο σοφότερος κώλος;" (Of all the Greeks, who is wisest ass?).
|
46,065 |
And in what sense could he be called wise?
Can you please help me in this essay assignment?
|
2017/09/16
|
['https://philosophy.stackexchange.com/questions/46065', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/28693/']
|
I am just going to quote wikipedia:
>
> According to Plato's Apology, Socrates' life as the "gadfly" of Athens began when his friend Chaerephon asked the oracle at Delphi if anyone were wiser than Socrates; the Oracle responded that no-one was wiser. Socrates believed the Oracle's response was not correct, because he believed he possessed no wisdom whatsoever. He proceeded to test the riddle by approaching men considered wise by the people of Athens—statesmen, poets, and artisans—in order to refute the Oracle's pronouncement. Questioning them, however, Socrates concluded: while each man thought he knew a great deal and was wise, in fact they knew very little and were not wise at all. Socrates realized the Oracle was correct; while so-called wise men thought themselves wise and yet were not, he himself knew he was not wise at all, which, paradoxically, made him the wiser one since he was the only person aware of his own ignorance. Socrates' paradoxical wisdom made the prominent Athenians he publicly questioned look foolish, turning them against him and leading to accusations of wrongdoing.
> <https://en.wikipedia.org/wiki/Socrates>
>
>
>
|
He changed his mind when he discovered that the wise were not wise but did not know that they were not wise . Socrates was wise only in the sense that he knew that he was not wise .
|
46,065 |
And in what sense could he be called wise?
Can you please help me in this essay assignment?
|
2017/09/16
|
['https://philosophy.stackexchange.com/questions/46065', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/28693/']
|
There's a lot of interesting features to the question.
First, you need to consider how serious Socrates is being vs. how much of a joke he's making of the whole thing. Second, it's important to realize "Socrates" is a character Plato is using and the *Apology* is largely agreed to not be a factual representation of what's going on (See [What did Socrates mean by " there is no more fitting reward than maintenance in the prytaneum"?](https://philosophy.stackexchange.com/questions/28527/what-did-socrates-mean-by-there-is-no-more-fitting-reward-than-maintenance-in) and [Did Plato record actual conversations in his dialogues?](https://philosophy.stackexchange.com/questions/30278/did-plato-record-actual-conversations-in-his-dialogues)).
Building on these two considerations, we can trace the narrative form of Socrates' claim and then ask whether he's being a jerk to the people of Athens or he's just that genuinely inquisitive and naturally trusting of what others tell him. So here's the narrative as Plato writes it (at least on my reading):
1. Socrates is told that he's the smartest
2. Socrates denies this based on a "principle of charity" argument that merges these three features:
* Socrates does not claim to be wise
* Other people do claim to be wise.
* Socrates accepts the claims of others at face value.
3. But this breaks down, because Socrates seeks out to prove the oracle wrong by proving others smart.
4. Socrates interrogates all of the people who claim to be wise and discovers they don't have any idea what they are talking about.
5. Ergo, Socrates is forced to conclude he is the wisest *because* he has the advantage over them of knowing that he does not know anything (whereas they claim to know things).
The face-value reading sounds plausible in a certain way, but it's also quite plausible to view him as never holding the naive belief that the people who said they were smart are not.
If we want to restructure the argument in the terms of modern logic, we would state that he's doing a reductio against the assumption that they are wise and this forces him to recognize them as fools and thus himself as wise insofar as he doesn't make the foolish claim to know things.
|
Socrates did not understand the situation surrounding Chaerephon's visit to Delphi. Chaerephon went to ask the oracle at Delphi, "Of all the Greeks, who is wisest?" (Από όλους τους Έλληνες, ποιος είναι πιο σοφός;) The Pythia replied, “Socrates”, perplexing even Socrates.
Clarity comes when we understand the full circumstance of the Delphic interrogation. Whether it was the Pythia inspiring fumes or a swallowed stray fly, something caused Chaerephon to end his question with a strangled cough swallow that sounded somewhat like kolos. Thus leading the Pythia to hear Chaerephon ask,"Από όλους τους Έλληνες, ποιος είναι ο σοφότερος κώλος;" (Of all the Greeks, who is wisest ass?).
|
46,065 |
And in what sense could he be called wise?
Can you please help me in this essay assignment?
|
2017/09/16
|
['https://philosophy.stackexchange.com/questions/46065', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/28693/']
|
There's a lot of interesting features to the question.
First, you need to consider how serious Socrates is being vs. how much of a joke he's making of the whole thing. Second, it's important to realize "Socrates" is a character Plato is using and the *Apology* is largely agreed to not be a factual representation of what's going on (See [What did Socrates mean by " there is no more fitting reward than maintenance in the prytaneum"?](https://philosophy.stackexchange.com/questions/28527/what-did-socrates-mean-by-there-is-no-more-fitting-reward-than-maintenance-in) and [Did Plato record actual conversations in his dialogues?](https://philosophy.stackexchange.com/questions/30278/did-plato-record-actual-conversations-in-his-dialogues)).
Building on these two considerations, we can trace the narrative form of Socrates' claim and then ask whether he's being a jerk to the people of Athens or he's just that genuinely inquisitive and naturally trusting of what others tell him. So here's the narrative as Plato writes it (at least on my reading):
1. Socrates is told that he's the smartest
2. Socrates denies this based on a "principle of charity" argument that merges these three features:
* Socrates does not claim to be wise
* Other people do claim to be wise.
* Socrates accepts the claims of others at face value.
3. But this breaks down, because Socrates seeks out to prove the oracle wrong by proving others smart.
4. Socrates interrogates all of the people who claim to be wise and discovers they don't have any idea what they are talking about.
5. Ergo, Socrates is forced to conclude he is the wisest *because* he has the advantage over them of knowing that he does not know anything (whereas they claim to know things).
The face-value reading sounds plausible in a certain way, but it's also quite plausible to view him as never holding the naive belief that the people who said they were smart are not.
If we want to restructure the argument in the terms of modern logic, we would state that he's doing a reductio against the assumption that they are wise and this forces him to recognize them as fools and thus himself as wise insofar as he doesn't make the foolish claim to know things.
|
He changed his mind when he discovered that the wise were not wise but did not know that they were not wise . Socrates was wise only in the sense that he knew that he was not wise .
|
31,524,073 |
I have something like below, which of course works if user had previously input his wrong credentials.
However if I directly go to my login fail url `/login?error` for example without any previous incorrect logins, `session[SPRING_SECURITY_LAST_EXCEPTION]` is of course `null` and I get a nasty **404**.
```
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
```
**Question**:
Is there a processor for something like below (which is too long to write and read most of the time), or should I just roll my own?
```
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION] != null ? session[SPRING_SECURITY_LAST_EXCEPTION].message : #messages.msg('AbstractUserDetailsAuthenticationProvider.badCredentials')}">
Invalid credentials
</span>
```
|
2015/07/20
|
['https://Stackoverflow.com/questions/31524073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1448229/']
|
You can use the th:if statement:
```
<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION].message}" th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
```
That will only display this line if there is a value present.
EDIT 1:
Extra check:
```
<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION] != null and session[SPRING_SECURITY_LAST_EXCEPTION].message != null}" th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
```
|
Try this:
```
<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION].message != null}">
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
</span>
```
|
31,524,073 |
I have something like below, which of course works if user had previously input his wrong credentials.
However if I directly go to my login fail url `/login?error` for example without any previous incorrect logins, `session[SPRING_SECURITY_LAST_EXCEPTION]` is of course `null` and I get a nasty **404**.
```
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
```
**Question**:
Is there a processor for something like below (which is too long to write and read most of the time), or should I just roll my own?
```
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION] != null ? session[SPRING_SECURITY_LAST_EXCEPTION].message : #messages.msg('AbstractUserDetailsAuthenticationProvider.badCredentials')}">
Invalid credentials
</span>
```
|
2015/07/20
|
['https://Stackoverflow.com/questions/31524073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1448229/']
|
You can use the th:if statement:
```
<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION].message}" th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
```
That will only display this line if there is a value present.
EDIT 1:
Extra check:
```
<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION] != null and session[SPRING_SECURITY_LAST_EXCEPTION].message != null}" th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
```
|
Try this code, it is more optimal:
```
${session['SPRING_SECURITY_LAST_EXCEPTION']?.message}
```
? - checks if the resource is not null
|
31,524,073 |
I have something like below, which of course works if user had previously input his wrong credentials.
However if I directly go to my login fail url `/login?error` for example without any previous incorrect logins, `session[SPRING_SECURITY_LAST_EXCEPTION]` is of course `null` and I get a nasty **404**.
```
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
```
**Question**:
Is there a processor for something like below (which is too long to write and read most of the time), or should I just roll my own?
```
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION] != null ? session[SPRING_SECURITY_LAST_EXCEPTION].message : #messages.msg('AbstractUserDetailsAuthenticationProvider.badCredentials')}">
Invalid credentials
</span>
```
|
2015/07/20
|
['https://Stackoverflow.com/questions/31524073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1448229/']
|
You can use the th:if statement:
```
<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION].message}" th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
```
That will only display this line if there is a value present.
EDIT 1:
Extra check:
```
<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION] != null and session[SPRING_SECURITY_LAST_EXCEPTION].message != null}" th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
```
|
In your controller set the null string variable as
```
String nullvalue="";
model.addAttribute("nullvalue",nullvalue);
model.addAttribute("entity",entity);
```
then in your view class as in thymeleaf
```
<td data-th-if="${entity.field != nullvalue}">ok</td>
```
|
31,524,073 |
I have something like below, which of course works if user had previously input his wrong credentials.
However if I directly go to my login fail url `/login?error` for example without any previous incorrect logins, `session[SPRING_SECURITY_LAST_EXCEPTION]` is of course `null` and I get a nasty **404**.
```
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
```
**Question**:
Is there a processor for something like below (which is too long to write and read most of the time), or should I just roll my own?
```
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION] != null ? session[SPRING_SECURITY_LAST_EXCEPTION].message : #messages.msg('AbstractUserDetailsAuthenticationProvider.badCredentials')}">
Invalid credentials
</span>
```
|
2015/07/20
|
['https://Stackoverflow.com/questions/31524073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1448229/']
|
Try this code, it is more optimal:
```
${session['SPRING_SECURITY_LAST_EXCEPTION']?.message}
```
? - checks if the resource is not null
|
Try this:
```
<span th:if="${session[SPRING_SECURITY_LAST_EXCEPTION].message != null}">
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
</span>
```
|
31,524,073 |
I have something like below, which of course works if user had previously input his wrong credentials.
However if I directly go to my login fail url `/login?error` for example without any previous incorrect logins, `session[SPRING_SECURITY_LAST_EXCEPTION]` is of course `null` and I get a nasty **404**.
```
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION].message}">Invalid credentials</span>
```
**Question**:
Is there a processor for something like below (which is too long to write and read most of the time), or should I just roll my own?
```
<span th:text="${session[SPRING_SECURITY_LAST_EXCEPTION] != null ? session[SPRING_SECURITY_LAST_EXCEPTION].message : #messages.msg('AbstractUserDetailsAuthenticationProvider.badCredentials')}">
Invalid credentials
</span>
```
|
2015/07/20
|
['https://Stackoverflow.com/questions/31524073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1448229/']
|
Try this code, it is more optimal:
```
${session['SPRING_SECURITY_LAST_EXCEPTION']?.message}
```
? - checks if the resource is not null
|
In your controller set the null string variable as
```
String nullvalue="";
model.addAttribute("nullvalue",nullvalue);
model.addAttribute("entity",entity);
```
then in your view class as in thymeleaf
```
<td data-th-if="${entity.field != nullvalue}">ok</td>
```
|
16,650 |
Another question I asked about Power Supply Noise pushed me to ask this question.
The background is as follows: I have a design with PD (Photodetector) and Opamp at medium frequency (couple hundred KHz). I am trying to test my design when it come back. I am looking at power supply noise, opamp supply noise and opamp output noise. I realized, there is more to it than just touching the probe. People talk about power loops, having special cables etc.
I will spin another board in two weeks and I wanted to ask, if you are designing your board now, what type of test points or elements you place on your board so that you can measure the noise accurately. We are talking about <20mV type signals.
Bonus question: The output of the opamp is connected to an ADC of the processor. Could I simply run the ADC and plot that to gain a deeper understanding of the noise compared to connecting my cheap scope?
|
2011/07/11
|
['https://electronics.stackexchange.com/questions/16650', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/4861/']
|
Noise is difficult to measure, and the **amplitude** you see on your your **scope is only a first indication** of the level.
Do you want to measure absolute noise levels, or just comparative? In the latter case the scope could be a good instrument, but at the given levels the average $500 scope will have so much noise itself that any measurement becomes in fact meaningless. You need a high quality scope + ditto probes to do this.
The difficulty with measuring noise is that it has a wide bandwidth continuous energy spectrum (the continuous spectrum makes it hard to separate noise from signal, notch filters may work). Ideally you measure the **noise energy** through **RMS-to-DC conversion**. This is not for the faint-of-heart, as your RMS-to-DC converter has to be very sensitive due to the low levels, and wideband. And of course be low-noise itself! Liquid nitrogen helps :-).
In any case, absolute signal-to-noise ratio is not as easy as reading amplitudes.
|
Stevenvh is correct that noise can be very hard to measure, but I would like to point out a different point of view.
The only time that noise really matters to you is when it affects your readings. This means that you can just take an ADC of your input, pass it off to a computer, and then do some math on it. I am not entirely up to speed on your project, but I assume that you "know" what your signal is that you are receiving.
You can come up with an SNR figure by calculating the average power of your signal and then to get your noise, just subtract the known signal from your ADC signal, find the power of the resulting noise, and then divide the two. Most systems tend to convert this to a dB scale.
This won’t tell you anything about what part of the system the noise is coming from, but it will allow you to have an idea as to how well your system will function overall.
|
16,650 |
Another question I asked about Power Supply Noise pushed me to ask this question.
The background is as follows: I have a design with PD (Photodetector) and Opamp at medium frequency (couple hundred KHz). I am trying to test my design when it come back. I am looking at power supply noise, opamp supply noise and opamp output noise. I realized, there is more to it than just touching the probe. People talk about power loops, having special cables etc.
I will spin another board in two weeks and I wanted to ask, if you are designing your board now, what type of test points or elements you place on your board so that you can measure the noise accurately. We are talking about <20mV type signals.
Bonus question: The output of the opamp is connected to an ADC of the processor. Could I simply run the ADC and plot that to gain a deeper understanding of the noise compared to connecting my cheap scope?
|
2011/07/11
|
['https://electronics.stackexchange.com/questions/16650', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/4861/']
|
Noise is difficult to measure, and the **amplitude** you see on your your **scope is only a first indication** of the level.
Do you want to measure absolute noise levels, or just comparative? In the latter case the scope could be a good instrument, but at the given levels the average $500 scope will have so much noise itself that any measurement becomes in fact meaningless. You need a high quality scope + ditto probes to do this.
The difficulty with measuring noise is that it has a wide bandwidth continuous energy spectrum (the continuous spectrum makes it hard to separate noise from signal, notch filters may work). Ideally you measure the **noise energy** through **RMS-to-DC conversion**. This is not for the faint-of-heart, as your RMS-to-DC converter has to be very sensitive due to the low levels, and wideband. And of course be low-noise itself! Liquid nitrogen helps :-).
In any case, absolute signal-to-noise ratio is not as easy as reading amplitudes.
|
Typically you design some parts on the first spins of the board to help measure stuff like this. Be generous with footprints for bypass caps and filters, and put for example SMA coaxial contacts at key places in the signal chain, but put them with a removable SMD 0-ohm resistor at the T-junction so the stub doesn't have to affect the signal chain if not used.
For low-frequency signals you could hook this directly to the scope, but the SMA coaxes have a good feature in that some of the probes with the ground-lead built into the tip can be stuck into the center position of the coax connector and the ground lead will or can be made to touch the shielding.. note though that for best results with a probe it need to be active, and then the probe itself will cost 3000 dollars :/
With photodiodes and transimpedance amplifiers you have the problem that for a typical setup (you don't specify your parameters..) you have only a couple of microamps and a transimpedance gain of several hundred thousand. Inserting elements at the PD-side of the opamp, and indeed just having PCB traces in the vicinity might disrupt your precision and noiselevels. The solder resist coating has a non-infinite resistance for example.
Therefore if you can control the gain of the ADC and know you have designed a very good ADC circuit (this you can test separately, with separate SMA coax inputs to it for example) you can use that as a probe replacement yes if the sample rate is high enough. This is a good solution and postpones the need for the more expensive scope (you can rent these if you really need it sometime though).
|
16,650 |
Another question I asked about Power Supply Noise pushed me to ask this question.
The background is as follows: I have a design with PD (Photodetector) and Opamp at medium frequency (couple hundred KHz). I am trying to test my design when it come back. I am looking at power supply noise, opamp supply noise and opamp output noise. I realized, there is more to it than just touching the probe. People talk about power loops, having special cables etc.
I will spin another board in two weeks and I wanted to ask, if you are designing your board now, what type of test points or elements you place on your board so that you can measure the noise accurately. We are talking about <20mV type signals.
Bonus question: The output of the opamp is connected to an ADC of the processor. Could I simply run the ADC and plot that to gain a deeper understanding of the noise compared to connecting my cheap scope?
|
2011/07/11
|
['https://electronics.stackexchange.com/questions/16650', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/4861/']
|
Typically you design some parts on the first spins of the board to help measure stuff like this. Be generous with footprints for bypass caps and filters, and put for example SMA coaxial contacts at key places in the signal chain, but put them with a removable SMD 0-ohm resistor at the T-junction so the stub doesn't have to affect the signal chain if not used.
For low-frequency signals you could hook this directly to the scope, but the SMA coaxes have a good feature in that some of the probes with the ground-lead built into the tip can be stuck into the center position of the coax connector and the ground lead will or can be made to touch the shielding.. note though that for best results with a probe it need to be active, and then the probe itself will cost 3000 dollars :/
With photodiodes and transimpedance amplifiers you have the problem that for a typical setup (you don't specify your parameters..) you have only a couple of microamps and a transimpedance gain of several hundred thousand. Inserting elements at the PD-side of the opamp, and indeed just having PCB traces in the vicinity might disrupt your precision and noiselevels. The solder resist coating has a non-infinite resistance for example.
Therefore if you can control the gain of the ADC and know you have designed a very good ADC circuit (this you can test separately, with separate SMA coax inputs to it for example) you can use that as a probe replacement yes if the sample rate is high enough. This is a good solution and postpones the need for the more expensive scope (you can rent these if you really need it sometime though).
|
Stevenvh is correct that noise can be very hard to measure, but I would like to point out a different point of view.
The only time that noise really matters to you is when it affects your readings. This means that you can just take an ADC of your input, pass it off to a computer, and then do some math on it. I am not entirely up to speed on your project, but I assume that you "know" what your signal is that you are receiving.
You can come up with an SNR figure by calculating the average power of your signal and then to get your noise, just subtract the known signal from your ADC signal, find the power of the resulting noise, and then divide the two. Most systems tend to convert this to a dB scale.
This won’t tell you anything about what part of the system the noise is coming from, but it will allow you to have an idea as to how well your system will function overall.
|
849,786 |
Asking this question with C# tag, but if it is possible, it should be possible in any language.
Is it possible to implement a doubly linked list using Interlocked operations to provide no-wait locking? I would want to insert, add and remove, and clear without waiting.
|
2009/05/11
|
['https://Stackoverflow.com/questions/849786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92692/']
|
Well you haven't actually asked how to do it. But, provided you can do an atomic CAS in c# it's entirely possible.
In fact I'm just working through an implementation of a doubly linked wait free list in C++ right now.
Here is paper describing it.
<http://www.cse.chalmers.se/~tsigas/papers/Haakan-Thesis.pdf>
And a presentation that may also provide you some clues.
<http://www.ida.liu.se/~chrke/courses/MULTI/slides/Lock-Free_DoublyLinkedList.pdf>
|
I would say that the answer is a very deeply qualified "yes, it is **possible**, but hard". To implement what you're asking for, you'd basically need something that would compile the operations together to ensure no collisions; as such, it would be very hard to create a general implementation for that purpose, and it would still have some significant limitations. It would probably be simpler to create a specific implementation tailored to the precise needs, and even then, it wouldn't be "simple" by any means.
|
849,786 |
Asking this question with C# tag, but if it is possible, it should be possible in any language.
Is it possible to implement a doubly linked list using Interlocked operations to provide no-wait locking? I would want to insert, add and remove, and clear without waiting.
|
2009/05/11
|
['https://Stackoverflow.com/questions/849786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92692/']
|
A simple google search will reveal many lock-free doubly linked list papers.
However, they are based on atomic CAS (compare and swap).
I don't know how atomic the operations in C# are, but according to this website
<http://www.albahari.com/threading/part4.aspx>
C# operations are only guaranteed to be atomic for reading and writing a 32bit field. No mention of CAS.
|
It is possible to write lock free algorithms for *all* copyable data structures on most architectures [1]. But it is hard to write efficient ones.
I wrote an [implementation](https://github.com/2i/lfdll) of the [lock-free doubly linked list by Håkan Sundell and Philippas Tsigas](http://www.researchgate.net/publication/237782379_Lock-Free_and_Practical_Deques_and_Doubly_Linked_Lists_using_Single-Word_Compare-And-Swap1) for .Net. Note, that it does not support atomic PopLeft due to the concept.
[1]: [Maurice Herlihy: Impossibility and universality results for wait-freesynchronization (1988)](http://repository.cmu.edu/cgi/viewcontent.cgi?article=2796&context=compsci)
|
849,786 |
Asking this question with C# tag, but if it is possible, it should be possible in any language.
Is it possible to implement a doubly linked list using Interlocked operations to provide no-wait locking? I would want to insert, add and remove, and clear without waiting.
|
2009/05/11
|
['https://Stackoverflow.com/questions/849786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92692/']
|
I don't believe this is possible, since you're having to set multiple references in one shot, and the interlocked operations are limited in their power.
For example, take the add operation - if you're inserting node B between A and C, you need to set B->next, B->prev, A->next, and C->prev in one atomic operation. Interlocked can't handle that. Presetting B's elements doesn't even help, because another thread could decide to do an insert while you're preparing "B".
I'd focus more on getting the locking as fine-grained as possible in this case, not trying to eliminate it.
|
Read the footnote - they plan to pull ConcurrentLinkedList from 4.0 prior to the final release of VS2010
|
849,786 |
Asking this question with C# tag, but if it is possible, it should be possible in any language.
Is it possible to implement a doubly linked list using Interlocked operations to provide no-wait locking? I would want to insert, add and remove, and clear without waiting.
|
2009/05/11
|
['https://Stackoverflow.com/questions/849786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92692/']
|
Here is a [paper](http://citeseer.ist.psu.edu/cache/papers/cs/32904/http:zSzzSzwww.cs.chalmers.sezSz~phszSzTechnicalReportszSzSunT04_Deque.pdf/sundell04lockfree.pdf) which discribes a lock free doublly linked list.
>
> We present an efficient and practical
> lock-free implementation of a
> concurrent deque that is
> disjoint-parallel accessible and uses
> atomic primitives which are available
> in modern computer systems. Previously
> known lock-free algorithms of deques
> are either based on non-available
> atomic synchronization primitives,
> only implement a subset of the
> functionality, or are not designed for
> disjoint accesses. Our algorithm is
> based on a doubly linked list, and
> only requires single-word
> compare-and-swap...
>
>
>
Ross Bencina has some really good links I just found with numerious papers and source code excamples for "[Some notes on lock-free and wait-free algorithms](http://www.audiomulch.com/~rossb/code/lockfree/)".
|
Read the footnote - they plan to pull ConcurrentLinkedList from 4.0 prior to the final release of VS2010
|
849,786 |
Asking this question with C# tag, but if it is possible, it should be possible in any language.
Is it possible to implement a doubly linked list using Interlocked operations to provide no-wait locking? I would want to insert, add and remove, and clear without waiting.
|
2009/05/11
|
['https://Stackoverflow.com/questions/849786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92692/']
|
Read the footnote - they plan to pull ConcurrentLinkedList from 4.0 prior to the final release of VS2010
|
FWIW, .NET 4.0 is adding a ConcurrentLinkedList, a threadsafe doubly linked list in the System.Collections.Concurrent namespace. You can read the [documentation](http://msdn.microsoft.com/en-us/library/dd381935(VS.100).aspx) or the [blog post](http://blogs.msdn.com/pfxteam/archive/2009/03/04/9457880.aspx) describing it.
|
849,786 |
Asking this question with C# tag, but if it is possible, it should be possible in any language.
Is it possible to implement a doubly linked list using Interlocked operations to provide no-wait locking? I would want to insert, add and remove, and clear without waiting.
|
2009/05/11
|
['https://Stackoverflow.com/questions/849786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92692/']
|
Yes it's possible, here's my implementation of an STL-like [Lock-Free Doubly-Linked List](https://github.com/Qarterd/Honeycomb/blob/master/src/common/Honey/Thread/LockFree/List.h) in C++.
[Sample code that spawns threads to randomly perform ops on a list](https://github.com/Qarterd/Honeycomb/blob/master/test/Test.cpp#L12)
It requires a 64-bit compare-and-swap to operate without ABA issues. This list is only possible because of a [lock-free memory manager](https://github.com/Qarterd/Honeycomb/blob/master/src/common/Honey/Thread/LockFree/HazardMem.h).
Check out the [benchmarks on page 12](http://docs.google.com/viewer?url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.140.5222%26rep%3Drep1%26type%3Dpdf). Performance of the list scales linearly with the number of threads as contention increases. The algorithm supports parallelism for disjoint accesses, so as the list size increases contention can decrease.
|
Well you haven't actually asked how to do it. But, provided you can do an atomic CAS in c# it's entirely possible.
In fact I'm just working through an implementation of a doubly linked wait free list in C++ right now.
Here is paper describing it.
<http://www.cse.chalmers.se/~tsigas/papers/Haakan-Thesis.pdf>
And a presentation that may also provide you some clues.
<http://www.ida.liu.se/~chrke/courses/MULTI/slides/Lock-Free_DoublyLinkedList.pdf>
|
849,786 |
Asking this question with C# tag, but if it is possible, it should be possible in any language.
Is it possible to implement a doubly linked list using Interlocked operations to provide no-wait locking? I would want to insert, add and remove, and clear without waiting.
|
2009/05/11
|
['https://Stackoverflow.com/questions/849786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92692/']
|
Here is a [paper](http://citeseer.ist.psu.edu/cache/papers/cs/32904/http:zSzzSzwww.cs.chalmers.sezSz~phszSzTechnicalReportszSzSunT04_Deque.pdf/sundell04lockfree.pdf) which discribes a lock free doublly linked list.
>
> We present an efficient and practical
> lock-free implementation of a
> concurrent deque that is
> disjoint-parallel accessible and uses
> atomic primitives which are available
> in modern computer systems. Previously
> known lock-free algorithms of deques
> are either based on non-available
> atomic synchronization primitives,
> only implement a subset of the
> functionality, or are not designed for
> disjoint accesses. Our algorithm is
> based on a doubly linked list, and
> only requires single-word
> compare-and-swap...
>
>
>
Ross Bencina has some really good links I just found with numerious papers and source code excamples for "[Some notes on lock-free and wait-free algorithms](http://www.audiomulch.com/~rossb/code/lockfree/)".
|
FWIW, .NET 4.0 is adding a ConcurrentLinkedList, a threadsafe doubly linked list in the System.Collections.Concurrent namespace. You can read the [documentation](http://msdn.microsoft.com/en-us/library/dd381935(VS.100).aspx) or the [blog post](http://blogs.msdn.com/pfxteam/archive/2009/03/04/9457880.aspx) describing it.
|
849,786 |
Asking this question with C# tag, but if it is possible, it should be possible in any language.
Is it possible to implement a doubly linked list using Interlocked operations to provide no-wait locking? I would want to insert, add and remove, and clear without waiting.
|
2009/05/11
|
['https://Stackoverflow.com/questions/849786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92692/']
|
Here is a [paper](http://citeseer.ist.psu.edu/cache/papers/cs/32904/http:zSzzSzwww.cs.chalmers.sezSz~phszSzTechnicalReportszSzSunT04_Deque.pdf/sundell04lockfree.pdf) which discribes a lock free doublly linked list.
>
> We present an efficient and practical
> lock-free implementation of a
> concurrent deque that is
> disjoint-parallel accessible and uses
> atomic primitives which are available
> in modern computer systems. Previously
> known lock-free algorithms of deques
> are either based on non-available
> atomic synchronization primitives,
> only implement a subset of the
> functionality, or are not designed for
> disjoint accesses. Our algorithm is
> based on a doubly linked list, and
> only requires single-word
> compare-and-swap...
>
>
>
Ross Bencina has some really good links I just found with numerious papers and source code excamples for "[Some notes on lock-free and wait-free algorithms](http://www.audiomulch.com/~rossb/code/lockfree/)".
|
It is possible to write lock free algorithms for *all* copyable data structures on most architectures [1]. But it is hard to write efficient ones.
I wrote an [implementation](https://github.com/2i/lfdll) of the [lock-free doubly linked list by Håkan Sundell and Philippas Tsigas](http://www.researchgate.net/publication/237782379_Lock-Free_and_Practical_Deques_and_Doubly_Linked_Lists_using_Single-Word_Compare-And-Swap1) for .Net. Note, that it does not support atomic PopLeft due to the concept.
[1]: [Maurice Herlihy: Impossibility and universality results for wait-freesynchronization (1988)](http://repository.cmu.edu/cgi/viewcontent.cgi?article=2796&context=compsci)
|
849,786 |
Asking this question with C# tag, but if it is possible, it should be possible in any language.
Is it possible to implement a doubly linked list using Interlocked operations to provide no-wait locking? I would want to insert, add and remove, and clear without waiting.
|
2009/05/11
|
['https://Stackoverflow.com/questions/849786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92692/']
|
Here is a [paper](http://citeseer.ist.psu.edu/cache/papers/cs/32904/http:zSzzSzwww.cs.chalmers.sezSz~phszSzTechnicalReportszSzSunT04_Deque.pdf/sundell04lockfree.pdf) which discribes a lock free doublly linked list.
>
> We present an efficient and practical
> lock-free implementation of a
> concurrent deque that is
> disjoint-parallel accessible and uses
> atomic primitives which are available
> in modern computer systems. Previously
> known lock-free algorithms of deques
> are either based on non-available
> atomic synchronization primitives,
> only implement a subset of the
> functionality, or are not designed for
> disjoint accesses. Our algorithm is
> based on a doubly linked list, and
> only requires single-word
> compare-and-swap...
>
>
>
Ross Bencina has some really good links I just found with numerious papers and source code excamples for "[Some notes on lock-free and wait-free algorithms](http://www.audiomulch.com/~rossb/code/lockfree/)".
|
Well you haven't actually asked how to do it. But, provided you can do an atomic CAS in c# it's entirely possible.
In fact I'm just working through an implementation of a doubly linked wait free list in C++ right now.
Here is paper describing it.
<http://www.cse.chalmers.se/~tsigas/papers/Haakan-Thesis.pdf>
And a presentation that may also provide you some clues.
<http://www.ida.liu.se/~chrke/courses/MULTI/slides/Lock-Free_DoublyLinkedList.pdf>
|
849,786 |
Asking this question with C# tag, but if it is possible, it should be possible in any language.
Is it possible to implement a doubly linked list using Interlocked operations to provide no-wait locking? I would want to insert, add and remove, and clear without waiting.
|
2009/05/11
|
['https://Stackoverflow.com/questions/849786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92692/']
|
A simple google search will reveal many lock-free doubly linked list papers.
However, they are based on atomic CAS (compare and swap).
I don't know how atomic the operations in C# are, but according to this website
<http://www.albahari.com/threading/part4.aspx>
C# operations are only guaranteed to be atomic for reading and writing a 32bit field. No mention of CAS.
|
FWIW, .NET 4.0 is adding a ConcurrentLinkedList, a threadsafe doubly linked list in the System.Collections.Concurrent namespace. You can read the [documentation](http://msdn.microsoft.com/en-us/library/dd381935(VS.100).aspx) or the [blog post](http://blogs.msdn.com/pfxteam/archive/2009/03/04/9457880.aspx) describing it.
|
15,337,469 |
Whenever a unit test fails due to a `StackOverflowException` the unit test process immediately exits - the only way to find out what happened (that I am aware of) is to debug a crash dump of the unit test process obtained by following the steps found here
* [Collecting User-Mode Dumps](http://msdn.microsoft.com/en-us/library/bb787181%28VS.85%29.aspx)
What is the easiest way of getting the name of the unit test that was running at the time that the `StackOverflowException` was thrown? Even when debugging the unit test I'm struggling to find the name of the current unit test as its at the bottom of the stack and Visual Studio wont' shown the entire stack in the debugging window because its too large.
Is there some way to find out which unit test failed without collecting and debugging crash dumps?
|
2013/03/11
|
['https://Stackoverflow.com/questions/15337469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113141/']
|
Use [Eclipse](http://www.eclipse.org/). Cloudera has a great screencast [here](http://blog.cloudera.com/blog/2009/04/configuring-eclipse-for-hadoop-development-a-screencast/) for configuring eclipse for hadoop development.
Also debugging a hadoop job locally is pretty cool using eclipse (though not trivial). To know more on that, see [here](http://amnigos.com/post/44631353593/how-to-guide-hadoop-mapreduce-debugging-in-lo).
|
[Here](http://www.thecloudavenue.com/2012/10/debugging-hadoop-mapreduce-program-in.html) is a blog for Debugging/Developing Hadoop Jobs on Eclipse/Linux. Also, check [Karmasphere Studio](http://karmasphere.com/karmasphere-studio-resources).
|
15,337,469 |
Whenever a unit test fails due to a `StackOverflowException` the unit test process immediately exits - the only way to find out what happened (that I am aware of) is to debug a crash dump of the unit test process obtained by following the steps found here
* [Collecting User-Mode Dumps](http://msdn.microsoft.com/en-us/library/bb787181%28VS.85%29.aspx)
What is the easiest way of getting the name of the unit test that was running at the time that the `StackOverflowException` was thrown? Even when debugging the unit test I'm struggling to find the name of the current unit test as its at the bottom of the stack and Visual Studio wont' shown the entire stack in the debugging window because its too large.
Is there some way to find out which unit test failed without collecting and debugging crash dumps?
|
2013/03/11
|
['https://Stackoverflow.com/questions/15337469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113141/']
|
You should also check out the IntelliJ IDEA as the Apache Hadoop wiki pages have instructions on how to set up your development environment using it.
References:
<http://www.jetbrains.com/idea/>
<http://wiki.apache.org/hadoop/HadoopUnderIDEA>
|
Use [Eclipse](http://www.eclipse.org/). Cloudera has a great screencast [here](http://blog.cloudera.com/blog/2009/04/configuring-eclipse-for-hadoop-development-a-screencast/) for configuring eclipse for hadoop development.
Also debugging a hadoop job locally is pretty cool using eclipse (though not trivial). To know more on that, see [here](http://amnigos.com/post/44631353593/how-to-guide-hadoop-mapreduce-debugging-in-lo).
|
15,337,469 |
Whenever a unit test fails due to a `StackOverflowException` the unit test process immediately exits - the only way to find out what happened (that I am aware of) is to debug a crash dump of the unit test process obtained by following the steps found here
* [Collecting User-Mode Dumps](http://msdn.microsoft.com/en-us/library/bb787181%28VS.85%29.aspx)
What is the easiest way of getting the name of the unit test that was running at the time that the `StackOverflowException` was thrown? Even when debugging the unit test I'm struggling to find the name of the current unit test as its at the bottom of the stack and Visual Studio wont' shown the entire stack in the debugging window because its too large.
Is there some way to find out which unit test failed without collecting and debugging crash dumps?
|
2013/03/11
|
['https://Stackoverflow.com/questions/15337469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113141/']
|
Use [Eclipse](http://www.eclipse.org/). Cloudera has a great screencast [here](http://blog.cloudera.com/blog/2009/04/configuring-eclipse-for-hadoop-development-a-screencast/) for configuring eclipse for hadoop development.
Also debugging a hadoop job locally is pretty cool using eclipse (though not trivial). To know more on that, see [here](http://amnigos.com/post/44631353593/how-to-guide-hadoop-mapreduce-debugging-in-lo).
|
Yes, It's possible to run the MapReduce jobs in Eclipse. There is a lot of difference running MapReduce programs on a cluster and in Eclipse.
Bellow are the few points worth noting:
* In Eclipse, it runs in a special mode called: LocalJobRunner mode i.e. all Hadoop daemons are run in single JVM.
* In Eclipse, All paths refer to local file paths, and not to HDFS path.
|
15,337,469 |
Whenever a unit test fails due to a `StackOverflowException` the unit test process immediately exits - the only way to find out what happened (that I am aware of) is to debug a crash dump of the unit test process obtained by following the steps found here
* [Collecting User-Mode Dumps](http://msdn.microsoft.com/en-us/library/bb787181%28VS.85%29.aspx)
What is the easiest way of getting the name of the unit test that was running at the time that the `StackOverflowException` was thrown? Even when debugging the unit test I'm struggling to find the name of the current unit test as its at the bottom of the stack and Visual Studio wont' shown the entire stack in the debugging window because its too large.
Is there some way to find out which unit test failed without collecting and debugging crash dumps?
|
2013/03/11
|
['https://Stackoverflow.com/questions/15337469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113141/']
|
You should also check out the IntelliJ IDEA as the Apache Hadoop wiki pages have instructions on how to set up your development environment using it.
References:
<http://www.jetbrains.com/idea/>
<http://wiki.apache.org/hadoop/HadoopUnderIDEA>
|
[Here](http://www.thecloudavenue.com/2012/10/debugging-hadoop-mapreduce-program-in.html) is a blog for Debugging/Developing Hadoop Jobs on Eclipse/Linux. Also, check [Karmasphere Studio](http://karmasphere.com/karmasphere-studio-resources).
|
15,337,469 |
Whenever a unit test fails due to a `StackOverflowException` the unit test process immediately exits - the only way to find out what happened (that I am aware of) is to debug a crash dump of the unit test process obtained by following the steps found here
* [Collecting User-Mode Dumps](http://msdn.microsoft.com/en-us/library/bb787181%28VS.85%29.aspx)
What is the easiest way of getting the name of the unit test that was running at the time that the `StackOverflowException` was thrown? Even when debugging the unit test I'm struggling to find the name of the current unit test as its at the bottom of the stack and Visual Studio wont' shown the entire stack in the debugging window because its too large.
Is there some way to find out which unit test failed without collecting and debugging crash dumps?
|
2013/03/11
|
['https://Stackoverflow.com/questions/15337469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113141/']
|
[Here](http://www.thecloudavenue.com/2012/10/debugging-hadoop-mapreduce-program-in.html) is a blog for Debugging/Developing Hadoop Jobs on Eclipse/Linux. Also, check [Karmasphere Studio](http://karmasphere.com/karmasphere-studio-resources).
|
Yes, It's possible to run the MapReduce jobs in Eclipse. There is a lot of difference running MapReduce programs on a cluster and in Eclipse.
Bellow are the few points worth noting:
* In Eclipse, it runs in a special mode called: LocalJobRunner mode i.e. all Hadoop daemons are run in single JVM.
* In Eclipse, All paths refer to local file paths, and not to HDFS path.
|
15,337,469 |
Whenever a unit test fails due to a `StackOverflowException` the unit test process immediately exits - the only way to find out what happened (that I am aware of) is to debug a crash dump of the unit test process obtained by following the steps found here
* [Collecting User-Mode Dumps](http://msdn.microsoft.com/en-us/library/bb787181%28VS.85%29.aspx)
What is the easiest way of getting the name of the unit test that was running at the time that the `StackOverflowException` was thrown? Even when debugging the unit test I'm struggling to find the name of the current unit test as its at the bottom of the stack and Visual Studio wont' shown the entire stack in the debugging window because its too large.
Is there some way to find out which unit test failed without collecting and debugging crash dumps?
|
2013/03/11
|
['https://Stackoverflow.com/questions/15337469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113141/']
|
You should also check out the IntelliJ IDEA as the Apache Hadoop wiki pages have instructions on how to set up your development environment using it.
References:
<http://www.jetbrains.com/idea/>
<http://wiki.apache.org/hadoop/HadoopUnderIDEA>
|
Yes, It's possible to run the MapReduce jobs in Eclipse. There is a lot of difference running MapReduce programs on a cluster and in Eclipse.
Bellow are the few points worth noting:
* In Eclipse, it runs in a special mode called: LocalJobRunner mode i.e. all Hadoop daemons are run in single JVM.
* In Eclipse, All paths refer to local file paths, and not to HDFS path.
|
45,692,532 |
I am using recyclerview in my app. I want to start a fragment when click on image view. But i don't know how to. Also i want to put data when starting fragment. I know how to start the activity with below code. But how can i start fragment same way?
Edited Code
```
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.layoutContent, frag);
ft.commit();
```
|
2017/08/15
|
['https://Stackoverflow.com/questions/45692532', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8042837/']
|
Here is a workaround which you can use to do this.
```
@BindingAdapter("touchListener")
public void setTouchListener(View self,boolean value){
self.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
// Check if the button is PRESSED
if (event.getAction() == MotionEvent.ACTION_DOWN){
//do some thing
}// Check if the button is RELEASED
else if (event.getAction() == MotionEvent.ACTION_UP) {
//do some thing
}
return false;
}
});
}
```
And then in xml
```
<Button app:touchListener="@{true}"/>
```
|
ViewModel
```
public class RecyclerViewModel {
public View.OnTouchListener onTouchListener;
public void setOnTouchListener( View.OnTouchListener onTouchListener) {
this.onTouchListener = onTouchListener;
}
}
```
DataBinding
```
@BindingAdapter("onTouchListener")
public static void setOnTouchListener(View view, View.OnTouchListener onTouchListener) {
if (onTouchListener != null)
view.setOnTouchListener(onTouchListener);
}
```
Use in xml
```
<Button app:onTouchListener="@{viewModel.onTouchListener}"/>
```
|
45,692,532 |
I am using recyclerview in my app. I want to start a fragment when click on image view. But i don't know how to. Also i want to put data when starting fragment. I know how to start the activity with below code. But how can i start fragment same way?
Edited Code
```
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.layoutContent, frag);
ft.commit();
```
|
2017/08/15
|
['https://Stackoverflow.com/questions/45692532', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8042837/']
|
Here is a workaround which you can use to do this.
```
@BindingAdapter("touchListener")
public void setTouchListener(View self,boolean value){
self.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
// Check if the button is PRESSED
if (event.getAction() == MotionEvent.ACTION_DOWN){
//do some thing
}// Check if the button is RELEASED
else if (event.getAction() == MotionEvent.ACTION_UP) {
//do some thing
}
return false;
}
});
}
```
And then in xml
```
<Button app:touchListener="@{true}"/>
```
|
ViewModel
```
private var tapTime: Long = 0
fun onTouchListener(view:View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
tapTime = Date().time
// more commands for touch down event
}
MotionEvent.ACTION_UP -> {
if (Date().time - tapDate < 300) {
view.performClick()
// more commands if click event
} else {
// any commands if holded toch on screen
}
}
}
return true
}
```
**No need for data binding adapter. It exists already.**
XML
```
<Button
...
app:onTouchListener="@{viewModel.onTouchListener}"
...
/>
```
**Warning**
You need to use the right signature in ViewModel:
```
fun name(view:View, event: MotionEvent): Boolean
```
and right name of the attribute in XML:
```
app:onTouchListener
```
|
45,692,532 |
I am using recyclerview in my app. I want to start a fragment when click on image view. But i don't know how to. Also i want to put data when starting fragment. I know how to start the activity with below code. But how can i start fragment same way?
Edited Code
```
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.layoutContent, frag);
ft.commit();
```
|
2017/08/15
|
['https://Stackoverflow.com/questions/45692532', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8042837/']
|
ViewModel
```
public class RecyclerViewModel {
public View.OnTouchListener onTouchListener;
public void setOnTouchListener( View.OnTouchListener onTouchListener) {
this.onTouchListener = onTouchListener;
}
}
```
DataBinding
```
@BindingAdapter("onTouchListener")
public static void setOnTouchListener(View view, View.OnTouchListener onTouchListener) {
if (onTouchListener != null)
view.setOnTouchListener(onTouchListener);
}
```
Use in xml
```
<Button app:onTouchListener="@{viewModel.onTouchListener}"/>
```
|
ViewModel
```
private var tapTime: Long = 0
fun onTouchListener(view:View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
tapTime = Date().time
// more commands for touch down event
}
MotionEvent.ACTION_UP -> {
if (Date().time - tapDate < 300) {
view.performClick()
// more commands if click event
} else {
// any commands if holded toch on screen
}
}
}
return true
}
```
**No need for data binding adapter. It exists already.**
XML
```
<Button
...
app:onTouchListener="@{viewModel.onTouchListener}"
...
/>
```
**Warning**
You need to use the right signature in ViewModel:
```
fun name(view:View, event: MotionEvent): Boolean
```
and right name of the attribute in XML:
```
app:onTouchListener
```
|
24,735 |
Condoms don't give 100% protection and can break, that's a known fact.
I would like to know, are there any ways/hacks to check a single condom (before using it) and see if it might be defective and break while using it? Anything that can prevent such an "accident" before it happens (i.e. if there will be a chance for defective condom I can just use another one) would be welcome.
|
2021/05/03
|
['https://lifehacks.stackexchange.com/questions/24735', 'https://lifehacks.stackexchange.com', 'https://lifehacks.stackexchange.com/users/1399/']
|
You should not attempt to test a condom yourself. (See other post.)
The “test” is circumstantial:
All condoms1 are tested at the manufacturer’s, individually, before packaging. This is certified on the packaging and guaranteed for a certain time, provided correct storage conditions etc. are maintained. Your assessment of the usability/safety of the condoms hinges on whether that state is maintained between the product leaving the factory and you using it. In short, start with the assumption that the condom is safe, discard any where there’s any doubt that they are no longer, for whatever reason.
* If you can be reasonably sure that these conditions (e.g. temperature range) were maintained, the condoms should be fully functional until you intend to use them, at least until the given date on the packaging.
* Any sign of tampering (even inadvertently) means that the product is to be considered “not safe” (which doesn’t necessarily translate to defective), so don’t buy the ones where the box is damaged. And don’t use those where the individual packaging isn’t like a slightly inflated cushion or deflates when pressed.
* Follow the instructions for use, that includes opening the packaging carefully and keeping all sharp and pointy things away. So no dramatic “ripping the pack open with your teeth”, sorry.
So the responsible answer to the question for a *lifehack* must be: **Don’t attempt to hack it, follow the instructions.**
———
1 assuming the genuine medicinal protective item, not novelty items that are “toys” and were never intended as true form of protection
|
The standard way to check the integrity of a condom is to inflate it and wait as long as you can stand it a while to see if it deflates.
**EDIT**: According to Rick Sowadsky, MSPH at [TheBody.com](https://www.thebody.com/article/testing-condoms-holes), you must **NOT** attempt to test a condom for holes before or after use. Doing so may damage the condom. The information is within the context of HIV infection rather than unanticipated pregnancy.
It's probably good to mention that the answer and Web site cited above provides general health information that is not intended to replace medical advice or treatment recommendations from a qualified health care professional.
The usual way (wait to see if menstrual cycle remains regular) is less desirable for a number of reasons.
Good luck.
|
28,390,611 |
I am trying to use Selenium in Java to get the user's geographical coordinates, but using IP address isn't accurate enough, so i wanted to use this website <http://www.whataremycoordinates.com/> , but it isn't working, and I am guessing it is because you have to allow location use, so is there anyway I can allow location use in Selenium, or maybe some other way to get exact geographical coordinates
|
2015/02/08
|
['https://Stackoverflow.com/questions/28390611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4542233/']
|
Usually, when a site wants to get this kind of data, a browser asks you if you want to share your location. The question is inside a popup which *cannot be controlled* with `selenium`. In this case, you need to tell the browser, not to open the popup and allow to share your location at the same time so that the popup would not be opened in the first place.
For `Firefox`, you need to:
* open the site
* allow to share your location (you can also check `about:permissions` to see the setting)
* save the current firefox profile
* start firefox with `FirefoxProfile` pointing to the profile you've saved before
For more information, see:
* [Custom Firefox Profile for Selenium](http://www.toolsqa.com/selenium-webdriver/custom-firefox-profile/)
* [How to open specified profile Firefox with Selenium 2 Webdriver?](https://stackoverflow.com/questions/20543013/how-to-open-specified-profile-firefox-with-selenium-2-webdriver)
* [How to use custom Firefox Profile with Selenium? (Java) (And pass HTML Authorization Window)](https://stackoverflow.com/questions/14458289/how-to-use-custom-firefox-profile-with-selenium-java-and-pass-html-author)
* [Change GeoLocation using Selenium WebDriver in Firefox](http://techyworks.blogspot.com/2013/10/change-geolocation-using-selenium.html)
* [Webdriver: Click "Share Location" button in Firefox](https://stackoverflow.com/questions/3859935/webdriver-click-share-location-button-in-firefox)
|
you can inject firefox profile at the time of creating driver
selenium 3 I am using if you are using selenium 2 no need for firefoxOptions you can directly pass the profile into driver.
lat-log-json:[How to enable geolocation permissions for a website in firefox profile using selenium webdriver](https://stackoverflow.com/questions/34740547/how-to-enable-geolocation-permissions-for-a-website-in-firefox-profile-using-sel)
```
FirefoxOptions opt = getFirefoxOptions();
WebDriver webDriver = new FirefoxDriver(opt);
//method for fire fox profile//////////////////////////////////
public static FirefoxProfile getFirefoxProfile() {
ProfilesIni profileIni = new ProfilesIni();
FirefoxProfile profile = profileIni.getProfile("webDriverProfile");
System.out.println("profile is null : " + (profile == null));
if (profile == null) {
profile = new FirefoxProfile();
}
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", "download/path");
profile.setPreference(
"browser.helperApps.neverAsk.saveToDisk",
"application/pdf,application/octet-stream,"
+ "application/download,text/html,application/xhtml+xml");
profile.setPreference("pdfjs.disabled", true);
// profile.setPreference("dom.webnotifications.enabled", true);
profile.setPreference("geo.enabled", true);
profile.setPreference("geo.provider.use_corelocation", true);
profile.setPreference("geo.prompt.testing", true);
profile.setPreference("geo.prompt.testing.allow", true);
profile.setPreference("geo.wifi.uri", "path-to-loglatjson\\geo-location-ITPL.json");
// profile.setPreference("browser.helperApps.neverAsk.openFile",
// "application/pdf");
// profile.setPreference("browser.helperApps.alwaysAsk.force", false);
/*
* profile.setPreference("browser.download.manager.alertOnEXEOpen",
* false);
* profile.setPreference("browser.download.manager.focusWhenStarting",
* false); profile.setPreference("browser.download.manager.useWindow",
* false);
* profile.setPreference("browser.download.manager.showAlertOnComplete",
* false);
* profile.setPreference("browser.download.manager.closeWhenDone",
* false);
*/
return profile;
}
```
|
13,043,111 |
I am new to Swing, UI and MVC
I have created a code based on MVC. Now my problem is that that in the controller part i have an actioneventlistener which listens to different button clicks. Out of all those buttons i have "select all" and "de-select all". In my view i have a table, one of the column of that table contains "check boxes". Now, when i click the "select-all" button i want to check all the check boxes and with "de-select all" i want to uncheck all of them.
Below is my code which is not working. Please tell me what am i doing wrong here. Also, if someone knows a more elagent way please share. Thanks
In my view
```
public class CustomerSelectorDialogUI extends JFrame{
public CustomerSelectorDialogUI(TestApplicationUI ownerView, DummyCustomerStore dCStore, boolean modality) {
//super(ownerView, modality);
setTitle("[=] Customer Selection Dialog [=]");
//setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
custSelectPanel = new JPanel();
buttonPanel = new JPanel();
selectAllButton = new JButton(" Select All ");
clearAllButton = new JButton(" Clear All ");
applyButton = new JButton(" Apply ");
cancelButton = new JButton(" Cancel ");
PopulateAndShow(dCStore, Boolean.FALSE);
}
public void PopulateAndShow(DummyCustomerStore dCStore, Boolean select) {
List data = new ArrayList();
for (Customer customer : dCStore.getAllCustomers()) {
Object record[] = new Object[COLUMN_COUNT];
record[0] = (select == false) ? Boolean.FALSE : Boolean.TRUE;
record[1] = Integer.toString(customer.customerId);
record[2] = customer.fullName;
data.add(record);
}
tModel = new TableModel(data);
// In the above for loop accoring to user input (i.e click on check all or
// uncheck all) i have tried to update the data. As it can be seen that i
// have a condition for record[0].
//After the loop, here i have tried several options like validate(). repaint but to no avail
customerTable = new JTable(tModel);
scrollPane = new JScrollPane(customerTable);
setContentPane(this.createContentPane());
setSize(480, 580);
setResizable(false);
setVisible(true);
}
private JPanel createContentPane() {
custSelectPanel.setLayout(null);
customerTable.setDragEnabled(false);
customerTable.setFillsViewportHeight(true);
scrollPane.setLocation(10, 10);
scrollPane.setSize(450,450);
custSelectPanel.add(scrollPane);
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 480);
buttonPanel.setSize(450, 100);
custSelectPanel.add(buttonPanel);
selectAllButton.setLocation(0, 0);
selectAllButton.setSize(100, 40);
buttonPanel.add(selectAllButton);
clearAllButton.setLocation(110, 0);
clearAllButton.setSize(100, 40);
buttonPanel.add(clearAllButton);
applyButton.setLocation(240, 0);
applyButton.setSize(100, 40);
buttonPanel.add(applyButton);
cancelButton.setLocation(350, 0);
cancelButton.setSize(100, 40);
buttonPanel.add(cancelButton);
return custSelectPanel;
}
}
```
Table Model
```
private class TableModel extends AbstractTableModel {
private List data;
public TableModel(List data) {
this.data = data;
}
private String[] columnNames = {"Selected ",
"Customer Id ",
"Customer Name "
};
public int getColumnCount() {
return COLUMN_COUNT;
}
public int getRowCount() {
return data == null ? 0 : data.size();
}
public String getColumnName(int col) {
return columnNames[col];
}
public void setValueAt(Object value, int rowIndex, int columnIndex) {
getRecord(rowIndex)[columnIndex] = value;
super.fireTableCellUpdated(rowIndex, columnIndex);
}
private Object[] getRecord(int rowIndex) {
return (Object[]) data.get(rowIndex);
}
public Object getValueAt(int rowIndex, int columnIndex) {
return getRecord(rowIndex)[columnIndex];
}
public Class getColumnClass(int columnIndex) {
if (data == null || data.size() == 0) {
return Object.class;
}
Object o = getValueAt(0, columnIndex);
return o == null ? Object.class : o.getClass();
}
public boolean isCellEditable(int row, int col) {
if (col > 0) {
return false;
} else {
return true;
}
}
}
}
```
A Views Action Listener
```
class CustomerSelectorUIListener implements ActionListener{
CustomerSelectorDialogUI custSelectView;
Controller controller;
public CustomerSelectorUIListener (Controller controller, CustomerSelectorDialogUI custSelectView) {
this.custSelectView = custSelectView;
this.controller = controller;
}
@Override
public void actionPerformed(ActionEvent e) {
String actionEvent = e.getActionCommand();
else if ( actionEvent.equals( "clearAllButton" ) )
{
controller.checkButtonControl(false);
}
else if ( actionEvent.equals( "selectAllButton" ) )
{
controller.checkButtonControl(true);
}
}
}
```
Main Controller
```
public class Controller implements ActionListener{
CustomerSelectorDialogUI selectUI;
DummyCustomerStore store;
public Controller( DummyCustomerStore store, TestApplicationUI appUI )
{
this.store = store;
this.appUI = appUI;
appUI.ButtonListener( this );
}
@Override
public void actionPerformed(ActionEvent event) {
String viewAction = event.getActionCommand();
if (viewAction.equals("TEST")) {
selectUI = new CustomerSelectorDialogUI(appUI, store, true);
selectUI.showTextActionListeners(new CustomerSelectorUIListener( this, selectUI ) );
selectUI.setVisible( true );
}
}
public void checkButtonControl (Boolean checkAll) {
selectUI.PopulateAndShow(store, checkAll);
}
}
```
|
2012/10/24
|
['https://Stackoverflow.com/questions/13043111', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1010943/']
|
It looks like the issue is related to the way you recreate the table once the button is clicked. You are creating a new table and adding it to a content pane. However the old controls also remain there. If you add:
```
getContentPane().removeAll();
```
Before calling:
```
setContentPane(this.createContentPane());
```
It should fix the immediate issue. However, you should consider using much more efficient way of updating the table - simply update the model or replace it. Removing the whole table is not necessary.
EDIT:
Here is a simplfied example how to update the model:
```
public void toggleSelection(Boolean select) {
for (int rowIndex = 0; rowIndex < tModel.getRowCount(); rowIndex++) {
tModel.setValueAt(select, rowIndex, 0);
}
}
```
Then, just execute this method from the controller.
You can also rebuild the model if necessary, ie (again, simplified):
```
public void toggleSelection(Boolean select) {
List data = new ArrayList();
for (int idx = 0; idx < 5; idx++){
Object record[] = new Object[] {select, "test", "test"};
data.add(record);
}
TableModel model = new TableModel(data);
customerTable.setModel(model);
}
```
|
adding `revalidate()` in `PopulateAndShow` may help
```
setSize(480, 580);
setResizable(false);
setVisible(true);
revalidate();
```
|
16,817,377 |
I have passed a value from one page to another in array. I can extract first two vars by explode but I can't get the third value which is formed in an array out.
This is my array:
```
$user_rate=$_POST['user_rate'];//15000|ss|Array
list($total,$promo,$rate)=explode("|",$user_rate);
```
So I get:
```
$total=15000;
$promo=ss;
$rate=Array;
```
While Array comes from the previous page by looping the daily rate and put in an array. And I need to know what each rate is, so I wrote:
```
foreach($rate as $val){
echo "$val<br>";
}
```
But it shows nothing. How can I get this?
Updated : This is the code before the var is sent.
```
echo "
<tr>
<td align=\"right\" colspan=\"3\">Total</td>
<td align=\"right\"><label for=\"promo_3\"><input type=\"radio\" name=\"user_rate\" id=\"promo_3\" value=\"$ss_total|ss|$cost_ss\" /> <u><b>".number_format($ss_total)."</b></u></label></td>
<td align=\"right\"><label for=\"promo_1\"><input type=\"radio\" name=\"user_rate\" id=\"promo_1\" value=\"$net_total|nc|$cost_nr\" checked/> <u><b>".number_format($net_total)."</b></u></label></td>
</tr>";
```
**AND THIS FORMAT OF VALUE CANNOT CHANGE BECAUSE I NEED IT FOR A LATER JAVASCRIPT EXTRACT**
While **$cost\_ss** and **$cost\_nr** are derived from database query looping.
```
while($rec=mysql_fetch_array($result)){
$cost_ss[]=$rec['rate_ss'];
$cost_nr[]=$rec['rate_nr'];
}
```
|
2013/05/29
|
['https://Stackoverflow.com/questions/16817377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620626/']
|
this probably be a wrong `$user_rate=$_POST['user_rate'];//15000|ss|Array`
you can use `serialize / unserialize` for array
|
You could `serialize` your array parameters before you pass it. Then `unserialize` them on the 2nd page.
```
$rate = serialize($rate);
```
On your 2nd page before you run it through the loop:
```
$rate = unserialize($rate);
```
|
16,817,377 |
I have passed a value from one page to another in array. I can extract first two vars by explode but I can't get the third value which is formed in an array out.
This is my array:
```
$user_rate=$_POST['user_rate'];//15000|ss|Array
list($total,$promo,$rate)=explode("|",$user_rate);
```
So I get:
```
$total=15000;
$promo=ss;
$rate=Array;
```
While Array comes from the previous page by looping the daily rate and put in an array. And I need to know what each rate is, so I wrote:
```
foreach($rate as $val){
echo "$val<br>";
}
```
But it shows nothing. How can I get this?
Updated : This is the code before the var is sent.
```
echo "
<tr>
<td align=\"right\" colspan=\"3\">Total</td>
<td align=\"right\"><label for=\"promo_3\"><input type=\"radio\" name=\"user_rate\" id=\"promo_3\" value=\"$ss_total|ss|$cost_ss\" /> <u><b>".number_format($ss_total)."</b></u></label></td>
<td align=\"right\"><label for=\"promo_1\"><input type=\"radio\" name=\"user_rate\" id=\"promo_1\" value=\"$net_total|nc|$cost_nr\" checked/> <u><b>".number_format($net_total)."</b></u></label></td>
</tr>";
```
**AND THIS FORMAT OF VALUE CANNOT CHANGE BECAUSE I NEED IT FOR A LATER JAVASCRIPT EXTRACT**
While **$cost\_ss** and **$cost\_nr** are derived from database query looping.
```
while($rec=mysql_fetch_array($result)){
$cost_ss[]=$rec['rate_ss'];
$cost_nr[]=$rec['rate_nr'];
}
```
|
2013/05/29
|
['https://Stackoverflow.com/questions/16817377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620626/']
|
You could `serialize` your array parameters before you pass it. Then `unserialize` them on the 2nd page.
```
$rate = serialize($rate);
```
On your 2nd page before you run it through the loop:
```
$rate = unserialize($rate);
```
|
Hi i think that i understand you probleme, when you passe and array from as string try to "serialize" it and "unserialize" it in the other page, for exemple :
```
$array = serialize(array('toto', 'titi', array('coco', 'cici')));
```
will give you somthing like this
`a:3:{i:0;s:4:"toto";i:1;s:4:"titi";i:2;a:2:{i:0;s:4:"coco";i:1;s:4:"cici";}}`
and if you use`unserialize($array);` it will give you your array back
|
16,817,377 |
I have passed a value from one page to another in array. I can extract first two vars by explode but I can't get the third value which is formed in an array out.
This is my array:
```
$user_rate=$_POST['user_rate'];//15000|ss|Array
list($total,$promo,$rate)=explode("|",$user_rate);
```
So I get:
```
$total=15000;
$promo=ss;
$rate=Array;
```
While Array comes from the previous page by looping the daily rate and put in an array. And I need to know what each rate is, so I wrote:
```
foreach($rate as $val){
echo "$val<br>";
}
```
But it shows nothing. How can I get this?
Updated : This is the code before the var is sent.
```
echo "
<tr>
<td align=\"right\" colspan=\"3\">Total</td>
<td align=\"right\"><label for=\"promo_3\"><input type=\"radio\" name=\"user_rate\" id=\"promo_3\" value=\"$ss_total|ss|$cost_ss\" /> <u><b>".number_format($ss_total)."</b></u></label></td>
<td align=\"right\"><label for=\"promo_1\"><input type=\"radio\" name=\"user_rate\" id=\"promo_1\" value=\"$net_total|nc|$cost_nr\" checked/> <u><b>".number_format($net_total)."</b></u></label></td>
</tr>";
```
**AND THIS FORMAT OF VALUE CANNOT CHANGE BECAUSE I NEED IT FOR A LATER JAVASCRIPT EXTRACT**
While **$cost\_ss** and **$cost\_nr** are derived from database query looping.
```
while($rec=mysql_fetch_array($result)){
$cost_ss[]=$rec['rate_ss'];
$cost_nr[]=$rec['rate_nr'];
}
```
|
2013/05/29
|
['https://Stackoverflow.com/questions/16817377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620626/']
|
this probably be a wrong `$user_rate=$_POST['user_rate'];//15000|ss|Array`
you can use `serialize / unserialize` for array
|
ok, many answers and no luck... i'll try it again:
you have an array $rate before you submit your form:
```
foreach($rate as $val){
echo "$val<br>";
}
```
and you want to add $ss\_total and the string "ss" and submit it
so you need to:
```
$newarray = array('rate'=>$rate, 'type'=>'ss', 'ss_total'=>$ss_total);
// now you have a 2-dimensional array ($newarray)
// the next step is to prepare it for form-submitting (serialize and base64_encode):
$stringvalue = base64_encode(serialize($newarray));
// ok, now you are able to submit it as radio-field-value:
echo '<input type="radio" name="user_rate" id="promo_3" value="'.$stringvalue.'" />';
```
when the form is submitted you get a serialized and encoded string in $\_POST['user\_rate'], you can do an echo if you'd like to see how it looks.
Now you need to base64\_decode and unserialize:
```
$arr = unserialize(base64_decode($_POST['user_rate']));
```
and you have now full access to your array:
```
echo $arr['type']."<br />";
echo $arr['ss_total']."<br />";
echo $arr['rate']['index_of_rate']; // i dont know the keys of rate array...
```
access $arr in javascript:
```
echo "<script>";
echo "var jsarr = ".json_encode($arr).";\n";
echo "alert(jsarr.ss_total);\n";
echo "</script>";
```
I hope you get it now.
|
16,817,377 |
I have passed a value from one page to another in array. I can extract first two vars by explode but I can't get the third value which is formed in an array out.
This is my array:
```
$user_rate=$_POST['user_rate'];//15000|ss|Array
list($total,$promo,$rate)=explode("|",$user_rate);
```
So I get:
```
$total=15000;
$promo=ss;
$rate=Array;
```
While Array comes from the previous page by looping the daily rate and put in an array. And I need to know what each rate is, so I wrote:
```
foreach($rate as $val){
echo "$val<br>";
}
```
But it shows nothing. How can I get this?
Updated : This is the code before the var is sent.
```
echo "
<tr>
<td align=\"right\" colspan=\"3\">Total</td>
<td align=\"right\"><label for=\"promo_3\"><input type=\"radio\" name=\"user_rate\" id=\"promo_3\" value=\"$ss_total|ss|$cost_ss\" /> <u><b>".number_format($ss_total)."</b></u></label></td>
<td align=\"right\"><label for=\"promo_1\"><input type=\"radio\" name=\"user_rate\" id=\"promo_1\" value=\"$net_total|nc|$cost_nr\" checked/> <u><b>".number_format($net_total)."</b></u></label></td>
</tr>";
```
**AND THIS FORMAT OF VALUE CANNOT CHANGE BECAUSE I NEED IT FOR A LATER JAVASCRIPT EXTRACT**
While **$cost\_ss** and **$cost\_nr** are derived from database query looping.
```
while($rec=mysql_fetch_array($result)){
$cost_ss[]=$rec['rate_ss'];
$cost_nr[]=$rec['rate_nr'];
}
```
|
2013/05/29
|
['https://Stackoverflow.com/questions/16817377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620626/']
|
ok, many answers and no luck... i'll try it again:
you have an array $rate before you submit your form:
```
foreach($rate as $val){
echo "$val<br>";
}
```
and you want to add $ss\_total and the string "ss" and submit it
so you need to:
```
$newarray = array('rate'=>$rate, 'type'=>'ss', 'ss_total'=>$ss_total);
// now you have a 2-dimensional array ($newarray)
// the next step is to prepare it for form-submitting (serialize and base64_encode):
$stringvalue = base64_encode(serialize($newarray));
// ok, now you are able to submit it as radio-field-value:
echo '<input type="radio" name="user_rate" id="promo_3" value="'.$stringvalue.'" />';
```
when the form is submitted you get a serialized and encoded string in $\_POST['user\_rate'], you can do an echo if you'd like to see how it looks.
Now you need to base64\_decode and unserialize:
```
$arr = unserialize(base64_decode($_POST['user_rate']));
```
and you have now full access to your array:
```
echo $arr['type']."<br />";
echo $arr['ss_total']."<br />";
echo $arr['rate']['index_of_rate']; // i dont know the keys of rate array...
```
access $arr in javascript:
```
echo "<script>";
echo "var jsarr = ".json_encode($arr).";\n";
echo "alert(jsarr.ss_total);\n";
echo "</script>";
```
I hope you get it now.
|
Hi i think that i understand you probleme, when you passe and array from as string try to "serialize" it and "unserialize" it in the other page, for exemple :
```
$array = serialize(array('toto', 'titi', array('coco', 'cici')));
```
will give you somthing like this
`a:3:{i:0;s:4:"toto";i:1;s:4:"titi";i:2;a:2:{i:0;s:4:"coco";i:1;s:4:"cici";}}`
and if you use`unserialize($array);` it will give you your array back
|
16,817,377 |
I have passed a value from one page to another in array. I can extract first two vars by explode but I can't get the third value which is formed in an array out.
This is my array:
```
$user_rate=$_POST['user_rate'];//15000|ss|Array
list($total,$promo,$rate)=explode("|",$user_rate);
```
So I get:
```
$total=15000;
$promo=ss;
$rate=Array;
```
While Array comes from the previous page by looping the daily rate and put in an array. And I need to know what each rate is, so I wrote:
```
foreach($rate as $val){
echo "$val<br>";
}
```
But it shows nothing. How can I get this?
Updated : This is the code before the var is sent.
```
echo "
<tr>
<td align=\"right\" colspan=\"3\">Total</td>
<td align=\"right\"><label for=\"promo_3\"><input type=\"radio\" name=\"user_rate\" id=\"promo_3\" value=\"$ss_total|ss|$cost_ss\" /> <u><b>".number_format($ss_total)."</b></u></label></td>
<td align=\"right\"><label for=\"promo_1\"><input type=\"radio\" name=\"user_rate\" id=\"promo_1\" value=\"$net_total|nc|$cost_nr\" checked/> <u><b>".number_format($net_total)."</b></u></label></td>
</tr>";
```
**AND THIS FORMAT OF VALUE CANNOT CHANGE BECAUSE I NEED IT FOR A LATER JAVASCRIPT EXTRACT**
While **$cost\_ss** and **$cost\_nr** are derived from database query looping.
```
while($rec=mysql_fetch_array($result)){
$cost_ss[]=$rec['rate_ss'];
$cost_nr[]=$rec['rate_nr'];
}
```
|
2013/05/29
|
['https://Stackoverflow.com/questions/16817377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620626/']
|
this probably be a wrong `$user_rate=$_POST['user_rate'];//15000|ss|Array`
you can use `serialize / unserialize` for array
|
Hi i think that i understand you probleme, when you passe and array from as string try to "serialize" it and "unserialize" it in the other page, for exemple :
```
$array = serialize(array('toto', 'titi', array('coco', 'cici')));
```
will give you somthing like this
`a:3:{i:0;s:4:"toto";i:1;s:4:"titi";i:2;a:2:{i:0;s:4:"coco";i:1;s:4:"cici";}}`
and if you use`unserialize($array);` it will give you your array back
|
16,817,377 |
I have passed a value from one page to another in array. I can extract first two vars by explode but I can't get the third value which is formed in an array out.
This is my array:
```
$user_rate=$_POST['user_rate'];//15000|ss|Array
list($total,$promo,$rate)=explode("|",$user_rate);
```
So I get:
```
$total=15000;
$promo=ss;
$rate=Array;
```
While Array comes from the previous page by looping the daily rate and put in an array. And I need to know what each rate is, so I wrote:
```
foreach($rate as $val){
echo "$val<br>";
}
```
But it shows nothing. How can I get this?
Updated : This is the code before the var is sent.
```
echo "
<tr>
<td align=\"right\" colspan=\"3\">Total</td>
<td align=\"right\"><label for=\"promo_3\"><input type=\"radio\" name=\"user_rate\" id=\"promo_3\" value=\"$ss_total|ss|$cost_ss\" /> <u><b>".number_format($ss_total)."</b></u></label></td>
<td align=\"right\"><label for=\"promo_1\"><input type=\"radio\" name=\"user_rate\" id=\"promo_1\" value=\"$net_total|nc|$cost_nr\" checked/> <u><b>".number_format($net_total)."</b></u></label></td>
</tr>";
```
**AND THIS FORMAT OF VALUE CANNOT CHANGE BECAUSE I NEED IT FOR A LATER JAVASCRIPT EXTRACT**
While **$cost\_ss** and **$cost\_nr** are derived from database query looping.
```
while($rec=mysql_fetch_array($result)){
$cost_ss[]=$rec['rate_ss'];
$cost_nr[]=$rec['rate_nr'];
}
```
|
2013/05/29
|
['https://Stackoverflow.com/questions/16817377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620626/']
|
this probably be a wrong `$user_rate=$_POST['user_rate'];//15000|ss|Array`
you can use `serialize / unserialize` for array
|
you can encode the values on the page as
```
implode("|", array($total, $promo, implode(",",$rate));
```
Then decode it with
```
list($total, $promo, $rates) = explode("|", $_POST["user_rate"]);
$rates = explode(",", $rates);
```
|
16,817,377 |
I have passed a value from one page to another in array. I can extract first two vars by explode but I can't get the third value which is formed in an array out.
This is my array:
```
$user_rate=$_POST['user_rate'];//15000|ss|Array
list($total,$promo,$rate)=explode("|",$user_rate);
```
So I get:
```
$total=15000;
$promo=ss;
$rate=Array;
```
While Array comes from the previous page by looping the daily rate and put in an array. And I need to know what each rate is, so I wrote:
```
foreach($rate as $val){
echo "$val<br>";
}
```
But it shows nothing. How can I get this?
Updated : This is the code before the var is sent.
```
echo "
<tr>
<td align=\"right\" colspan=\"3\">Total</td>
<td align=\"right\"><label for=\"promo_3\"><input type=\"radio\" name=\"user_rate\" id=\"promo_3\" value=\"$ss_total|ss|$cost_ss\" /> <u><b>".number_format($ss_total)."</b></u></label></td>
<td align=\"right\"><label for=\"promo_1\"><input type=\"radio\" name=\"user_rate\" id=\"promo_1\" value=\"$net_total|nc|$cost_nr\" checked/> <u><b>".number_format($net_total)."</b></u></label></td>
</tr>";
```
**AND THIS FORMAT OF VALUE CANNOT CHANGE BECAUSE I NEED IT FOR A LATER JAVASCRIPT EXTRACT**
While **$cost\_ss** and **$cost\_nr** are derived from database query looping.
```
while($rec=mysql_fetch_array($result)){
$cost_ss[]=$rec['rate_ss'];
$cost_nr[]=$rec['rate_nr'];
}
```
|
2013/05/29
|
['https://Stackoverflow.com/questions/16817377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620626/']
|
this probably be a wrong `$user_rate=$_POST['user_rate'];//15000|ss|Array`
you can use `serialize / unserialize` for array
|
Using serialize is definitely the key to getting this to work, but base64\_encode() is the **ideal** way to make it less obfuscated. When you only use serialize, then you get semicolons, commas, double quotes, single quotes, and several other characters that could cause problems when you pass them through to your script that reassembles it.
For instance,
after serializing an array, you will get this, like Sidux pointed out
```
a:3:{i:0;s:4:"toto";i:1;s:4:"titi";i:2;a:2:{i:0;s:4:"coco";i:1;s:4:"cici";}}
```
When you add base64\_encode to the mix you will get an easier value to work with.
```
YTozOntpOjA7czo0OiJ0b3RvIjtpOjE7czo0OiJ0aXRpIjtpOjI7YToyOntpOjA7czo0OiJjb2NvIjtpOjE7czo0OiJjaWNpIjt9fQ==
```
With this, you can easily send/receive your saved array without any trimming, adding of slashes, etcetera.
Assuming you send your data this way, your new code will look like this
```
$user_rate=$_POST['user_rate'];//15000|ss|Array
list($total,$promo,$rate)=explode("|",$user_rate);
$rate = unserialize( base64_decode($rate) );
```
Now, `$rate` is a functional array
|
16,817,377 |
I have passed a value from one page to another in array. I can extract first two vars by explode but I can't get the third value which is formed in an array out.
This is my array:
```
$user_rate=$_POST['user_rate'];//15000|ss|Array
list($total,$promo,$rate)=explode("|",$user_rate);
```
So I get:
```
$total=15000;
$promo=ss;
$rate=Array;
```
While Array comes from the previous page by looping the daily rate and put in an array. And I need to know what each rate is, so I wrote:
```
foreach($rate as $val){
echo "$val<br>";
}
```
But it shows nothing. How can I get this?
Updated : This is the code before the var is sent.
```
echo "
<tr>
<td align=\"right\" colspan=\"3\">Total</td>
<td align=\"right\"><label for=\"promo_3\"><input type=\"radio\" name=\"user_rate\" id=\"promo_3\" value=\"$ss_total|ss|$cost_ss\" /> <u><b>".number_format($ss_total)."</b></u></label></td>
<td align=\"right\"><label for=\"promo_1\"><input type=\"radio\" name=\"user_rate\" id=\"promo_1\" value=\"$net_total|nc|$cost_nr\" checked/> <u><b>".number_format($net_total)."</b></u></label></td>
</tr>";
```
**AND THIS FORMAT OF VALUE CANNOT CHANGE BECAUSE I NEED IT FOR A LATER JAVASCRIPT EXTRACT**
While **$cost\_ss** and **$cost\_nr** are derived from database query looping.
```
while($rec=mysql_fetch_array($result)){
$cost_ss[]=$rec['rate_ss'];
$cost_nr[]=$rec['rate_nr'];
}
```
|
2013/05/29
|
['https://Stackoverflow.com/questions/16817377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620626/']
|
you can encode the values on the page as
```
implode("|", array($total, $promo, implode(",",$rate));
```
Then decode it with
```
list($total, $promo, $rates) = explode("|", $_POST["user_rate"]);
$rates = explode(",", $rates);
```
|
Hi i think that i understand you probleme, when you passe and array from as string try to "serialize" it and "unserialize" it in the other page, for exemple :
```
$array = serialize(array('toto', 'titi', array('coco', 'cici')));
```
will give you somthing like this
`a:3:{i:0;s:4:"toto";i:1;s:4:"titi";i:2;a:2:{i:0;s:4:"coco";i:1;s:4:"cici";}}`
and if you use`unserialize($array);` it will give you your array back
|
16,817,377 |
I have passed a value from one page to another in array. I can extract first two vars by explode but I can't get the third value which is formed in an array out.
This is my array:
```
$user_rate=$_POST['user_rate'];//15000|ss|Array
list($total,$promo,$rate)=explode("|",$user_rate);
```
So I get:
```
$total=15000;
$promo=ss;
$rate=Array;
```
While Array comes from the previous page by looping the daily rate and put in an array. And I need to know what each rate is, so I wrote:
```
foreach($rate as $val){
echo "$val<br>";
}
```
But it shows nothing. How can I get this?
Updated : This is the code before the var is sent.
```
echo "
<tr>
<td align=\"right\" colspan=\"3\">Total</td>
<td align=\"right\"><label for=\"promo_3\"><input type=\"radio\" name=\"user_rate\" id=\"promo_3\" value=\"$ss_total|ss|$cost_ss\" /> <u><b>".number_format($ss_total)."</b></u></label></td>
<td align=\"right\"><label for=\"promo_1\"><input type=\"radio\" name=\"user_rate\" id=\"promo_1\" value=\"$net_total|nc|$cost_nr\" checked/> <u><b>".number_format($net_total)."</b></u></label></td>
</tr>";
```
**AND THIS FORMAT OF VALUE CANNOT CHANGE BECAUSE I NEED IT FOR A LATER JAVASCRIPT EXTRACT**
While **$cost\_ss** and **$cost\_nr** are derived from database query looping.
```
while($rec=mysql_fetch_array($result)){
$cost_ss[]=$rec['rate_ss'];
$cost_nr[]=$rec['rate_nr'];
}
```
|
2013/05/29
|
['https://Stackoverflow.com/questions/16817377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620626/']
|
Using serialize is definitely the key to getting this to work, but base64\_encode() is the **ideal** way to make it less obfuscated. When you only use serialize, then you get semicolons, commas, double quotes, single quotes, and several other characters that could cause problems when you pass them through to your script that reassembles it.
For instance,
after serializing an array, you will get this, like Sidux pointed out
```
a:3:{i:0;s:4:"toto";i:1;s:4:"titi";i:2;a:2:{i:0;s:4:"coco";i:1;s:4:"cici";}}
```
When you add base64\_encode to the mix you will get an easier value to work with.
```
YTozOntpOjA7czo0OiJ0b3RvIjtpOjE7czo0OiJ0aXRpIjtpOjI7YToyOntpOjA7czo0OiJjb2NvIjtpOjE7czo0OiJjaWNpIjt9fQ==
```
With this, you can easily send/receive your saved array without any trimming, adding of slashes, etcetera.
Assuming you send your data this way, your new code will look like this
```
$user_rate=$_POST['user_rate'];//15000|ss|Array
list($total,$promo,$rate)=explode("|",$user_rate);
$rate = unserialize( base64_decode($rate) );
```
Now, `$rate` is a functional array
|
Hi i think that i understand you probleme, when you passe and array from as string try to "serialize" it and "unserialize" it in the other page, for exemple :
```
$array = serialize(array('toto', 'titi', array('coco', 'cici')));
```
will give you somthing like this
`a:3:{i:0;s:4:"toto";i:1;s:4:"titi";i:2;a:2:{i:0;s:4:"coco";i:1;s:4:"cici";}}`
and if you use`unserialize($array);` it will give you your array back
|
12,714,602 |
I am new to class templates and am having trouble. I have a function that doesn't declare (ie. to be an int, double etc). But it doesn't make sense to declare in this function. Therefore I am getting errors. Thanks for the help.
I have the following function:
```
bool QueType<ItemType>::IsEmpty() const
// Returns true if there are no elements on the queue and false otherwise.
{
return (front == NULL);
}
```
This returns the following errors:
Error 1 error C2065: 'ItemType' : undeclared identifier
Error 2 error C2955: 'QueType' : use of class template requires template argument list
Error 3 error C2509: 'IsEmpty' : member function not declared in 'QueType'
|
2012/10/03
|
['https://Stackoverflow.com/questions/12714602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1060794/']
|
You need to put your database name after the MySQL port (:3306/DB\_name). Here's one of my connections:
```
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQL{
static Connection connect;
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
Credentials();
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
String url = "jdbc:mysql://" + host + ":3306/" + datab;
Driver test = DriverManager.getDriver(url);
// testing to make sure i'm using the correct
//driver and further testing host
System.out.println(test);
connect = DriverManager.getConnection(url, userName, password);
System.out.println ("Connected to " + host);
}
}
```
You'll need to supply the "host" and "datab" string values
|
I hate to add a new post to something so old but I ran across the same issues with GoDaddy and their dbname.db.######.hostedresource.com implementation. Granted, I looked across a few Overflow posts and saw no mention of the direct IP method; hopefully I'm not breaking some GoDaddy code here.
Any who, the only way I was able to connect through my Workbench & through JDBC was by going to the PHP admin page and grabbing the direct IP to the database - in my case :
```
private static final String URL = "jdbc:mysql://11.11.111.11:3306/dbname";
```
|
12,714,602 |
I am new to class templates and am having trouble. I have a function that doesn't declare (ie. to be an int, double etc). But it doesn't make sense to declare in this function. Therefore I am getting errors. Thanks for the help.
I have the following function:
```
bool QueType<ItemType>::IsEmpty() const
// Returns true if there are no elements on the queue and false otherwise.
{
return (front == NULL);
}
```
This returns the following errors:
Error 1 error C2065: 'ItemType' : undeclared identifier
Error 2 error C2955: 'QueType' : use of class template requires template argument list
Error 3 error C2509: 'IsEmpty' : member function not declared in 'QueType'
|
2012/10/03
|
['https://Stackoverflow.com/questions/12714602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1060794/']
|
If memory serves, GoDaddy has a couple of different MySQL DB implementations you can choose. One that allows for remote access, and one that does not. Are you sure that you have chosen the correct one?
Have you tried connecting remotely using MySQL Workbench first? Or even telnetting to the port? That will ensure you have the right db name and permissions to connect remotely. Once you can confirm that works, getting the code to work should be easier.
|
I hate to add a new post to something so old but I ran across the same issues with GoDaddy and their dbname.db.######.hostedresource.com implementation. Granted, I looked across a few Overflow posts and saw no mention of the direct IP method; hopefully I'm not breaking some GoDaddy code here.
Any who, the only way I was able to connect through my Workbench & through JDBC was by going to the PHP admin page and grabbing the direct IP to the database - in my case :
```
private static final String URL = "jdbc:mysql://11.11.111.11:3306/dbname";
```
|
28,923,698 |
I want the value in the input to filter the values in the dropdown, and ng-selected to be true for the option that has $index == 0.
When the filter takes action, the value in ng-selected changes to true and the selected property on the element does not change to selected="selected". If I remove the model, it works as intended.
```
<div ng-app ng-controller="AppCtrl" ng-init="sigStyles.companies = ['facebook', 'twitter', 'tumblr', 'myspace']">
<input type="text" ng-model="socialSearch"></input>
<select>
<option ng-repeat="company in sigStyles.companies | filter:socialSearch" value="{{company}}" ng-selected="{{$index === 0}}">{{company}}</option>
</select>
</div>
```
Does someone know how to get the selected property to change or does anyone know how to make a search input to remove options from a select based on its input?
Link to my fiddle [here](https://jsfiddle.net/p0lska/3h69b6my/44/).
|
2015/03/08
|
['https://Stackoverflow.com/questions/28923698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4414626/']
|
So the answer above is correct if not a little verbose. I would not recommend using a watch because I find it to be a little more troublesome. So basically here is what I came up with (feel free to ding me if I missed something but remember I am trying to help :-) [Plnkr](https://jsfiddle.net/partyk1d24/w6tt4esy/8/) **This one I forgot to include the list but it can be included like the second one**.
Basically the JS looks like this...
```
angular.module('myApp', []);
function MainCtrl($scope) {
$scope.options = ['as', 'b', 'c', 'a2'];
$scope.opt1 = 0;
$scope.selectedOpt = $scope.options[0];
$scope.setOption = function() {
if($scope.options.indexOf($scope.inFilter) > -1){
$scope.selectedOpt = $scope.inFilter
};
}
}
```
The set options is just checking to see if the text exists and set the value if it does.
I would probably recommend something more [like this](https://jsfiddle.net/partyk1d24/w6tt4esy/21/) that way if you want to display a message when there are no matches you can.
Hope this helps!
|
We can use the search model to as an argument to the filter to create a new array which is filtered. This array is used in ng-select. Any changes in the search model are watched and used to update the filtered array.
```
<div ng-app="myapp">
<div ng-controller="ctrlParent">
<input type="text" ng-model="search" />
<select ng-model="storedModel" ng-options="opt for opt in filteredArray | filter:search"></select>
</div>
</div>
```
js:
```
var app = angular.module('myapp',[]);
app.controller('ctrlParent',function($scope,filterFilter){
$scope.list = ["facebook","twitter","tumblr","google"];
$scope.filteredArray = $scope.list;
$scope.storedModel = $scope.filteredArray[0];
$scope.$watch('search',function(newValue){
$scope.filteredArray = filterFilter($scope.list, newValue);
$scope.storedModel = $scope.filteredArray[0];
});
});
```
Fiddle of working solution [here](https://jsfiddle.net/p0lska/d79bLw3a/4/).
|
4,019,553 |
Could you give a recommendation for differential geometry or curves and surfaces with lots of examples and calculations?
I need lots of examples to understand a topic therefore it would great if there are some book with good calculations.
|
2021/02/09
|
['https://math.stackexchange.com/questions/4019553', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/740715/']
|
Barrett O'Neill's Elementary Differential Geometry. A classic, you can't go wrong with this one..
[Download link](http://cfile4.uf.tistory.com/attach/141C9D474D800C58102354)
|
The ones I used and liked were:
Differential Geometry of Curves and Surfaces - Manfredo Do Carmo
Modern Differential Geometry of Curves and Surfaces with Mathematica - Alfred Gray
|
4,019,553 |
Could you give a recommendation for differential geometry or curves and surfaces with lots of examples and calculations?
I need lots of examples to understand a topic therefore it would great if there are some book with good calculations.
|
2021/02/09
|
['https://math.stackexchange.com/questions/4019553', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/740715/']
|
The ones I used and liked were:
Differential Geometry of Curves and Surfaces - Manfredo Do Carmo
Modern Differential Geometry of Curves and Surfaces with Mathematica - Alfred Gray
|
For the geometry of surfaces I recommend the book Differential Geometry of Curves and Surfaces by Manfredo Do Carmo, which is clear, self-contained and with a lot of examples and exercises.
If you want to go further and learn modern differential geometry (manifolds etc) an excellent book is An introduction to manifolds by Loring Tu, which contains a lot of examples and explicit calculations. Moreover it is self-contained, and has a lot of appendices in the case you have to strengthen you background.
Another very good book about manifolds is Introduction to smooth manifolds by Lee. You can read some of its chapters as a complement of Tu’s book, indeed it contains some important topics that you can’t find in the book of Loring Tu.
|
4,019,553 |
Could you give a recommendation for differential geometry or curves and surfaces with lots of examples and calculations?
I need lots of examples to understand a topic therefore it would great if there are some book with good calculations.
|
2021/02/09
|
['https://math.stackexchange.com/questions/4019553', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/740715/']
|
Barrett O'Neill's Elementary Differential Geometry. A classic, you can't go wrong with this one..
[Download link](http://cfile4.uf.tistory.com/attach/141C9D474D800C58102354)
|
For the geometry of surfaces I recommend the book Differential Geometry of Curves and Surfaces by Manfredo Do Carmo, which is clear, self-contained and with a lot of examples and exercises.
If you want to go further and learn modern differential geometry (manifolds etc) an excellent book is An introduction to manifolds by Loring Tu, which contains a lot of examples and explicit calculations. Moreover it is self-contained, and has a lot of appendices in the case you have to strengthen you background.
Another very good book about manifolds is Introduction to smooth manifolds by Lee. You can read some of its chapters as a complement of Tu’s book, indeed it contains some important topics that you can’t find in the book of Loring Tu.
|
12,657,317 |
Today I started observing some new kind of error which does not allow me to create a new Android application in Eclipse. It says "Update Tools", Your tools installation appears to be out of date. This wizard depends on templates distributed with the Android SDK Tools...."
I have android 2.2 API 8 which I thought is stable when I started working. Can some one suggest me what this error? Or do I need to update to Android 4.1 API 16? Will the existing project run on that version?
Here are the errors when I tried to update to 2.3.3:
```
[2012-09-29 18:17:22 - SDK Manager] File not found: C:\Program Files (x86)\Android\android-sdk\temp\platform-tools_r14-windows.zip (Access is denied)
[2012-09-29 18:17:23 - SDK Manager] File not found: C:\Program Files (x86)\Android\android-sdk\temp\usb_driver_r07-windows.zip (Access is denied)
[2012-09-29 18:17:24 - SDK Manager] Skipping 'Android SDK Tools, revision 20.0.3'; it depends on 'Android SDK Platform-tools, revision 14' which was not installed.
[2012-09-29 18:18:56 - SDK Manager] File not found: C:\Program Files (x86)\Android\android-sdk\temp\android-2.3.3_r02-linux.zip (Access is denied)
[2012-09-29 18:18:57 - SDK Manager] File not found: C:\Program Files (x86)\Android\android-sdk\temp\samples-2.3.3_r01-linux.zip (Access is denied)
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Google APIs, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Intel Atom x86 System Image, Android API 10, revision 1'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Dual Screen APIs, Android API 10, revision 1'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Real3D, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'ADMIRAL, Android API 10, revision 5'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'ATRIX2, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Bionic, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'defy+, Android API 10, revision 1'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Droid4, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'DroidRAZR, Android API 10, revision 5'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'MotorolaPro+, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'MT870, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'MT917, Android API 10, revision 1'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'PHOTON, Android API 10, revision 1'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'XT882, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'XT928, Android API 10, revision 3'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Sony Xperia Extensions EDK 2.0, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
```
|
2012/09/29
|
['https://Stackoverflow.com/questions/12657317', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1494754/']
|
best things to do that is recommended by google is to use the latest version of the sdk version.
set the targetSdkVersion to the latest one (currently it's 16) and also set it in the project.properties file . this will allow your app to be optimized for the newest android version and also allow you to use the latest classes and functions . you also get fuller API javadocs and more constants.
of course , you need to know that if you use a function or a class that is supported only on a new version , the app will crush on old versions . constants are safe to use since they are converted to simple strings and values .
that's why you should run Lint before you publish the app , to make sure that such a thing won't happen.
|
You can safely update your Android SDK tools and still support Android 2.2 (API 8). Once you download the SDK tools, you can choose for which platforms you want to develop, and there you can select API 8. Anything you develop for Android 2.2 will work for Android 4.1.
|
12,657,317 |
Today I started observing some new kind of error which does not allow me to create a new Android application in Eclipse. It says "Update Tools", Your tools installation appears to be out of date. This wizard depends on templates distributed with the Android SDK Tools...."
I have android 2.2 API 8 which I thought is stable when I started working. Can some one suggest me what this error? Or do I need to update to Android 4.1 API 16? Will the existing project run on that version?
Here are the errors when I tried to update to 2.3.3:
```
[2012-09-29 18:17:22 - SDK Manager] File not found: C:\Program Files (x86)\Android\android-sdk\temp\platform-tools_r14-windows.zip (Access is denied)
[2012-09-29 18:17:23 - SDK Manager] File not found: C:\Program Files (x86)\Android\android-sdk\temp\usb_driver_r07-windows.zip (Access is denied)
[2012-09-29 18:17:24 - SDK Manager] Skipping 'Android SDK Tools, revision 20.0.3'; it depends on 'Android SDK Platform-tools, revision 14' which was not installed.
[2012-09-29 18:18:56 - SDK Manager] File not found: C:\Program Files (x86)\Android\android-sdk\temp\android-2.3.3_r02-linux.zip (Access is denied)
[2012-09-29 18:18:57 - SDK Manager] File not found: C:\Program Files (x86)\Android\android-sdk\temp\samples-2.3.3_r01-linux.zip (Access is denied)
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Google APIs, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Intel Atom x86 System Image, Android API 10, revision 1'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Dual Screen APIs, Android API 10, revision 1'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Real3D, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'ADMIRAL, Android API 10, revision 5'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'ATRIX2, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Bionic, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'defy+, Android API 10, revision 1'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Droid4, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'DroidRAZR, Android API 10, revision 5'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'MotorolaPro+, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'MT870, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'MT917, Android API 10, revision 1'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'PHOTON, Android API 10, revision 1'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'XT882, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'XT928, Android API 10, revision 3'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
[2012-09-29 18:18:58 - SDK Manager] Skipping 'Sony Xperia Extensions EDK 2.0, Android API 10, revision 2'; it depends on 'SDK Platform Android 2.3.3, API 10, revision 2' which was not installed.
```
|
2012/09/29
|
['https://Stackoverflow.com/questions/12657317', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1494754/']
|
best things to do that is recommended by google is to use the latest version of the sdk version.
set the targetSdkVersion to the latest one (currently it's 16) and also set it in the project.properties file . this will allow your app to be optimized for the newest android version and also allow you to use the latest classes and functions . you also get fuller API javadocs and more constants.
of course , you need to know that if you use a function or a class that is supported only on a new version , the app will crush on old versions . constants are safe to use since they are converted to simple strings and values .
that's why you should run Lint before you publish the app , to make sure that such a thing won't happen.
|
* Right Click SDK Manager
* Select Run As Administrator
* Click the YES button
|
47,405,426 |
I am using the following formula to yield a 1 if a CS number exists in the cell, and a 0 if it does not. The nested formula works correctly.
The issue is with the outside IF function. What happens is that when it does not find a CS number, it yields `#VALUE!` in the cell. When that happens, I want the cell to say 1.
Using the function below, it still is filling in `#VALUE!` when a CS number is not found.
```
=IF(IF(ISERR(NUMBERVALUE(MID(K2,SEARCH("CS",K2)+M39,1))),MID(K2,SEARCH("CS",K2),9),MID(K2,SEARCH("CS",K2),10)) = "#VALUE!", 1, 0)
```
Is there a more appropriate way to reference this to yield 1 instead?
|
2017/11/21
|
['https://Stackoverflow.com/questions/47405426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5389099/']
|
Ironically, *`#VALUE!` isn't a Value*, so you can't use a comparison function like `If` to deal with it as if it's a string.
Change your formula to:
```
=IFERROR(IF(ISERR(NUMBERVALUE(MID(K2,SEARCH("CS",K2)+M39,1))),MID(K2,SEARCH("CS",K2),9),MID(K2,SEARCH("CS",K2),10)),1)
```
...and it will return a `1` instead of `#VALUE!` if the text you're searching for isn't found.
* [Here is a handy guide](http://www.exceltactics.com/definitive-guide-excel-error-types-error-handling/) to Excel formula errors and how to handle them:
|
Did you try
```
=IFERROR( your formula here, 1 )
```
Basically, it evaluates your formula as usual, but when *anything* in your formula returns an error, you will get an 1 in return.
Using this idea, you can wrap each part of your formula in an IFERROR to define the default value to return whenever it encounters one. Kinda wasteful though.
|
51,296,572 |
It seems that there are two ways to define a sealed class, which one is corret between Code A and CodeB ?
**Code A**
```
sealed class ExprA
data class Const(val number: Double) : ExprA()
data class Sum(val e1: ExprA, val e2: ExprA) : ExprA()
```
**Code B**
```
sealed class ExprB{
data class Const(val number: Double) : ExprB()
data class Sum(val e1: ExprB, val e2: ExprB) : ExprB()
}
```
|
2018/07/12
|
['https://Stackoverflow.com/questions/51296572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/828896/']
|
<https://kotlinlang.org/docs/reference/sealed-classes.html>
>
> To declare a sealed class, you put the sealed modifier before the name of the class. A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class itself. (Before Kotlin 1.1, the rules were even more strict: classes had to be nested inside the declaration of the sealed class).
>
>
>
If you're on < kotlin 1.1, then you MUST nest the classes in the sealed class; otherwise, you can declare them outside BUT those classes must be in the same file. Both are correct for kotlin >= 1.1
|
I can't say I've personally used the first way to write a sealed class so I'm not sure if that is syntactically correct. If it is, it would really be a preference of code style. From a maintenance perspective, I would personally prefer the second because it is easier to read and ensure what is encapsulated in that sealed class.
|
15,127,388 |
Hello Dear Stack Overflow friends! I've been trying to solve this problem for a couple of days with no success. I've read almost every post available here at Stack Overflow but I can't find out how to solve this.
When I share a link on Facebook, the thumbnail corresponds to the image I defined in the
meta property="og:image"
It works and everything is fine there... But,
I would like that each post could display its own featured image as a thumbnail when shared. How on earth can I do that?
I've tried with this code in function.php
```
function insert_image_src_rel_in_head() {
global $post;
if ( !is_singular()) //if it is not a post or a page
return;
if(!has_post_thumbnail( $post->ID )) { //the post does not have featured image, use a default image
$default_image="http://example.com/image.jpg"; //replace this with a default image on your server or an image in your media library
echo '<meta property="og:image" content="' . $default_image . '"/>';
}
else{
$thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
echo '<meta property="og:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/>';
}
echo "
";
} add_action( 'wp_head', 'insert_image_src_rel_in_head', 5 );
```
And nothing happens...
I've also tried this code in header.php
```
<?php
global $wp_query;
$thePostID = $wp_query->post->ID;
if( has_post_thumbnail( $thePostID )){
$thumb_id = get_post_thumbnail_id( $thePostID );
$image = wp_get_attachment_image_src( $thumb_id );
echo '<meta property="og:image" content="'.$image[0].'" />';
} ?>
```
No success there either.
The featured image is activated in the functions.php like this.
```
add_theme_support('post-thumbnails');
```
As I said, all og tags are set.
What Is happening? It's not a cache thing because I'm using the facebook debugger to flush it.
I will be eternally grateful if anybody out there can help me.
Thanks a lot.
Benjamin.
|
2013/02/28
|
['https://Stackoverflow.com/questions/15127388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2118014/']
|
I just found that code in my production.log
```
GET "/assets/&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["
```
Rails 3.2.13 dealt with it with `Completed 406 Not Acceptable`
|
I found the same in my logs but in november 2012:
`ActionController::RoutingError (No route matches [GET] "/assets/&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["):`
|
38,007,738 |
I have an encoding program which allows the user to enter some text and a password to send messages securely.
However, when I try to run the following code, JQuery does not work properly:
```
text = CryptoJS.AES.encrypt(text, pass);
$("#encodedText").html(text);
```
```html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
<link rel="icon" sizes="192x192" href="http://www.tdat.byethost10.com/web_images/favicon.ico">
<link rel="apple-touch-startup-image" href="http://www.tdat.byethost10.com/web_images/favicon.ico">
<link rel="shortcut icon" href="" type="image/icon">
<link rel="icon" href="http://www.tdat.byethost10.com/web_images/favicon.ico" type="image/icon">
<meta name="viewport" content="width = device-width">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<meta name="mobile-web-app-capable" content="yes">
<title>ENCRYPT</title>
<meta charset="UTF-8">
</head>
<style>
#first {
font-family: "courier";
text-align: center;
color: #00FF04;
}
#second {
color: white;
}
#myDIV {
border: 1px solid green;
margin-bottom: 10px;
}
button {
border-radius: 50%;
background-color: #00FF04;
border-color: #00FF04;
color: white;
font-size: 40px;
transition-duration: 0.4s;
width: 25%;
height: 80px;
}
button:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0, 0, 0, 0.19);
background-color: red;
border-color: red;
}
.searchTxt {
color: #00FF04;
font-family: "courier";
border: solid #00FF04;
border-radius: 5px;
background-color: black;
}
.heading {
font-size: 80px
}
</style>
<body bgcolor="black" id="first">
<p class="heading">ENCODE TEXT</p>
<p>
Your text:
</p>
<br>
<input class="searchTxt" size="50" id="textToEncode">
<br>
<p>Your password:</p>
<br>
<input class="searchTxt" size="50" id="textToRedact">
<br>
<br>
<br>
<button id="encodeButton">Encode!</button>
<br>
<br>
<br>
<br>
<p id="encodedText"></p>
<p class="heading">DECODE TEXT</p>
<p>Text:</p>
<br>
<input class="searchTxt" size="50" id="textToDecode">
<br>
<p>Key:</p>
<br>
<input class="searchTxt" size="50" id="keyForDecode">
<br>
<br>
<br>
<button id="decodeButton">Decode!</button>
<br>
<br>
<br>
<br>
<p id="decodedText"></p>
<script>
var text = "";
var word = "";
var redacted = "";
var encodedInfo = [];
var key = "";
var pass = "";
$("#encodeButton").on("click", function() {
$("#key").html("");
$("#encodedText").html("");
encodedInfo = [];
redacted = "";
text = $("#textToEncode").val();
pass = $("#textToRedact").val();
text = CryptoJS.AES.encrypt(text, pass);
alert("Your encrypted message is as such: " + text);
$("#encodedText").html(text);
});
$("#decodeButton").on("click", function() {
$("#decodedText").html("");
redacted = "";
word = "REDACTED";
text = $("#textToDecode").val();
key = $("#keyForDecode").val();
decrypted = CryptoJS.AES.decrypt(text, key);
decrypted = decrypted.toString(CryptoJS.enc.Utf8);
if (decrypted === "") {
alert("FAIL!!! Wrong password.");
} else {
$("#decodedText").html(decrypted);
alert("The message is: " + decrypted);
}
});
</script>
</body>
</html>
```
As you can see in the snippet it correctly alerts you the encoded message, but it does not change the value of `#encodedText`. Why might this be so?
LIVE DEMO: [redacted.ga/advance.html](http://redacted.ga/advance.html)
|
2016/06/24
|
['https://Stackoverflow.com/questions/38007738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
A lot of it depends on how you gathered the data. Often ratings that seem explicit can actually be implicit. For instance, assume you give the option of allowing users to rate items that they have purchased / used before. This means that the very fact that they have spent their time evaluating that particular item means that the item is of a high quality. As such, items of poor quality are not rated at all because people do not even bother to use them. As such, even though the dataset is intended to be explicit, you may get better results because if you consider the results to be implicit. Again, this varies significantly based on how the data is obtained.
|
The explict data (like ratings) normally comes with bias - people go and rate a product because they like it! Think about your experience shopping and then rating on Amazon.com :-)
On the contrary, implict info often can truly reflect user's favor on a product, like viewing duration, comment length, etc. Even a like/dislike is better that rating because it provides a very simple 'bad' option without bothering a user to think "if I should give a 3, 3.5, or 4?".
|
1,017,598 |
I have a need for a "run once" query (so performance isn't that critical) using tables similar to these (simplified versions of the actual):
```
CREATE TABLE #Items
( ItemPK int not null primary key
,ItemDescription varchar(25) not null
)
INSERT INTO #Items VALUES (1,'rock')
INSERT INTO #Items VALUES (2,'wood')
INSERT INTO #Items VALUES (3,'plastic')
CREATE TABLE #ItemTypes
( ItemType char(1) not null primary key
,ItemTypeDescription varchar(25) not null
)
INSERT INTO #ItemTypes VALUES ('A','Type A')
INSERT INTO #ItemTypes VALUES ('B','BBBBB')
INSERT INTO #ItemTypes VALUES ('C','Color')
CREATE TABLE #ItemInfo
( InfoPK int not null primary key identity(1,1)
,ItemPK int not null foreign key references #ListOfItems.ItemPK
,ItemType char(1) not null foreign key references #ItemTypes.ItemType
,ItemValue varchar(10) not null
)
INSERT INTO #ItemInfo VALUES (1,'A','hard')
INSERT INTO #ItemInfo VALUES (1,'A','natural')
INSERT INTO #ItemInfo VALUES (1,'B','cold')
INSERT INTO #ItemInfo VALUES (1,'C','gray')
INSERT INTO #ItemInfo VALUES (2,'B','grain')
INSERT INTO #ItemInfo VALUES (2,'B','brown')
INSERT INTO #ItemInfo VALUES (3,'A','flexible')
INSERT INTO #ItemInfo VALUES (3,'A','colorful')
INSERT INTO #ItemInfo VALUES (3,'A','unnatural')
INSERT INTO #ItemInfo VALUES (3,'C','waterproof')
```
You'll get warnings about FKs and temp tables; I just show them for clarity. You can remove the "#" to make permanent tables...
When I run this query:
```
SELECT
i.ItemDescription
,t.ItemTypeDescription
,o.ItemValue
FROM #Items i
LEFT OUTER JOIN #ItemInfo o ON i.ItemPK=o.ItemPk
LEFT OUTER JOIN #ItemTypes t ON o.ItemType=t.ItemType
```
I get this output:
```
ItemDescription ItemTypeDescription ItemValue
------------------------- ------------------------- ----------
rock Type A hard
rock Type A natural
rock BBBBB cold
rock Color gray
wood BBBBB grain
wood BBBBB brown
plastic Type A flexible
plastic Type A colorful
plastic Type A unnatural
plastic Color waterproof
```
However, I need output like:
```
ItemDescription CombinedDescription
------------------------- -----------------------------------------------
rock Type A: hard, natural; BBBBB: cold; Color: gray
wood BBBBB: grain, brown
plastic Type A: flexible, colorful, unnatural; Color: waterproof
(3 row(s) affected)
```
thanks...
|
2009/06/19
|
['https://Stackoverflow.com/questions/1017598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65223/']
|
The various options for aggregate string concatention in SQL Server were summed up by Anith Sen in this post: <http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/>
Usually the best option is the XML PATH trick.
|
you could write a scalar value function that would contain a subquery in which it would perform the concatenation, or you could try coalesce, [example here](http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string)
|
1,017,598 |
I have a need for a "run once" query (so performance isn't that critical) using tables similar to these (simplified versions of the actual):
```
CREATE TABLE #Items
( ItemPK int not null primary key
,ItemDescription varchar(25) not null
)
INSERT INTO #Items VALUES (1,'rock')
INSERT INTO #Items VALUES (2,'wood')
INSERT INTO #Items VALUES (3,'plastic')
CREATE TABLE #ItemTypes
( ItemType char(1) not null primary key
,ItemTypeDescription varchar(25) not null
)
INSERT INTO #ItemTypes VALUES ('A','Type A')
INSERT INTO #ItemTypes VALUES ('B','BBBBB')
INSERT INTO #ItemTypes VALUES ('C','Color')
CREATE TABLE #ItemInfo
( InfoPK int not null primary key identity(1,1)
,ItemPK int not null foreign key references #ListOfItems.ItemPK
,ItemType char(1) not null foreign key references #ItemTypes.ItemType
,ItemValue varchar(10) not null
)
INSERT INTO #ItemInfo VALUES (1,'A','hard')
INSERT INTO #ItemInfo VALUES (1,'A','natural')
INSERT INTO #ItemInfo VALUES (1,'B','cold')
INSERT INTO #ItemInfo VALUES (1,'C','gray')
INSERT INTO #ItemInfo VALUES (2,'B','grain')
INSERT INTO #ItemInfo VALUES (2,'B','brown')
INSERT INTO #ItemInfo VALUES (3,'A','flexible')
INSERT INTO #ItemInfo VALUES (3,'A','colorful')
INSERT INTO #ItemInfo VALUES (3,'A','unnatural')
INSERT INTO #ItemInfo VALUES (3,'C','waterproof')
```
You'll get warnings about FKs and temp tables; I just show them for clarity. You can remove the "#" to make permanent tables...
When I run this query:
```
SELECT
i.ItemDescription
,t.ItemTypeDescription
,o.ItemValue
FROM #Items i
LEFT OUTER JOIN #ItemInfo o ON i.ItemPK=o.ItemPk
LEFT OUTER JOIN #ItemTypes t ON o.ItemType=t.ItemType
```
I get this output:
```
ItemDescription ItemTypeDescription ItemValue
------------------------- ------------------------- ----------
rock Type A hard
rock Type A natural
rock BBBBB cold
rock Color gray
wood BBBBB grain
wood BBBBB brown
plastic Type A flexible
plastic Type A colorful
plastic Type A unnatural
plastic Color waterproof
```
However, I need output like:
```
ItemDescription CombinedDescription
------------------------- -----------------------------------------------
rock Type A: hard, natural; BBBBB: cold; Color: gray
wood BBBBB: grain, brown
plastic Type A: flexible, colorful, unnatural; Color: waterproof
(3 row(s) affected)
```
thanks...
|
2009/06/19
|
['https://Stackoverflow.com/questions/1017598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65223/']
|
Using XML trick, this should do it:
```
SELECT i.ItemDescription,
(SELECT x.ItemTypeDescription + ': ' + x.vals +
CASE WHEN (ROW_NUMBER() OVER (ORDER BY x.ItemType DESC) = 1) THEN '' ELSE '; ' END
FROM ( SELECT DISTINCT
ii.ItemPK,
t.ItemTypeDescription,
ii.ItemType,
(SELECT x.ItemValue +
CASE WHEN (ROW_NUMBER() OVER (ORDER BY x.ItemValue DESC) = 1) THEN '' ELSE ', ' END
FROM #ItemInfo x
WHERE x.ItemPK = ii.ItemPK
AND x.ItemType = ii.ItemType
ORDER BY x.ItemValue
FOR XML PATH('')
) AS VALS
FROM #ItemInfo ii
JOIN #ItemTypes t
ON ii.ItemType = t.ItemType
) x
WHERE x.ItemPK = i.ItemPK
ORDER BY x.ItemType
FOR XML PATH('')
) AS CombinedDescription
FROM #Items i
```
|
The various options for aggregate string concatention in SQL Server were summed up by Anith Sen in this post: <http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/>
Usually the best option is the XML PATH trick.
|
1,017,598 |
I have a need for a "run once" query (so performance isn't that critical) using tables similar to these (simplified versions of the actual):
```
CREATE TABLE #Items
( ItemPK int not null primary key
,ItemDescription varchar(25) not null
)
INSERT INTO #Items VALUES (1,'rock')
INSERT INTO #Items VALUES (2,'wood')
INSERT INTO #Items VALUES (3,'plastic')
CREATE TABLE #ItemTypes
( ItemType char(1) not null primary key
,ItemTypeDescription varchar(25) not null
)
INSERT INTO #ItemTypes VALUES ('A','Type A')
INSERT INTO #ItemTypes VALUES ('B','BBBBB')
INSERT INTO #ItemTypes VALUES ('C','Color')
CREATE TABLE #ItemInfo
( InfoPK int not null primary key identity(1,1)
,ItemPK int not null foreign key references #ListOfItems.ItemPK
,ItemType char(1) not null foreign key references #ItemTypes.ItemType
,ItemValue varchar(10) not null
)
INSERT INTO #ItemInfo VALUES (1,'A','hard')
INSERT INTO #ItemInfo VALUES (1,'A','natural')
INSERT INTO #ItemInfo VALUES (1,'B','cold')
INSERT INTO #ItemInfo VALUES (1,'C','gray')
INSERT INTO #ItemInfo VALUES (2,'B','grain')
INSERT INTO #ItemInfo VALUES (2,'B','brown')
INSERT INTO #ItemInfo VALUES (3,'A','flexible')
INSERT INTO #ItemInfo VALUES (3,'A','colorful')
INSERT INTO #ItemInfo VALUES (3,'A','unnatural')
INSERT INTO #ItemInfo VALUES (3,'C','waterproof')
```
You'll get warnings about FKs and temp tables; I just show them for clarity. You can remove the "#" to make permanent tables...
When I run this query:
```
SELECT
i.ItemDescription
,t.ItemTypeDescription
,o.ItemValue
FROM #Items i
LEFT OUTER JOIN #ItemInfo o ON i.ItemPK=o.ItemPk
LEFT OUTER JOIN #ItemTypes t ON o.ItemType=t.ItemType
```
I get this output:
```
ItemDescription ItemTypeDescription ItemValue
------------------------- ------------------------- ----------
rock Type A hard
rock Type A natural
rock BBBBB cold
rock Color gray
wood BBBBB grain
wood BBBBB brown
plastic Type A flexible
plastic Type A colorful
plastic Type A unnatural
plastic Color waterproof
```
However, I need output like:
```
ItemDescription CombinedDescription
------------------------- -----------------------------------------------
rock Type A: hard, natural; BBBBB: cold; Color: gray
wood BBBBB: grain, brown
plastic Type A: flexible, colorful, unnatural; Color: waterproof
(3 row(s) affected)
```
thanks...
|
2009/06/19
|
['https://Stackoverflow.com/questions/1017598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65223/']
|
Using XML trick, this should do it:
```
SELECT i.ItemDescription,
(SELECT x.ItemTypeDescription + ': ' + x.vals +
CASE WHEN (ROW_NUMBER() OVER (ORDER BY x.ItemType DESC) = 1) THEN '' ELSE '; ' END
FROM ( SELECT DISTINCT
ii.ItemPK,
t.ItemTypeDescription,
ii.ItemType,
(SELECT x.ItemValue +
CASE WHEN (ROW_NUMBER() OVER (ORDER BY x.ItemValue DESC) = 1) THEN '' ELSE ', ' END
FROM #ItemInfo x
WHERE x.ItemPK = ii.ItemPK
AND x.ItemType = ii.ItemType
ORDER BY x.ItemValue
FOR XML PATH('')
) AS VALS
FROM #ItemInfo ii
JOIN #ItemTypes t
ON ii.ItemType = t.ItemType
) x
WHERE x.ItemPK = i.ItemPK
ORDER BY x.ItemType
FOR XML PATH('')
) AS CombinedDescription
FROM #Items i
```
|
you could write a scalar value function that would contain a subquery in which it would perform the concatenation, or you could try coalesce, [example here](http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string)
|
1,746,762 |
I'm trying to create a cron job that will send a weekly newsletter. I tried creating a shell task following what [Cakephp manual](http://book.cakephp.org/view/110/Creating-Shells-Tasks) says. Then I go to the Media Temple Cron jobs and type in the following:
`php /home/#####/domains/domain.com/html/cake/console/cake -app /home//#####//domains/domain.com/html/vendors/shells newsletter`
I created the shell task on vendors/shell folder and named it newsletter.php and here's the code for it:
```
class NewsletterShell extends Shell {
function main() {
$this->sendEmailTo("Newsletter","subject","[email protected]");
}
}
```
The sendEmailTo is a controller function I have in my appController so all my controller have access to it.
My problem is every time the Cron Job runs I get this message:
Could not open input file: /home/#####/domains/domain.com/html/cake/console/cake
I even gave all the console files (cake.php , cake.bat etc) 0777 read write properties as well as for the vendors/shell/newsletter.php
The ##### are the site number that media temple gives you but I'm not really sure I have it correct. They show an example of a cron job like this: /home/50838/data/script-name.sh
So my questions are:
Is my cake shell task correct and is the way I'm running it as a cron job accurate?
Also does anyone know where to confirm my media temple site number so I can write that off as a possible error.
Thanks in advance,
Fabian
|
2009/11/17
|
['https://Stackoverflow.com/questions/1746762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193482/']
|
You can try to `var_dump(ROOT)` or any one of the other [Core Definition Constants](http://book.cakephp.org/view/122/Core-Definition-Constants) to find your directory. Just put it in a controller method somewhere, but make sure to remove it again. Or, if you have SSH access, do `pwd` on the command line.
Other than that, when invoking the `cake` console task, the `-app` parameter is supposed to point to the `app` directory, not the `shells` directory.
---
Try to use [this script](http://book.cakephp.org/view/846/Running-Shells-as-cronjobs) to run your shell as cron job, there may be some missing shell vars.
|
```
ls -l /home/#####/domains/domain.com/html/cake/console/cake
```
says what? does the cron job run as user #####? if not, the problem is probably permissions on /home/#####/, check them with
```
ls -ld /home/#####/
```
|
1,746,762 |
I'm trying to create a cron job that will send a weekly newsletter. I tried creating a shell task following what [Cakephp manual](http://book.cakephp.org/view/110/Creating-Shells-Tasks) says. Then I go to the Media Temple Cron jobs and type in the following:
`php /home/#####/domains/domain.com/html/cake/console/cake -app /home//#####//domains/domain.com/html/vendors/shells newsletter`
I created the shell task on vendors/shell folder and named it newsletter.php and here's the code for it:
```
class NewsletterShell extends Shell {
function main() {
$this->sendEmailTo("Newsletter","subject","[email protected]");
}
}
```
The sendEmailTo is a controller function I have in my appController so all my controller have access to it.
My problem is every time the Cron Job runs I get this message:
Could not open input file: /home/#####/domains/domain.com/html/cake/console/cake
I even gave all the console files (cake.php , cake.bat etc) 0777 read write properties as well as for the vendors/shell/newsletter.php
The ##### are the site number that media temple gives you but I'm not really sure I have it correct. They show an example of a cron job like this: /home/50838/data/script-name.sh
So my questions are:
Is my cake shell task correct and is the way I'm running it as a cron job accurate?
Also does anyone know where to confirm my media temple site number so I can write that off as a possible error.
Thanks in advance,
Fabian
|
2009/11/17
|
['https://Stackoverflow.com/questions/1746762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193482/']
|
You can try to `var_dump(ROOT)` or any one of the other [Core Definition Constants](http://book.cakephp.org/view/122/Core-Definition-Constants) to find your directory. Just put it in a controller method somewhere, but make sure to remove it again. Or, if you have SSH access, do `pwd` on the command line.
Other than that, when invoking the `cake` console task, the `-app` parameter is supposed to point to the `app` directory, not the `shells` directory.
---
Try to use [this script](http://book.cakephp.org/view/846/Running-Shells-as-cronjobs) to run your shell as cron job, there may be some missing shell vars.
|
Have you given the "cake" file in "cake/console" directory executable permissions as well as cake.php and cake.bat?
The cron command should be:
php /home/#####/domains/domain.com/html/cake/console/cake newsletter -app /home/#####/domains/domain.com/html/app
|
16,169,654 |
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:
```
\---/\---/\---/_______________
/ /
\ \
/ DATEPICKER1 /
\ \
/ DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one. Did you follow that? :)
So to sum up, clicking a date in datepicker2 activates datepicker1.
I have no idea why this is happening - they have different ids and names, as outlined below.
To create the datepickers I'm just using:
```
$(function() {
$("#datepicker1").datepicker();
$("#datepicker2").datepicker();
});
```
The fields are simply:
```
<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />
```
I'm using jQuery v1.9.0 and jQueryui v1.10.0.
Any thoughts on this? As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification. Any and all help would be greatly appreciated!!
|
2013/04/23
|
['https://Stackoverflow.com/questions/16169654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2311268/']
|
Try this friend:
in your JS
```js
$(function() {
$( "#from" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
```
```css
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"/>
```
```html
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
Start date: <input type="text" id="from" name="from">
End date: <input type="text" id="to" name = "to">
```
In your input
Start date: input type="text" id="from" name="from"
End date: input type="text" id="to" name = "to"
This worked for me :)
by MacElie M.
|
Try putting the contents of the JQuery UI Dialog into an IFrame. That might help you get around some of your issues.
```
\---/\---/\---/_______________
/ /
\ ####IFRAME###### \
\ # # \
/ #DATEPICKER1 # /
\ # # \
/ #DATEPICKER2 # /
\ # # \
/ ################ /
\ \
/____________________________/
```
|
16,169,654 |
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:
```
\---/\---/\---/_______________
/ /
\ \
/ DATEPICKER1 /
\ \
/ DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one. Did you follow that? :)
So to sum up, clicking a date in datepicker2 activates datepicker1.
I have no idea why this is happening - they have different ids and names, as outlined below.
To create the datepickers I'm just using:
```
$(function() {
$("#datepicker1").datepicker();
$("#datepicker2").datepicker();
});
```
The fields are simply:
```
<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />
```
I'm using jQuery v1.9.0 and jQueryui v1.10.0.
Any thoughts on this? As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification. Any and all help would be greatly appreciated!!
|
2013/04/23
|
['https://Stackoverflow.com/questions/16169654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2311268/']
|
**UPDATE:**
It looks like the behavior described below was addressed in another stackoverflow question here:
[Prevent jQuery UI dialog from setting focus to first textbox](https://stackoverflow.com/questions/1202079/prevent-jquery-ui-dialog-from-setting-focus-to-first-textbox)
Apologies for the "duplicate" question - if I had known this was the problem I would have figured it out quickly!!!
################################################################################
Well, the resolution is very simple, and perhaps someone can enlighten me as to why it works this way because I'm a bit clueless at the moment.
Here's what I did:
I added another two text input fields to the form (they were needed) and reordered the layout so that one of those new input fields was the "first" element (in the top-left corner), like so:
```
\---/\---/\---/_______________
/ /
\ \
/ TEXTFIELD1 DATEPICKER1 /
\ \
/ TEXTFIELD2 DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
Suddenly the problem has vanished! However, I notice an interesting behavior:
When I select a date in EITHER datepicker, the cursor then immediately jumps back to the first text field.
So if this were happening when I had the datepickers with no text fields, that behavior would mean that the cursor would immediately have jumped back to the first datepicker which could have cause the issue I was having.
Now, as to WHY it works this way I have no idea. I tried setting the tabindex parameters for the various textfields/datepickers but that didn't change the behavior.
Anyway, I appreciate the input from everyone who chimed in - this was a weird problem, but I'll never forget how to fix it now. Thanks everyone for your help!!
|
Just to preface, I am a backend database programmer so know little about JavaScript so looked to find this post with the exact same question. Gleaning from what I read above and comparing to my existing code, I modified my JavaScript so that it works and thought I would share it.
The only caveat was that my existing forms with single date selectors no longer worked so I had to add a bit to handle those and all seem fine now. In this case, the database fields are actually a Unix timestamp so the form gets processed when submitted with the two fields converted as needed but for clarity, I did not include that code here.
```
$(document).ready(function(){
$( "#StartDate" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#StartDate" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#EndDate" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#EndDate" ).datepicker( "option", "maxDate", selectedDate );
}
});
$( "#datepicker" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#datepicker" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
```
|
16,169,654 |
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:
```
\---/\---/\---/_______________
/ /
\ \
/ DATEPICKER1 /
\ \
/ DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one. Did you follow that? :)
So to sum up, clicking a date in datepicker2 activates datepicker1.
I have no idea why this is happening - they have different ids and names, as outlined below.
To create the datepickers I'm just using:
```
$(function() {
$("#datepicker1").datepicker();
$("#datepicker2").datepicker();
});
```
The fields are simply:
```
<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />
```
I'm using jQuery v1.9.0 and jQueryui v1.10.0.
Any thoughts on this? As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification. Any and all help would be greatly appreciated!!
|
2013/04/23
|
['https://Stackoverflow.com/questions/16169654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2311268/']
|
**UPDATE:**
It looks like the behavior described below was addressed in another stackoverflow question here:
[Prevent jQuery UI dialog from setting focus to first textbox](https://stackoverflow.com/questions/1202079/prevent-jquery-ui-dialog-from-setting-focus-to-first-textbox)
Apologies for the "duplicate" question - if I had known this was the problem I would have figured it out quickly!!!
################################################################################
Well, the resolution is very simple, and perhaps someone can enlighten me as to why it works this way because I'm a bit clueless at the moment.
Here's what I did:
I added another two text input fields to the form (they were needed) and reordered the layout so that one of those new input fields was the "first" element (in the top-left corner), like so:
```
\---/\---/\---/_______________
/ /
\ \
/ TEXTFIELD1 DATEPICKER1 /
\ \
/ TEXTFIELD2 DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
Suddenly the problem has vanished! However, I notice an interesting behavior:
When I select a date in EITHER datepicker, the cursor then immediately jumps back to the first text field.
So if this were happening when I had the datepickers with no text fields, that behavior would mean that the cursor would immediately have jumped back to the first datepicker which could have cause the issue I was having.
Now, as to WHY it works this way I have no idea. I tried setting the tabindex parameters for the various textfields/datepickers but that didn't change the behavior.
Anyway, I appreciate the input from everyone who chimed in - this was a weird problem, but I'll never forget how to fix it now. Thanks everyone for your help!!
|
This is a total shot in the dark but have you tried initialising each one seperately? Something like the following
```
$(function() {
$('.datepicker').each(function(){
$(this).datepicker();
});
});
```
It's probably what the others have mentioned and you are encountering some form of interference with your code, but it's worth a quick shot.
|
16,169,654 |
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:
```
\---/\---/\---/_______________
/ /
\ \
/ DATEPICKER1 /
\ \
/ DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one. Did you follow that? :)
So to sum up, clicking a date in datepicker2 activates datepicker1.
I have no idea why this is happening - they have different ids and names, as outlined below.
To create the datepickers I'm just using:
```
$(function() {
$("#datepicker1").datepicker();
$("#datepicker2").datepicker();
});
```
The fields are simply:
```
<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />
```
I'm using jQuery v1.9.0 and jQueryui v1.10.0.
Any thoughts on this? As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification. Any and all help would be greatly appreciated!!
|
2013/04/23
|
['https://Stackoverflow.com/questions/16169654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2311268/']
|
On your example both datepickers have different id's and name's, however, the problem you describe is exactly what'll happen if you use the same name for both.
Does your actual code use different id and name for both datepickers?
|
**EXPLANATION of issue**
I have the same issue and its very disappointing.
I searched through the source code of jquery and found this:
```
if ( $.ui.dialog.overlayInstances ) {
this._on( this.document, {
focusin: function( event ) {
if ( !$( event.target ).closest(".ui-dialog").length ) {
event.preventDefault();
$(".ui-dialog:visible:last .ui-dialog-content")
.data("ui-dialog")._focusTabbable();
}
}
});
}
```
So when you set focus in element thats not inside the `.ui-dialog`, it will trigger `_focusTabbable()` function which set focus to the first input in dialog.
The problem is, that `$.datepicker` creates div on the end of body - so it is outside of `.ui-dialog`
If there is another input which `_focusTabbable()` will give focus its ok, as datepicker can handle that. But if this input has datepicker binded, it will close the previous datepicker, open another on the first input and the select on the previous datepicker is not fired.
**One of possible solutions**
The solution is in this case have input wich will take first focus in dialog and does not have datepicker on it.
I simply use this HTML code as first input on begin of dialog content where otherwise datepicker input will be on first place:
```
<span class="ui-helper-hidden-accessible"><input type="text" /></span>
```
|
16,169,654 |
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:
```
\---/\---/\---/_______________
/ /
\ \
/ DATEPICKER1 /
\ \
/ DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one. Did you follow that? :)
So to sum up, clicking a date in datepicker2 activates datepicker1.
I have no idea why this is happening - they have different ids and names, as outlined below.
To create the datepickers I'm just using:
```
$(function() {
$("#datepicker1").datepicker();
$("#datepicker2").datepicker();
});
```
The fields are simply:
```
<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />
```
I'm using jQuery v1.9.0 and jQueryui v1.10.0.
Any thoughts on this? As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification. Any and all help would be greatly appreciated!!
|
2013/04/23
|
['https://Stackoverflow.com/questions/16169654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2311268/']
|
On your example both datepickers have different id's and name's, however, the problem you describe is exactly what'll happen if you use the same name for both.
Does your actual code use different id and name for both datepickers?
|
in a js archive:
```
$("#fecha_1").datepicker({
dateFormat: "dd/mm/yy",
dayNames: "Domingo Lunes Martes Miercoles Jueves Viernes Sabado".split(" "),
dayNamesMin: "Do Lu Ma Mi Ju Vi Sa".split(" "),
dayNamesShort: "Do Lu Ma Mi Ju Vi Sa".split(" "),
monthNames: "Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre".split(" "),
monthNamesShort: "Ene Feb Mar Abr May Jun Jul Ago Sep Oct Nov Dic".split(" "),
prevText: "Ant",
nextText: "Sig",
currentText: "Hoy",
changeMonth: !0,
changeYear: !0,
showAnim: "slideDown",
yearRange: "1900:2100"
});
$("#fecha_2").datepicker({
dateFormat: "dd/mm/yy",
dayNames: "Domingo Lunes Martes Miercoles Jueves Viernes Sabado".split(" "),
dayNamesMin: "Do Lu Ma Mi Ju Vi Sa".split(" "),
dayNamesShort: "Do Lu Ma Mi Ju Vi Sa".split(" "),
monthNames: "Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre".split(" "),
monthNamesShort: "Ene Feb Mar Abr May Jun Jul Ago Sep Oct Nov Dic".split(" "),
prevText: "Ant",
nextText: "Sig",
currentText: "Hoy",
changeMonth: !0,
changeYear: !0,
showAnim: "slideDown",
yearRange: "1900:2100"
});
```
in ur page: `<input type="text" id="fecha_1"><input type="text" id="fecha_2">`
|
16,169,654 |
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:
```
\---/\---/\---/_______________
/ /
\ \
/ DATEPICKER1 /
\ \
/ DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one. Did you follow that? :)
So to sum up, clicking a date in datepicker2 activates datepicker1.
I have no idea why this is happening - they have different ids and names, as outlined below.
To create the datepickers I'm just using:
```
$(function() {
$("#datepicker1").datepicker();
$("#datepicker2").datepicker();
});
```
The fields are simply:
```
<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />
```
I'm using jQuery v1.9.0 and jQueryui v1.10.0.
Any thoughts on this? As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification. Any and all help would be greatly appreciated!!
|
2013/04/23
|
['https://Stackoverflow.com/questions/16169654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2311268/']
|
Try this friend:
in your JS
```js
$(function() {
$( "#from" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
```
```css
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"/>
```
```html
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
Start date: <input type="text" id="from" name="from">
End date: <input type="text" id="to" name = "to">
```
In your input
Start date: input type="text" id="from" name="from"
End date: input type="text" id="to" name = "to"
This worked for me :)
by MacElie M.
|
Just to preface, I am a backend database programmer so know little about JavaScript so looked to find this post with the exact same question. Gleaning from what I read above and comparing to my existing code, I modified my JavaScript so that it works and thought I would share it.
The only caveat was that my existing forms with single date selectors no longer worked so I had to add a bit to handle those and all seem fine now. In this case, the database fields are actually a Unix timestamp so the form gets processed when submitted with the two fields converted as needed but for clarity, I did not include that code here.
```
$(document).ready(function(){
$( "#StartDate" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#StartDate" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#EndDate" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#EndDate" ).datepicker( "option", "maxDate", selectedDate );
}
});
$( "#datepicker" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#datepicker" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
```
|
16,169,654 |
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:
```
\---/\---/\---/_______________
/ /
\ \
/ DATEPICKER1 /
\ \
/ DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one. Did you follow that? :)
So to sum up, clicking a date in datepicker2 activates datepicker1.
I have no idea why this is happening - they have different ids and names, as outlined below.
To create the datepickers I'm just using:
```
$(function() {
$("#datepicker1").datepicker();
$("#datepicker2").datepicker();
});
```
The fields are simply:
```
<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />
```
I'm using jQuery v1.9.0 and jQueryui v1.10.0.
Any thoughts on this? As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification. Any and all help would be greatly appreciated!!
|
2013/04/23
|
['https://Stackoverflow.com/questions/16169654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2311268/']
|
On your example both datepickers have different id's and name's, however, the problem you describe is exactly what'll happen if you use the same name for both.
Does your actual code use different id and name for both datepickers?
|
Just to preface, I am a backend database programmer so know little about JavaScript so looked to find this post with the exact same question. Gleaning from what I read above and comparing to my existing code, I modified my JavaScript so that it works and thought I would share it.
The only caveat was that my existing forms with single date selectors no longer worked so I had to add a bit to handle those and all seem fine now. In this case, the database fields are actually a Unix timestamp so the form gets processed when submitted with the two fields converted as needed but for clarity, I did not include that code here.
```
$(document).ready(function(){
$( "#StartDate" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#StartDate" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#EndDate" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#EndDate" ).datepicker( "option", "maxDate", selectedDate );
}
});
$( "#datepicker" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#datepicker" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
```
|
16,169,654 |
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:
```
\---/\---/\---/_______________
/ /
\ \
/ DATEPICKER1 /
\ \
/ DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one. Did you follow that? :)
So to sum up, clicking a date in datepicker2 activates datepicker1.
I have no idea why this is happening - they have different ids and names, as outlined below.
To create the datepickers I'm just using:
```
$(function() {
$("#datepicker1").datepicker();
$("#datepicker2").datepicker();
});
```
The fields are simply:
```
<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />
```
I'm using jQuery v1.9.0 and jQueryui v1.10.0.
Any thoughts on this? As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification. Any and all help would be greatly appreciated!!
|
2013/04/23
|
['https://Stackoverflow.com/questions/16169654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2311268/']
|
Case 1:
@antony's comment(including jsfiddle link below the question) works as of
version `jquery-1.9.1` and `1.9.2/jquery-ui.js`
Case 2:
OP's case where datepicker1 works well but choosing datepicker2 will open datepicker1
version: `jQuery v1.9.0` and `jQueryui v1.10.0`
Case 3:
My case where choosing datepicker1 works well but choosing datepicker2 has no any effect.
version: `jquery-3.1.1.min.js` and `jQueryui v1.12.1`
Case 3 solution:
initialize date1 first `$('date1').datepicker()` date1 will works
For date2, first destroy date1 then initialize date2
```
$('date1').datepicker('destroy');
$('date2').datepicker();
```
Now for date1, destroy date2 and initialize date1.
|
Just to preface, I am a backend database programmer so know little about JavaScript so looked to find this post with the exact same question. Gleaning from what I read above and comparing to my existing code, I modified my JavaScript so that it works and thought I would share it.
The only caveat was that my existing forms with single date selectors no longer worked so I had to add a bit to handle those and all seem fine now. In this case, the database fields are actually a Unix timestamp so the form gets processed when submitted with the two fields converted as needed but for clarity, I did not include that code here.
```
$(document).ready(function(){
$( "#StartDate" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#StartDate" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#EndDate" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#EndDate" ).datepicker( "option", "maxDate", selectedDate );
}
});
$( "#datepicker" ).datepicker({
altField: '#datepicker',
altFormat: 'yy-mm-dd',
dateFormat: 'D M d, yy',
firstDay: 1,
onClose: function( selectedDate ) {
$( "#datepicker" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
```
|
16,169,654 |
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:
```
\---/\---/\---/_______________
/ /
\ \
/ DATEPICKER1 /
\ \
/ DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one. Did you follow that? :)
So to sum up, clicking a date in datepicker2 activates datepicker1.
I have no idea why this is happening - they have different ids and names, as outlined below.
To create the datepickers I'm just using:
```
$(function() {
$("#datepicker1").datepicker();
$("#datepicker2").datepicker();
});
```
The fields are simply:
```
<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />
```
I'm using jQuery v1.9.0 and jQueryui v1.10.0.
Any thoughts on this? As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification. Any and all help would be greatly appreciated!!
|
2013/04/23
|
['https://Stackoverflow.com/questions/16169654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2311268/']
|
Try putting the contents of the JQuery UI Dialog into an IFrame. That might help you get around some of your issues.
```
\---/\---/\---/_______________
/ /
\ ####IFRAME###### \
\ # # \
/ #DATEPICKER1 # /
\ # # \
/ #DATEPICKER2 # /
\ # # \
/ ################ /
\ \
/____________________________/
```
|
in a js archive:
```
$("#fecha_1").datepicker({
dateFormat: "dd/mm/yy",
dayNames: "Domingo Lunes Martes Miercoles Jueves Viernes Sabado".split(" "),
dayNamesMin: "Do Lu Ma Mi Ju Vi Sa".split(" "),
dayNamesShort: "Do Lu Ma Mi Ju Vi Sa".split(" "),
monthNames: "Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre".split(" "),
monthNamesShort: "Ene Feb Mar Abr May Jun Jul Ago Sep Oct Nov Dic".split(" "),
prevText: "Ant",
nextText: "Sig",
currentText: "Hoy",
changeMonth: !0,
changeYear: !0,
showAnim: "slideDown",
yearRange: "1900:2100"
});
$("#fecha_2").datepicker({
dateFormat: "dd/mm/yy",
dayNames: "Domingo Lunes Martes Miercoles Jueves Viernes Sabado".split(" "),
dayNamesMin: "Do Lu Ma Mi Ju Vi Sa".split(" "),
dayNamesShort: "Do Lu Ma Mi Ju Vi Sa".split(" "),
monthNames: "Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre".split(" "),
monthNamesShort: "Ene Feb Mar Abr May Jun Jul Ago Sep Oct Nov Dic".split(" "),
prevText: "Ant",
nextText: "Sig",
currentText: "Hoy",
changeMonth: !0,
changeYear: !0,
showAnim: "slideDown",
yearRange: "1900:2100"
});
```
in ur page: `<input type="text" id="fecha_1"><input type="text" id="fecha_2">`
|
16,169,654 |
So here is the setup:
I have two jquery datepickers, inside a jquery tab, inside a jquery modal dialog window:
```
\---/\---/\---/_______________
/ /
\ \
/ DATEPICKER1 /
\ \
/ DATEPICKER2 /
\ \
/ /
\ \
/____________________________/
```
The first datepicker functions normally, but when I try to click a date in the second datepicker it simply activates the first one. Did you follow that? :)
So to sum up, clicking a date in datepicker2 activates datepicker1.
I have no idea why this is happening - they have different ids and names, as outlined below.
To create the datepickers I'm just using:
```
$(function() {
$("#datepicker1").datepicker();
$("#datepicker2").datepicker();
});
```
The fields are simply:
```
<input type="text" id="datepicker1" name="datepicker1" value="" />
<input type="text" id="datepicker2" name="datepicker2" value="" />
```
I'm using jQuery v1.9.0 and jQueryui v1.10.0.
Any thoughts on this? As a caveat, I am unable to post actual code due to restrictions from my employer, but I can answer most questions if you need any clarification. Any and all help would be greatly appreciated!!
|
2013/04/23
|
['https://Stackoverflow.com/questions/16169654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2311268/']
|
Try this friend:
in your JS
```js
$(function() {
$( "#from" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( "#to" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
```
```css
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"/>
```
```html
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
Start date: <input type="text" id="from" name="from">
End date: <input type="text" id="to" name = "to">
```
In your input
Start date: input type="text" id="from" name="from"
End date: input type="text" id="to" name = "to"
This worked for me :)
by MacElie M.
|
Case 1:
@antony's comment(including jsfiddle link below the question) works as of
version `jquery-1.9.1` and `1.9.2/jquery-ui.js`
Case 2:
OP's case where datepicker1 works well but choosing datepicker2 will open datepicker1
version: `jQuery v1.9.0` and `jQueryui v1.10.0`
Case 3:
My case where choosing datepicker1 works well but choosing datepicker2 has no any effect.
version: `jquery-3.1.1.min.js` and `jQueryui v1.12.1`
Case 3 solution:
initialize date1 first `$('date1').datepicker()` date1 will works
For date2, first destroy date1 then initialize date2
```
$('date1').datepicker('destroy');
$('date2').datepicker();
```
Now for date1, destroy date2 and initialize date1.
|
49,820,228 |
I'm currently creating a program that can compute near-dupliate score within a corpus of text documents (+5000 docs).
I'm using Simhash to generate a uniq footprint of a document (thanks to this [github repo](https://github.com/memosstilvi/simhash))
my datas are :
```
data = {
1: u'Im testing simhash algorithm.',
2: u'test of simhash algorithm',
3: u'This is simhash test.',
}
```
and this gives me 3 hash like this :
00100110101110100011111000100010010101011001000001110000111001011100110101001101111010100010001011001011000110000100110101100110
00001001110010000000011000001000110010001010000101010000001100000100100011100100110010100000010000000110001001010110000010000100
10001110101100000100101010000010010001011010001000000000101000101100001100100000110011000000011001000000000110000000100110000000
And now, how to compare those 3 hashes ? I know that I have to split them into blocks but dont have the exact method ?
What i want to do is the output all the duplicated documents (>70%) with their ID and the IDs of duplicates docs.
Can someone help ?
|
2018/04/13
|
['https://Stackoverflow.com/questions/49820228', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2947435/']
|
Before I answer your question, it is important to keep in mind:
1. Simhash is useful as it detects near duplicates. This means that near duplicates will end up with the same hash.
2. For exact duplicates you can simply use any one way, consistent hashing mechanism (ex. md5)
3. The examples that you pasted here are too small and given their size, their differences are significant. The algorithm is tailored to work with large Web Documents and not small sentences.
Now, I have replied to your question on the Github issue that you raised [here](https://github.com/memosstilvi/simhash/issues/2 "here").
For reference though, here is some sample code you can use to print the final near duplicate documents after hashing them.
```
# assuming that you have a dictionary with document id as the key and the document as the value:
# documents = { doc_id: doc } you can do:
from simhash import simhash
def split_hash(str, num):
return [ str[start:start+num] for start in range(0, len(str), num) ]
hashes = {}
for doc_id, doc in documents.items():
hash = simhash(doc)
# you can either use the whole hash for higher precision or split into chunks for higher recall
hash_chunks = split_hash(hash, 4)
for chunk in hash_chunks:
if chunk not in hashes:
hashes[chunk] = []
hashes[chunk].append(doc_id)
# now you can print the duplicate documents:
for hash, doc_list in hashes:
if len(doc_list) > 1: # if the length of doc is greater than 1
print("Duplicates documents: ", doc_list)
```
Please let me know if something is not clear.
|
Further to Memos' answer, if you want to detect >=70% similarity, you cannot use simhash. Simhash only allows quite small hamming distances to be detected, up to around 6 or 7 bits difference, at a stretch, depending on the size of your corpus. For 70% similarity you'd have to allow 19 bits difference, which is not possible in any normal scenario.
You should instead look into minhash.
If you're interested, here's an extensive [explanation of simhash](http://benwhitmore.altervista.org/simhash-and-solving-the-hamming-distance-problem-explained/).
|
2,169 |
What (if any) are the differences between [The Standard for Software Component Testing](http://www.testingstandards.co.uk/Component%20Testing.pdf) (from the British Computing Society SIGIST and available for free) and BS 7925-2 (which is available to purchase for £170)?
|
2011/11/26
|
['https://sqa.stackexchange.com/questions/2169', 'https://sqa.stackexchange.com', 'https://sqa.stackexchange.com/users/1656/']
|
The first document appears to be the last draft version of the published (expensive) version - in fact, this page states that and appears (to my reading) to be recommending that you use the draft: <http://www.testingstandards.co.uk/bs_7925-2.htm>
What reasons do you have for using either standard at all?
Neither will help you to fulfil your stakeholders' needs for relevant, timely, quality-related information - only you can do that, by doing a good job of discussing their needs with them, analysing the testing problems that you have, and staying in close communication with them during the course of the project.
If your stakeholders have specific needs for following a particular standard, then you need to explain the context for that before anybody can help you.
|
You probably better spend 164 CHF and purchase the draft ISO 29119 parts 2 & 3 (parts 1 & 4 are still not for sale), it is partially based on BS 7925-2 and might replace it in the future.
I'm reading it now, and it seems they did a good job with it, it gives you the right foundation but leaves a lot of context to be added.
|
24,556,316 |
I'm having a problem regarding comparing two dates. I know this sound kinda silly but I want you all to try this example.
```
$a = date('d-m-Y', strtotime('2014-07-03'));
$b = date('d-m-Y', strtotime('2014-03-17'));
$c = date('d-m-Y', strtotime('2015-03-16'));
if(($a > $b) && ($a < $c) ) {
echo "1";
}
else {
echo "2";
}
```
How come the result is 2?
|
2014/07/03
|
['https://Stackoverflow.com/questions/24556316', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3802062/']
|
Your "logic" is wrong.

> [xkcd](http://xkcd.com/1179/)
```
$a = '2014-07-03';
$b = '2014-03-17';
$c = '2015-03-16';
if(($a > $b) && ($a < $c)) {
echo "1"; // it works!
}
```
Big-endian formats are awesome.
|
After your date/strtotime function, you have :
```
$a = '03-07-2014'
$b = '17-03-2014'
$c = '16-03-2015'
```
So when you compare, $a is less than $b because it compares the day first.
|
24,556,316 |
I'm having a problem regarding comparing two dates. I know this sound kinda silly but I want you all to try this example.
```
$a = date('d-m-Y', strtotime('2014-07-03'));
$b = date('d-m-Y', strtotime('2014-03-17'));
$c = date('d-m-Y', strtotime('2015-03-16'));
if(($a > $b) && ($a < $c) ) {
echo "1";
}
else {
echo "2";
}
```
How come the result is 2?
|
2014/07/03
|
['https://Stackoverflow.com/questions/24556316', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3802062/']
|
Your "logic" is wrong.

> [xkcd](http://xkcd.com/1179/)
```
$a = '2014-07-03';
$b = '2014-03-17';
$c = '2015-03-16';
if(($a > $b) && ($a < $c)) {
echo "1"; // it works!
}
```
Big-endian formats are awesome.
|
Because your date format is *not* good for comparing. Always use YYYY-MM-DD format when comparing dates (or use DateTime() objects). This is because 04-01-2014 is less than 05-01-2014 when compared as strings.
```
$a = '2014-07-03';
$b = '2014-03-17';
$c = '2015-03-16';
if(($a > $b) && ($a < $c) ) {
echo "1";
}
else {
echo "2";
}
```
Or when using DateTime() objects:
```
$a = new DateTime('2014-07-03');
$b = new DateTime('2014-03-17');
$c = new DateTime('2015-03-16');
if(($a > $b) && ($a < $c) ) {
echo "1";
}
else {
echo "2";
}
```
|
24,556,316 |
I'm having a problem regarding comparing two dates. I know this sound kinda silly but I want you all to try this example.
```
$a = date('d-m-Y', strtotime('2014-07-03'));
$b = date('d-m-Y', strtotime('2014-03-17'));
$c = date('d-m-Y', strtotime('2015-03-16'));
if(($a > $b) && ($a < $c) ) {
echo "1";
}
else {
echo "2";
}
```
How come the result is 2?
|
2014/07/03
|
['https://Stackoverflow.com/questions/24556316', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3802062/']
|
Because your date format is *not* good for comparing. Always use YYYY-MM-DD format when comparing dates (or use DateTime() objects). This is because 04-01-2014 is less than 05-01-2014 when compared as strings.
```
$a = '2014-07-03';
$b = '2014-03-17';
$c = '2015-03-16';
if(($a > $b) && ($a < $c) ) {
echo "1";
}
else {
echo "2";
}
```
Or when using DateTime() objects:
```
$a = new DateTime('2014-07-03');
$b = new DateTime('2014-03-17');
$c = new DateTime('2015-03-16');
if(($a > $b) && ($a < $c) ) {
echo "1";
}
else {
echo "2";
}
```
|
After your date/strtotime function, you have :
```
$a = '03-07-2014'
$b = '17-03-2014'
$c = '16-03-2015'
```
So when you compare, $a is less than $b because it compares the day first.
|
46,163,665 |
I want to run a function inside evaluate(), I'm passing it as an argument, but I'm getting **'func is not a function'**, what am I missing?
Puppeteer version: 10.2
Platform / OS version: Windows 10, Node 8.2.1
```
var func = function() {
console.log("xxxxx");
};
var response = await page.evaluate( (func) => {
func(); //func is not a function
}, func);
```
|
2017/09/11
|
['https://Stackoverflow.com/questions/46163665', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6391788/']
|
You can use [`page.exposeFunction(name, puppeteerFunction)`](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageexposefunctionname-puppeteerfunction):
```
await page.exposeFunction("add", (a, b) => a + b);
const response = await page.evaluate(() => {
return window.add(2, 2);
});
```
|
If I understand it correctly, puppeteer has to marshal the code in your evaluate function ultimately as a string and inject it into to page context. You can't pass function references or anything non-serializable across that boundary.
|
12,423,218 |
I have a problem on postgresql which I think there is a bug in the postgresql, I wrongly implement something.
There is a table including `colmn1(primary key)`, `colmn2(unique)`, `colmn3`, ...
After an insertion of a row, if I try another insertion with an existing `colmn2` value I am getting a duplicate value error as I expected. But after this unsuccesful try, `colmn1`'s next value is
incremented by 1 although there is no insertion so i am getting rows with id sequences like , `1,2,4,6,9.(3,5,6,7,8` goes for unsuccessful trials).
I need help from the ones who can explain this weird behaviour.
This information may be useful: I used "`create unique index on tableName (lower(column1))` " query to set unique constraint.
|
2012/09/14
|
['https://Stackoverflow.com/questions/12423218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1021294/']
|
See the [PostgreSQL sequence FAQ](http://www.neilconway.org/docs/sequences/):
>
> Sequences are intended for generating unique identifiers — not
> necessarily identifiers that are strictly sequential. If two
> concurrent database clients both attempt to get a value from a
> sequence (using nextval()), each client will get a different sequence
> value. If one of those clients subsequently aborts their transaction,
> the sequence value that was generated for that client will be unused,
> creating a gap in the sequence.
>
>
> This can't easily be fixed without incurring a significant performance
> penalty. For more information, see Elein Mustein's "[Gapless Sequences for Primary Keys](http://www.varlena.com/GeneralBits/130.php)" in the General Bits Newsletter.
>
>
>
|
From the [manual](http://www.postgresql.org/docs/current/static/functions-sequence.html):
>
> Important: Because sequences are non-transactional, changes made by
> setval are not undone if the transaction rolls back.
>
>
>
In other words, it's normal to have gaps. If you don't want gaps, don't use a sequence.
|
46,675,296 |
I want to make my react web app full screen after user go to specific web page (no address bar, no navigation bar, only display the web page). I tried many modules online, but they didn't work. Is there a good solution for this problem?
|
2017/10/10
|
['https://Stackoverflow.com/questions/46675296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8162459/']
|
You can try to use Javascript Fullscreen API. For example:
```
document.documentElement.webkitRequestFullscreen()
```
|
One way is to just select the container that you want to place the app within. For example, say you want to keep all the styles from the parent application, you could target the body in your ReactDOM render.
```
ReactDOM.render(
<ActiveWidgetArea widgets={yourData}/>,
document.querySelector('body')
);
```
I tried this in a Drupal site, and it filled the screen with my React App, but left a lot of things intact. Perhaps these were things loaded after the React app loaded. You could also target the html element.
It might also help to know what your parent application is, how the rest of the site is built.
|
46,675,296 |
I want to make my react web app full screen after user go to specific web page (no address bar, no navigation bar, only display the web page). I tried many modules online, but they didn't work. Is there a good solution for this problem?
|
2017/10/10
|
['https://Stackoverflow.com/questions/46675296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8162459/']
|
You can try to use Javascript Fullscreen API. For example:
```
document.documentElement.webkitRequestFullscreen()
```
|
This is my approach:
```
const toggleFullSceen = (): void => {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
}
};
<button onClick={() => toggleFullSceen()}>
Toggle full screen mode
</button>
```
|
45,317,517 |
I have installed Heroku CLI and git. After installation, I restarted the command prompt. When I run git commands, those are recognized fine. But when I type Heroku commands such as `heroku version`, they are not recognized.
So I set the path variable to point to the Heroku installation. Now, Heroku commands are working but the git commands have become unrecognized.
What is the actual problem?
Here is the cmd prompt content.
```
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\Deva 5>git config --list
core.symlinks=false
core.autocrlf=true
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
diff.astextplain.textconv=astextplain
rebase.autosquash=true
credential.helper=manager
user.email=****
user.name=****
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.symlinks=false
core.ignorecase=true
core.hidedotfiles=dotGitOnly
gui.wmstate=normal
gui.geometry=888x427+150+150 171 192
C:\Users\Deva 5>heroku version
'heroku' is not recognized as an internal or external command,
operable program or batch file.
C:\Users\Deva 5>heroku login
'heroku' is not recognized as an internal or external command,
operable program or batch file.
C:\Users\Deva 5>set path="C:\Program Files\Heroku\bin"
C:\Users\Deva 5>heroku version
heroku-cli: Updating to 6.13.1-7bcaf87... 11.6 MB/11.6 MB
heroku-cli/6.13.1-7bcaf87 (windows-x64) node-v8.2.1
C:\Users\Deva 5>git config --list
'git' is not recognized as an internal or external command,
operable program or batch file.
```
|
2017/07/26
|
['https://Stackoverflow.com/questions/45317517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6299496/']
|
>
>
> ```
> set path="C:\Program Files\Heroku\bin"
>
> ```
>
>
By doing that, you *replaced* your PATH variable to *only* contain that path. So you essentially broke everything else.
What you usually do is append or prepend the new path to the PATH variable, e.g. like this:
```
set PATH=%PATH%;C:\Program Files\Heroku\bin
```
The permanent solution would be to edit your Windows to include that path to the Heroku executables by default. See this question on SuperUser for more information and instructions: [What are PATH and other environment variables, and how can I set or use them?](https://superuser.com/q/284342/24082)
|
1. Just close the vs code, command prompt and all the browser.
2. And restart your pc. Then open your cmd,
3. go the project file and writr "heroku login"
it will work
|
1 |
So I'm in the UK, but I do home improvement too. But, over here, building codes are different, you'd not want to mess around with our 230V power, and even simple things like paint are quite different.
On the other hand the basics of how buildings are constructed are the same - despite the language differences, wall-board works the same here.
How do we plan to cover these differences on the site? By geography-specific tags?
|
2010/07/21
|
['https://diy.meta.stackexchange.com/questions/1', 'https://diy.meta.stackexchange.com', 'https://diy.meta.stackexchange.com/users/17/']
|
If it is an item that is specific to your area, you could tag it with a UK/Canada/USA/Country tag.
|
This problem is universal. I'm a member of a dutch diy forum. And we sometimes get questions from people from Belgium (similar language different regulations) which require different answers if regulations are part of the solution.
A possible solution would be to introduce country tags (possibly with a country flag/symbol). To avoid problems.
|
1 |
So I'm in the UK, but I do home improvement too. But, over here, building codes are different, you'd not want to mess around with our 230V power, and even simple things like paint are quite different.
On the other hand the basics of how buildings are constructed are the same - despite the language differences, wall-board works the same here.
How do we plan to cover these differences on the site? By geography-specific tags?
|
2010/07/21
|
['https://diy.meta.stackexchange.com/questions/1', 'https://diy.meta.stackexchange.com', 'https://diy.meta.stackexchange.com/users/17/']
|
Not only are building codes different, but so is terminology (drywall vs plaster board etc), so there will need to be a glossary / dictionary maintained so that people can 'translate' terms...
|
This problem is universal. I'm a member of a dutch diy forum. And we sometimes get questions from people from Belgium (similar language different regulations) which require different answers if regulations are part of the solution.
A possible solution would be to introduce country tags (possibly with a country flag/symbol). To avoid problems.
|
1 |
So I'm in the UK, but I do home improvement too. But, over here, building codes are different, you'd not want to mess around with our 230V power, and even simple things like paint are quite different.
On the other hand the basics of how buildings are constructed are the same - despite the language differences, wall-board works the same here.
How do we plan to cover these differences on the site? By geography-specific tags?
|
2010/07/21
|
['https://diy.meta.stackexchange.com/questions/1', 'https://diy.meta.stackexchange.com', 'https://diy.meta.stackexchange.com/users/17/']
|
Maybe have a tag called "location-specific" so people know right off the bat. If we just had a tag for the region, we could have SO many tags by state / city / country / continent showing up and that would be a nightmare.
|
This problem is universal. I'm a member of a dutch diy forum. And we sometimes get questions from people from Belgium (similar language different regulations) which require different answers if regulations are part of the solution.
A possible solution would be to introduce country tags (possibly with a country flag/symbol). To avoid problems.
|
1 |
So I'm in the UK, but I do home improvement too. But, over here, building codes are different, you'd not want to mess around with our 230V power, and even simple things like paint are quite different.
On the other hand the basics of how buildings are constructed are the same - despite the language differences, wall-board works the same here.
How do we plan to cover these differences on the site? By geography-specific tags?
|
2010/07/21
|
['https://diy.meta.stackexchange.com/questions/1', 'https://diy.meta.stackexchange.com', 'https://diy.meta.stackexchange.com/users/17/']
|
Let's try to be as regionally agnostic as possible. Where regulations may apply (construction permits, electrical codes etc), one should mention that, but no one should feel obligated to specify specific requirements for various regions.
Perhaps the best way to handle this would be to have a series of Community Wiki questions where we compile links to various regions' building codes and requirements, and then all other posts can just refer to those (i.e. "check the [regulations] tag for information on building codes that may apply to your region").
|
This problem is universal. I'm a member of a dutch diy forum. And we sometimes get questions from people from Belgium (similar language different regulations) which require different answers if regulations are part of the solution.
A possible solution would be to introduce country tags (possibly with a country flag/symbol). To avoid problems.
|
45,949,267 |
Is there a reason why the same query executed a number of times have huge variance in response times? from 50% - 200% what the projected response time is? They range from 6 seconds to 20 seconds even though it is the only active query in the database.
Context:
1. Database on Postgres 9.6 on AWS RDS (with Provisioned IOPS)
2. Contains one table comprising five numeric columns, indexed on id, holding 200 million rows
The query:
`SELECT col1, col2
FROM calculations
WHERE id > 0
AND id < 100000;`
The query's explain plan:
`Bitmap Heap Scan on calculation (cost=2419.37..310549.65 rows=99005 width=43)
Recheck Cond: ((id > 0) AND (id <= 100000))
-> Bitmap Index Scan on calculation_pkey (cost=0.00..2394.62 rows=99005 width=0)
Index Cond: ((id > 0) AND (id <= 100000))`
Is there any reasons why a simple query like this isn't more predictable in response time?
Thanks.
|
2017/08/29
|
['https://Stackoverflow.com/questions/45949267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8534637/']
|
When you see something like this in PostgreSQL `EXPLAIN ANALYZE`:
```
(cost=2419.37..310549.65)
```
...it doesn't mean the cost is between 2419.37 and 310549.65. These are in fact two different measures. The first value is the startup cost, and the second value is the total cost. Most of the time you'll care only about the total cost. The times that you should be concerned with startup cost is when that component of the execution plan is in relation to (for example) an `EXISTS` clause, where only the first row needs to be returned (so you only care about startup cost, not total, as it exits almost immediately after startup).
The [PostgreSQL documentation on `EXPLAIN`](https://www.postgresql.org/docs/9.3/static/sql-explain.html) goes into greater detail about this.
|
After investigation of the historical load, we have found out that the provisioned IOPS we originally configured had been exhausted during the last set of load tests performed on the environment.
According to Amazon's documentation @<http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html>, after this point, Amazon does not guarantee consistency in execution times and the SLAs are no longer applicable.
We have confirmed that replicating the database onto a new instance of AWS RDS with same configuration yields consistent response times when executing the query multiple times.
|
45,949,267 |
Is there a reason why the same query executed a number of times have huge variance in response times? from 50% - 200% what the projected response time is? They range from 6 seconds to 20 seconds even though it is the only active query in the database.
Context:
1. Database on Postgres 9.6 on AWS RDS (with Provisioned IOPS)
2. Contains one table comprising five numeric columns, indexed on id, holding 200 million rows
The query:
`SELECT col1, col2
FROM calculations
WHERE id > 0
AND id < 100000;`
The query's explain plan:
`Bitmap Heap Scan on calculation (cost=2419.37..310549.65 rows=99005 width=43)
Recheck Cond: ((id > 0) AND (id <= 100000))
-> Bitmap Index Scan on calculation_pkey (cost=0.00..2394.62 rows=99005 width=0)
Index Cond: ((id > 0) AND (id <= 100000))`
Is there any reasons why a simple query like this isn't more predictable in response time?
Thanks.
|
2017/08/29
|
['https://Stackoverflow.com/questions/45949267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8534637/']
|
A query may be (and should be, excluding special cases) more predictable in response time when you are a sole user of the server. In the case of a cloud server, you do not know anything about the actual server load, even if your query is the only one performed on your database, because the server most likely supports multiple databases at the same time. As you asked about *response time*, there may be also various circumstances involved in accessing a remote server over the network.
|
After investigation of the historical load, we have found out that the provisioned IOPS we originally configured had been exhausted during the last set of load tests performed on the environment.
According to Amazon's documentation @<http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html>, after this point, Amazon does not guarantee consistency in execution times and the SLAs are no longer applicable.
We have confirmed that replicating the database onto a new instance of AWS RDS with same configuration yields consistent response times when executing the query multiple times.
|
46,149,981 |
I'm trying to implement a custom validator in JavaScript for my vb.net page. This validator should check if in a multichoice listbox there aren't any selected values, showing an error pop up if so.
The thing is, I want to do it client side, but in my 'validateFunction' function I only get the last selected (or unselected, if it was selected already) item. I know how to do it in code-behind code, but I want to do it client-side.
*aspx code:*
```
<asp:ListBox ID="lbEdit" runat="server" SelectionMode="Multiple">
</asp:ListBox>
<asp:CustomValidator id="cvEdit" runat="server" Display="None" ControlToValidate="lbEdit" ClientValidationFunction="validateFunction"/>
<ajax:ValidatorCalloutExtender runat="server" ID="vceEdit" TargetControlID="cvEdit" />
```
*JavaScript code:*
```
function validateFunction(source, arguments) {
var options = document.getElementById(source.controltovalidate).options;
for (var i = 0; i < options.length; i++) {
if (options[i].selected == true) {
args.IsValid = true;
return;
}
}
args.IsValid = false;
}
```
As I said, since last (un)selected item will be the only one selected in the 'options' array, the validating function will always return true...
I thought of populating another array in another javascript function as the 'true selected array' and compare its values with the selected option each time the function fires.. but I think there should be a better way.
So... Is there a straight forward way to get ALL the selected items from a multichoice listbox in javascript?
|
2017/09/11
|
['https://Stackoverflow.com/questions/46149981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7126334/']
|
Your question is a bit unclear, and your function seems working, but what I will answer here is the last part of your question *So... Is there a straight forward way to get ALL the selected items from a multichoice listbox in javascript?*
Try this js function
```
<script type="text/javascript">
function validateFunction() {
var options = document.getElementById('<% = this.lbEdit.ClientID %>').options;
var selectedItems;
for (var i = 0; i < options.length; i++) {
if (options[i].selected == true) {
if (selectedItems) {
selectedItems = selectedItems + ";" + options[i].value;
}
else {
selectedItems = options[i].value;
}
}
}
if (selectedItems) {
alert(selectedItems);
return true;
}
else {
alert("No item was selected");
return false;
}
}
</script>
```
And this is the aspx code, I removed the validator
```
<asp:ListBox ID="lbEdit" runat="server" SelectionMode="Multiple" >
</asp:ListBox>
<asp:Button ID="test" runat="server" Text="send" OnClientClick="return validateFunction();"/>
```
In the developer tools of your browser you can see a detailed information about all the properties of your object
[](https://i.stack.imgur.com/ZC8Hh.png)
|
```
let a1 = [
{
Selected:false,
},
{
Selected:false
},
{
Selected:false
}];
```
if (a1.some(i => i.Selected))
console.log(true);
else
console.log(false);
Maybe what you want
|
31,778,365 |
So I am trying to read the words from a file. However, I have to use `putchar(ch)` where `ch` is an `int`. How do I convert ch to a string (char \*) so I can store it in a char \* variable and pass it to another function that takes char \* as a parameter. And I actually just want to store it but not print it.
This is what I have:
```
int main (void)
{
static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
if ( file != NULL )
{
int ch, word = 0;
while ( (ch = fgetc(file)) != EOF )
{
if ( isspace(ch) || ispunct(ch) )
{
if ( word )
{
word = 0;
putchar('\n');
}
}
else
{
word = 1;
putchar(ch);
}
}
fclose(file);
}
return 0;
}
```
|
2015/08/03
|
['https://Stackoverflow.com/questions/31778365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4807625/']
|
`sprintf(char_arr, "%d", an_integer);`
This makes `char_arr` equal to string representation of `an_integer`
(This doesn't print anything to console output in case you're wondering, this just 'stores' it)
An example:
```
char char_arr [100];
int num = 42;
sprintf(char_arr, "%d", num);
```
`char_arr` now is the string `"42"`. `sprintf`automatically adds the null character `\0` to `char_arr`.
If you want to append more on to the end of char\_arr, you can do this:
```
sprintf(char_arr+strlen(char_arr), "%d", another_num);
```
the '+ strlen' part is so it starts appending at the end.
more info here: <http://www.cplusplus.com/reference/cstdio/sprintf/>
|
So you have a single value of `char` type, aka `int8_t` (or `uint8_t` on some systems). You have it stored in an `int`, so `fgetc` can return `-1` for error, but still be able to return any 8bit character.
Single characters are just 8-bit integers, which you can store in any size of integer variable without problems. Put them in an array with a zero-byte at the end, and you have a string.
```
char buffer[10] = {0};
int c = 'H';
buffer[0] = c;
// now buffer holds the null-terminated string "H"
buffer[1] = 'e';
buffer[2] = 'l'; // you can see where this is going.
c = buffer[1]; // c = 'e' = 101
// (assuming you compile this on a system that uses ASCII / unicode, not EBCDIC or some other dead character mapping).
```
Note that the string-terminating zero-bytes got into buffer because I initialized it. Using an array initializer zeroes any elements you don't mention in your initializer list.
|
31,778,365 |
So I am trying to read the words from a file. However, I have to use `putchar(ch)` where `ch` is an `int`. How do I convert ch to a string (char \*) so I can store it in a char \* variable and pass it to another function that takes char \* as a parameter. And I actually just want to store it but not print it.
This is what I have:
```
int main (void)
{
static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
if ( file != NULL )
{
int ch, word = 0;
while ( (ch = fgetc(file)) != EOF )
{
if ( isspace(ch) || ispunct(ch) )
{
if ( word )
{
word = 0;
putchar('\n');
}
}
else
{
word = 1;
putchar(ch);
}
}
fclose(file);
}
return 0;
}
```
|
2015/08/03
|
['https://Stackoverflow.com/questions/31778365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4807625/']
|
To represent a single character as a character string, I find using a simple 2-character buffer to be as easy as anything else. You can take advantage of the fact that dereferencing the string points to the first character and simply assign the character you wish to represent as a string. If you have initialized your 2-char buffer to `0` (or `'\0'`) when declared, you have insured your string is always `null-terminated`:
**Short Example**
```
#include <stdio.h>
int main (void) {
int ch;
char s[2] = {0};
FILE *file = stdin;
while ( (ch = fgetc(file)) != EOF ) {
*s = ch;
printf ("ch as char*: %s\n", s);
}
return 0;
}
```
**Use/Output**
```
$ printf "hello\n" | ./bin/i2s2
ch as char*: h
ch as char*: e
ch as char*: l
ch as char*: l
ch as char*: o
ch as char*:
```
**Note:** you can add `&& ch != '\n'` to the while condition to prevent printing the newline.
|
So you have a single value of `char` type, aka `int8_t` (or `uint8_t` on some systems). You have it stored in an `int`, so `fgetc` can return `-1` for error, but still be able to return any 8bit character.
Single characters are just 8-bit integers, which you can store in any size of integer variable without problems. Put them in an array with a zero-byte at the end, and you have a string.
```
char buffer[10] = {0};
int c = 'H';
buffer[0] = c;
// now buffer holds the null-terminated string "H"
buffer[1] = 'e';
buffer[2] = 'l'; // you can see where this is going.
c = buffer[1]; // c = 'e' = 101
// (assuming you compile this on a system that uses ASCII / unicode, not EBCDIC or some other dead character mapping).
```
Note that the string-terminating zero-bytes got into buffer because I initialized it. Using an array initializer zeroes any elements you don't mention in your initializer list.
|
31,778,365 |
So I am trying to read the words from a file. However, I have to use `putchar(ch)` where `ch` is an `int`. How do I convert ch to a string (char \*) so I can store it in a char \* variable and pass it to another function that takes char \* as a parameter. And I actually just want to store it but not print it.
This is what I have:
```
int main (void)
{
static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
if ( file != NULL )
{
int ch, word = 0;
while ( (ch = fgetc(file)) != EOF )
{
if ( isspace(ch) || ispunct(ch) )
{
if ( word )
{
word = 0;
putchar('\n');
}
}
else
{
word = 1;
putchar(ch);
}
}
fclose(file);
}
return 0;
}
```
|
2015/08/03
|
['https://Stackoverflow.com/questions/31778365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4807625/']
|
`sprintf(char_arr, "%d", an_integer);`
This makes `char_arr` equal to string representation of `an_integer`
(This doesn't print anything to console output in case you're wondering, this just 'stores' it)
An example:
```
char char_arr [100];
int num = 42;
sprintf(char_arr, "%d", num);
```
`char_arr` now is the string `"42"`. `sprintf`automatically adds the null character `\0` to `char_arr`.
If you want to append more on to the end of char\_arr, you can do this:
```
sprintf(char_arr+strlen(char_arr), "%d", another_num);
```
the '+ strlen' part is so it starts appending at the end.
more info here: <http://www.cplusplus.com/reference/cstdio/sprintf/>
|
To represent a single character as a character string, I find using a simple 2-character buffer to be as easy as anything else. You can take advantage of the fact that dereferencing the string points to the first character and simply assign the character you wish to represent as a string. If you have initialized your 2-char buffer to `0` (or `'\0'`) when declared, you have insured your string is always `null-terminated`:
**Short Example**
```
#include <stdio.h>
int main (void) {
int ch;
char s[2] = {0};
FILE *file = stdin;
while ( (ch = fgetc(file)) != EOF ) {
*s = ch;
printf ("ch as char*: %s\n", s);
}
return 0;
}
```
**Use/Output**
```
$ printf "hello\n" | ./bin/i2s2
ch as char*: h
ch as char*: e
ch as char*: l
ch as char*: l
ch as char*: o
ch as char*:
```
**Note:** you can add `&& ch != '\n'` to the while condition to prevent printing the newline.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.