text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Can I access Android HCE application if device is turned off?
I'm currently write Android HCE application. And I want to use my HCE application when the device is turned off. I found a way to "Access HCE when Screen off", but no information of power off status.
Is there any way to use HCE application when phone is turned off?
A:
No you can't access because of security reason
One correction also its not accessible if screen is off as mentioned in provided link.
Current Android implementations turn the NFC controller and the application processor off completely when the screen of the device is turned off. HCE services will therefore not work when the screen is off.
It may work on some devices only if vendor implements the OS customized.
| {
"pile_set_name": "StackExchange"
} |
Q:
Disable the link on the active tab (Bootstrap)
I use tabs via Bootstrap. I can't reach my goals for this problem. Imagine a simple case such as the example below. When I click on a tab, the content is displayed, it is perfect.
Now assume that the content to load resource intensive and is long to arrive (eg a large SQL query), I don't want when I click again on the same tab, the content is recharging.
However, I can't produce it. The example below illustrates my problem, because if you re-click on the tab, we see that the background changes anyway, so I wouldn't change it.
The HTML :
<div role="tabpanel">
<ul class="nav nav-tabs" role="tablist" id="myTab">
<li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
<li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
<li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
<li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
</ul>
<div class="tab-content text-center">
<div role="tabpanel" class="tab-pane active" id="home"><p><i class="fa fa-refresh fa-spin"></i> HOME </p></div>
<div role="tabpanel" class="tab-pane" id="profile"><p><i class="fa fa-refresh fa-spin"></i> PROFILE </p></div>
<div role="tabpanel" class="tab-pane" id="messages"><p><i class="fa fa-refresh fa-spin"></i> MESSAGES </p></div>
<div role="tabpanel" class="tab-pane" id="settings"><p><i class="fa fa-refresh fa-spin"></i> SETTINGS </p></div>
</div>
</div>
And the associated jQuery is just that the documentation provided by Bootstrap $('#myTab a').tab('show');
Please look at this JSFIDDLE
So how to disable the tab when it is active?
A:
Check the DEMO
$(document).ready(function(){
$('#myTab a').tab('show');
$('#myTab a').click(function(){
if (!$(this).closest('li').hasClass('active')) {
$('.tab-content').css('background', '#' + random_colour());
}
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
JAVA quiz - Same question repeating while answers do cycle correctly
I'm doing a quiz that has a sequence of 3 questions. After choosing the right or wrong answer, it should go to the next question and present the next set of possible answers.
My code does show the answers correctly, but the question repeats itself three times. As another side effect, the set of three quizzes become nine, with the following order: Q1/A1, Q1/A2, Q1/A3, Q2/A1, Q2/A2, Q2/A3, Q3/A1, Q3/A2, Q3/A3.
The desired result is Q1/A1, Q2/A2, Q3/A3.
Here is my code:
import javax.swing.JOptionPane;
public class Quiz {
private static String answer = null;
private static String answer2 = null;
private static String answer3 = null;
static int nQuestions = 0;
static int nCorrect = 0;
//Main program, will call the questions to be answered in the quiz and checks if it's correct
//counting both the number of questions and correct answers.
public static void main(String[] args) {
String question = "What is the planet with fastest orbit?\n";
check(question, answer);
nQuestions = nQuestions+1;
JOptionPane.showMessageDialog(null,"Out of " + nQuestions + " you had "+ nCorrect + " correct answers");
String question2 = "The sum of 2 + 2.0 is?\n";
check(question2, answer2);
nQuestions = nQuestions+1;
String question3 = "What is the sport the player shoots the ball in a basket\n";
check(question3, answer3);
nQuestions = nQuestions+1;
JOptionPane.showMessageDialog(null,"Out of " + nQuestions + " you had "+ nCorrect + " correct answers");
}
//The quiz #1
static String ask(String question) {
question += "A. Mercury, with a rotation that takes 58d 16h.\n";
question += "B. Earth, with a rotation that takes 23h 56m.\n";
question += "C. Mars, with a rotation that takes 24h 36m.\n";
question += "D. Venus, with a rotation that takes 243d 26m.\n";
question += "E. Uranus, with a rotation that takes 17h 14m.\n";
String answer = JOptionPane.showInputDialog(question);
answer = answer.toUpperCase();
while (!answer.equals("A") && !answer.equals("B") && !answer.equals("C") && !answer.equals("D") && !answer.equals("E")) {
JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
answer = JOptionPane.showInputDialog(question);
answer = answer.toUpperCase();
}
return answer;
}
//The quiz #2
static String ask2(String question2) {
question2 += "A. 4\n";
question2 += "B. 4.0\n";
question2 += "C. 3\n";
question2 += "D. 5\n";
question2 += "E. -4\n";
String answer2 = JOptionPane.showInputDialog(question2);
answer2 = answer2.toUpperCase();
while (!answer2.equals("A") && !answer2.equals("B") && !answer2.equals("C") && !answer2.equals("D") && !answer2.equals("E")) {
JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
answer2 = JOptionPane.showInputDialog(question2);
answer2 = answer2.toUpperCase();
}
return answer2;
}
//The quiz #3
static String ask3(String question3) {
question3 += "A. Basketball.\n";
question3 += "B. Volleyball.\n";
question3 += "C. Baseball.\n";
question3 += "D. Football.\n";
question3 += "E. Tennis\n";
String answer3 = JOptionPane.showInputDialog(question3);
answer3 = answer3.toUpperCase();
while (!answer3.equals("A") && !answer3.equals("B") && !answer3.equals("C") && !answer3.equals("D") && !answer3.equals("E")) {
JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
answer3 = JOptionPane.showInputDialog(question3);
answer3 = answer3.toUpperCase();
}
return answer3;
}
//Answer verifier
static void check(String question, String correctAnswer) {
String answer = ask(question);
String correct = "D";
if (answer.equals(correct)) {
JOptionPane.showMessageDialog(null,"Correct!");
nCorrect = nCorrect+1;
}
else if (answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("E")) {
JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct);
}
//checking Quiz#2
String answer2 = ask2(question);
String correct2 = "B";
if (answer2.equals(correct2)) {
JOptionPane.showMessageDialog(null,"Correct!");
nCorrect = nCorrect+1;
}
else if (answer2.equals("A") || answer2.equals("C") || answer2.equals("D") || answer2.equals("E")) {
JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct2);
}
//checking Quiz#3
String answer3 = ask3(question);
String correct3 = "A";
if (answer3.equals(correct3)) {
JOptionPane.showMessageDialog(null,"Correct!");
nCorrect = nCorrect+1;
}
else if (answer3.equals("B") || answer3.equals("C") || answer3.equals("D") || answer3.equals("E")) {
JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct3);
}
}
}
I'm a beginner java student and I do realize some sort of unintended loop, but I'm not being able to fix it.
Any suggestions? Thanks in advance.
A:
Welcome to SO.
There are a lot of issues with your code, but since you've just started that's understandable.
You should really consider using arrays, and that's why I added one for you so you can get a feel for them.
Your main issue was that you are using the same answer selections for each question 3 times.
The following code should give you what you want:
import javax.swing.JOptionPane;
public class Quiz {
private static String answer = null;
private static String answer2 = null;
private static String answer3 = null;
static int nQuestions = 0;
static int nCorrect = 0;
//Main program, will call the questions to be answered in the quiz and checks if it's correct
//counting both the number of questions and correct answers.
public static void main(String[] args) {
String[] questions = {"What is the planet with fastest orbit?\n",
"The sum of 2 + 2.0 is?\n",
"What is the sport the player shoots the ball in a basket\n"
};
nQuestions = questions.length;
checkQuestions(questions, answer3);
JOptionPane.showMessageDialog(null,"Out of " + nQuestions + " you had "+ nCorrect + " correct answers");
}
//The quiz #1
static String ask(String question) {
question += "A. Mercury, with a rotation that takes 58d 16h.\n";
question += "B. Earth, with a rotation that takes 23h 56m.\n";
question += "C. Mars, with a rotation that takes 24h 36m.\n";
question += "D. Venus, with a rotation that takes 243d 26m.\n";
question += "E. Uranus, with a rotation that takes 17h 14m.\n";
String answer = JOptionPane.showInputDialog(question);
answer = answer.toUpperCase();
while (!answer.equals("A") && !answer.equals("B") && !answer.equals("C") && !answer.equals("D") && !answer.equals("E")) {
JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
answer = JOptionPane.showInputDialog(question);
answer = answer.toUpperCase();
}
return answer;
}
//The quiz #2
static String ask2(String question2) {
question2 += "A. 4\n";
question2 += "B. 4.0\n";
question2 += "C. 3\n";
question2 += "D. 5\n";
question2 += "E. -4\n";
String answer2 = JOptionPane.showInputDialog(question2);
answer2 = answer2.toUpperCase();
while (!answer2.equals("A") && !answer2.equals("B") && !answer2.equals("C") && !answer2.equals("D") && !answer2.equals("E")) {
JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
answer2 = JOptionPane.showInputDialog(question2);
answer2 = answer2.toUpperCase();
}
return answer2;
}
//The quiz #3
static String ask3(String question3) {
question3 += "A. Basketball.\n";
question3 += "B. Volleyball.\n";
question3 += "C. Baseball.\n";
question3 += "D. Football.\n";
question3 += "E. Tennis\n";
String answer3 = JOptionPane.showInputDialog(question3);
answer3 = answer3.toUpperCase();
while (!answer3.equals("A") && !answer3.equals("B") && !answer3.equals("C") && !answer3.equals("D") && !answer3.equals("E")) {
JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
answer3 = JOptionPane.showInputDialog(question3);
answer3 = answer3.toUpperCase();
}
return answer3;
}
//Answer verifier
static void checkQuestions(String[] questions, String correctAnswer) {
String answer = ask(questions[0]);
String correct = "D";
if (answer.equals(correct)) {
JOptionPane.showMessageDialog(null,"Correct!");
nCorrect = nCorrect+1;
}
else if (answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("E")) {
JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct);
}
//checking Quiz#2
String answer2 = ask2(questions[1]);
String correct2 = "B";
if (answer2.equals(correct2)) {
JOptionPane.showMessageDialog(null,"Correct!");
nCorrect = nCorrect+1;
}
else if (answer2.equals("A") || answer2.equals("C") || answer2.equals("D") || answer2.equals("E")) {
JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct2);
}
//checking Quiz#3
String answer3 = ask3(questions[2]);
String correct3 = "A";
if (answer3.equals(correct3)) {
JOptionPane.showMessageDialog(null,"Correct!");
nCorrect = nCorrect+1;
}
else if (answer3.equals("B") || answer3.equals("C") || answer3.equals("D") || answer3.equals("E")) {
JOptionPane.showMessageDialog(null,"Incorrect! The answer is " + correct3);
}
}
}
Let me know if you have any questions about what I did. I tried to keep as much of the code the same while fixing the issue.
Good luck.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use JavaScript variable in img src attribute?
Below JavaScript function is called after selecting option from <select> tag.
function function1()
{
var country=document.getElementById('id1').value;
switch(country)
{
case "India":
logo="rupee.png";
break;
case "US":
logo="dollar-logo.png";
break;
case "Britan":
logo="yen.png";
break;
}
Now i want to display flag of country according to selection has made..
Below is HTML file where i want to display image..
<td><img src="+logo+" width=30 height=30></td>
I also tried this one..
<td><img src="<%Eval(logo)%>" width=30 height=30></td>
A:
You can just use
case "India":
myImg.src="rupee.png";
break;
case "US":
myImg.src="dollar-logo.png";
break;
case "Britan":
myImg.src="yen.png";
break;
where myImg is your image. In your current html, it is:
var myImg = document.getElementsByTagName("img")[0];
Or you can add id attribute to your image (<img id="logo" width=30 height=30>), so you can use
var myImg = document.getElementById("logo");
(you should place myImg initialization at the beginning of the function1())
| {
"pile_set_name": "StackExchange"
} |
Q:
How to uninstall "Munki Managed Software Center.app"?
How to properly uninstall
mymac:~ meself$ brew doctor
Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry and just ignore them. Thanks!
Warning: "config" scripts exist outside your system or Homebrew directories.
`./configure` scripts often look for *-config scripts to determine if
software packages are installed, and what additional flags to use when
compiling and linking.
Having additional scripts in your path can confuse software installed via
Homebrew if the config script overrides a system or Homebrew provided
script of the same name. We found the following "config" scripts:
/usr/local/munki/munkiwebadmin-config
mymac:~ meself$ locate munki
/Applications/Managed Software Center.app/Contents/Resources/MunkiStatus.app/Contents/Resources/munki.py
/Applications/Managed Software Center.app/Contents/Resources/MunkiStatus.app/Contents/Resources/munki.pyc
/Applications/Managed Software Center.app/Contents/Resources/munki.py
/Library/LaunchAgents/com.googlecode.munki.ManagedSoftwareCenter.plist
/Library/LaunchAgents/com.googlecode.munki.MunkiStatus.plist
/Library/LaunchAgents/com.googlecode.munki.managedsoftwareupdate-loginwindow.plist
/Library/LaunchDaemons/com.googlecode.munki.logouthelper.plist
/Library/LaunchDaemons/com.googlecode.munki.managedsoftwareupdate-check.plist
/Library/LaunchDaemons/com.googlecode.munki.managedsoftwareupdate-install.plist
/Library/LaunchDaemons/com.googlecode.munki.managedsoftwareupdate-manualcheck.plist
/private/etc/paths.d/munki
/private/var/db/BootCaches/85073A52-7A3F-4A63-B0B6-C992C2CAFBC6/app.com.googlecode.munki.ManagedSoftwareCenter.playlist
/private/var/db/receipts/com.googlecode.munki.admin.bom
/private/var/db/receipts/com.googlecode.munki.admin.plist
/private/var/db/receipts/com.googlecode.munki.app.bom
/private/var/db/receipts/com.googlecode.munki.app.plist
/private/var/db/receipts/com.googlecode.munki.core.bom
/private/var/db/receipts/com.googlecode.munki.core.plist
/private/var/db/receipts/com.googlecode.munki.launchd.bom
/private/var/db/receipts/com.googlecode.munki.launchd.plist
/private/var/db/receipts/com.googlecode.munki.munkiwebadmin-scripts.bom
/private/var/db/receipts/com.googlecode.munki.munkiwebadmin-scripts.plist
/usr/local/munki
/usr/local/munki/launchapp
/usr/local/munki/logouthelper
/usr/local/munki/makecatalogs
/usr/local/munki/makepkginfo
/usr/local/munki/managedsoftwareupdate
/usr/local/munki/manifestutil
/usr/local/munki/munkiimport
/usr/local/munki/munkilib
/usr/local/munki/munkilib/FoundationPlist.py
/usr/local/munki/munkilib/FoundationPlist.pyc
/usr/local/munki/munkilib/__init__.py
/usr/local/munki/munkilib/__init__.pyc
/usr/local/munki/munkilib/adobeutils.py
/usr/local/munki/munkilib/adobeutils.pyc
/usr/local/munki/munkilib/appleupdates.py
/usr/local/munki/munkilib/appleupdates.pyc
/usr/local/munki/munkilib/fetch.py
/usr/local/munki/munkilib/fetch.pyc
/usr/local/munki/munkilib/gurl.py
/usr/local/munki/munkilib/gurl.pyc
/usr/local/munki/munkilib/iconutils.py
/usr/local/munki/munkilib/installer.py
/usr/local/munki/munkilib/installer.pyc
/usr/local/munki/munkilib/keychain.py
/usr/local/munki/munkilib/keychain.pyc
/usr/local/munki/munkilib/launchd.py
/usr/local/munki/munkilib/launchd.pyc
/usr/local/munki/munkilib/munkicommon.py
/usr/local/munki/munkilib/munkicommon.pyc
/usr/local/munki/munkilib/munkistatus.py
/usr/local/munki/munkilib/munkistatus.pyc
/usr/local/munki/munkilib/removepackages.py
/usr/local/munki/munkilib/removepackages.pyc
/usr/local/munki/munkilib/updatecheck.py
/usr/local/munki/munkilib/updatecheck.pyc
/usr/local/munki/munkilib/utils.py
/usr/local/munki/munkilib/utils.pyc
/usr/local/munki/munkilib/version.plist
/usr/local/munki/munkiwebadmin-config
/usr/local/munki/postflight
/usr/local/munki/preflight
/usr/local/munki/ptyexec
/usr/local/munki/report_broken_client
/usr/local/munki/supervisor
mymac:~ meself$
The reason to uninstall it is that it is incompatible with Homebrew.
A:
Munki and Managed Software Center are not incompatible with Homebrew. You might be better off describing the specific issues you are seeing.
One known issue is that certain versions of the Homebrew installer recursively change the owner of /usr/bin and contents to that of the user installing Homebrew. For Munki to function properly, /usr/local/munki and contents must have a user of root, group of wheel, and not allow writes to everyone. You can fix the issue that a Homebrew install causes simply:
sudo chown -R root:wheel /usr/local/munki
sudo chmod -R o-w /usr/local/munki
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ cin Question
Okay, I was writing a simple C++ function to combine cin'd strings. I'm working on Linux at the moment, so I don't have the luxury of a simple "getline(cin, input)" command. Here's the code so far:
string getLine()
{
string dummy;
string retvalue;
do
{
cin << dummy;
retvalue += dummy;
} while
return retvalue;
}
What I want to know is this: is the prompt actually asking the user for input, or is it still reading from the buffer that was left over because of a space?
A:
There is a getline defined for strings:
std::string line;
std::getline(std::cin, line);
A:
I'm working on Linux at the moment, so I don't have the luxury of a simple "getline(cin, input)" command.
What's Linux got to do with it? getline is standard C++, except it's spelled cin.getline(input, size[, delimiter]).
Edit: Not deleting this because it's a useful reference, but AraK's post illustrating std::getline should be preferred for people who want a std::string. istream's getline works on a char * instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can someone explain the Yoneda Lemma to an applied mathematician?
I have trouble following the category-theoretic statement and proof of the Yoneda Lemma. Indeed, I followed a category theory course for 4-5 lectures (several years ago now) and felt like I understood everything until we covered the Yoneda Lemma, after which point I lost interest.
I guess what I'm asking for are some concrete examples of the Yoneda Lemma in action. For example, how does it apply to specific categories, like a category with one element, or the category Grp or Set? What results does it generalize? Is there a canonical route to understanding the statement of the Lemma?
If you need to assume knowledge, then assume I have a fairly rigorous education in pure/applied mathematics at the undergraduate level but no further.
A:
Roughly speaking, the Yoneda lemma says that one can recover an object $X$ up to isomorphism from knowledge of the hom-sets $\text{Hom}(X, Y)$ for all other objects $Y$. Equivalently, one can recover an object $X$ up to isomorphism from knowledge of the hom-sets $\text{Hom}(Y, X)$.
As I have said before on math.SE, there is a meta-principle in category theory that to understand something for all categories, you should first understand it for posets, regarded as categories where $a \le b$ if and only if there is a single arrow $a \to b$, and otherwise there are no morphisms from $a$ to $b$. For posets, Yoneda's lemma says that an object is determined up to isomorphism by the set of objects less than or equal to it (equivalently, the set of objects greater than or equal to it). In other words, it is determined by a Dedekind cut! In other other words, Yoneda's lemma for posets says the following:
$a \le b$ if and only if for all objects $c$ we have $c \le a \Rightarrow c \le b$.
This is a surprisingly useful idea in real analysis. More generally it leads to the idea that Yoneda's lemma, among other things, embeds a category into a certain "completion" of that category: in fact the standard contravariant Yoneda embedding embeds a category into its free cocompletion, the category given by "freely adjoining colimits."
As far as examples go, it turns out that in many categories one can restrict attention to a few specific objects $Y$. For example:
In $\text{Set}$ one can completely recover an object $S$ from $\text{Hom}(1, S)$.
In $\text{Grp}$ one can completely recover an object $G$ from $\text{Hom}(\mathbb{Z}, G)$. This is because a homomorphism from $\mathbb{Z}$ is freely determined by where it sends $1$, and one can recover the multiplication because $\mathbb{Z}$ is naturally a cogroup object, which is equivalent to the claim that $\text{Hom}(\mathbb{Z}, G)$ naturally carries a group structure (that of $G$).
In $\text{CRing}$ (the category of commutative rings) one can completely recover an object $R$ from $\text{Hom}(\mathbb{Z}[x], R)$. The story is similar to that above; it is explained in this blog post. Geometrically this means that one can completely recover an affine scheme $\text{Spec } R$ from $\text{Hom}(\text{Spec } R, \mathbb{A}^1(\mathbb{Z}))$, the ring of functions on it.
In $\text{Top}$ (the category of topological spaces) one can completely recover an object $X$ from $\text{Hom}(1, X)$ (the points of $X$) and $\text{Hom}(X, \mathbb{S})$, where $\mathbb{S}$ is the Sierpinski space. The latter precisely gives you the open sets of $X$, and together with knowledge of the composition map $\text{Hom}(1, X) \times \text{Hom}(X, \mathbb{S}) \to \text{Hom}(1, \mathbb{S})$ you can recover the knowledge of which points sit inside which open sets.
A:
I think there are two important questions.
A. Why does it work?
When you have an object $A$, then you may think of any object $X$ as of a "perspective" from which the object $A$ is seen. Then a morphism $X \rightarrow A$ corresponds to a particular point of view from a given perspective $X$. In this sense, ordinary sets have one global perspective (a singleton, or a "terminal" set) that describes all aspects of a particular set --- namely morphisms $1 \rightarrow A$ correspond to the elements of $A$, and sets having the same elements are "the same". On the contrary in a category like $\mathbf{Grp}$, the global perspective says exactly nothing about objects.
Yoneda lemma works, because (in general) watching objects from all perspectives give you all (important, that is external) information about the objects. That is: $$\mathit{hom}(-, A) \approx \mathit{hom}(-, B) \Rightarrow A \approx B$$
B. What does it mean?
Almost everything, but I like, and do think is the most important, the following. You may think of a functor $F \colon \mathbb{C}^{op} \rightarrow \mathbf{Set}$ as of a kind of a generalized algebra over signature $\mathbb{C}$ --- objects of $\mathbb{C}$ correspond to "sorts" whereas morphisms to "operations"; then functor $F$ gives just an interpretation for every "sort" (a set), and for every morphism (a function between sets); it is easy to see that then natural transformations between such functors are generalizations of algebra homomorphisms in the usual sense.
Yoneda lemma says that every category can be thought as a full subcategory of generalized algebras over generalized signatures. Particularly, categories are given as merely generalized graphs satisfying some equations; thanks to Yoneda lemma, we may think of these abstract nodes (objects) as of "real structures" (algebras), and of edges (morphisms), as of "real functions" preserving that structures.
Put it another way. The standard mathematics starts from "elements" formed into structures. This is the "internal view". Then we define "mappings" that preserve structures, and we are (mostly) willing to forget about specific elements --- what becomes important is how these structures look from the perspective of "mappings" (for example, we do not want to distinguish isomorphic structures, despite the fact that their "elements" may be far different). This is the "external view".
So the standard mathematics starts from the "internal view" and then switches to the "external view", whilst category theory starts from the "external view" --- and due to Yoneda lemma --- we know that the "internal view" exists as well.
One may also say that the difference between the standard mathematics and category theory is just like the difference between Aristotelian physics and Galilean physics. Take for example the concept of velocity. In Aristotelian physics we may say that an object moves at a certain velocity (the concept of a velocity is an internal property of an object). By contrast, such a statement does not make any sense in Galilean physics --- in the later we may only say that an object moves at a certain velocity with respect to another object (the concept of a velocity is an external aspect of some objects, it is not a property of a single object). However, in Galilean physics, we may "internalize" the concept of velocity by saying what are the velocities of an object in respect to all possible objects (such a collection of velocities indexed by objects would be its internal property).
A:
I view the Yoneda lemma as a generalization of Cayleys theorem. http://en.wikipedia.org/wiki/Cayley%27s_theorem . This interpretation is useful if you are somewhat comfortable with groups.
Suppose we are given a group $G$, e.g. $\mathbb{Z}/{3\mathbb{Z}}$. Then we can study how the elements of this group act on itself, via left multiplication. For example, multiplying all elements in the example group by the element $\overline{2}$ does the following to the elements
$\overline{0}\mapsto \overline{2}$
$\overline{1}\mapsto \overline{0}$
$\overline{2}\mapsto \overline{1}$
Note that this map is a permutation of the elements of the group (i.e. we attached an permutation of the group elements to the element $\overline{2}$). What we construct here is a homomorphism $G\rightarrow S_{G}$. The group on the right hand side is the group of all permutations on elements of $G$. This map is injective. The first isomorphism theorem now shows that $G$ is isomorphic to a subgroup of $S_G$. Hence all groups are subgroups of symmetric groups. This is Cayley's theorem.
The Yoneda lemma shows that this also works for categories. Any subcategory can be viewed as a subcategory of presheaves. Presheaves play the role of permutations.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to implement a queue in Go?
The current Go library doesn't provide the queue container.
To implement a simple queue, I use circle array as the underlying data structure.
It follows algorithms mentioned in TAOCP:
Insert Y into queue X: X[R]<-Y; R<-(R+1)%M; if R=F then OVERFLOW.
Delete Y from queue X: if F=R then UNDERFLOW; Y<-X[F]; F<-(F+1) % M.
F: Front, R: Rear, M: Array length.
Following is the code:
package main
import (
"fmt"
)
type Queue struct {
len int
head, tail int
q []int
}
func New(n int) *Queue {
return &Queue{n, 0, 0, make([]int, n)}
}
func (p *Queue) Enqueue(x int) bool {
p.q[p.tail] = x
p.tail = (p.tail + 1) % p.len
return p.head != p.tail
}
func (p *Queue) Dequeue() (int, bool) {
if p.head == p.tail {
return 0, false
}
x := p.q[p.head]
p.head = (p.head + 1) % p.len
return x, true
}
func main() {
q := New(10)
for i := 1; i < 13; i++ {
fmt.Println(i, q.Enqueue(i))
}
fmt.Println()
for i := 1; i < 13; i++ {
fmt.Println(q.Dequeue())
}
}
But the output is obviously wrong:
1 true
2 true
3 true
4 true
5 true
6 true
7 true
8 true
9 true
10 false
11 true
12 true
11 true
12 true
0 false
0 false
0 false
0 false
0 false
0 false
0 false
0 false
0 false
0 false
I think I need one more field to make the code work properly.
What do you suggest?
The improved code has a small shortcoming: an array of size n can contain only n-1 elements.
package main
import (
"fmt"
)
type Queue struct {
len int
head, tail int
q []int
}
func New(n int) *Queue {
return &Queue{n, 0, 0, make([]int, n)}
}
func (p *Queue) Enqueue(x int) bool {
p.q[p.tail] = x
ntail := (p.tail + 1) % p.len
ok := false
if ntail != p.head {
p.tail = ntail
ok = true
}
return ok
}
func (p *Queue) Dequeue() (int, bool) {
if p.head == p.tail {
return 0, false
}
x := p.q[p.head]
p.head = (p.head + 1) % p.len
return x, true
}
func main() {
q := New(10)
for i := 1; i < 13; i++ {
fmt.Println(i, q.Enqueue(i))
}
fmt.Println()
for i := 1; i < 13; i++ {
fmt.Println(q.Dequeue())
}
}
A:
You do not need all this hustle in any reasonable go version (after 1.x). Everything can be achieved with slices.
queue := []int{}
Add to a queue:
queue = append(queue, 6)
Pop from a queue:
el := queue[0]
queue = queue[1:]
Here is implementation that shows that pop does not take a lot of time (in fact here it is shorter than push because in my opinion of reallocation of memory when the queue is growing).
package main
import (
"fmt"
"time"
)
func main() {
n := 10000000
queue := []int{1, 2, 3}
start := time.Now()
for i := 0; i < n; i++ {
queue = append(queue, i)
}
elapsed := time.Since(start)
fmt.Println(elapsed)
start = time.Now()
for i := 0; i < n; i++ {
_ = queue[0]
queue = queue[1:]
}
elapsed = time.Since(start)
fmt.Println(elapsed)
fmt.Println(queue)
}
On my machine the numbers are:
216.611664ms
13.441106ms
From @DaveC's comment:
This is simple and works very well for everything except critical code
where allocations (pressure on the garbage collector) is
undesirable.Two things to note, first it does keep re-allocating the
underlying array on push (although efficiently and not on every call)
and pop doesn't free any space until that happens. This leads to the
second thing, if (as is common) the queue contains a pointer to
something, then it's good to do queue[0] = nil; queue = queue[1:] to
have the queue stop referencing the pointer right away.
A:
When Enqueue fails, you're still incrementing p.tail, so next time it will appear not to fail -- that explains the single false in your first loop (and messes everything up for the second one). The original algorithm says OVERFLOW meaning "give everything up", not "just keep going as if nothing untowards happened";-).
All you need to do is decrement p.tail if you've checked that failure's occurring -- or put the incremented value in a local temporary and move it to p.tail only if failure is not occurring, that may be more elegant. This way, the failing Enqueue does not enqueue the new value, but the queue itself (without that overflowing value) is still semantically intact and correct for future operations.
| {
"pile_set_name": "StackExchange"
} |
Q:
Typhoon support "Autowire" and "Scope" definition
If I compare Typhoon with one of the common IOC container spring in java i could not find two important freatures in the documentation.
How to annotate @autowired?
How to annotate @Scope? Especially distinglish between SCOPE_SINGLETON and SCOPE_PROTOTYPE.
More about spring here:
http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/html/beans.html#beans-standard-annotations
A:
Typhoon supports the prototype and singleton scopes along with two other scopes designed specifically for mobile and desktop applications.
In a server-side application, the server may be supporting any of the application's use-cases at a given time. Therefore it makes sense for those components to have the singleton scope. In a mobile application, while there are background services its more common to service one use case at a time. And there are memory, CPU and batter constraints.
Therefore the default scope with Typhoon is TyphoonScopeObjectGraph, which means that references to other components while resolving eg a top-level controller will be shared. In this way an object graph can be loaded up and then disposed of when done.
There's also the following:
TyphoonScopeSingleton
TyphoonScopePrototype
TyphoonScopeWeakSingleton
Auto-wiring macros vs native style assembly:
Unfortunately, Objective-C has only limited run-time support for "annotations" using macros. So the option was to use either a compile-time pre-processor, which has some drawbacks, or to work around the limitations and force it in using a quirky style. We decided that its best (for now) to use Macros only for simple convention-over-configuration cases.
For more control we strongly recommend using the native style of assembly. This allows the following:
Modularize an application's configuration, so that the architecture tells a story.
IDE code-completion and refactoring works without any additional plugins.
Components can be resolved at runtime using the assembly interface, using Objective-C's AOP-like dynamism.
To set the scope using the native style:
- (id)rootController
{
return [TyphoonDefinition withClass:[RootViewController class]
configuration:^(TyphoonDefinition* definition)
{
definition.scope = TyphoonScopeSingleton;
}];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Solve the differential equation $x^2\frac{d^2y}{dx^2}+x\frac{dy}{dx}+(x-1)y=0$
$$x^2\frac{d^2y}{dx^2}+x\frac{dy}{dx}+(x-1)y=0$$
$$\sum_{n=0}^{\infty}(n+r)(n+r-1)c_nx^{n+r}+\sum_{n=0}^{\infty}(n+r)c_nx^{n+r}+\sum_{n=1}^{\infty}c_{n-1}x^{n+r}-\sum_{n=0}^{\infty}c_nx^{n+r}$$
The exponents of the equation is then,
$$r^2-1=0$$
$$r_1=1,r_2=-1$$
The first solution is given by
$$c_n=\frac{c_{n-1}}{1-(n+1)^2}$$
$$c_1=-\frac{c_0}{3}$$
$$c_2=-\frac{c_1}{8}$$
$$c_3=-\frac{c_2}{15}$$
$$y_1(x)=1+2\sum_{n=1}^{\infty}\frac{(-1)^n(x^n)}{(n!)(n+2)!}$$
I can't seem to find the second solution,
$$r=r_2=-1$$
The recurrence formula is given by
$$c_n=\frac{c_{n-1}}{1-(n-1)^2},n\neq 2$$
We then have linearly independent solution
For $n>2$
$$c_3=-\frac{c_2}{3}$$
$$c_4=-\frac{c_3}{8}$$
$$c_5=-\frac{c_4}{15}$$
$$c_6=-\frac{c_5}{24}$$
I notice that the two are the same. How shall I find the linearly independent $y_2$ with log in it. Any help would be appreciated.
A:
First, you might note that your $c_n$ are given for $n > 2$ by $c_n = \frac{2(-1)^nc_2}{n!(n-2)!}$ (which we can get from your closed-form solution for the first sequence by simply shifting $n$ by $2$). This should allow you to construct your $y_2$. However, there is an easier way to get the solution by making this equation look like a more familiar ODE. Make the substitution $x = \frac{s^2}{4}$. Then, \begin{align*} \frac{\mathrm{d}y}{\mathrm{d}x} &= \frac{2}{s}\frac{\mathrm{d}y}{\mathrm{d}s} \\ \frac{\mathrm{d}^2y}{\mathrm{d}x^2} &= \frac{4}{s^2}\frac{\mathrm{d}^2y}{\mathrm{d}s^2}-\frac{4}{s^3}\frac{\mathrm{d}y}{\mathrm{d}s} \end{align*} This allows us to rewrite our equation as $$\frac{1}{4}\left(s^2\frac{\mathrm{d}^2y}{\mathrm{d}s^2}+s\frac{\mathrm{d}y}{\mathrm{d}s}+(s^2-4)y\right) = 0$$ Notice that this is Bessel's equation and will therefore have solutions $$y = c_1J_2(s)+c_2Y_2(s) = c_1J_2(2\sqrt{x})+c_2Y_2(2\sqrt{x})$$ The Bessel functions will have the same series representations as those produced by the Frobenius method you have used.
| {
"pile_set_name": "StackExchange"
} |
Q:
A weird problem with command printf
I am using Simple Scalar toolset to run some simulations on cache associativity. And I am seeing some strangest behavior with printf function. Here is the code snippet:
printf(" Name: %s %d %d %d \n", name, nsets, cp->set_shift, cp->set_mask);
printf(" Name: %s %d %d %d \n", name, cp->set_mask, nsets, cp->set_shift);
The printf lines are one after another, no other code in between. And here is the output:
Name: dl1 128 5 127
Name: dl1 127 0 128
The output of second printf is wrong. The output of the second printf should be :
Name: dl1 127 128 5
Changing the relative order of printf statements does not change the output. What part of printf I am missing to understand??
With regards
Newbie
A:
Go look at the variable declarations. My guess is somebody is a short or long, not an int. Since printf can't check what you pass for validity, it decides how many bites to grab from the stack based on the % signs. If your args don't agree with the format, not a compile error, but garbage can come out.
A:
I'd guess you have a mis-match between the type you're passing and the type you're telling print that you're passing. Specifically, it looks like cp->set_mask is some type larger than int. Since you've told printf that it's an int, it's taking the first sizeof(int) bytes as the first int, and then the next sizeof(int) bytes as if it were nsets (and since you're apparently on a little-endian machine, those bytes all contain 0). Note, in particular, that after the 0 comes the 128 that the first prints says is the value of nsets.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysql backup from ibdata1, ib_logfile1, ib_logfile0
I accidentally deleted my word press mysql DB. Below is the list of log files that i see in my directory where i am hoping i can get back some of my data.
I actually converted the first file (mysql-bin.000001) to sql and saw the create statements for wordpress tables. That made me hopeful about the fact that i might be able to recover all my data. However, i ran all the mysql commands in the below mysql binary log files, and could only bring up a very old version of the wordpress blog.
Can i recover my data using the ibdata1, ib_logfile1, ib_logfile0 files?
A:
i re-ran the sql statements in the binary log files on the same DB instance (which gave me a older version of my wordpress tables)
Ouch. How much hope there was for recovery depended on whether your tables were using the MyISAM or the InnoDB storage engine. If MyISAM, then... "none," and if InnoDB, then "some."
MyISAM, the older engine, stores its data in files named after the table, with an MYD extension, while InnoDB stores its data either in files named after the table, with an ibd extension, or in the ibdata1 file, which houses the system tablespace, depending on the setting of innodb_file_per_table in configuration. The definition of each the table (column names, data types, index definitions), for either engine, is stored in files named after the tables, with an frm extension.
The large size of your ibdata1 file suggested that maybe you didn't have innodb_file_per_table enabled, and that some variation of the following steps might have worked, if you were indeed using InnoDB without innodb_file_per_table:
Make a backup copy of everything.
Set up a separate, new MySQL server.
Apply the binlogs you have to the new server, in the interest of recreating the .frm files for the table definitions, and then manually altering any tables to make any changes you recall that aren't accounted for in the older binlogs.
Stop the new server.
Copy directories inside your data directory and their .frm files to the appropriate places on the old server
Start the old server, using innodb_force_recovery if needed, to see how well InnoDB would manage to pair up the .frm files with the table data in ibdata1, which it should, if the table definitions were the same.
Since you have already created new tables, presumably with the same names, on the existing server, any hope for that plan to have succeeded are likely to be eliminated, or significantly diminished to the point that it is unlikely to be worth trying, since your best hope if you tried it would be to see what you are seeing now -- old data that you inserted into tables you created from the binary logs.
So, what's plan B? To borrow a fitting phrase from the source I'll cite:
"It is a tedious process that requires an understanding of InnoDB's internal data storage format, C programming, and quite a bit of intuition and experience."
http://www.percona.com/docs/wiki/innodb-data-recovery-tool:start
The Percona InnoDB Data Recovery Tool is the only meaningful approach I can think of that might get you where you need to be... or any comparable tools, assuming there are comparable tools. I don't see any simple path... you're going to have to go "low level" if you want to rescue your data.
You have deleted important files, and in an effort to recover from the first problem, you have altered the one remaining file that might have been salvageable, and I'm not entirely sure how InnoDB will have handled those abandoned tables in its internal structures. The data may still be hiding.
There is one reason for optimism, though, and that is in the strings utility. The link I've provided is not to the genuine GNU "strings" utility, it's Microsoft's analogous semi-equivalent, but the point of this tool is to display strings embedded in files that the internal algorithm thinks might be human-meaningful strings.
There are two uses for this: one, you can try using it on your ibdata1 file (it only reads, shouldn't modify) to see what your eyeballs tell you about what you find in there. It offers essentially a brute-force window into the raw content living in the file, and if you find text in there that is newer than anything you put in using the binlog files, that's a good sign that time spent with the Percona tools could be worthwhile because the old data is actually in the file. If you see nothing at all that you recognize, there may be a problem with the method (though I've verified it works on Linux with genuine GNU "strings"), but if you see old content and not new, then the new content is likely gone.
Of course, the other potential use of "strings" if you do see the content and if it's primarily content that is the most valuable thing you've lost -- not configuration and customization -- then you could just use "strings" to extract the raw content, redirect it into another file, and proceed with a new wordpress installation where you could use that raw text to recreate things.
If the data is "that" important, Percona and SkySQL (I'm not affiliated with either company, but those seem to be the two big players in MySQL space) and other companies offer paid recovery services.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why isn't localStorage persisting in Chrome?
I'm trying to learn how to use the localStorage js object with the following code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function saveStuff() {
sessionStorage.setItem('sessionKey', 'sessionValue');
localStorage.setItem('localKey', 'localValue');
}
</script>
</head>
<body>
<button type="button" onclick="saveStuff()">Save</button>
</body>
</html>
I am aware this doesn't always work with file:/// so I'm using mongoose to serve it up. When I click the save button, the results look correct to me in Chrome's JavaScript console. However when I press refresh both the local and the session storage get cleared where I was expecting the local storage value to persist. This happens on both http://127.0.0.1/ and http://localhost/.
Does anyone know why this might be happening? In Settings, Content Settings I have selected 'Allow local data to be set (recommended)' and unticked 'Block third-party cookies and site data'. Am I missing something in my code?
(Chrome Version 23.0.1271.64 m)
A:
Ok. Thanks must go to pimvdb on this one but here's the solution.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function saveStuff() {
sessionStorage.setItem('sessionKey', 'sessionValue');
localStorage.setItem('localKey', 'localValue');
}
localStorage.getItem('localKey');
sessionStorage.getItem('sessionKey');
</script>
</head>
<body>
<button type="button" onclick="saveStuff()">Save</button>
</body>
</html>
Summary seems to be that that you must attempt a read of the key in order to persist it.
Conclusion: WTF.
A:
<!-- Necro post I know, but maybe it helps someone else -->
I couldn't figure out why I couldn't see something in my localStorage in Dev Tools, but could see it in the console when typing localStorage. Well, if you store something with Dev Tools open, you won't see Application -> Local Storage have anything listed for your host. When I closed/reopened Dev Tools, I could see my data.
So, in conclusion, close/reopen Dev Tools.
| {
"pile_set_name": "StackExchange"
} |
Q:
sfGuard token login for wkhtmltopdf
wkhtmltopdf allows to make a screenshot of a browser view with a webkit browser.
I have a Symfony 1.4 application that requires login, which I would like to use wkhtmltopdf to create a "print this page" function.
How can I securely facilitate this. I'm thinking of creating a one-off token on each screen for the print button that allows wkhtmltopdf to login without using the password of the user.
Any suggestions for how to structure this?
A:
We'vbe come to the conclusion to use the built in "keep me logged in" functionality for this problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Routing clients using Azure Mobile Services
I'd like to implement NAT Punchthrough as part of a client application to allow clients to connect to each other when behind a router. I'm hoping to use Azure Mobile Services to accomplish this, but in order to do so, the server needs to save the ip address and port of all incoming connections in a database (so that other clients can lookup the host, and connect back to the client that posted the data).
Is there anyway to acquire this connection (ip address & port) information in the server side scripts? If not, what alternative services exist that'll let me setup an API like this?
Thanks!
A:
I found got an answer on another thread over on the windows azure forums.
Headers are exposed through the mobile services custom api feature. Additionally, azure uses a forwarding machine to route incoming requests to the appropriate vm. This machine is a proxy which saves incoming connection information into the x-forwarded-for http header. Thus, from a custom script, we can query for incoming connection information from the headers. It should be noted that the x-forwarded-for header is supposed to include both the ip address and the port number.
Here's the custom api example given in the other thread.
exports.get = function(request, response) {
var ip = request.headers['x-forwarded-for'];
response.send(statusCodes.OK, ip);
};
The other thread is here: http://social.msdn.microsoft.com/Forums/windowsazure/en-US/a6aa306c-f117-4893-a50a-94418fafc1a9/client-ip-address-from-serverside-scripts-azure-mobile-services?forum=azuremobile&prof=required
| {
"pile_set_name": "StackExchange"
} |
Q:
Express Error Handling - Get Status Code
If I define error handling middleware with express like so:
app.use(function(err,req,res,next){
// Do Stuff
});
How do I get the HTTP status code of the error(or do I just assume is's a 500)?
Thanks,
Ari
A:
In short, your code has to decide the appropriate error code based on the specific error you are handling within your error handling middleware.
There is not necessarily an HTTP status code generated at this point. By convention, when I call next(error) from a middleware function or router handler function, I put a code property so my error handling middleware can do res.status(err.code || 500).render('error_page', error); or something along those lines. But it's up to you whether you want to use this approach for your common 404 errors or only 5XX server errors or whatever. Very few things in express itself or most middleware will provide an http status code when passing an error to the next callback.
For a concrete example, let's say someone tried to register a user account in my app with an email address that I found already registered in the database, I might do return next(new AlreadyRegistered()); where the AlreadyRegistered constructor function would put a this.code = 409; //Conflict property on the error instance so the error handling middleware would send that 409 status code. (Whether it's better to use error handling middleware vs just dealing with this during the normal routing chain for this "normal operating conditions" error is arguable in terms of design, but hopefully this example is illustrative nonetheless).
FYI I also recommend the httperrors npm module which provides nicely-named wrapper classes with a statusCode property. I have used this to good effect in a few projects.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nhibernate ICriteria and Using Lambda Expressions in queries
hi i am new in NHibernate and i am a little confused.
Suppose we have a product table.
Let the product table have 2 columns price1 and price2.
then i may query mapped product entities via HQL as follows:
string queryString = @"from product p
where p.price1 = p.price2 + 100 ";
IList result = session.CreateQuery(queryString).List();
How can i achieve that via ICriteria API.
i know it's absurd but i am trying sth like that:
session.CreateCriteria(typeof(product))
.Add(Expression.Eq("price1", "price2" + 100))
.List()
or more appropriately sth like that (using lambda extensions):
session.CreateCriteria(typeof(product))
.Add<product>(p => p.price1 == (p.price2 + 100))
.List()
in fact i downloaded lambda extensions project from googlecode and i extended it to recusively process Binary and Unary expressions to implement expresssions like:
session.CreateCriteria(typeof(product))
.Add<product>(p =>
(!(p.price1 > 29007) && (p.price1 > 19009))
|| (p.price2 == 29009));
i am currently processing queries like above but the arithmethic clauses are annoying me since i can't return the appropriate Restriction to obtain the Criterion i need.
mpffh i m tired of trying to explain it in a comprehensive way. i hope it worked. Any help is appreciated.
A:
You could try this:
ISQLFunction sqlAdd = new VarArgsSQLFunction("(", "+", ")");
var products = session
.CreateCriteria<product>()
.Add(
Expression.EqProperty(
"price1",
Projections.SqlFunction(
sqlAdd,
// TODO: replace this with appropriate type
NHibernateUtil.Double,
Projections.Property("price2"),
Projections.Constant(100)
)
)
)
.List<product>();
| {
"pile_set_name": "StackExchange"
} |
Q:
Installed .Net 4.5 but can't use ZipFile class in Visual C#
I'm kind of a newbie to Visual Studio programming.
I recently upgraded .Net 4.0 to 4.5 in order to use the ZipFile class under System.IO.Compression, but after the installation completed, Visual Studio (I'm using 2012) still cannot recognize ZipFile as a class name.
I've made sure that .Net 4.5 appears in Control Panel programs list and my C# solution sets .Net Framework 4 as the target framework.
Could someone help me figure this out?
A:
See ZipFile Class on MSDN. It shows the required framework version is 4.5. Once the framework version is fixed check you have added a reference to the System.IO.Compression.FileSystem.dll assembly and added a using System.IO.Compression directive to your class.
A:
You also need to reference the System.IO.Compression.FileSystem.dll assembly.
A:
Just to further clarify the previous answers, here's how to add the references manually to a Web.config:
<configuration>
<system.web>
<compilation targetFramework="4.5">
<assemblies>
<add assembly="System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.IO.Compression.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
</compilation>
</system.web>
</configuration>
Or to a *.csproj:
<Project ...>
<ItemGroup>
<Reference Include="System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089, processorArchitecture=MSIL" />
<Reference Include="System.IO.Compression.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089, processorArchitecture=MSIL" />
</ItemGroup>
</Project>
The files can be found in C:\Windows\Microsoft.NET\assembly\GAC_MSIL\ and the subfolders contain the necessary info on version, culture and PublicKeyToken as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
My width calculations don't match pixels
I have an outer and inner div. Both are positioned relative.
The outer div is 593px wide (by measurement, but created by percent).
The inner div width, allowing for 20px padding on each side, should be 553px wide so that it matches the width of its parent outer div. But I want the actual value to be a %.
553/593 x 100 = 93.25% -- But that did not work, it was slightly wide.
The value that actually made the inner div match the outer div was: 92%
Why?
A:
My solution was to use the value of 92% for the inner div. I assume the difference from my calculated value is due to rounding. Going forward I will use the same procedure of calculating + visual adjustment.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery hide/show issue with offset
I have a navbar on my website that is too wide for all buttons to display on mobiles devices. So I want to hide when the offset of the navigation buttons from the viewport is less than 150px (a drop down will take it's place). If there is more than 150px offset, then the navbar needs to be displayed.
I have made a Fiddle that shows what I want (resize the window). It correctly hides the navbar from view, but it won't make it appear again if there offset is greater than 150.
I know this happens because the element gets width "auto" and so the condition cannot be checked, but I don't know a workaround for this.
How can I fix this issue? Thanks.
HTML
<div>
<div class="container">
<div class="item">Some</div>
<div class="item">Example</div>
<div class="item">Text</div>
</div>
</div>
CSS
div {
background: red;
text-align: center;
}
.container {
display: inline-block;
background: green;
}
.item {
display: inline-block;
background: green;
}
JS
$(window).on('resize', function(){
var offset = $('.container').offset();
if (offset.left < 150) {
$('.container').hide();
} else {
$('.container').show();
}
}).resize();
A:
The reason this is happening is that once you hide something, it is no longer rendered and so it does not know the .offset() of the container.
Maybe try css "visibility" instead?
See: http://jsfiddle.net/hnwacrzq/5/
$(window).on('resize', function(){
var offset = $('.container').offset();
console.log(offset);
if (offset.left < 150) {
$('.container').css("visibility", "hidden");
} else {
$('.container').css("visibility", "visible");
}
}).resize();
| {
"pile_set_name": "StackExchange"
} |
Q:
django postgres could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1)
I just deploy Django app on aws-lambda with Zappa but I am getting an error. I don't know if I have to install Postgres because I think its automatically installed from requirements.txt
OperationalError at /admin/login/ could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
Request Method: POST
Request URL: https://tmzgl5al3h.execute-api.ap-south-1.amazonaws.com/dev/admin/login/?next=%2Fdev%2Fadmin%2F
Django Version: 2.1.4
Exception Type: OperationalError
Exception Value: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
Exception Location: /var/task/psycopg2/__init__.py in connect, line 130
Python Executable: /var/lang/bin/python3.6
Python Version: 3.6.1
Python Path: ['/var/task', '/opt/python/lib/python3.6/site-packages', '/opt/python', '/var/runtime', '/var/runtime/awslambda', '/var/lang/lib/python36.zip', '/var/lang/lib/python3.6', '/var/lang/lib/python3.6/lib-dynload', '/var/lang/lib/python3.6/site-packages', '/opt/python/lib/python3.6/site-packages', '/opt/python', '/var/task']
A:
PostgreSQL is not python library but a standalone open source database, you should definitely have it setup
In AWS realm you should set it up it as RDS instance and configure your enviroment accordingly
| {
"pile_set_name": "StackExchange"
} |
Q:
Division of polynomials
If $f(x)$ is a polynomial in $x$ and $a,b$ are distinct real numbers , then the remainder in the division of $f(x)$ by $(x-a)(x-b)$ is
$(a)$ $ ((x-a)*f(a)-(x-b)*f(b))/(a-b) $
$(b)$ $ ((x-a)*f(b)-(x-b)*f(a))/(b-a) $
$(c)$ $((x-a)*f(b)-(x-b)*f(a))/(a-b) $
$(d)$ $((x-a)*f(a)-(x-b)*f(b))/(b-a) $
My attempt - My attempt has largely been feeble . In fact using basic division theorem till now , I have only been able to identify that $f(a) = r(a)$ and $f(b) = r(b)$. Since if we use the division algorithm with $ x=a $ and $ x=b $ we could easily determine this.
A:
Let's first note that the reminder of division of f(x) on x-a is f(a). The proof is very simple:
f(x)=fa(x)(x-a)+ r(a)
Applying x=a,
f(a) =fa(a)(a-a) +r(a)
r(a)=f(a)
Then f(x) =fa(x)(x-a) + f(a)
Where fa(x) = (f(x)- f(a)) /(x-a)
Now
fa(x)=fab(x)(x-b) + fa(b)
From the previous equation,
fa(b) = (f(b)-f(a))/(b-a)
Finally
f(x) = fab(x)(x-a)(x-b) + (f(b)-f(a))(x-a)/(b-a) + f(a)
The last two terms is the reminder
Multiplying the last term by (b-a)/(b-a) we arrive at
(f(b)(x-a) - f(a)(x-a) + f(a)(b-a)) / (b-a) =
= (f(b)(x-a) - f(a)(x-b))/(b-a)
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieving Input Text Value
For the following HTML
<form>
Enter hash here: <input type="text" name="hash">
<button type="submit" formaction="/tasks/">Retrieve Url</button>
</form>
How can I re-direct the user to /tasks/A where A = whatever the user typed in the "hash" <input> box?
Thanks
A:
Take a look at this post will help.
It do exactly the same thing you want with example.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access OSGI console of wso2 carbon remotely
I have a carbon instance running on one machine and i want to access it from another machine is it possible?
My requirement is ,i have Started wso2 carbon in OSGI console mode (wso2server.bat -DosgiConsole)
I want to add features into that carbon instance.. using provaddrepo and provinstall command.. I want to do this from a remote machine??
Is it possible to do that... suppose 3 nodes are running the carbon(osgi console mode),i need to access it from a remote machine to execute the commands ( like to install features using prov commands)
Is it possible,any script is there to do like that,how to connect that cmd instance from another machine
Thanks in advance
A:
To access OSGI console from a remote host, start it specifying the port number :
wso2server.bat -DosgiConsole=19444
And to access it from the remote host :
telnet hostname 19444
| {
"pile_set_name": "StackExchange"
} |
Q:
Making sense of Scala development tools
There is a myriad of development tools and terms in the ecosystem, for example, language server, build server, Metals, BSP, LSP, Bloop, Zinc, Coursier, incremental compiler, presentation compiler, etc.
I was wondering if someone could demonstrate how they fit together and briefly explain relations and differences. Specifically I am hoping for a diagram and answer along the lines of Making sense of Scala FP Libraries. For example, here is my attempt
(Concept) (Example implementation)
--------------------------------------------------------------------
IDE Visual Studio Code
| |
Scala IDE plugin Metals Visual Studio Extension
| |
Language Server Protocol Microsoft LSP
| |
Scala language server Metals
| |
Build Server Protocol BSP from JetBrains and Scala Center
| |
Scala build server Bloop
| |
Build tool sbt
| |
Dependency resolution Coursier
| |
Incremental compiler Zinc
| |
Presentation compiler parser and typer phases of scalac
| |
Bytecode generation remaining compiler phases
A:
IDEs like Intellij or (once) Scala IDE are intended for "smart" development, where the editor tells you if your code is correct, suggest fixes, autogenerate some code, provide navigation around code, refactoring - in other words many features that expand way beyond simple text edition with perhaps only syntax highlighting.
Intellij has a Scala extension which makes use of their own reimplementation of a Scala compiler - they needed that for better partial compilation and intellisense working even if part of the code is broken. The import build definition from other build tool (e.g. sbt or bloop) and from then Intellij doesn't reply on anything external (unless you use some option like "build with sbt").
Scala IDE relied on Scala presentation compiler for intellisense. As you can read on scala-ide.org:
The Scala IDE for Eclipse uses the Scala Presentation Compiler, a faster asynchronous version of the Scala Compiler. The presentation compiler only runs the phases up until and including the typer phase, that is, the first 4 of the 27 scala compilation phases. The IDE uses the presentation compiler to provide semantic features such as live error markers, inferred type hovers, and semantic highlighting. This document describes the key classes you need to know in order to understand how the Scala IDE uses the presentation compiler and provides some examples of interactions between the IDE and the presentation compiler.
Every other editor/IDE is intended to use Language Server Protocol - LSP is Microsoft's invention in order to standardize a way of supporting languages within different editors (though they invented it for the sake of VS Code) that would allow them to provide IDE features. Metals (from ScalaMeta Language
Server) is LSP implementation for Scala. As you can read here:
Code completions, type at point and parameter hints are implemented using the Scala presentation compiler, which is maintained by the Scala compiler team at Lightbend.
You can add it to VS Code using Scala Metals extension.
sbt, gradle, mill, fury, cbt, etc are build tools which use something like ivy2 or coursier to resolve and download dependencies, and then use Zinc incremental compiler in order to provide ability to (re)build things incrementally to normal compiler. Build tools can run tests, generate artifacts and deploy them to repository.
bloop is a solution to problem that compiletion is fast if JVM is hot, and JVM gets cold every time you kill your build tool/IDE. For that reason you use nailgun to keep some JVM warm, running build tasks in background. On its own bloop cannot generate configuration and in general it is something that should be generated by other build tool to speed up compilation during development. Protocol used to communicate with bloop server running in background is build server protocol (bsp).
Coursier, while is used primarily for dependency resolution, can also be used to install scala programs. Some of the noteworthy programs that you can install are:
scalafmt - scala formatter
ammonite - alternative REPL to scala which provides a lot of nice features
scalafix - code-rewriting tool which is used to provide automatic code migrations
I gave up on describing thing in table, as it would much better be shown on a graph, but since SO doesn't support that visuals I just resorted to a plain text.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can Ruby return nothing?
Can I return nothing in ruby?
Just for educational purpose
For example:
myarray = [1,2,3]
myarray << some_method
def some_method
if Date.today.day > 15
return "Trololo"
else
return __NOTHING__
end
end
So if today is 11'th March myarray won't add new item. I don't want nil - because nil is not nothing :)
And I understand, that I can use if | unless statement like myarray << some_method if some_method etc. I want to understand can I return nothing or every time in ruby I am returning something (least I can get is Nil Object)
A:
Basically, what you are looking for is a statement. But Ruby doesn't have statements, only expressions. Everything is an expression, i.e. everything returns a value.
A:
No, you can't return nothing. In ruby you always return something (even if it's just nil) - no way around that.
A:
You can't return "nothing" from a method in ruby. As you point out you could conditionally add elements to your array. You can also invoke .compact on your array to remove all nil elements.
| {
"pile_set_name": "StackExchange"
} |
Q:
Local Storage edit not working
localStorage.setItem('gameState', '{"
grid ":{"
size ":4,"
cells ":[[{"
position ":{"
x ":0,"
y ":0},"
value ":1024},{"
position ":{"
x ":0,"
y ":1},"
value ":1024},{"
position ":{"
x ":0,"
y ":2},"
value ":1024},{"
position ":{"
x ":0,"
y ":3},"
value ":1024}],[{"
position ":{"
x ":1,"
y ":0},"
value ":1024},{"
position ":{"
x ":1,"
y ":1},"
value ":1024},{"
position ":{"
x ":1,"
y ":2},"
value ":1024},{"
position ":{"
x ":1,"
y ":3},"
value ":1024}],[{"
position ":{"
x ":2,"
y ":0},"
value ":1024},{"
position ":{"
x ":2,"
y ":1},"
value ":1024},{"
position ":{"
x ":2,"
y ":2},"
value ":1024},{"
position ":{"
x ":2,"
y ":3},"
value ":1024}],[{"
position ":{"
x ":3,"
y ":0},"
value ":1024},{"
position ":{"
x ":3,"
y ":1},"
value ":1024},{"
position ":{"
x ":3,"
y ":2},"
value ":1024},{"
position ":{"
x ":3,"
y ":3},"
value ":1024}]]},"
score ":272,"
over ":false,"
won ":false,"
keepPlaying ":false}');
My script is just a simple one meant to implement into the browser bar of chrome but it returns SyntaxError: Unexpected token ILLEGAL. I have tried setting the local storage to something simple and it works. Can someone tell me what is wrong or rewrite it so it works.
A:
Like mentioned in the comments, you had wrong indentation as well as some extra spaces and missing commas.
localStorage.setItem('gameState',
'{"grid":{"size":4,"cells":[[{"position":{"x":0,"y":0},"value": 1024},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}},{"position":{"x":0, "y": 1}{"value":1024}}]]},"score":272,"over":false,"won":false,"keepPlaying ":false}');
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make an SSL connection to MySQL using MariaDB Connector/J?
I'm using MySQL 5.7.10 with SSL enabled and certificates generated as per these instructions. My Java 7 application uses a MariaDB Connector/J and SSL is enabled in the JDBC URL:
jdbc:mysql://dbservername:3306/dbname?useSSL=true&trustServerCertificate=false
But the connection fails with:
Caused by: java.lang.RuntimeException: Could not generate DH keypair
...
Caused by: java.security.InvalidAlgorithmParameterException: Prime size must be multiple of
64, and can only range from 512 to 1024 (inclusive)
According to this blog post, the problem could be resolved by:
Upgrading to Java 8 (or higher).
Downgrading to MySQL 5.7.5 (or lower).
Excluding Diffie-Hellman (DH) ciphers.
(1) isn't an option on the project I'm working on. (2) seems restrictive and would prevent access to future MySQL improvements. (3) seems the most promising: I've verified it does work with MySQL connector/J but unfortunately its GPL license prevents me from being able to use it on my project.
Does MariaDB Connector/J have an equivalent property to enabledSSLCipherSuites or is there any other way to prevent it from using DH ciphers when connecting?
A:
The requested feature options have now been implemented in MariaDB Connector/J version 1.5.0-RC:
enabledSslProtocolSuites Force TLS/SSL protocol to a specific set of
TLS versions (comma separated list). Example : "TLSv1, TLSv1.1,
TLSv1.2" Default: TLSv1, TLSv1.1. Since 1.5.0
enabledSslCipherSuites Force TLS/SSL cipher (comma separated list).
Example : "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_DHE_DSS_WITH_AES_256_GCM_SHA384" Default: use JRE ciphers. Since
1.5.0
(See the comments below the question, the release notes and this Jira ticket.)
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP copy() error
I'm getting error while using php function copy()
Warning: copy() [function.copy]:
Couldn't resolve host name in
Warning:
copy(http://www.foodtest.ru/images/big_img/sausage_3.jpg)
[function.copy]: failed to open
stream: operation failed in
what's wrong with that url?
A:
Try enclosing the url withing quotes "".
| {
"pile_set_name": "StackExchange"
} |
Q:
Is template qualifier required in class template non-dependent member variables?
I got the compile error "error: use 'template' keyword to treat 'foo' as a dependent template name" when I compile the following code on commented line. (test4)
All other parts of codes are successfully compiled.
#include <tuple>
struct my {
template <typename T>
void foo() {}
};
void test1() {
my m;
auto tr = std::forward_as_tuple(m);
auto& t0 = std::get<0>(tr);
t0.foo<int>();
}
template <typename T>
struct test2 {
void method() {
my m;
auto tr = std::forward_as_tuple(m);
auto& t0 = std::get<0>(tr);
t0.foo<int>();
}
};
template <typename T>
struct test3 {
void method() {
m.foo<int>();
}
my m;
};
template <typename T>
struct test4 {
void method() {
auto tr = std::forward_as_tuple(m);
auto& t0 = std::get<0>(tr);
t0.foo<int>(); // error: use 'template' keyword to treat 'foo' as a dependent template name
t0.template foo<int>(); // OK
}
my m;
};
template <typename T>
struct test5 {
void method() {
std::tuple<my> tr = std::forward_as_tuple(m);
auto& t0 = std::get<0>(tr);
t0.foo<int>();
}
my m;
};
template <typename T>
struct test6 {
void method() {
auto tr = std::forward_as_tuple(m);
my& t0 = std::get<0>(tr);
t0.foo<int>();
}
my m;
};
int main() {
test1();
test2<int>().method();
test3<int>().method();
test4<int>().method();
test5<int>().method();
test6<int>().method();
}
test4 is a class template but m is non dependent type.
I tried to compile gcc and clang. gcc 7.1.0 dosen't report errors, but clang 4.0 and later report the compile error.
Error
https://wandbox.org/permlink/HTSBJMD2kXwfWObl (clang 4.0)
https://wandbox.org/permlink/BcUT8gtaFxwC41c5 (clang HEAD)
No error
https://wandbox.org/permlink/GjIvZa3i5HB8uh6w (gcc 7.1.0)
Which is correct behavior?
A:
I'm going to agree with your suspicion. This is indeed a clang bug.
The template is required if and only if t0 is a dependent name. In particular, it's required if t0 depends on T. And that's the T in test4<T>.
Now, t0 depends on my m, and there's a my::foo<T>, but that's an unrelated T in a different scope. Additionally, t0 doesn't depend on my::foo<T>.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove a commit from a branch and put it on a separate branch
My project has a single branch master. Let's say I've performed four commits A, B, C and D. Now I just realized that D is something that is too experimental, so it should not be on master (yet), but rather on a separate branch of its own, say experimental.
How do I:
Put D on a branch of its own?
Go back to C as master and perform new commits on this branch?
(Note: I don't want to just undo the commit)
A:
First, you need to branch the experimental branch from master:
mureinik@computer ~/src/git/myproject [master] $ git branch experimental
Then, you can reset the master branch to one commit behind:
mureinik@computer ~/src/git/myproject [master] $ git reset HEAD~ --hard
| {
"pile_set_name": "StackExchange"
} |
Q:
How to import a Tensorflow model?
I've trained a network in Tensorflow and have the checkpoint files, I'd like to if anyone has written a parser or importer to pull the evaluation graph and/or weights into Mathematica?
A:
In this question,I find this notebook.
And it tells us:
PS:In this website(Deep Learning - The Straight Dope),I find MXNet will support some converters
So in the future,Tensorflow model -> MXNet model -> then importing to Mathematica
| {
"pile_set_name": "StackExchange"
} |
Q:
JSON foreach only gets first result out of an array
I have a JSON file (test.json) which is
{
"fruit": [{
"id": 364823,
"name": "Lemon",
"amount": [33],
"profile": "http://google.com",
"buyid": 5
}, {
"id": 367851,
"name": "Orange",
"amount": [69, 95, 166],
"profile": "http://google.com",
"buyid": 3
},{
"id": 35647,
"name": "Apple",
"amount": [77, 43],
"profile": "http://google.com",
"buyid": 31
} ]
}
then i have my PHP script to echo
$url="test.json";
$json = file_get_contents($url);
$json = json_decode($json, true);
$names = array();
foreach($json['fruit'][0]['amount'] as $val)
{
echo $val . " <br> ";
}
Which returns
33
how can i get it to return?
33
69 95 166
77 43
i can get it to work with the others like id,profile and buyid but not this array
A:
foreach($json['fruit'] as $fruit){
echo implode(' ',$fruit['amount']);
}
Live demo
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove rows from a data frame according to a range of row names
I would like to remove from a data.frame all rows from, for example, row number 10 plus the subsequent 4 rows, i.e. from row 10 to row 14.
The starting row for rows removing (in this case the row number 10) results from a test so that I saved the output of the test in my_test variable. Briefly I have to remove rows from my_test variable plus 4 rows. I tried:
myfile_cleaned <- my_original_file[-c(test:test+4),]
but it does not work.
Can anyone help me please?
A:
You can use
myfile_cleaned <- my_original_file[-(test:(test + 4)), ]
Due to R's operator precedence, : is evaluated before +. Therefore you need extra parentheses.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why my key commands are not working
My issue is that my javascript is not seeing when i push my key down to move the object on the screen.
So here is my java script code:
var canvas = document.getElementById("maincanvas");
var context = canvas.getContext("2d");
var keys = [];
var width = 500,
height = 400,
speed = 3;
var player = {
x: 10,
y: 10,
width: 20,
height: 20
};
window.addEventListener("keydown", function (e) {
keys[e.keycode] = true;
}, false);
window.addEventListener("keyup", function (e) {
delete keys[e.keycode];
}, false);
/*
up - 38
down - 40
left - 37
right - 39
*/
function game() {
update();
render();
}
function update() {
if (keys[38]) player.y -= speed;
if (keys[40]) player.y += speed;
if (keys[37]) player.x -= speed;
if (keys[39]) player.x += speed;
}
function render() {
context.clearRect(0, 0, 100, 100)
context.fillRect(player.x, player.y, player.width, player.height);
}
setInterval(function () {
game();
}, 1000 / 30);
if you can not tell i am very new to this and just learning the basics.
A:
The value you want out of the event object is called keyCode, not keycode:
var canvas = document.getElementById("maincanvas");
var context = canvas.getContext("2d");
var keys = [];
var width = 500,
height = 400,
speed = 3;
var player = {
x: 10,
y: 10,
width: 20,
height: 20
};
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e) {
delete keys[e.keyCode];
}, false);
/*
up - 38
down - 40
left - 37
right - 39
*/
function game() {
update();
render();
}
function update() {
if (keys[38]) player.y -= speed;
if (keys[40]) player.y += speed;
if (keys[37]) player.x -= speed;
if (keys[39]) player.x += speed;
}
function render() {
context.clearRect(0, 0, 100, 100)
context.fillRect(player.x, player.y, player.width, player.height);
}
setInterval(function() {
game();
}, 1000 / 30);
<canvas id="maincanvas"></canvas>
| {
"pile_set_name": "StackExchange"
} |
Q:
Does R Automatically Calculate Single Degrees of Freedom?
I would like to know whether R produces single degrees of freedom tests for a formula. Assume we have a model in R:
model = lm(x ~ a + b + c, data=mydata) # augmented model
Is R only doing an omnibus test and comparing my augmented model to a null model with only an intercept:
null=lm(x ~ 1, data=mydata) # compact model
or is it doing multiple single-degree-of-freedom tests, such as comparing:
model = lm(x ~ a + b + c, data=mydata) # augmented model
to all of the following compact models:
null1=lm(x ~ b + c, data=mydata) # compact model1
null2=lm(x ~ a + c, data=mydata) # compact model2
null3=lm(x ~ a + b, data=mydata) # compact model3
I am worried because I was taught to compare models with only a single degree of freedom between them, ie an augmented model that includes the parameter of interest against a compact model that excludes the parameter of interest. So, if I was interested in the effect of a, then I was taught to compare the augmented model with the compact model as follows:
model = lm(x ~ a + b + c, data=mydata) #augmented model
null = lm(x ~ b + c, data=mydata) #compact model
anova(null, model) # single degree-of-freedom comparison between augmented model and compact model.
But this latter approach isn't very often taught, particularly when one is using R, though Bodo Winter seems to be an exception [EDIT: I've realised that the Winter tutorial is for random effects using lmer(), which does not automatically produce a p value, so this would explain why he teaches the model comparison approach in that context]. Is there any point in doing the comparison?
In other words, if R is doing the first thing (comparing to a null with just an intercept), then I think this is contrary to what I've been taught, but if the latter (comparing to multiple nulls, each test being a single degree of freedom comparison), then I don't think there is a problem.
A:
The two approaches (the t and the partial F-with-1-df) are equivalent as long as the t is two-tailed.
There's no additional benefit to the F (it never tells you anything you couldn't get from the t-test), except for the fact that it generalizes - e.g. to testing more than one variable at a time, and to the general linear hypothesis.
A:
From your elaboration, it appears you want to know what the F statistic means when you summary(lm(x~a+b+c))?
Basically, it tells you the difference between the model x~a+b+c compared to the intercept only model x~1. That is not the same as comparing full vs reduced models. To compare full vs reduced models you are removing only one variable and seeing if that affects the sums of squares explained by the new model. On this case, anyone of a, b, or c could be having an effect. But the point is just look at the t values and you can see which one is significant--within the model anyway.
Or maybe that's exactly what you want, to just compare your model against the intercept only model, which is what it's doing; but a single significant t test would tell you that the F test would therefore have to be significant anyway.
Just to show you that the F statistic is the same: run the following code (I have generated a bunch of random uniform variables to make a regression, but you can replace it with your own variables and it should be the same)
> a<-runif(100,1,3); b<-runif(100,1,2); c<-runif(100,1,2);summary(lm(a~b+c))
Call:
lm(formula = a ~ b + c)
Residuals:
Min 1Q Median 3Q Max
-0.8875 -0.5368 -0.1291 0.5712 1.0798
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.09554 0.48939 4.282 4.36e-05 ***
b -0.13188 0.21375 -0.617 0.539
c -0.01779 0.22475 -0.079 0.937
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.5995 on 97 degrees of freedom
Multiple R-squared: 0.003936, Adjusted R-squared: -0.0166
F-statistic: 0.1916 on 2 and 97 DF, p-value: 0.8259
Notice the F statistic and how many degrees of freedom it has
> anova(lm(a~1),lm(a~b+c))
Analysis of Variance Table
Model 1: a ~ 1
Model 2: a ~ b + c
Res.Df RSS Df Sum of Sq F Pr(>F)
1 99 35.003
2 97 34.865 2 0.13776 0.1916 0.8259
Same F, same degrees of freedom.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using variables in parboiled
I'm attempting to create a simple XML parser using the parboiled Java library.
The following code attempts to use a variable to verify that the closing tag contains the same identifier as the opening tag.
class SimpleXmlParser2 extends BaseParser<Object> {
Rule Expression() {
StringVar id = new StringVar();
return Sequence(OpenElement(id), ElementContent(), CloseElement(id));
}
Rule OpenElement(StringVar id) {
return Sequence('<', Identifier(), ACTION(id.set(match())), '>');
}
Rule CloseElement(StringVar id) {
return Sequence("</", id.get(), '>');
}
Rule ElementContent() {
return ZeroOrMore(NoneOf("<>"));
}
Rule Identifier() {
return OneOrMore(CharRange('A', 'z'));
}
}
The above, however, fails with the error message org.parboiled.errors.GrammarException: 'null' cannot be automatically converted to a parser Rule, when I create the ParseRunner.
It would appear that I have a basic misunderstanding of how variables should be used in parboiled. Can anyone help me resolve this?
A:
Came up with an answer. Including it here for any other parboiled newbie who may struggle with the same issue.
The problem was that any access to the variable's content must happen in a parser action to ensure that it takes place in the parse-phase, rather than in the rule construction phase.
The following changes to the program above, ensures that parsing fails if an element identifier is unmatched.
Rule CloseElement(StringVar id) {
return Sequence("</", Identifier(), matchStringVar(id), '>');
}
Action matchStringVar(final StringVar var) {
return new Action() {
public boolean run(Context ctx) {
String match = ctx.getMatch();
return match.equals(var.get());
}
};
}
| {
"pile_set_name": "StackExchange"
} |
Q:
returning string from function without malloc
Is it possible to return string from a function without calling malloc?
I have a function as below:
char* getString(){
char tempStr[20]
// open file, read char by char and assign to tempStr
// ....
char* str = (char*)malloc(sizeof(char)*20);
strcpy(str, tempStr); // assume this copy the null terminating char as well
return str;
}
And then when I call the getString(), I assign the return value to a char*, and then free it when I'm done, just like below:
void randomFunction(){
char* line = NULL;
int i = 0;
while (i < 1000) {
line = getString();
// do stuff with line
free (line);
line = NULL;
}
}
However, I am wondering if there is any way to do this without malloc? And, is this the proper way of returning string from a C function?
I tried to do some research regarding how to return without malloc, but didn't find clear answers. I am new to C and still learning.
A:
You can not return temporary from a function and unless you use a malloc your character array defined in the function will be a temporary. An alterantive solution is to pass a character array as parameter to the function and use it as output parameter.
A:
There are three common ways to return a string from a function. (Well, actually there are none, but there are three common ways to return a pointer to a string, which the caller can then use to access the string.)
Allocate space for the string using malloc() inside the function. This is the most flexible method, but it makes the caller responsible for free()ing the allocated array. It can also impose some performance overhead.
Require the caller to allocate space for the string and pass in a pointer to that space. This imposes some inconvenience on the caller. In particular, the caller has to decide how big the string can be.
Return a pointer to (the first element of) a static array defined inside the function. The array will continue to exist after the function returns, but there's only one copy, which means that successive calls will clobber the result returned by previous calls. It also means the array has to be of some fixed size, chosen when you write the code.
A:
It depends.
You could decide and document that the returned string is a pointer to some static internal buffer. Then your routine is not re-entrant (nor thread-safe). For instance ctime or getpwent does that.
A better thing would be to pass the result string and size as arguments, and to fill that string and possibly return that. getcwd (or snprintf or strftime which returns a size, not a pointer) works that way.
But usually, you decide and document that the returned string is heap allocated, and it is the responsability of the caller to free it. You might want to use strdup or asprintf in that case.
And you might use in your entire program Boehm's conservative garbage collector (e.g. use its GC_STRDUP or GC_MALLOC_ATOMIC for strings, and GC_MALLOC for heap values containing some pointers.)
If you feel that standard malloc or strdup is too slow (but please measure that first), you could have your own pool allocators, etc.
You could also have alternate schemes (but it is important to document them). For example, you could return some interned string, or even a canonical interned string (sometimes called "quark" or "symbol") - then be able to use pointer equality instead of string equality. You could also have some reference counter scheme. Look for example at what Glib (from GTK, but usable outside of GUI programs!) provides: GString-s, GQuark-s, string utilities
It is however important to decide if the result is heap allocated or not, and to define clearly who has the responsibility to free (and how should it be freed) that heap-allocated result.
You may want to use valgrind to chase memory leaks. Don't forget to pass -Wall -g to your gcc compiler!
PS. I would consider using Boehm's GC. And I don't think that malloc (or strdup, asprintf ....) should be rejected for performance reasons (you could chose some other & faster malloc implementation, or use your own memory pools). However, memory leaks could be an issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a middleware for check role in Nuxtjs
I'm trying to create a middleware for check role of my users.
// middleware/is-admin.js
export default function (context) {
let user = context.store.getters['auth/user']
if ( user.role !== 'admin' ) {
return context.redirect('/errors/403')
}
}
In my .vue file, I'm putting this on:
middleware: [ 'is-admin' ]
It works.
Now, I'd like to check if the user also has another role. So, I create a new middleware:
// middleware/is-consultant.js
export default function (context) {
let user = context.store.getters['auth/user']
if ( user.role !== 'consultant' ) {
return context.redirect('/errors/403')
}
}
And in my .vue file:
middleware: [ 'is-admin', 'is-consultant' ]
Unfortunately, when I do that, if I visit the route with an administrator role, it does not work anymore.
Can you tell me how I can create a middleware that checks multiple roles with Nuxt.js?
Thank you!
A:
The idea is that every page has its authority level. Then in middleware you can compare your current user authority level with the current page authority level, and if it's lower redirect the user. It's very elegant solution that was proposed by Nuxt.js creator. GitHub issue.
<template>
<h1>Only an admin can see this page</h1>
</template>
<script>
export default {
middleware: 'auth',
meta: {
auth: { authority: 2 }
}
}
</script>
Then in your middleware/auth.js:
export default ({ store, route, redirect }) => {
// Check if user is connected first
if (!store.getters['user/user'].isAuthenticated) return redirect('/login')
// Get authorizations for matched routes (with children routes too)
const authorizationLevels = route.meta.map((meta) => {
if (meta.auth && typeof meta.auth.authority !== 'undefined')
return meta.auth.authority
return 0
})
// Get highest authorization level
const highestAuthority = Math.max.apply(null, authorizationLevels)
if (store.getters['user/user'].details.general.authority < highestAuthority) {
return error({
statusCode: 401,
message: 'Du måste vara admin för att besöka denna sidan.'
})
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What does the programming term "identity function" have to do with identity? (Java-oriented)
I just read Bloch's Effective Java and there was one section talking about an "identity function" in the Generics chapter.
public interface UnaryFunction<T> {
T apply(T arg);
}
// Generic singleton factory pattern
private static UnaryFunction<Object> IDENTITY_FUNCTION = new UnaryFunction<Object>() {
public Object apply(Object arg) { return arg; }
};
// IDENTITY_FUNCTION is stateless and its type parameter is
// unbounded so it's safe to share one instance across all types.
@SuppressWarnings("unchecked")
public static <T> UnaryFunction<T> identityFunction() {
return (UnaryFunction<T>) IDENTITY_FUNCTION;
}
I already read "Why is it safe to suppress this unchecked warning?" and the answers explain the unchecked warning question, but leave me totally unhappy with the concept of the "identity function" when it seems the identity function has nothing to do with identities.
Bloch just assumes I know what it is, but in the implementation he uses to illustrate it, it has nothing to do with identity or identities.
I checked it out on wikipedia: Identity Function @ wikipedia but the pure theoretical description of it tells me nothing about what it has got to do with identities either.
I searched on google, and some people refer to the .equals() and .hashCode() methods as identity functions which makes a bit of sense, but of course their implementation is completely different from Bloch's method which returns the input parameter untouched. What does that have to do with identity?
Other people talked about database functions as identity functions, giving a new ID on each call, which makes more sense as well, but is obviously very limited in scope.
A:
An identity function, in the context of the code in your question, is simply a function that returns the same argument passed to it :
In math you can denote it as:
f(x) = x
A:
Identity functions are similar to other "identity" concepts, i.e. an operation that effectively does nothing.
As an example: in math you have identity matrices which if multiplied with a vector/matrix result in the same vector/matrix as if the multiplication never happend.
The same applied to an identity function: it returns the parameter as is and effectively does nothing when it comes to logic. It's as if the function never had been called - as I said from a logic point of view, you might still see some technical impact, e.g. a few instructions being executed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Best way to find recent papers in a special field of mathematics?
My subjects of interest are Geometry of Banach spaces, renorming theory and fixed point theory. When I want to find recent papers in these fields of mathematics, mostly, I search name of paper, say, renorming of Banach spaces and applications in fixed point theory, in ScienceDirect and Google Scholar. So, if anyone knows the best way to find out recently paper in a special field of mathematics please do share.
A:
The usual way to find papers on a given subject is to take one of them, and look at the references in it. Good modern databases allow you to to the inverse: to find the papers which cite this one. Very good databases which allow you to to this (and are quite complete) in mathematics are arXiv and Mathscinet, but Google Scholar also helps sometimes.
In this way, you can quickly find most of the relevant papers on a given math subject. Mathscinet has especially advanced search system: you can search on keywords in the title, keywords in the review itself, author name, and names in the reference list, and combine all of the above. The unique feature of Mathscinet is that it really identifies authors in most cases, even those with such names as Jones or Zhang.
Arxiv has relatively poor search system, and (unfortunately) not everyone places his/her papers on the arxiv. But its great advantage, is that it gives you the most recent items, not yet published. For my own research I read the titles of all new entries in the arxiv in the area of principal interest, at least once per month. (In pre-Internet time, I read all titles in the corresponding chapter of Math Reviews).
It is somewhat more difficult to search old publications (of pre-computer and pre-Math Reviews era), publications which are not digitalized or poorly digitalized. Judging by the topics you list, this is not very important for you. But there exist tools which permit you to search even 19s century papers effectively.
| {
"pile_set_name": "StackExchange"
} |
Q:
‘Don’t work for yourself, you will have no job security.’
I have clients whose parents and grandparents would say things like,
‘Don’t show yourself up’ because they wanted to be a performer, ‘Don’t
ask for a discount, it’s embarrassing’, ‘Don’t work for yourself, you
will have no job security.’ If you were meant to be like your parents
and grandparents there would be no point in you being here, and if we
didn’t challenge other people’s beliefs, opinions and convictions life
would never advance.
Peer, Marisa. Ultimate Confidence: The Secrets to Feeling Great About
Yourself Every Day (Kindle Locations 2909-2912). Little, Brown Book
Group. Kindle Edition.
What does the sentence mean? 'Work for yourself' seems to mean something I can't guess.
A:
Working for yourself means that you are self-employed:
[Merriam-Webster]
: earning income directly from one's own business, trade, or profession rather than as a specified salary or wages from an employer
In other words, you need to worry about generating your own clients, and your pay will almost always vary from month to month—sometimes even with the possibility of not having any work to do at all on a given month, resulting in no income.
This is opposed to working for somebody else or a company, especially if it's full-time work, where you are normally paid a set amount regardless of what's going on with clients.
Having no job security if you're working for yourself is a little bit misleading—because job security normally implies the fact that you're not going to lose your job. But if you're self-employed, you can't be fired. (Quitting would be entirely your decision.)
In that sense, it might be better to say that working for yourself means you don't have any "monetary security." But that's a subtle distinction and most people will understand what is meant in context.
| {
"pile_set_name": "StackExchange"
} |
Q:
Exporting SSL certificate from Juniper SA 2000 to IIS 7
Has anyone exported SSL certificate (cert and private key) from a Juniper SA 2000 box and tried to import it to IIS 7 box ?
I have tried to google for ways to export the private key from SA 2000 but haven't got any good links. (IIS 7 requires the cert and key put into a .pfx format to import). But if i can export the private key and also have the cert i can create the pfx using openssl.
Any help regarding this is appreciated.
Thanks.
A:
If you can't export the certificate with the private. I would suggest to contact your CA provider to reissue your certificate using the new CSR generated from your IIS 7 server. Reissuing of certificate in free of charge if you are a GlobalSign customer or your certificate is issued by GlobalSign.
Reissuing your certificate using the CSR generated from the IIS 7 server will allow you to install the certificate using the PEM certificate format (.crt file)
You may refer to this link: https://support.globalsign.com/customer/portal/articles/1226960-install-certificate---internet-information-services-iis-7
| {
"pile_set_name": "StackExchange"
} |
Q:
Expected number of colliding pairs in hashing (example)
Suppose we use a hash function $h$ to hash $n$ distinct keys into an array $T$ of length $m$. Assuming simple uniform hashing --- that is, with each key mapped independently and uniformly to a random bucket --- what is the expected number of pairs of distinct keys that collide? (As above, distinct keys $x,y$ are said to collide if $h(x)=h(y)$)
$n/m$
$n/m^2$
$n(n-1)/2m$
$n^2/m$
$n(n-1)/m$
This question came up in a quiz in Coursera assignment on Algorithms.
My thought is that there can be $n/m$ expected number of elements in one of any $m$ bucket, so pair of collisions is $\binom{n/m}{2}$ and this multiplied by $m$ gives total pairs colliding, but where is the flaw as answer according to this vision comes as $\color{red}{\frac{n(n-m)}{2m}}$
A:
Let $\mathbf{1}_{ij}$ denote the indicator random variable for the event that keys $i$ and $j$ are mapped to the same bucket. You are then looking for $\mathbb{E}\left[ \sum_{1\leq i\leq j \leq n} \mathbf{1}_{ij} \right].$ By linearity of expectation, that is
$$ \sum_{1\leq i \leq j \leq n} \mathbb{E}[\mathbf{1}_{ij} ]$$
There are $\binom{n}{2} = \frac{n(n-1)}{2}$ such $i,j$ pairs that we are summing over. Each term is $$\mathbb{E}[\mathbf{1}_{ij}] = \mathbb{P}(\text{keys i and j are mapped to the same bucket}).$$
Since they are mapped uniformly and independently into $m$ buckets, the probability that two keys are mapped to the same bucket is $\frac{1}{m}.$ So the 3rd option is the correct answer.
The step going from "there are $n/m$ expected elements in any bucket" to "so the number of colliding pairs is.." does not work. For example, $n/m$ may not be an integer. Using this approach, we would need to figure out the distribution of the bucket counts. Say we have $2$ buckets and $2$ keys. The two buckets can have the following number of keys in them: $(0, 2), (0,2)$ and $(1,1). (1,1)$ occurs with probability $1/2$, the others have probability $1/4$. Then for each case, we apply your logic to get the number of pair collisions. For $(0,2)$, there's $0$ pairs colliding in bucket $1$ and $1$ pair in bucket $2$. So in this case, there is $1$ colliding pair and this case happens with probability $1/4.$ In the $(1,1)$ case there are $0$ colliding pairs in total, and this case has probability $1/2.$ In the $(0,2)$ case we again have $1$ colliding pair, and that case is probability $1/4.$ So the expected value for $n=2, m=2$ is $$1\cdot(1/4) + 0\cdot(1/2) + 1\cdot(1/4) = 1/2. $$
In principle we can do this same computation for general $n,m$ but these are the types of questions where linearity of expectation comes in so useful - when we only want an expected value, linearity of expectation often allows us to dodge actually computing the distribution.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proving or disproving $c-d|p(c)-p(d)$ where $p$ is a polynomial.
I have $p(X)=\sum_{i=0}^{n}{a_iX^i}$, where $a_i\in\Bbb{Z}$. Let $c,d\in\Bbb{Z}$.
Prove or disprove: $c-d|p(c)-p(d)$.
I did some algebra but I can't think of a way to divide high power parts by $c-d$. I can't on the other hand find a counter example, and it does feel like a true statement.
I would really appreciate your help here.
A:
It is true because $c-d \mid c^k-d^k, k \in \mathbb {N}$
A:
Alternatively, consider the polynomial
$$
p(x) - p(d).
$$
Clearly this has $d$ as a root. Therefore
$$
x - d \mid p(x) - p(d).
$$
Now substitute $x = c$.
| {
"pile_set_name": "StackExchange"
} |
Q:
D'Alembert's Principle - rocket
Consider a one-dimensional, force-free motion of a rocket with constant mass emission $\mu$ and constant outflow velocity c of the gases. At $t=0$ let $m=m_0$ and $v=0$.
a) When is the kinetic energy of the rocket at a maximum and what are its mass and velocity at this point in time.
b) Assume a quadratic resistance acts on the movement of the rocket in the form of $R=-\alpha v^2$. In that case the rocket can only achieve a certain velocity $v_c$. Determine $v_c$.
c) Consider a motion of the rocket without resistance in the homogeneous gravitational field of earth. Determine the reached height $h$ as a function of time with the initial value of $m=m_0$ at $t=t_0$.
Here were my ideas so far:
a) First of all the basis. There is a constant mass emission, meaning $\dot{m}=-\mu$.
Now to my approach: The first formula that came to mind was $\sum_i(F_i-m_ia_i-\dot{m_i}v_i)\cdot \partial r_i=0$ Since we only consider a rocket it should be $(F-m_0a_r+\mu v_r)\cdot \partial r=0$, correct?
Now, I'm not sure what force $F$ actually is. Is it the force acting upwards on the rocket or the force acting on the gas particles? Putting that aside: I suppose I should try to find different expressions for $a_r$ and $v_r$? I was thinking that $\mu$ is the mass of the gas "shot" out of the rocket and since their outflow is constant their momentum should be conserved, so something like $p_g=\mu \cdot c=(m_0-\mu t)v_r$? I didn't know how to express the mass of the rocket at some random point, so I was thinking of just going with $m_0-\mu t$. Anyway, This would give me $v_r=\frac{\mu\cdot c}{m_0-\mu t}$.
Giving me $(F-m_0a_r+\mu \frac{\mu\cdot c}{m_0-\mu t})\partial r=0$. Can I assume that $F=\dot{p_g}=0$, because the outflow velocity is constant?
I'm basically lost on b) and c), don't know how to approach them.
Could anyone more fluent in this subject help me here?
A:
The usual way of deriving rocket equations, and variable mass equations in general, is to use the impulse-momentum principle -
The impulse of external forces in time $\delta t=$ the increase in momentum in time $\delta t$
Conservation of mass implies that ejected particles of mass in time $\delta t$ are assigned a value $-\delta m$
Applying this principle in part a) (assuming $c$ is the ejection speed relative to the rocket) gives:$$(m+\delta m)(v+\delta v)-\delta m(v+\delta v-c)-mv=0$$
$$\Rightarrow m\delta v+c\delta m=0$$
Dividing by $\delta t$ and allowing $\delta t \rightarrow 0$, we have $$m\frac{dv}{dt}=\mu c$$
The kinetic energy is $T=\frac 12 mv^2$
To find the maximum kinetic energy, set $\tfrac{dT}{dt}=0$
From this we get $v=0$ where the kinetic energy is zero, or $v=2c$, which gives the maximum.
To get the mass at this instant solve, with the initial conditions given, the rocket equation in the form (allowing $\delta m\rightarrow0$ instead) $$m\frac{dv}{dm}=-c$$ whereupon $$m=m_0e^{-2}$$
The rest of the question can be solved in the same way...
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery option to show input disappears
I have this simple <select> that should display an input if "Other" option is selected. However, if I open/close select, or pick any other option, "Other" disappears.
Here's what I mean:
<script type="text/javascript">
$(document).ready(function(){
var $milestones = $(".other"),
$selector = $('#source');
$selector.change(function() {
var selected = $selector.find('option:selected').attr('class');
$milestones.hide();
$('#' + selected).show();
});
});
</script>
And below is HTML that holds select as well as hidden div to show the input:
<div class="field text">
<label>Where did you hear about us?</label>
<select name="source" id="source">
<option value="Facebook">Facebook</option>
<option value="Twitter">Twitter</option>
<option value="Other" class="other">Other</option>
</select>
</div>
<div class="field text">
<div id="other" class="hideme">
<label>Sources:</label><input type="email">
</div>
</div>
A:
I guess you want to show input while option.other is selected. So here is the code:
$(document).ready(function(){
var $selector = $('#source');
$selector.change(function() {
var showOther = $('option.other').is(':selected');
$('#other').toggle(showOther);
});
});
And for that purpose, you should hide input from start, and let jQuery.toggle() do its job.
.hideme {
display: none;
}
http://jsfiddle.net/kWSrh/
| {
"pile_set_name": "StackExchange"
} |
Q:
Comparing a Date to the Datetime Created_at in rails3
So I'm trying to do things like so:
today = Date.today - 1
todaysReport = Report.where(:created_at => today).find_by_user_id(user.id)
The problem is created_at is a datetime, so it won't find any matches..Any suggestions?
A:
You probably want something like this:
yesterday = Time.now - 1.day
user = User.find(user_id)
todaysReport = user.reports.where(["created_at >= ? AND created_at <= ?", yesterday.beginning_of_day, yesterday.end_of_day])
A:
In postgres, you can cast a timestamp as a date. For example:
Report.where("created_at::date = ?", Date.today - 1)
Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL
A:
You need to compare against a range from one midnight to the next.
Also, this is a good candidate for making your own class method
for higher flexibility.
class Report
# All reports created on the specified Date
def self.created_on(date)
where(['created_at >= ? AND created_at < ?', date, date + 1])
end
end
# Find all reports created yesterday by our user
Report.created_on(Date.today - 1).where(:user_id => user.id)
| {
"pile_set_name": "StackExchange"
} |
Q:
Rewrite jQuery function to Vanilla JS and optimize
First I want to apologize, because I am a bit newbie with JS and it's library jQuery. Basically I have written a javascript function that toggles my hamburger menu:
const menuToggle = document.querySelector('.menu-toggle');
let menuOpen = false;
menuToggle.addEventListener('click', () => {
if(!menuOpen) {
menuToggle.classList.add('open');
menuOpen = true;
} else {
menuToggle.classList.remove('open');
menuOpen = false;
}
});
Now I want to rewrite this jQuery function to Vanilla JS
$(function() {
$('.toggle').on('click', function() {
$('.inner-wrapper').toggleClass('open');
});
});
I tried this, but it is not working:
var searchElement = document.createElement(".inner-wrapper");
document.querySelector(".toggle").appendChild(searchElement);
searchElement.addEventListener("open", handleClick);
I would like to combine both functions if possible. Thanks in advance!
A:
First, this code of yours:
menuToggle.addEventListener('click', () => {
if(!menuOpen) {
menuToggle.classList.add('open');
menuOpen = true;
} else {
menuToggle.classList.remove('open');
menuOpen = false;
}
});
can be simplified to this:
menuToggle.addEventListener('click', () => {
menuToggle.classList.toggle('open');
menuOpen = !menuOpen;
});
Second, the equivalent vanilla JavaScript version of this:
$(function() {
$('.toggle').on('click', function() {
$('.inner-wrapper').toggleClass('open');
});
});
is this:
document.querySelector('.toggle').addEventListener('click', function () {
document.querySelector('.inner-wrapper').classList.toggle('open');
});
Finally, this code of yours has problems:
var searchElement = document.createElement(".inner-wrapper");
document.querySelector(".toggle").appendChild(searchElement);
searchElement.addEventListener("open", handleClick);
There is no HTML element called ".inner-wrapper". You probably wanted to create an element with that class, something like this:
var searchElement = document.createElement("div"); // or any valid tag name
searchElement.className = 'inner-wrapper';
Also, there's no event called "open". You probably want that to be "click", and you probably want to target that to the ".toggle" element (not the '.inner-wrapper' element).
| {
"pile_set_name": "StackExchange"
} |
Q:
Making a bar chart with object returned by pd.groupby.sum()
I am trying to take a pandas dataframe (created by doing a groupby partnerid) that looks like this: (Only with many more rows)
|---------------------|------------------|
| partnerid | |
|---------------------|------------------|
| 6 | 25153 |
|---------------------|------------------|
| 9 | 13370 |
|---------------------|------------------|
| 75 | 47 |
|---------------------|------------------|
And want to make a bar chart.
Normally I would use
df['partnerid'].value_counts().sort_index().plot.bar()
But I get the error
KeyError: 'partnerid'
Alternatively I could use Matplotlib, but I do not know how to reference the unnamed column and when renaming it the code runs but does not change the column name.
I think that it might be me trying to do illegal things with the datatype that I am using.
Could someone please help me understand the datatype that comes from a df.groupby.sum() and how I can change it into something that can be turned into a bar chart?
Thanks
A:
May be this is what you do in the first step,
df = df_initial.groupby(['partnerid']).sum()
then, it looks like your df is a pd.Series object, hence you can plot using the following command
df.value_counts().sort_index().plot.bar()
| {
"pile_set_name": "StackExchange"
} |
Q:
Munin Limits on COUNTER and DERIVE Data
For Munin plugins of COUNTER and DERIVE type, what values should I use for ${name}.warning and ${name}.critical values?
A:
It depends on the data you're measuring (and not really on the data type).
COUNTERs are absolute values, so you just specify the minimum and maximum values that should be present. A common example is the number of users currently logged into a system. It's (usually) okay not to have anyone logged in, so there would be no minimum threshold. On a server, you normally wouldn't have too many simultaneously active logins, so you could warn if there were five active logins and issue a critical alert if there were ten or more. That would look like this:
users.warning :5
users.critical :10
DERIVE fields are rate-of-change values, so you just consider the minimum and maximum rates you want to see. Let's say you're monitoring electrical power in watts (and it's a DERIVE field because the system reports the total number of joules it's consumed since poweron and you're deriving watts from that). If the system normally draws 80 watts, you might set your thresholds at 75 and 100 watts for a warning and 70 and 130 watts for a critical status. (If power consumption is too low, one of the system components is probably broken, since most computers have a lower bound for normal operating current. On the other hand, a "too high" wattage is going to depend on more external factors like the capacity of your electrical infrastructure.) That would look like this:
power.warning: 75:100
power.critical: 70:130
I hope I've illustrated with my examples that the limit settings depending significantly on what exactly you're measuring and there's no general way to say things like, "A DERIVE data source should have a warning threshold of X:Y."
| {
"pile_set_name": "StackExchange"
} |
Q:
tweepy get media url from json response
I want to get twitter image URL from its JSON response. I used a python script.below is the code.
import re
import tweepy
import sys
consumer_key = 'xxxx'
consumer_secret = 'xxx'
access_token ='xxxx'
access_token_secret = 'xxxx'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
media_files = set()
for status in tweepy.Cursor(api.home_timeline,screen_name='@yyyyy').items(250):
media = status.entities.get('media', [])
if(len(media) > 0):
media_files.add(media[0]['media_url'])
url=status._json['media_url']
print(url)
I need to sperate image URLs from JSON response and print it. It shows an error message as below.
url=status._json['media_url']
KeyError: 'media_url'
A:
for status in tweepy.Cursor(api.home_timeline,screen_name='@yyyyy').items(250):
if 'media' in status.entities:
for image in status.entities['media']:
print(image['media_url'])
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding Elements To An Array Using Array.Add
I am new to C# and am trying to make a basic game in Unity. I am trying to add bullet gameObject to an array. I have researched how to add elements to an array in C# and have found the Add method. However, when I try to use this MonoDevelop doesn't highlight the method as if the method doesn't exist and I get an error. Here is is the error message:
Assets/Scripts/SpaceShipController.cs(126,25): error CS0118:
SpaceShipController.gameManager' is afield' but a `type' was
expected
Here is the line of code which trips the error:
gameManager.bullets[].Add(bulletObject);
Here is the rest of my code. The class called SpaceShipController trips the error when it tries to add bullet objects to an array in a GameManager objects with the script GameManager attached. Finally the BulletBehaviour class just makes the bullet move forward. The code is labelled by class:
SpaceShipController:
using UnityEngine;
using System.Collections;
public class SpaceShipController : MonoBehaviour {
public GameObject bulletObject;
public GameManager gameManager;
//private GameObject[] bullets;
public float shipSpeed;
public float bulletSpeed = 1;
private Vector3 spaceShip;
private Quaternion spaceShipRotation;
private Vector3 bulletPosition;
private int coolDown = 10;
private bool moveRight = false;
private bool moveLeft = false;
private bool fire = false;
// Use this for initialization
void Start () {
spaceShip = transform.position;
spaceShipRotation = transform.rotation;
bulletObject.transform.position = bulletPosition;
}
// Update is called once per frame
void Update () {
coolDown--;
inputHandler();
this.transform.position = spaceShip;
}
void inputHandler() {
if (Input.GetKeyDown(KeyCode.RightArrow)) {
moveRight = true;
}
if (Input.GetKeyDown(KeyCode.LeftArrow)) {
moveLeft = true;
}
if (Input.GetKeyUp(KeyCode.RightArrow)) {
moveRight = false;
}
if (Input.GetKeyUp(KeyCode.LeftArrow)) {
moveLeft = false;
}
if (Input.GetKeyDown(KeyCode.Space)) {
fire = true;
}
if (Input.GetKeyUp(KeyCode.Space)) {
fire = false;
}
if (moveRight == true) {
spaceShip.x += shipSpeed;
}
if (moveLeft == true) {
spaceShip.x -= shipSpeed;
}
if (coolDown <= 0) {
if (fire == true) {
Fire ();
coolDown = 10;
}
}
}
void Fire () {
for (var i = 0; i < 2; i++) {
if (i == 0) {
spaceShip = new Vector3 (transform.position.x + 0.9f, transform.position.y + 0.9f, transform.position.z);
}
else if (i == 1) {
spaceShip = new Vector3 (transform.position.x - 0.9f, transform.position.y + 0.9f, transform.position.z);
}
Instantiate(bulletObject, spaceShip, spaceShipRotation);
bulletObject.AddComponent<BulletBehaviour>();
gameManager.bullets[].Add(bulletObject);
spaceShip = this.transform.position;
}
}
}
GameManager:
using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
public GameObject[] bullets;
public Camera cam;
private Vector2 cameraBounds;
// Use this for initialization
void Start () {
cameraBounds = new Vector2 (cam.orthographicSize * Screen.width/Screen.height, cam.orthographicSize);
}
// Update is called once per frame
void Update () {
/*for (int i = 0; i < bullets.Length; i++) {
if (bullets[i].transform.position.y >= cameraBounds.y) {
Destroy(bullets[i]);
}
}*/
}
}
BulletBehaviour:
using UnityEngine;
using System.Collections;
public class BulletBehaviour : MonoBehaviour {
public SpaceShipController ship;
private Vector3 shipPosition;
// Use this for initialization
void Start () {
shipPosition = transform.position;
}
// Update is called once per frame
void Update () {
shipPosition.y += 1;
transform.position = shipPosition;
}
}
As always any help would be greatly appreciated. Thanks in advance for any help you can provide.
A:
Arrays are fixed-size. This means that, once they have been initialized with a certain length (e.g., bullets = new GameObject[10]), its length can no longer change.
In order to "add" an item to a array, you have to specify in which position you'd like the item to be. By default, arrays' indexing is 0-based. For example, to insert an element in the first position:
bullets[0] = myItem;
If you don't know how many items you'll have beforehand, and want to add/remove items at will, you should use a resizable collection, such as List<T>.
public List<GameObject> Bullets {get; set;}
You can use it like so:
//initialize with 0 items
Bullets = new List<GameObject>();
//add a new item at the end of the list
Bullets.Add(item);
Read also:
Arrays Tutorial
List<T> class
C# Collections
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel 5 HTTP/Requests - pass url parameter to the rules() method
I'm trying to create a set of rules under the new \HTTP\Requests\UpdateArticle class for the slug field, which needs to have unique filter applied, but only when the id is not equal the url parameter of the route name article/{article}.
What I got so far is:
public function rules()
{
return [
'title' => 'required|min:3',
'excerpt' => 'required',
'body' => 'required',
'slug' => 'required|unique:articles,slug,?',
'active' => 'required',
'published_at' => 'required|date'
];
}
I need to replace the question mark at the end of the unique filter for slug field with the id from the url, but don't know how to obtain it.
A:
You can retrieve route parameters by name with input():
$id = Route::input('id');
return [
// ...
'slug' => 'required|unique:articles,id,' . $id,
// ...
];
It's right there in the docs (scroll down to Accessing A Route Parameter Value)
| {
"pile_set_name": "StackExchange"
} |
Q:
Does reference counting still works with Delphi Interfaces when you don't provide a guid?
I have the following interface:
type IDataAccessObject<Pk; T:class> = interface
getByPrimaryKey(key: PK) : T;
//... more methods
end;
And an implementation of the interface as follows:
type TMyClassDAO = class(TInterfacedObject, IDataAccessObject<integer, TMyClass>)
getByPrimaryKey(key:integer) : TMyClass;
// more methods
end;
Note that I am not providing a guid for the interface (because every instantiation of the previous generic interface is a different interface and they should not share the same guid). However I am not sure whether that does not break reference counting implemented by TInterfacedObject?
A:
Reference counting does not rely on a GUID, but on _AddRef() and _Release() method implementations.
Since you inherit from TInterfacedObject, reference counting will work for all of your object instances.
The only thing you lose if you don't provide a GUID is the ability to query one interface from another, such as in calls to the Supports() function, QueryInterface() interface method, and the is and as operators.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to retrieve stackoverflow tag usage count via stackexchange api call?
I want to retrieve the 'tag usage count' of a language like Ruby or Java via the StackExchange API.
Basically I want to retrieve these numbers via API call:
https://stackoverflow.com/tags
e.g. how do I get the 780k for Java as seen in the link via StackExchange API call?
Does anyone know?
I tried this:
https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&tagged=java&site=stackoverflow
but that doesn't give me the total count
It seems to be easy with the Stack Exchange Data Explorer
http://data.stackexchange.com/stackoverflow/query/229727
But how to retrieve these counts via API?
A:
ok found the answer myself:
https://api.stackexchange.com/2.2/tags?order=desc&sort=popular&inname=java&site=stackoverflow
just replace java with whatever tag you need.
The Tag count then is included in the json response.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert an array of custom objects to an array of strings?
I currently have an array of custom objects
[GenrePosters]
which is defined like so:
public struct GenrePosters: Decodable, Equatable{
public let poster : String
public init? (json: JSON) {
guard let poster: String = "poster_path" <~~ json
else {return nil}
self.poster = poster
}
public static func ==(lhs: GenrePosters, rhs: GenrePosters) -> Bool {
return lhs.poster == rhs.poster
}
When printed to console it looks like this:
[MyMovieGuide.GenrePosters(poster:
"/e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg"), MyMovieGuide.GenrePosters(poster:
"/jjBgi2r5cRt36xF6iNUEhzscEcb.jpg"), MyMovieGuide.GenrePosters(poster:
"/tIKFBxBZhSXpIITiiB5Ws8VGXjt.jpg")]
I'm trying to convert the array of GenrePosters to an array of strings with only the poster values that like this:
[
"/e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg"
"/jjBgi2r5cRt36xF6iNUEhzscEcb.jpg"
"/tIKFBxBZhSXpIITiiB5Ws8VGXjt.jpg"]
Any help will be appreciated!
A:
You should be able to do this using map(_:) method:
let posters = posterList.map {$0.poster}
| {
"pile_set_name": "StackExchange"
} |
Q:
DD sda1 (or whatever) to a file. Then at some point mount that file as ISO or some other means?
Death to Windows. I am done with it.
I would like to preserve the Windows partition in case I will need it later. I was wondering if I can use dd to copy the partition to some file so that if I need to I can restore the partition as-is. That if, in the course of things I need some files from that partition (file), can I mount the file like an iso file.
dd if=/dev/sda1 of=/my/preserved/windows.iso
mount windows.iso
Is that doable? Is there another method/suggestion?
A:
Yes, that will work as long as you have the tools to read the ntfs partition that resides on Windows.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Display a Total number of data entered in a Field in SQL
How to display a total number of data entered in a field in SQL?
This what I have as SQL statement. I would like to see something like this:
SELECT u.username, cl.Branch,
vt.service,
vt.sales,
vt.debtors,
vt.contact_via
FROM Visits_table vt
JOIN user u ON u.id = vt.Rep_Id
JOIN Client_table cl ON cl.Client_Id = vt.client_fk
WHERE vt.Start_Date >= '2015-1-3'
AND vt.Start_Date <= '2015-1-10'
ORDER BY Start_Date DESC
Output:
Username --- Branch ---- Service ---- Sales ---- Debtors ---- Contact_Via
1 username, 1 Branch, Total number of (Services), Total number of(Sales), Total number of(Debtors), Total number of (Contact_Via).
All in a single SQL Statement.
Is it possible to have these total number of data field in 1 single row?
A:
According to my comments, do a GROUP BY and use SUM:
SELECT u.username, cl.Branch,
SUM(vt.service),
SUM(vt.sales),
SUM(vt.debtors,
SUM(vt.contact_via)
FROM Visits_table vt
JOIN user u ON u.id = vt.Rep_Id
JOIN Client_table cl ON cl.Client_Id = vt.client_fk
WHERE vt.Start_Date >= '2015-1-3'
AND vt.Start_Date <= '2015-1-10'
GROUP BY u.username, cl.Branch
ORDER BY Start_Date DESC
Maybe you should try COUNT(DISTINCT vt.service) etc instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Embed Excel Files and Link Data into PowerPoint by python in specific place of slide
There is an excel file with different sheets which is included by different charts and data. I want to make a powerpoint for my daily presentation automatically by python(PPTx lib in python).
my problem is I have to copy the charts which exist in excel and past in my powerpoint which is created by python (pptx). I want to know is there any possibility to export charts from excel file to powerpoint by python?
A:
There is no direct API support for this in python-pptx. However, there are other approaches that might work for you.
Perhaps the simplest would be to use a package like openpyxl to read the data from the spreadsheet and recreate the chart using python-pptx, based on the data read from Excel.
If you wanted to copy the chart exactly, this is also possible but would require detailed knowledge of the Open Packaging Convention (OPC) file format and XML schemas to accomplish. Essentially, you would copy the chart-part for the chart into the PowerPoint package (zip file) and connect it to a graphic-frame shape on a slide. You'd also need to embed the Excel worksheet into the PowerPoint, perhaps repeatedly (once for each chart) and make any format-specific adjustments (Excel and PowerPoint handle charts slightly differently in certain details).
This latter approach would be a big job, so I would recommend trying the simpler approach first and see if that will get it done for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Internet explorer 6 Z-index problem
I have a popup DIV (js triggered) which shows an image. Very simple.
The problem is, that this DIV must overlap the SELECTS which lie underneath the DIV.
It works in all browsers but IE6.
When the js is triggered, and the DIV is displayed, the z-index isn't right because the SELECT drop lists overlap parts of the DIV.
This is only in IE6.
Anybody have a clue?
Here is the css for the div:
.pop_komm {
position: absolute;
z-index: 20;
height: 52px;
width: 208px;
left: 760px;
top: 239px;
display:none;
zoom:1;
}
I have tried removing the zoom, and editing some of the css above without luck.
Why is this not working in IE6?
Thanks
A:
If I can recall correctly it's a fairly well known bug that IE6 ignores z-index for select elements, that is, it's always in front of all other elements, regardless of their z-index.
The basic method is either to hide the select in question when you need something on top of it with Javascript, or overlay a iframe "shim" to hide it. See this question for more detail: iframe shimming or ie6 (and below) select z-index bug
| {
"pile_set_name": "StackExchange"
} |
Q:
SendKeys not working?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
CheckBox1.Checked = True
While CheckBox1.Checked = True
SendKeys("{END}")
End While
End Sub
That is the code, the error is "SendKeys is a type and cannot be used as an expression."
How could I fix this?
Thanks!
A:
use
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
CheckBox1.Checked = True
While CheckBox1.Checked = True
SendKeys.Send("{END}")
End While
End Sub
You need to refer SendKeys.Send();
| {
"pile_set_name": "StackExchange"
} |
Q:
JBoss AS 5.x EOL?
I can't find any official date on the JBoss web site when JBoss AS 5.x will be end-of-life. Can anyone give me a hint where to look?
A:
Finally found it:
https://access.redhat.com/support/policy/updates/jboss_notes/
| {
"pile_set_name": "StackExchange"
} |
Q:
AngularJS not finding values in array
I have a AngularJS app developed.
On a view I have a list of items - each with its own set of radio buttons. The list and buttons are built at run-time from an API call.
Both the list and radio buttons can be of any length e.g. list item 1 might contain 3 radio buttons while list item n might contain 2 radio buttons.
When the user selects a radio button I fire a ng-click method that sends both the list ID as well as the radio button ID to the controller.
The view looks as follows and I have tested this and the values are being sent to the controller.
<label class="radio-button" ng-repeat="option in checkItemDescription.options">
<input type="radio" name="option_question_id_{{checkItemDescription.fleetcheckitemid}}"
ng-model="checkItemDescription.selected_id"
ng-click="doSomething(checkItemDescription.fleetcheckitemid, option.fleetcheckid)"
ng-value="option.fleetcheckid">
<div class="radio-button__checkmark"></div>
Description: {{option.checkvaluedesc}}
</label>
In my doSomething() method i am trying to see if either the checkItemDescription.fleetcheckitemid or the option.fleetcheckid id is in a existing array.
I use indexOf() method to compare the values but the method does not seem to work - even though console.log() shows values are sent to the controller.
Below is my doSomething() method.
$scope.doSomething = function(fleetCheckItemID, fleetCheckID)
{
if ( $scope.initialFleetCheckIssueItemIDArray.indexOf(fleetCheckItemID))
{
console.log("Yeah!"); // Never gets to here even though logs show values exist
}
else
{
console.log("Ah!"); // Always get here
}
}
What I need to do is to to create a JSON object with the list item ID, radio button ID and some other values e.g. date/time based on the user selection to send to my Database.
Is this the best way to do it or is there a better way?
A:
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
-referenced from MDN.
so if your element is first in the collection then indexOf would return 0 which would result in the execution of else block so change your if condition like this.
if ( $scope.initialFleetCheckIssueItemIDArray.indexOf(fleetCheckItemID) != -1 )
{
//element found, do stuff here.
}
else
{
//element does not found, else stuff here.
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Navigate to another route from a service
I have service that intercepts all my Http requests so I can check if the user's token is valid or not. When a Http response is 401, I want the current user to be logged out of the application:
import { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, Request, Response } from '@angular/http'
import { Router } from '@angular/router'
import { Observable } from 'rxjs/Observable'
import { Injectable } from '@angular/core'
import { Config } from './shared/config'
import { RouterExtensions } from 'nativescript-angular/router'
import 'rxjs/add/observable/throw'
@Injectable()
export class RequestInterceptorService extends Http {
private config: Config = new Config()
constructor(
backend: ConnectionBackend,
defaultOptions: RequestOptions,
private router: Router,
private routerExtensions: RouterExtensions,
) {
super(backend, defaultOptions)
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.request(url, options))
}
intercept(observable: Observable<Response>): Observable<Response> {
return observable.catch((err, source) => {
if (err.status === 401) {
this.logout()
return Observable.empty()
} else {
return Observable.throw(err)
}
})
}
logout() {
this.config.clear()
this.routerExtensions.navigate(["/signin"], {
clearHistory: true
})
}
}
My issue is that router or routerExtensions are always undefined, so I can't really redirect the user to any other path at all using this service.
A:
So, I found the solution. It was just a mater of understanding all of what I was doing.
I created a RequestInterceptor service that extends Http module. It includes a interceptor that checks if the status code is equal to 401. In order to make it compatible with my project, I decided to provide it as custom implementation of Http. The following code on my @NgModule does just that:
providers: [
{
provide: Http,
useClass: RequestInterceptorService
}
]
But the thing RequestInterceptorService does not have access to Http dependencies: ConnectionBackend and RequestOptions, so I had to inject them using the deps property, which is an array where I can identify an array of dependencies that will get injected. In my case, I need to inject not only the dependencies that Http requires (XHRBackend, RequestOptions), but also the one that my service will use: RouterExtensions.
My providers declaration looks like this:
providers: [
{
provide: Http,
useClass: RequestInterceptorService,
deps: [XHRBackend, RequestOptions, RouterExtensions]
}
]
After doing this, I was able to successfully redirect a user to the login page when a 401 status code is returned from any request.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS greyscale and brightness at same time
I wanted to change image to grayscale(0.9) and brightness (120%) at the same time. How can I do that?
img{
-webkit-filter: grayscale(0.9);
-webkit-filter: brightness(1.2);
}
How?
A:
img {
filter: grayscale(0.9) brightness(1.2);
}
<img src="http://beerhold.it/400/300">
| {
"pile_set_name": "StackExchange"
} |
Q:
ERROR en array de strings dentro de una estructura c++
Pongamos como ejemplo el siguiente:
Una sala de cine pone a la venta los abonos de temporada. Cada abono corresponde a un asiento de la sala al cual el socio podría acudir durante toda la temporada. En la sala existen 25 filas de 20 asientos cada una.
Por cada asiento habría que almacenar el nombre del abonado y si ese asiento esta libre o no para su compra.
He pensado en lo siguiente:
#include <iostream>
#include <array>
#include <string>
using namespace std;
const int Fil=25;
const int Col=20;
typedef array <string,Fil> TFila;
typedef array <TFila,Col> TFila_asiento; // array de strings locooo!!
struct TSalaCine{
TFila_asiento Fila_asiento; //array de string asiento y fila
string abonado;
};
int main(){
}
void asientos_libres(TSalaCine &sala){
for(int fila=0; fila<25; fila++){
for(int col=0;col<20; col++){
sala.Fila_asiento[fila][col]='0';
}
}
}
¿Es posible hacer un array de strings, es decir que en cada posición del array lo que yo almacene sea un string?
En caso afirmativo, como relleno ese string para inicializarlo como conjunto vacío, he probado con poner de valor en el bucle for '0', pero no funciona.
El objetivo que tengo en mente es primero inicializar a 0 (conjunto vacío) el array de strings, y luego pedir al usuario el nombre del cliente e insertarlo en el lugar del respectivo sitio.
El problema es que cuando voy a comparar si el sitio esta vacio o no if(sala.Fila_asiento[fila][col]=='\0') me sale el siguiente error:
ejercicio3.cpp:48:36: error: no match for ‘operator==’ (operand types
are ‘std::arraystd::__cxx11::basic_string<char, 25ul>::value_type
{aka std::__cxx11::basic_string}’ and ‘char’)
if(sala.Fila_asiento[fila][col]=='\0'){
In file included from /usr/include/c++/6/iosfwd:40:0,
from /usr/include/c++/6/ios:38,
from /usr/include/c++/6/ostream:38,
from /usr/include/c++/6/iostream:39,
from ejercicio3.cpp:1: /usr/include/c++/6/bits/postypes.h:216:5: note: candidate:
template bool std::operator==(const
std::fpos<_StateT>&, const std::fpos<_StateT>&)
operator==(const fpos<_StateT>& __lhs, const fpos<_StateT>& __rhs)
Gracias por la respuesta. Un saludo :D
A:
El error no tiene nada que ver con el array de string dentro de una estructura. Obtendrías exáctamente el mismo error fuera de una estructura:
error: no match for ‘operator==’ (operand types are ‘std::array<std::__cxx11::basic_string<char>, 25ul>::value_type {aka std::__cxx11::basic_string<char>}’ and ‘char’)
if(sala.Fila_asiento[fila][col]=='\0'){
Para empezar, parece que no compartes el código que genera el error. En el error indica que estás usando el operador de comparación ‘operator==’, en tu código muestras el operador de asignación:
for(int fila=0; fila<25; fila++){
for(int col=0;col<20; col++){
sala.Fila_asiento[fila][col]='0';
// Asignación ---> ^
}
}
El código que muestras no da fallo alguno. Si en lugar de una asignación fuese una comparación ¿Qué significaría el error?
error: no match for ‘operator==’: No hay coincidencia para el operador de comparación.
(operand types are ‘std::array<std::__cxx11::basic_string<char>, 25ul>::value_type {aka std::__cxx11::basic_string<char>}’ and ‘char’): Los operandos son TFila::value_type (que es un std::string) y char.
Es decir, estás comparando una cadena (std::string) con un carácter (char), podemos ver que este operador tiene dos sobrecargas:
constexpr bool operator==( const std::string& lhs, const std::string& rhs ) noexcept;
constexpr bool operator==( const std::string& lhs, const CharT* rhs );
Y ninguna de las sobrecargas compara una cadena con un carácter, de ahí el error.
Respecto a tus dudas:
¿Es posible hacer un array de strings, es decir que en cada posición del array lo que yo almacene sea un string?
Por supuesto, en tu caso no estás haciendo eso si no un std::array de std::array de std::string, pero el concepto es el mismo. Podrías aplicar las siguientes mejoras a tu diseño:
Transforma el objeto sala en una plantilla y Parametriza sus filas y columnas.
Define los alias de tipos internamente en el objeto sala.
Usa alias tipo C++11.
template <auto Fil, auto Col>
struct TSalaCine{
using TFila = array<string,Fil>;
using TFila_asiento<TFila,Col>;
TFila_asiento Fila_asiento; //array de string asiento y fila
};
// Cine con 25 filas y 20 columnas:
using cine_25x20 = TSalaCine<25, 20>;
¿Cómo relleno ese string para inicializarlo como conjunto vacío?
No tienes que hacer nada, por defecto los std::string se construyen vacíos. Puedes comprobar si un elemento está vacío llamando a std::string::empty:
if (sala.Fila_asiento[fila][col].empty()){
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamics table in Angular from two array of object
I'm making a dynamic table (from scratch), which build itself from two array of objects, "columns" and "rows".
Each column object have a property, "id", which I want to use in order to select the good property to display on each column (because I don't know the number of columns that will be in the row).
component html:
<table>
<thead>
<tr>
<th *ngFor='let key of columns'>
{{ key.label }}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let row of rows'>
<td></td> <!-- I don't know how to do from here -->
</tr>
</tbody>
</table>
Sample data:
Columns :
this.columns = [{
id: "id",
label: "Id"
},
{
id: "name",
label: "Name"
},
{
id: "postal_code",
label: "Postal Code"
}
];
Rows:
this.rows = [{
id: 120000,
name: 'Test0',
postal_code: 44000
},
{
id: 120001,
useless_column: true,
postal_code: 44000
},
{
name: 'Test2',
id: 120002,
postal_code: 44000
},
{
name: 'Test3',
id: 120003
},
]
The result should looks something like the following :
| Id | Name |Postal Code|
|------|------|-----------|
|120000|Test0 | 44000|
|120001| | 44000|
|120002|Test2 | 44000|
|120003|Test3 | |
A:
You will need to loops on columns inside the row loop and then access specific row key something like
<table>
<thead>
<tr>
<th *ngFor='let key of columns'>
{{ key.label }}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let row of rows'>
<td *ngFor='let key of columns'>
{{row[key.id]}}
</td>
</tr>
</tbody>
</table>
demo
| {
"pile_set_name": "StackExchange"
} |
Q:
Notepad problem in delphi
hi we are using the Delphi 5 version. We are getting problem while opening the notepad in delphi. We want to open notepad on a button click and pass the data to it so that notepad can display that data. I dont want to save it. please help me regarding this. thanks.
A:
You can use something like:
uses
Clipbrd;
procedure LaunchNotepad(const Text: string);
var
SInfo: TStartupInfo;
PInfo: TProcessInformation;
Notepad: HWND;
NoteEdit: HWND;
ThreadInfo: TGUIThreadInfo;
begin
ZeroMemory(@SInfo, SizeOf(SInfo));
SInfo.cb := SizeOf(SInfo);
ZeroMemory(@PInfo, SizeOf(PInfo));
CreateProcess(nil, PChar('Notepad'), nil, nil, False,
NORMAL_PRIORITY_CLASS, nil, nil, sInfo, pInfo);
WaitForInputIdle(pInfo.hProcess, 5000);
Notepad := FindWindow('Notepad', nil);
// or be a little more strict about the instance found
// Notepad := FindWindow('Notepad', 'Untitled - Notepad');
if Bool(Notepad) then begin
NoteEdit := FindWindowEx(Notepad, 0, 'Edit', nil);
if Bool(NoteEdit) then begin
SendMessage(NoteEdit, WM_SETTEXT, 0, Longint(Text));
// To force user is to be asked if changes should be saved
// when closing the instance
SendMessage(NoteEdit, EM_SETMODIFY, WPARAM(True), 0);
end;
end
else
begin
ZeroMemory(@ThreadInfo, SizeOf(ThreadInfo));
ThreadInfo.cbSize := SizeOf(ThreadInfo);
if GetGUIThreadInfo(0, ThreadInfo) then begin
NoteEdit := ThreadInfo.hwndFocus;
if Bool(NoteEdit) then begin
Clipboard.AsText := Text;
SendMessage(NoteEdit, WM_PASTE, 0, 0);
end;
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
LaunchNotepad('test string');
end;
| {
"pile_set_name": "StackExchange"
} |
Q:
Enum bit fields that support inheritance
I apologize for the Title of this Question, but I couldn't think of a better way to describe what I'm trying to accomplish..
I want to make an Enum using the Flags attribute whereby the bitwise values of the enum create somewhat of an inheritance schema.
Example: Say we have a bit field enum of food:
[Flags]
enum Foods
{
// Top Level foods
Meat,
Fruit,
Vegetables,
Dairy,
Grain,
BenJerrysOatmealCookieChunk, // ;)
// sub-Meat
Chicken,
Beef,
Fish,
// sub-Fruit
Apple,
Banana,
// sub-Vegetables
Spinach,
Broccoli,
// sub-Dairy
Cheese,
Milk,
// sub-Grain
Bread,
Pasta,
Rice,
// sub-Beef
Tritip,
Hamburger,
// sub-Fish
Salmon,
Halibut,
}
Notice how the enum contains sub-categories of food as well as sub-sub-categories. In my real-world scenario, I have an unknown number of top-level categories and an unknown number of sub-level categories (including an unknown level of sub-sub-sub-n-categories)
I would like to set the bit values of the enum such that sub-categories (and sub-sub-n-categories) will "inherit" the bit value of its immediate parent.
I am wanting to avoid the client setter of the Foods property to have to explicitly set all flags for a particular food. In other words, I do not want the client setter to have to do something like:
myClass.Foods = Foods.Tritip | Foods.Beef | Foods.Meat;
I am trying to create a construct so that the client setter simply has to set one flag and all parents of that flag are implicit within the child flag.
So if the client setter did this:
myClass.Foods = Foods.Tritip;
We would be able to run the following conditions successfully:
if((myClass.Foods & Foods.Meat) == Foods.Meat)
Console.WriteLine("I am meat");
if((myClass.Foods & Foods.Beef) == Foods.Beef)
Console.WriteLine("I am beef");
if((myClass.Foods & Foods.Tritip) == Foods.Tritip)
Console.WriteLine("I am tritip");
if((myClass.Foods & Foods.Meat) == Foods.Meat)
Console.WriteLine("I am meat");
if((myClass.Foods & Foods.Rice) != Foods.Rice)
Console.WriteLine("I am definitely not rice!");
What confuses me about this problem is what bit values to use for each food item in the enum. I initially started out with:
[Flags]
enum Foods
{
// Top Level foods
Meat = 0x1,
Fruit = 0x2,
Vegetables = 0x4,
Dairy = 0x8,
Grain = 0x10,
BenJerrysOatmealCookieChunk = 0x20, // ;)
...and so on.
}
.. but since I don't know how many levels there will be (the enum list will grow over time).. I don't know how to create my bit values so that they allow for growth.
Has anyone attempted to do this before? If so, what was your business logic for your bit values?
I have a sneaky feeling this Question will need a bounty ;)
A:
You could do this by doing bitwise OR inside of the enum declaration itself. While this will not give you a nice clean ToString like you normally get with the Flags attribute, it does give you the desired result:
[Flags]
public enum Foods : ulong
{
Meat = 0x100000,
Fruit = 0x200000,
Vegetables = 0x400000,
Dairy = 0x800000,
Grain = 0xF00000,
Beef = Meat | 0x100,
Chicken = Meat | 0x200,
Fish = Meat | 0x400,
Apple = Fruit | 0x100,
Banana = Fruit | 0x200,
Spinach = Vegetables | 0x100,
Broccoli = Vegetables | 0x200,
Cheese = Dairy | 0x100,
Milk = Dairy | 0x200,
Bread = Grain | 0x100,
Pasta = Grain | 0x200,
Rice = Grain | 0x400,
Tritip = Beef | 0x1,
Hamburger = Beef | 0x2,
Salmon = Fish | 0x100,
Halibut = Fish | 0x200,
}
I used ulong for the enum's base so that you get more space for subcategories. I didn't start at the highest order bit possible, but if I were you, I would so that there would be room to represent deeper categories. Also, you'd want to play around with the spacing between sub-categories to yield the optimal results.
A:
OP said (and I quote)
Notice how the enum contains sub-categories of food as well as sub-sub-categories.
In my real-world scenario, I have an unknown number of top-level categories and
an unknown number of sub-level categories (including an unknown level of
sub-sub-sub-n-categories).
Then you don't have an enum: you have some sort of type hierarchy. Enums (by design) wrap some sort of integral type and have a fixed number of elements. The fact that they are fundamentally fixed-point integers puts an upper bound on the number of available bits: an enum is 8-, 16-, 32- or 64-bits in size.
Given those restriction enums, you can do something like the following (and you don't need or want the [Flags] attribute). In the example below, I've reserved 32 bits for the "category" and 32 bits for the "subcategory".
enum Foods : ulong
{
CategoryMask = 0xFFFFFFFF00000000 ,
// Top Level foods
Meat = 0x0000000100000000 ,
Fruit = 0x0000000200000000 ,
Vegetables = 0x0000000400000000 ,
Dairy = 0x0000000800000000 ,
Grain = 0x0000001000000000 ,
BenJerrysOatmealCookieChunk = 0x0000002000000000 , // ;)
Chicken = Meat | 0x0000000000000001 ,
Beef = Meat | 0x0000000000000002 ,
Fish = Meat | 0x0000000000000004 ,
Apple = Fruit | 0x0000000000000001 ,
Banana = Fruit | 0x0000000000000002 ,
Spinach = Vegetables | 0x0000000000000001 ,
Broccoli = Vegetables | 0x0000000000000002 ,
Cheese = Dairy | 0x0000000000000001 ,
Milk = Dairy | 0x0000000000000002 ,
Bread = Grain | 0x0000000000000001 ,
Pasta = Grain | 0x0000000000000002 ,
Rice = Grain | 0x0000000000000004 ,
TriTip = Beef | 0x0000000000000001 ,
Hamburger = Beef | 0x0000000000000002 ,
Salmon = Fish | 0x0000000000000004 ,
Halibut, = Fish | 0x0000000000000008 ,
}
Note that interrogating a Foods value for its category will requires some bit twiddling, like so:
Foods item = Foods.Hamburger ;
Foods category = (Foods) ( (ulong)item & (ulong)Foods.CategoryMask ) ;
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding template equality operators
I want to write a proxy class, that takes a template value and can be compared to any class that the template can be compared to.
template <class T>
class Proxy {
public:
Proxy(T value) : _value(value) {}
template <class U> // this should exist only if the T == U operator is defined
bool operator==(U const& other) const { return _value == other; }
template <class U> // this should exist only if U == T is defined
friend bool operator==(U const& first, Proxy<T> const& second) const { return first == second._value; }
private:
T _value;
};
for example, since this is legal code:
bool compare(std::string first, std::string_view second) {
return first == second;
}
I want this to be legal, too:
bool compare(std::string first, Proxy<std::string_view> second) {
return first == second;
}
but just to clarify, this should work for any classes that can be compared, or can be implicitly converted in order to be compared. Can I define a template conditional that will check for either case?
A:
Since your criteria is essentially whether or not an expression like _value == other is well-formed, you can just rely on expression SFINAE to test it.
template <class U> // this should exist only if the T == U operator is defined
auto operator==(U const& other) const -> decltype(_value == other)
{ return _value == other; }
template <class U, std::enable_if_t<!std::is_same<U, Proxy>::value, int> = 0> // this should exist only if U == T is defined
friend auto operator==(U const& first, Proxy const& second) -> decltype(first == second._value)
{ return first == second._value; }
It may not be very DRY, since we need to repeat the expression twice, but it's a fairly simple way to do SFINAE, which is a major plus.
The other thing to note is that we do not want the second overload to be considered recursively, which may happen upon comparison of two proxies. So we need another SFINAE condition, spelled out the old fashioned way with enable_if, to discard the overload when U is a Proxy. This relies on the C++14 feature whereby substitutions are checked in declaration order. Putting it first prevents the recursion in first == second._value.
| {
"pile_set_name": "StackExchange"
} |
Q:
Eclipse Google SDK
So essentially what I have is a libGdx Program that I have written in Eclipse and I want to add in Google Leaderboards to my app. I have looked at what google has posted on their website on how to add BaseGameUtils to your project. I cannot seem to follow and understand how to add BaseGameUtils to my project. I need it most specifically for GameHelper. I would appreciate any guidance, step by step instructions, or even screenshot instructions.
A:
alright first of all you need to download the google play services sdk from the sdk manager and install it.
2) you need to download the Library Project named BaseGameUtils
3) you need to open eclipse and import the project into the workspace
4)Right-click your project and select Properties
5)Select Android in the list, In the Library panel click add project as library and select the BaseGameUtils and your done...i hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wcopyfind for python - plagiarism software?
Is there anything like wcopyfind for python?
http://plagiarism.bloomfieldmedia.com/z-wordpress/software/wcopyfind/
A:
The inbuilt difflib might help
http://docs.python.org/2/library/difflib.html
But people seem to think this is tough
Can difflib be used to make a plagiarism detection program?
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery code not working on IE 8
following code works perfectly on FF and Chrome but not in IE8.
$(window).keyup(function(e) {
var code = e.which
if (code == 9)
{
alert("do stuff");
cellContent();
autoDate();
}
});
This code will recognize the tab and does the function cellContent() and autoDate(). I added alert to see if this functions are ever used on IE8 but it doesnt seem like it recognizes it.
Thanks in advance!
A:
I have found the answer! All I had to do was instead of doing
$(window).keyup(function(e) {
var code = e.which
if (code == 9)
{
alert("do stuff");
cellContent();
autoDate();
}
});
I just had to do change $(window) to $(document)
$(document).keyup(function(e)
{
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9)
{
alert("hello world");
cellContent();
autoDate();
}
});
Thank you for all the help
| {
"pile_set_name": "StackExchange"
} |
Q:
Al iniciar pagina, cargar select onchange
Buenas como puedo hacer que al cargar la pagina se active el ajax con el valor actual que tiene el select??
$( window ).load(function() {
/* $("#medidas").each(function() {
$("#valorPrecio").html($(this).val())
});
$("#medidas").focus();*/
$('#medidas').on('change',function(){
$value=$(this).val();
$medida=$('select[name="medidas"] option:selected').text();
//console.log($medida);
$.ajax({
type: "GET",
url : '{{URL::to('medidas')}}',
data:{'idproducto':$value,
'medida':$medida},
beforeSend: function() {
$('#valorPrecio').html('<img src="{{ asset('images/loading.gif') }}" class="loading">');
},
success: function(data)
{
$('#valorPrecio').html(data.precio);
if (data.pvpAntes === null){
$('#simboloEuro').css("display","none");
$('.pvpAntesFIN1').css("display","none");
}
else{
$('.pvpAntesFIN1').html(data.pvpAntes);
$('.pvpAntesFIN1').css("display","inline-block");
$('#simboloEuro').css("display","inline-block");
}
console.log(data);
}
});
});
})
A:
Para hacerlo deberas usar una funcion con nombre y no una funcion anonima, pero para poder que la funcion anonima tenga nombre deberas separarla de tu onchange, por lo tanto tu codigo queda asi:
$(document).ready(function() {
/* $("#medidas").each(function() {
$("#valorPrecio").html($(this).val())
});
$("#medidas").focus();*/
function changeSelect(ev){
$value=$(ev.target).val();
$medida=$('select[name="medidas"] option:selected').text();
console.log($value);
$.ajax({
type: "GET",
url : "{{URL::to('medidas')}}",
data:{'idproducto':$value,
'medida':$medida},
beforeSend: function() {
$('#valorPrecio').html('<img src="{{ asset(\'images/loading.gif\')}}" class="loading">');
},
success: function(data)
{
$('#valorPrecio').html(data.precio);
if (data.pvpAntes === null){
$('#simboloEuro').css("display","none");
$('.pvpAntesFIN1').css("display","none");
}
else{
$('.pvpAntesFIN1').html(data.pvpAntes);
$('.pvpAntesFIN1').css("display","inline-block");
$('#simboloEuro').css("display","inline-block");
}
console.log(data);
}
});
}
$('#medidas').on('change', changeSelect);
changeSelect({target: $("#medidas")[0]});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id = "medidas">
<option value = "hola">hola</option>
<option value = "mundo">mundo</option>
</select>
Tenias comillas mal escapadas, por lo que tuve que corregirlas, si tu las dejas asi javascript no va a interpretar bien el codigo y tu ajax no se ejecutara.
Con respecto a que cambios hice, realmente lo unico que hice fue separar la funcion aparte y le llame changeSelect a la cual se le pasa un evento, dentro de esta tambien le hice cambios a:
$value=$(ev.target).val();
Para que pudiese ser usado mediante un evento ligado o directamente que se le pase el elemento para invocarlo.
por ultimo, esta parte de aqui:
$('#medidas').on('change', changeSelect);
changeSelect({target: $("#medidas")[0]});
como vemos el evento ahora esta ligado a una funcion con nombre llamada changeSelect, ademas, al final usamos de manera directa nuestra funcion pasandole como parametro la simulacion de un evento, de esta manera la funcion hara su trabajo en ambos casos.
Ademas tu tenias:
$( window ).load(function() {
No creo que tenga mucha relevancia, pero lo cambie a:
$(document).ready(function() {
Son practicamente lo mismo, solo que el primero apunta a la ventana y el segundo al documento.
| {
"pile_set_name": "StackExchange"
} |
Q:
IISExpress.exe lags, PDB load problems
I was getting "Cannot find or open the PDB file" in the Output window when trying to debug an ASP.NET MVC application in Visual Studio 2013. The IDE would hang and the browser reported that it was waiting for localhost...
A:
What worked for me is to rebuild the symbol cache. Be sure you have internet access--then, in the VS 2013 IDE, go to Tool | Options | Debugging | Symbols. Click "Empty Symbol Cache" and wait for that operation to complete. Then click "Load all symbols".
I hope this helps someone other than me.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert response data into string in Xcode6
I downloaded Xcode6 and tried a project with NSUrlConnection.
How do i convert response data into string in Xcode6?any help will be appreciated.thanks in advance
A:
var outputString:NSString = NSString(data:data, encoding:NSUTF8StringEncoding)
| {
"pile_set_name": "StackExchange"
} |
Q:
Scan and Compare Two Rows
Currently have an Excel document with a Module connected to a button.
Excel document resembles the below:
ROW | COLUMN C | COLUMN K
1 808 253
2 808 256
3 908 355
4 908 355
5 908 356
6 907 253
7 907 253
When I click on the button the following Module kicks off:
Sub scan()
Dim dataRange As Range
Dim dataRange2 As Range
Dim oneCell As Range
Dim oneCell2 As Range
With ThisWorkbook.Sheets("Resource Info").Range("C:C")
Set dataRange = Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With
With ThisWorkbook.Sheets("Resource Info").Range("K:K")
Set dataRange2 = Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With
For Each oneCell In dataRange
If Application.WorksheetFunction.CountIf(dataRange, oneCell) > 1 Then
For Each oneCell2 In dataRange2
If Application.WorksheetFunction.CountIf(dataRange, oneCell) > 1 And Application.WorksheetFunction.CountIf(dataRange2, oneCell2) <> 1 Then
With oneCell
.EntireRow.Interior.ColorIndex = 6
End With
End If
Next oneCell2
End If
Next oneCell
End Sub
I'm trying to have only Row 1,2,3,4,5 get highlighted since the Column C match but Column K data does not match from the Column C grouping.
The current Module I have highlights all rows no matter what is contained in Column K.
A:
Replace your multiple Application.CountIf functions with a single Appl;ication.CountIfs.
Sub scan()
Dim rw As Long
With ThisWorkbook.Sheets("Resource Info")
.UsedRange.offset(1, 0).EntireRow.Interior.Pattern = xlNone
For rw = 2 To .Cells(.Rows.Count, "C").End(xlUp).Row
If CBool(Application.CountIfs(.Columns("C"), .Cells(rw, "C").Value2, .Columns("K"), "<>" & .Cells(rw, "K"))) Then
.Rows(rw).EntireRow.Interior.ColorIndex = 6
End If
Next rw
End With
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
How to scale data in Open CV LibSVM
i am developing English Handwriting OCR with OpenCV and Visual C++. I use Zone based approach for feature extraction. Here I use 64×64 images.
So i have 64 features for one sample image. My SVM will be Multi-class SVM because i have 52 classes for both capital and simple letters.
Here is the format of feature vector.
Class A image1 0:0.222000 1:0.0250222 ..... 63:0.000052
Class A image2 (some float values) ....
Class A image200 (some float values)
likewise i have 200 images for both 52 classes. When testing my current accuracy rate is 35% - 40% only.I have read as scaling data increase the accuracy of the prediction.
But i have few things to be make clear.
How can i scale these feature values ?
Is there any function to get the matching probability of each test feature vector in OpenCV LibSVM (I search the OpenCV 2.4.5 documentation, but I couldn't find this).
Can anyone explain these? , and also with some very few code lines if possible.
A:
Take a look at A Practical Guide to Support Vector
Classification. Basically, you should scale each dimension of your feature vector to [-1, 1] or [0, 1] (same across all dimensions). For example, for the first dimension, if you know the possible maximum and minimum values are v_max and v_min (like if it's pixel gray value, then they are 0 and 255). Then you can compute the new feature value as new_val = (old_val-v_min)/(v_max-v_min);
This is the documentation for OpenCV SVM predict function: predict.
float CvSVM::predict(const CvMat* sample, bool returnDFVal=false ) const
If you pass in returnDFVal as true, then you will get the distance to the margin as returned value. It's not a probability, but you can use it as an indicator to how good your classification is.
Hope this helps.
A:
Your data is scaled somewhat already but the libsvm guys would recommend (http://www.csie.ntu.edu.tw/~cjlin/papers/guide/guide.pdf) scaling linearly to [0, 1] or [-1, 1]. If you have pixel data [0,1] probably makes more sense.
I don't see it either. You can link against the C++ libsvm (http://www.csie.ntu.edu.tw/~cjlin/libsvm/) and then you have two options. A) Train class probabilities, in which case you get those back or B) ask for distances from the decision boundary.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a 2D meshing algorithm in Mathematica
As what is proving to be a difficult, but entertaining task, I am attempting to adapt a 2D meshing algorithm created for MATLAB and port it to Mathematica. I understand meshing functions already exist in Mathematica so this is purely for fun/learning.
The paper here describes in great detail the algorithm created for MATLAB, in terms of the non code specific logic and each step of the code. I intend to modify this question as/if suggestions are made to show its progress.
To start off simple, I have a box that I'm creating a random selection of meshing points within. I modify these using Delaunay's Triangulation Algorithm and then create an initial triangular mesh. Next, imagining all these points are joined my 'magic springs', if the length, L, of a spring is less than a certain chosen scale length, L0, then it exerts a force on each joining point in the direction of increasing separation, proportional to L-L0. Thus you create a new set of points at a later artificial timestep due to the effect of these psuedoforces. Then if any points are outside of the original box, you drag 'em back in and repeat this process until some sort of equilibrium condition is met.
This is the code I've done so far:
SeedRandom[2];
bboxL = 10;
bboxH = 10;
Nnodes = 100;
p0 = Table[0, {i, Nnodes}, {i, 2}];
Do[
p0[[i, 1]] = RandomReal[{0, bboxL}];
p0[[i, 2]] = RandomReal[{0, bboxH}];
, {i, Nnodes}];
timeStep = 0.2;
Needs["ComputationalGeometry`"];
dt = DelaunayTriangulation[p0];
toPairs[{m_, ns_List}] := Map[{m, #} &, ns];
edges = Flatten[Map[toPairs, dt], 1];
Graphics[GraphicsComplex[
p0, {Line[edges], Red, PointSize[Medium], Point[p0]}]]
L0 = 1;
displacement[{m_, ns_List}] :=
Total[Map[
If[Norm[p0[[#, All]] - p0[[m, All]]] <
bboxL*bboxH/Nnodes, -p0[[#, All]] + p0[[m, All]], {0, 0}] &,
ns]];
Do[
p0 = p0 + timeStep*Map[displacement, dt];
Do[
p0[[i, 1]] = Max[p0[[i, 1]], 0];
p0[[i, 2]] = Max[p0[[i, 2]], 0];
p0[[i, 1]] = Min[p0[[i, 1]], bboxL];
p0[[i, 2]] = Min[p0[[i, 2]], bboxH];
, {i, Nnodes}];
dt = DelaunayTriangulation[p0];
edges = Flatten[Map[toPairs, dt], 1];
, {i, 400}];
Graphics[GraphicsComplex[
p0, {Line[edges], Red, PointSize[Medium], Point[p0]}]]
You start off with this mesh:
Then after some iterations you get:
What I'd like to do next is instead of meshing to a boring old square I'd like to be able to mesh to any geometry whether its given in a functional form or an array of points. Can anybody suggest how to proceed? Maybe just a simple circle would be a nice next step for practice?
Everyone feel free to edit my post and join in the fun. Many thanks for any help :)
Also many thanks go to MarkMcClure for helping me on getting to this stage!
A:
Update
The code from this post is part of the FEMAddOns and can be installed by evaluating
ResourceFunction["FEMAddOnsInstall"][]
End Update
Hm, I am late for the party but anyway here is my entry. This distmesh port works in 2D and 3D (though this has issues I should say) and does not need external code like qhull. It also has a quality control / max steps termination and boundary points to be included can be given. Note, however, this is a prototype code and it has issues. A word about distmesh before the code: distmesh is probably the simplest mesh generator (well if you have a Delaunay code) and produces high quality meshes. The downside, unfortunately, is that the algorithm is slow due to it's repeated re-delaunay-zation.
To understand the code you most likely will need some familiarity with the Person's Distmesh paper.
Preliminary Code:
Some computational geometry stuff:
ddiff[d1_, d2_] := Max[d1, -d2];
dunion[d1_, d2_] := Min[d1, d2];
dintersection[d1_, d2_] := Max[d1, d2];
dcircle[{x_, y_}, {cx_, cy_, r_}] := (x - cx)^2 + (y - cy)^2 - r^2
drectangle[{x_, y_}, {{x1_, y1_}, {x2_, y2_}}] := -Min[Min[Min[-y1 + y, y2 - y], -x1 + x], x2 - x]
dline[{x_,y_}, {{x1_, y1_}, {x2_,y2_}}] := ((x2 - x1)*(y2 - y) - (y2 - y1)*(x2 - x)) / Sqrt[(x2 - x1)^2 + (y2 - y1)^2 ]
dtriangle[{x_, y_}, {a : {x1_, y1_}, b : {x2_, y2_}, c : {x3_, y3_}}] :=
Max[ dline[{x, y}, {a, b}], dline[{x, y}, {b, c}],dline[{x, y}, {c, a}]]
dpoly[{x_, y_}, a : {{_, _} ..}] :=
Max @@ (dline[{x, y}, #] & /@ Partition[ a, 2, 1, {1, 1}])
Distmesh helper functions:
(* this is not quite correct, the coords in the mesh may not be the \
same as the ones origianly given as pts; e.g. when pts contain \
duplicate points *)
myDelaunay[ pts_, dim_] := Block[{tmp},
Switch[ dim,
2,
tmp = Graphics`Region`DelaunayMesh[ pts];
Developer`ToPackedArray[ tmp["MeshObject"]["MeshElements"]],
3,
TetGenDelaunay[ pts][[2]]
]
];
thresholdPosition[ p_, th_ ] :=
Flatten[ SparseArray[UnitStep[th], Automatic, 1] /.
HoldPattern[SparseArray[c___]] :> {c}[[4, 2, 2]] ]
getElementCoordinates =
Compile[{{coords, _Real, 2}, {part, _Integer, 1}},
Compile`GetElement[coords, #] & /@ part,
RuntimeAttributes -> Listable];
mkCompileCode[vars_, code_, idx_] :=
With[{fVars = Flatten[vars]}, Compile[{{in, _Real, idx}},
Block[fVars,
fVars = Flatten[ in];
code]
, RuntimeAttributes -> Listable]
]
mkcForces[ chCode_] := Compile[{{p, _Real, 2}, {bars, _Integer, 2}, {fScale, _Real, 0}},
Block[{barVec, len, hBars, l0, force, forceVec},
barVec = p[[ bars[[ All, 1]] ]] - p[[ bars[[ All, 2 ]] ]];
len = Sqrt[ Plus @@@ Power[ barVec, 2]];
hBars = chCode /@ ((( Plus @@ p[[#]] ) & /@ bars )/2 );
l0 = hBars*fScale*
Sqrt[ (Plus @@ Power[ len, 2 ]) /( Plus @@ Power[ hBars, 2 ]) ];
force = Max[ #, 0. ] & /@ (l0 - len);
forceVec = Transpose[ { #, -# } ] &[ (force / len ) * barVec ]
]
]
moveMeshPoints[ p_, bars_, cForces_, fScale_: 1.2 ] := Module[
{ totForce, forceVec},
forceVec = cForces[ p, bars, fScale];
totForce =
NDSolve`FEM`AssembleMatrix[ {bars,
ConstantArray[ Range[ Last[ Dimensions[p]]], {Length[ bars]}]},
Flatten[ forceVec, {{1}, {2, 3}} ], Dimensions[p]];
totForce
]
meshbarPlot[p_, bar_List] :=
Print[Show[{gr,
Graphics[Line /@ (Part[p, #] & /@ bar), AspectRatio -> Automatic,
PlotRange -> All]}]]
initialMeshPoints[ {{x1_, y1_}, {x2_, y2_} }, h0_ ] := Module[
{ xRow, yColumn, tmp },
xRow = Range[ x1, x2, h0 ];
yColumn = Range[ y1, y2, h0 *Sqrt[3]/2 ];
tmp = Transpose[ {
Flatten[
Transpose[
Table[ If[ OddQ[ i ], xRow, xRow + h0/2], { i,
Length[ yColumn ] } ] ] ],
Flatten[ Table[ yColumn, { Length[ xRow ] } ] ]
} ];
Developer`ToPackedArray@tmp
];
initialMeshPoints[ {{x1_, y1_, z1_}, {x2_, y2_, z2_} }, h0_ ] :=
Module[
{ xP, yP, zP },
xP = Range[ x1, x2, h0 ];
yP = Range[ y1, y2, h0 ];
zP = Range[ z1, z2, h0 ];
Flatten[ Outer[List, xP, yP, zP], 2]
];
Quality control functions [What is a good linear finite element]:
edgeLength[c : {{_, _} ..}] := EuclideanDistance @@@ Partition[c, 2, 1, 1];
TriangleAreaSymbolic[{c1_, c2_, c3_}] := 1/2*Det[Transpose[{c1, c2}] - c3];
triangleEdgeLength := edgeLength;
tri = Array[Compile`GetElement[X, ##] &, {3, 2}];
source = 4*Sqrt[3]* TriangleAreaSymbolic[tri] / Total[triangleEdgeLength[tri]^2];
meshQuality[triangle] =
With[{code = source},
Compile[{{in, _Real, 2}}, Block[{X}, X = in; code],
RuntimeAttributes -> Listable]];
(*Shewchuk vertex ordering is a_,b_,c_,d_*)
(*this is to acomodate the mesh element ordering*)
TetrahedronVolumeSymbolic[{a_, c_, b_, d_}] :=
1/6*Det[Transpose[{a, b, c}] - d];
tetEdgeLength[{c1_, c2_, c3_, c4_}] :=
Norm[#, 2] & /@ {c1 - c2, c2 - c3, c3 - c1, c1 - c4, c2 - c4, c3 - c4}
tet = Array[Compile`GetElement[X, ##] &, {4, 3}];
source = 6*Sqrt[2]*
TetrahedronVolumeSymbolic[tet]/
Sqrt[(1/6*Total[tetEdgeLength[tet]^2])]^3;
meshQuality[tetrahedra] =
With[{code = source},
Compile[{{in, _Real, 2}}, Block[{X}, X = in; code],
RuntimeAttributes -> Listable]];
Distmesh:
Options[distmesh] = {MaxIterations -> 150,
MeshElementQualityFactor -> 1/2,
MeshElementQualityFunction -> Min, ReturnBestMeshSofar -> True};
distmesh[ df_, rdf_, h0_, vars_, bbox_, pfix_, opts___ ] := Module[
{fopts, maxIterations, iterationNumber, meshQualityFactor,
meshQualityFunction,
dim,
p, ix, deps, cdfs, d,
dgradDim, dgradN, depsIM, dgrad,
pMid, t, bars, geps,
crdf, cForces,
mq, mqMax, elementType,
symElementCoords, qualityCode, cMeshQuality,
divisor, barSelectors,
saveBestMeshQ,
tBest, pBest,
dptol, ttol, fScale, deltat, r0, n, pOld, tmp, scaledR0, totForce,
dgradx, dgrady, dgrad2},
dim = Length[ vars];
fopts = FilterRules[{opts}, Options[distmesh]];
{maxIterations, meshQualityFactor, meshQualityFunction,
saveBestMeshQ} =
{MaxIterations, MeshElementQualityFactor,
MeshElementQualityFunction, ReturnBestMeshSofar} /.
fopts /. Options[distmesh];
meshQualityFactor = Min[1, Max[0, meshQualityFactor]];
iterationNumber = 0;
mqMax = 0;
dptol = .001;
ttol = .1;
fScale = 1.2;
deltat = .2;
geps = .001*h0;
deps = Sqrt[10^-$MachinePrecision]*h0;
(* compile the distance set fuction *)
cdfs = mkCompileCode[vars, df, 1];
(* compile raltive mesh coarsens function *)
crdf = mkCompileCode[vars, rdf, 1];
cForces = mkcForces[crdf];
(* select the mesh quality code *)
Switch[ dim,
2,
elementType = Global`triangle;
divisor = 3;
barSelectors = {{1, 2}, {2, 3}, {3, 1}};
,
3,
elementType = Global`tetrahedra;
divisor = 4;
barSelectors = {{1, 2}, {2, 3}, {3, 1}, {1, 4}, {2, 4}, {3, 4}}
];
cMeshQuality = meshQuality[elementType];
p = initialMeshPoints[bbox, h0];
(* p = Select[ p, ( fd @@ #<geps)& ]; *)
p = p[[thresholdPosition[p, cdfs[p] - geps]]];
r0 = 1/crdf[p]^2;
scaledR0 = r0/Max[r0];
p = Join[pfix,
p[[thresholdPosition[p,
RandomReal[{0, 1}, {Length[p]}] - scaledR0 ]]]];
n = Length[p];
pOld = Infinity;
While[True,
iterationNumber++;
If[Max[Sqrt[Total[(p - pOld)^2, {2}]]/h0 ] > ttol,
pOld = p;
t = myDelaunay[p, dim];
pMid = Total[getElementCoordinates[ p, t ], {2}]/divisor;
(* t = t[[ Flatten[ Position[ fd @@@
pMid, _?(# < -geps &) ] ] ]]; *)
t = t[[thresholdPosition[ p, cdfs[ pMid] - geps] ]];
bars = Union[Sort /@ Flatten[t[[All, # ]] & /@ barSelectors, 1]];
,
Null;
];
totForce = moveMeshPoints[p, bars, cForces];
totForce[[Range[Length[pfix ]]]] =
ConstantArray[0., {Length[pfix], dim}];
p = p + deltat*totForce;
d = cdfs[p];
(*ix = Flatten[ Position[ d, _?(#>0.&) ] ];*)
ix = thresholdPosition[d, -(d + 0.)];
dgradDim = Dimensions[p[[ix]]];
dgradN = ConstantArray[ 0., dgradDim ];
depsIM = deps*IdentityMatrix[dim];
Do[
dgradN[[All, i]] =
(cdfs[
p[[ix]] + ConstantArray[ depsIM[[i]], {Length[p[[ix]]]}]] -
d[[ix]])/deps
, {i, Last[dgradDim]}];
dgrad = Total[ dgradN^2, {2} ];
p[[ix]] = p[[ix]] - (d[[ix]]*dgradN)/dgrad;
If[ dim == 2 && meshBarPlotQ, meshbarPlot[ p, bars ]; ];
mq = meshQualityFunction[
cMeshQuality[ getElementCoordinates[ p, t ] ]];
If[ (mq >= meshQualityFactor) || iterationNumber >= maxIterations,
If[ mq <= mqMax && saveBestMeshQ, mq = mqMax; p = pBest;
t = tBest; ];
Break[],
If[ mq > mqMax && saveBestMeshQ, mqMax = mq; pBest = p;
tBest = t; ];
];
];
Print["it num: ", iterationNumber, " mq: ", mq];
Return[ { p, t } ];
]
Examples:
Example 1:
Square with hole and different refinement on boundaries:
di = Function[ {x, y},
ddiff[ drectangle[ {x, y}, {{-1, -1}, {1, 1}} ],
dcircle[ {x, y}, {0, 0, 0.4} ] ] ];
h = Function[ {x, y}, Min[ 4*Sqrt[Plus @@ ({x, y}^2) ] - 1, 2 ] ];
h0 = 0.05;
bbox = {{-1, -1}, {1, 1}};
pfix = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}} // N;
AbsoluteTiming[ {coords, inci} =
distmesh[ di[x, y], h[x, y], h0, {x, y}, bbox, pfix ];]
(* it num: 87 mq: 0.66096 *)
(* {0.849295, Null} *)
Graphics[{EdgeForm[Black], FaceForm[], Polygon[(coords[[#]] & /@ inci)]}]
Example 2:
Same example, finer base grid and animated:
di = Function[ {x, y},
ddiff[ drectangle[ {x, y}, {{-1, -1}, {1, 1}} ],
dcircle[ {x, y}, {0, 0, 0.4} ] ] ];
h = Function[ {x, y}, 1. ];
h0 = 0.1;
bbox = {{ -1, -1}, {1, 1} } // N;
pfix = {{-1, -1}, {1, -1}, {1, 1}, {-1, 1}} // N;
meshBarPlotQ = True;
gr = RegionPlot[
di[x, y] < 0, {x, bbox[[1, 1]], bbox[[2, 1]]}, {y, bbox[[1, 2]],
bbox[[2, 2]]}, AspectRatio -> Automatic, Frame -> False,
Axes -> False, Mesh -> False ];
distmesh[ di[x, y], h[x, y], h0, {x, y}, bbox, pfix ];
meshBarPlotQ = False;
ClearAll[gr]
Example 3:
Same example, anisotropic refinement:
h = Function[ {x, y}, 1. + Abs[x*y]];
h0 = 0.03;
bbox = {{ -1, -1}, {1, 1} } // N;
pfix = {{-1, -1}, {1, -1}, {1, 1}, {-1, 1}} // N;
AbsoluteTiming[ {coords, inci} =
distmesh[ di[x, y], h[x, y], h0, {x, y}, bbox, pfix ]; ]
Example 4:
A somewhat more complicated geometry:
di = Function[{x, y},
Evaluate[
Simplify[
dintersection[
ddiff[ ddiff[ dcircle[{x, y}, {0, 0, 2}],
dcircle[{x, y}, {3/2, 0, 1/5}]], dcircle[{x, y}, {0, 0, 1}]],
dtriangle[{x, y}, {{0, 0}, {2, 0}, {2, 1}}]]]]];
ci[{{x1_, y1_}, r_}, {m_, c_}] := Block[{tmpX, tmpH, tmpY},
tmpX = {(-(c*m) + x1 + m*y1 -
Sqrt[-c^2 + r^2 + m^2*r^2 - 2*c*m*x1 - m^2*x1^2 + 2*c*y1 +
2*m*x1*y1 - y1^2])/(1 + m^2), (-(c*m) + x1 + m*y1 +
Sqrt[-c^2 + r^2 + m^2*r^2 - 2*c*m*x1 - m^2*x1^2 + 2*c*y1 +
2*m*x1*y1 - y1^2])/(1 + m^2)};
tmpH = Function[{x}, m*x + c];
tmpY = tmpH /@ tmpX;
Transpose[{tmpX, tmpY}]
]
h = Function[ {x, y},
Min[ 5*Sqrt[Plus @@ ({x - 1.5, y}^2) ] - 0.2, 2 ] ];
h0 = 0.01;
bbox = { {0.8, 0}, {2, 1} } // N;
pfix = Join[ {{1., 0.}, {1.3, 0.}, {1.5, 0.2}, {1.7, 0.}, {2., 0.}},
ci[{{0, 0}, 2}, {1/2, 0}][[{2}]],
ci[{{0, 0}, 1}, {1/2, 0}][[{2}]] ] // N
AbsoluteTiming[ {coords, inci} =
distmesh[ di[x, y], h[x, y], h0, {x, y}, bbox, pfix,
MaxIterations -> 400 ];]
(*it num: 164 mq: 0.742647*)
(* {14.795667, Null} *)
Graphics[ {EdgeForm[Black], FaceForm[],
Polygon[ (coords[[#]] & /@ inci) ]} ]
Example 5:
3D:
di = Function[{x, y, z}, Sqrt[x^2 + y^2 + z^2] - 1];
h = Function[ {x, y, z}, 1. ];
h0 = 0.25;
bbox = {{ -1, -1, -1}, {1, 1, 1} } // N;
pfix = {} // N;
AbsoluteTiming[ {coords, inci} =
distmesh[ di[x, y, z], h[x, y, z], h0, {x, y, z}, bbox, pfix,
MaxIterations -> 20]; ]
TetrahedraWireframe[i_] :=
Line[ Flatten[
i[[All, #]] & /@ {{1, 2}, {2, 3}, {3, 1}, {1, 4}, {2, 4}, {3, 4}},
1]]
Graphics3D[GraphicsComplex[coords, TetrahedraWireframe[inci]]]
Example 6:
Converting a black and white image into a mesh:
shape
;
Convert the shape into a distance function:
dist = DistanceTransform[Image[1 - ImageData[EdgeDetect[shape]]]];
ImageAdjust@dist
Create an inteprolation function from it:
data = Transpose[Reverse[-ImageData[dist]*(2*ImageData[shape] - 1)]];
dataRange = Transpose[{{x, y}, {1, 1}, Dimensions[data]}];
if = ListInterpolation[ data, dataRange[[All, {2, 3}]],
InterpolationOrder -> 1];
Call distmesh:
di = if;
h = Function[ {x, y}, 1];
h0 = 5;
bbox = Transpose[if["Domain"]];
pfix = {} // N;
AbsoluteTiming[ {coords, inci} =
distmesh[ di[x, y], h[x, y], h0, {x, y}, bbox, pfix]; ]
(* it num: 150 mq: 0.535491 *)
(* {3.215599, Null} *)
A:
first part..i had lying around..
poly = Random[Real, {1, 2}] {Cos[#], Sin[#]} & /@ Sort[Table[Random[Real, {0, 2 Pi}], {5}]]
isLeft[P2_, {P0_, P1_}] := -Sign@Det@{P2 - P0, P1 - P0};
pinpoly[p_, poly_] := Module[{ed},(*winding rule*)
ed = Partition[Append[poly, poly[[1]]], {2}, 1];
Count[ed,pr_ /; (pr[[1, 2]] <= p[[2]] < pr[[2, 2]] &&isLeft[p, pr] == 1)]
- Count[ed, pr_ /; (pr[[2, 2]] <= p[[2]] < pr[[1, 2]] && isLeft[p, pr] == -1)] == 1];
seed = Select[ Table[RandomReal[{-2, 2}, 2], {2000}] , pinpoly[#, poly] &];
Show[{Graphics[Line[Append[poly, poly[[1]]]]], Graphics[{Red, Point /@ seed}]}]
allp = Join[seed, poly];
Show[{Graphics[(Line /@ (allp[[#]] & /@ Thread[#])) & /@ DelaunayTriangulation[allp]],
Graphics[{Red, PointSize[.02], Point /@ seed}],
Graphics[{Blue, PointSize[.02], Point /@ poly}]}]
EDIT--step 2: relaxing seed node positions, note I'm not doing anythng to keep in bounds..so you see a few go out where the boundary is not convex.
lastmf = 0;
dmf = 1;
Monitor[While[dmf > 10^-3,
allp = Join[seed, poly];
tri = DelaunayTriangulation[allp][[;; Length[seed]]];
alledges = Union@(Sort /@ Flatten[ Thread /@ tri , 1]);
(*unit vector associated with each edge*)
alledgesunitv = ((allp[[#[[2]]]] - allp[[#[[1]]]]) // Normal) & /@ alledges;
(* edgemap is a list of positions on elledges at each seed node,
signed to indicate if the unit vector points toward or away from the node *)
edgemap = Map[Function[t, (If[Length[(p = Position[alledges, #])] == 1,
p[[1, 1]], -Position[alledges, Reverse[#]][[1, 1]]]) & /@ Thread@ t], tri];
elen = Norm[(allp[[#[[1]]]] - allp[[#[[2]]]])] & /@ alledges;
targetlen = .8 Mean[elen];
(*note the mean does not include the bounding polygon edge lengths*)
eforce = 1 - targetlen/elen; (*nonlinear spring.. need to play with this..*)
{mf, dmf, lastmf} = {#, Abs[# - lastmf], mf} &@ Max@Abs@eforce;
seed += (Total /@
(Map[Sign[#] .01 eforce[[Abs[#]]] alledgesunitv[[Abs[#]]] & , edgemap , {2}]));
(* add code here to keep nodes in bounds..*)
g = Show[{Graphics[{Thick, Blue, Line[Append[poly, poly[[1]]]]}],
Graphics[Line /@ Map[allp[[#]] &, alledges, {2}]],
Graphics[{Red, PointSize[.02], Point /@ seed}],
Graphics[{Blue, PointSize[.02], Point /@ poly}]}]], {g, mf, dmf}]
I expect at the boundary you want to not only keep nodes inside, but look for nodes close inside and snap those to the edge.
Edit 3 ..
force the bounary polygon to have a minimum edge length:
seedlen = .25
poly = Flatten[(kk = Ceiling[Norm[Subtract @@ # ]/(1.2 seedlen )] ;
Table[#[[1]] ( 1 + ( 1 - ici )/kk) + (ici - 1)/ kk #[[2]] , {ici, kk}]) &
/@ Partition[Append[poly, poly[[1]]], {2}, 1], 1]
and simply discard nodes that wander out of bounds , where i had "add code here" above..
seed = Select[seed, pinpoly[#, poly] &];
works pretty good.. note when you drop nodes you need to render the plot after recomputing the triangulation.
A:
Table[drawtriangulation[mesh @@ example, First@example,
AspectRatio -> Automatic],
{example, {circle, circle34, ellipseeye}}] // GraphicsRow
Calculating specifications for these examples:
(* distance function, bounding box, fixed points,
number of initial points, max iterations, min triangle quality *)
circle = {Sqrt[#1^2 + #2^2] - 1. &,
{{-1, -1}, {1, 1}}, {}, 100, 200, .6};
circle34 = {Max[
Sqrt[#1^2 + #2^2] - 1.,
Min[Min[Min[1. + #2, -#2], #1], 1. - #1]] &,
{{-1, -1}, {1, 1}}, {{0, -1}, {0, 0}, {1, 0}}, 100, 200, .6};
ellipseeye = {Max[
Sqrt[#1^2 + 1.6 #2^2] - 1.,
-(Sqrt[#1^2 + #2^2] - .6)] &,
{{-1, -.8}, {1, .8}}, {}, 300, 200, .6};
Following OP and the paper he's following (A simple mesh generator in MATLAB), I wrote the main code in mesh below which iteratively relaxes and moves the mesh points, and, as it is, stops at iterationmax or already when quality of the worst triangle goes over qmin; region defines geometry and can be specified as a distance function (see above; negative inside geometry only and zero at boundary) or as a list of polygon points (see update), box are two corner points of a rectangle enclosing the geometry, and npts is the number of initial points inside box.
mesh[region_List | region_Function, box_List, pfix_List,
npts_Integer, iterationmax_Integer, qmin_Real] :=
With[{ttol = .1, fscale = 1.2, deltat = .2, geps = .001},
Module[{p, dp, pold = {}, t, bars, barvec,
l, l0, fvec, ftot, x1, y1, x2, y2, outlined,
iteration = 0, nf, grad, test},
{{x1, y1}, {x2, y2}} = box;
Switch[Head[region],
List, nf = Nearest[region -> Automatic,
DistanceFunction -> EuclideanDistance];
outlined = outline[region, geps (x2 - x1)],
Function, grad[x_, y_] := Grad[region[x, y], {x, y}] // Evaluate];
test = If[Head[region] === List,
Graphics`Mesh`InPolygonQ[outlined, #] &, region @@ # < geps &];
p = pfix~Join~Select[Transpose[{
RandomReal[{x1, x2}, npts],
RandomReal[{y1, y2}, npts]}], test@# &];
While[iteration++ < iterationmax,
If[pold == {} || Max[Divide[
Norm /@ (p - pold), (x2 - x1)/Sqrt[npts]]] > ttol,
pold = p;
t = qDelaunayTriangulation[p];
t = Select[t, test@Mean[p[[#]]] &];
bars = DeleteDuplicates[Sort /@ Flatten[
Partition[#, 2, 1, 1] & /@ t, 1]]];
If[Min[quality @@@ (p[[#]] & /@ t)] > qmin, Break[]];
barvec = Subtract @@ p[[#]] & /@ bars;
l = Norm /@ barvec;
l0 = fscale Sqrt[Total[l^2]/Length@bars];
fvec = Map[Max[#, 0] &, l0 - l]/l barvec;
ftot = SparseArray[MapThread[
{#1 -> Hold[#2], Reverse[#1] -> Hold[-#2]} &,
{bars, fvec}]~Flatten~1];
If[pfix =!= {}, ftot[[Range@Length@pfix, All]] = 0];
dp = deltat Total /@ Map[ReleaseHold, ftot, {2}];
p += dp;
p = MapAt[If[Head[region] === List,
backtoedgelist[#, region, nf],
backtoedgefunction[#, region, grad]] &, p,
Position[p, {x_Real, y_Real} /; ! test[{x, y}]]];
]; p]]
You can see mesh calls qDelaunayTriangulation which is an external program, so the first thing is to mathlink Qhull which supplies this relatively speedy triangulator (@halirutan discusses it here, compiled and ready for Windows via @Oleksandr R.). It's about 3,000 times faster than DelaunayTriangulation in package ComputationalGeometry.
Providing Qhull is in the directory following the one where notebook is saved:
lnk = Install[NotebookDirectory[] <> "\\qhull64\\qh-math.exe"]
This gives access to qDelaunayTriangulation. There is also a call to InPolygonQ which is an undocumented function that determines if a point is inside a polygon or not.
Finally, the functions below: quality for testing triangle quality (1 for equilateral, 0 for a degenerate triangle with zero area), backtoedgefunction for bringing a wentover point back to boundary defined with distance function, backtoedgelist for polygon boundary, and drawtriangulation for drawing result.
quality[p1_, p2_, p3_] := With[{
a = Norm[-p1 + p2],
b = Norm[-p2 + p3],
c = Norm[-p1 + p3]},
(b + c - a) (c + a - b) (a + b - c)/(a b c)]
(* point to boundary region = 0, preevaluated gradient *)
backtoedgefunction[point_, region_Function, gradient_] :=
With[{r = point + t gradient @@ point},
r /. FindRoot[region @@ r,
{t, 0, .1}, Method -> "Secant"]]
(* point to polygon boundary, precalculated nf *)
backtoedgelist[point_, region_List, nf_NearestFunction] :=
With[{i = nf[point][[1]], d = Length@region},
Module[{a, b, c, test},
{a, b, c} = Extract[region, List /@ Which[
1 < i < d, {i - 1, i, i + 1},
i == 1, {-1, 1, 2},
i == d, {d - 1, d, 1}]];
test = And @@ Thread[{
VectorAngle[#3 - #1, #2 - #1],
VectorAngle[#3 - #2, #1 - #2]} < .5 Pi] &;
Which[
test[a, b, point], a + Projection[point - a, b - a],
test[b, c, point], b + Projection[point - b, c - b],
True, b]]]
drawtriangulation[pts_List,
region_List | region_Function, opt___] :=
With[{geps = .001},
Module[{
dt = qDelaunayTriangulation@pts,
outlined, test},
test = If[Head[region] === List,
outlined = outline[region,
geps {-1, 1}.Through[{Min, Max}[First /@ region]]];
Graphics`Mesh`InPolygonQ[outlined, #] &, region @@ # < geps &];
dt = Select[dt, test@Mean@pts[[#]] &];
Graphics[GraphicsComplex[pts,
{EdgeForm[Opacity[.2]], Map[{
ColorData["AlpineColors"][quality @@ pts[[#]]],
Polygon[#]} &, dt]}], opt]]]
Update: Polygons
I extended the code to meshing polygons. (Testing whether a point is inside the region changes, also bringing the point back to the boundary changes.) Two examples:
heart = {
With[{n = 30, fx = 16 Sin[#]^3 &,
fy = 13 Cos[#] - 5 Cos[2 #] - 2 Cos[3 #] - Cos[4 #] &},
Table[{fx@t, fy@t}, {t, 0., 2 Pi (1 - 1/n), 2 Pi/n}]],
{{-16, -17}, {16, 12}}, {{0, 5}, {0, -17}}, 200, 200, .7};
slo = Module[{edge,
boundary = CountryData["Slovenia", "Polygon"][[1, 1]]},
edge = Take[boundary, {1, -1, 5}];
edge = # - Mean[edge] & /@ edge;
{edge, Transpose[{
Through[{Min, Max}[First /@ edge]],
Through[{Min, Max}[Last /@ edge]]}], {}, 200, 200, .7}];
Table[Graphics[Line@First@poly],
{poly, {heart, slo}}] // GraphicsRow
Table[drawtriangulation[mesh @@ example, First@example],
{example, {heart}}] // GraphicsRow
In both cases of region, whether it's a polygon or distance function, a geometric tolerance geps is used in testing whether a point lies inside the region. For this I "inflated" a polygon a tiny bit with these two functions:
moveout[{r1_, r2_, r3_}, d_] := Module[{
t = VectorAngle[r1 - r2, r3 - r2],
s = Normalize[r1 - r2], sign},
sign = If[Negative@Last@Cross[
(r2 - r1)~Append~0,
(r3 - r2)~Append~0], -1, 1];
r2 + Plus[d (s /. {x_, y_} :> {y, -x}), sign d Tan[.5 (Pi - t)] s]]
outline[poly_, d_] :=
Map[Function[tri, moveout[tri, d]], Partition[poly, 3, 1, 1]]
| {
"pile_set_name": "StackExchange"
} |
Q:
How does the Trance Advantage function?
While researching an answer to this question I asked, I came across the hero Raven, who has precognition (I was hoping her character info might shed light on my postcog dilemma). While reading about her I took note of the Trance advantage which states:
Through breathing and bodily control, you can slip into a
deep trance. This takes a minute of uninterrupted meditation
and a DC 15 Awareness check. While in the trance
you add your Awareness rank to your Stamina rank to determine
how long you can hold your breath and you use
the higher of your Fortitude or Will defenses for resistance
checks against suffocation (see Suffocation, page 170).
Poison and disease effects are suspended for the duration
of the trance. It requires a Perception check with a DC
equal to your Awareness check result to determine you’re
not dead because your bodily functions are so slow. You
are aware of your surroundings while in trance and can
come out of it at any time at will. You cannot take any actions
while in the trance, but your GM may allow mental
communication while in a trance.
1) Do you suffocate while tranced or use it to avoid other instances of suffocating?
2) What else does it do other than suspend disease and poison?? (other than "playing possum") ie When would you use trance when you are not poisoned or diseased?
It just seems that there are easier ways to avoid poison and diseases than going into a trance (obviously not accounting for the Role play reasons you might want Trance). And I am wondering if this is more for character flavor than any real mechanical advantage as it's not the most optimal way to avoid poison and disease. You basically put yourself into a coma, making you an easy target. Taking immunity to poison and disease would allow you to be active while avoiding those 2 conditions. So while I dont expect there to be any other uses of Trance, I am just trying to learn as much as I can about the advantage and its possible uses.
A:
Honestly, it's an artifact of earlier editions. In 1E, where it was introduced as a Feat, there was not a convenient immunity power. For whatever reason, it's been kept through the editions without any real update on how to use it. Personally, I'd argue for it giving all sorts of conditional modifiers such as bonuses to will saves versus mental attacks (composing your mind for defense) or the like.
In summary, it functions exactly as you stated when quoting the text of the Advantage. Yes, there are some powers that completely outstrip it, but honestly, you could say the same for things like Ricochet (replaceable by Indirect 1 without having to worry about the number of bounces) or Super-Movement (replaceable in almost every circumstance with Flight 1 with some small Limit to account for only being able to fly up walls, etc).
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Lua to call C (in Linux)
I made a C program and wrote the following two function in that
1. int c_add(lua_State* L)
{...some code here...
}
2. int main(int argc, char* argv)
{...some code here...
lua_register(L, "c_add", c_add);
}
And compiled it by following command successfully.
gcc -o test.exe test.c -I /home/ec2-user/install/lua-5.1.5/src -llua-5.1
But the following error showed after using a lua program to call it.
lua: func2.lua:2: attempt to call global 'c_add' (a nil value)
How to solve this problem?`
A:
You need to compile the code as a shared library to access the C functions from an external Lua instance. You don't need the main function and you pass the -shared flag to gcc. Then you need to let Lua know what to do when require is called by implementing the following function:
// same name as the so/dll
// v
LUALIB_API int luaopen_test(lua_State *L) {
lua_register(L, "c_add", c_add);
return 0;
}
This creates a single, global function. It's better to register a luaL_Reg array of functions with luaL_register:
static const luaL_Reg function_list[] = {
{"c_add", c_add},
{NULL, NULL}
};
LUALIB_API int luaopen_test(lua_State *L) {
luaL_register(L, "test", function_list);
return 1;
}
So that a table of functions is returned by require:
local my_c_functions = require("test")
print(my_c_functions.c_add(42, 42))
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there any patterns for serializing and deserializing object hierarchies in various formats?
Given a complex object hierarchy, which luckily contains no cyclic references, how do I implement serialization with support for various formats? I'm not here to discuss an actual implementation. Instead, I'm looking for hints on design patterns which might come in handy.
To be a little more precise: I'm using Ruby and I want to parse XML and JSON data to build up a complex object hierarchy. Furthermore, it should be possible to serialize this hierarchy to JSON, XML, and possibly HTML.
Can I utilize the Builder pattern for this? In any of the mentioned cases, I have some sort of structured data - either in memory or textual - which I want to use to build up something else.
I think it would be nice to separate the serialization logic from the actual business logic, so that I can easily support multiple XML formats later on.
A:
I ended up creating a solution which is based on the Builder and the Strategy pattern. I'm using the Builder pattern to extract parsing and building logic into there own classes. This allows me to easily add new parsers and builders, respectively. I'm using the Strategy pattern to implement the individual parsing and building logic, because this logic depends on my input and output format.
The figure below shows a UML diagram of my solution.
The listing below shows my Ruby implementation. The implementation is somewhat trivial because the object I'm building is fairly simple. For those of you who think that this code is bloated and Java-ish, I think this is actually good design. I admit, in such a trivial case I could have just build the construction methods directly into my business object. However, I'm not constructing fruits in my other application, but fairly complex objects instead, so separating parsing, building, and business logic seems like a good idea.
require 'nokogiri'
require 'json'
class Fruit
attr_accessor :name
attr_accessor :size
attr_accessor :color
def initialize(attrs = {})
self.name = attrs[:name]
self.size = attrs[:size]
self.color = attrs[:color]
end
def to_s
"#{size} #{color} #{name}"
end
end
class FruitBuilder
def self.build(opts = {}, &block)
builder = new(opts)
builder.instance_eval(&block)
builder.result
end
def self.delegate(method, target)
method = method.to_sym
target = target.to_sym
define_method(method) do |*attrs, &block|
send(target).send(method, *attrs, &block)
end
end
end
class FruitObjectBuilder < FruitBuilder
attr_reader :fruit
delegate :name=, :fruit
delegate :size=, :fruit
delegate :color=, :fruit
def initialize(opts = {})
@fruit = Fruit.new
end
def result
@fruit
end
end
class FruitXMLBuilder < FruitBuilder
attr_reader :document
def initialize(opts = {})
@document = Nokogiri::XML::Document.new
end
def name=(name)
add_text_node(root, 'name', name)
end
def size=(size)
add_text_node(root, 'size', size)
end
def color=(color)
add_text_node(root, 'color', color)
end
def result
document.to_s
end
private
def add_text_node(parent, name, content)
text = Nokogiri::XML::Text.new(content, document)
element = Nokogiri::XML::Element.new(name, document)
element.add_child(text)
parent.add_child(element)
end
def root
document.root ||= create_root
end
def create_root
document.add_child(Nokogiri::XML::Element.new('fruit', document))
end
end
class FruitJSONBuilder < FruitBuilder
attr_reader :fruit
def initialize(opts = {})
@fruit = Struct.new(:name, :size, :color).new
end
delegate :name=, :fruit
delegate :size=, :fruit
delegate :color=, :fruit
def result
Hash[*fruit.members.zip(fruit.values).flatten].to_json
end
end
class FruitParser
attr_reader :builder
def initialize(builder)
@builder = builder
end
def build(*attrs, &block)
builder.build(*attrs, &block)
end
end
class FruitObjectParser < FruitParser
def parse(other_fruit)
build do |fruit|
fruit.name = other_fruit.name
fruit.size = other_fruit.size
fruit.color = other_fruit.color
end
end
end
class FruitXMLParser < FruitParser
def parse(xml)
document = Nokogiri::XML(xml)
build do |fruit|
fruit.name = document.xpath('/fruit/name').first.text.strip
fruit.size = document.xpath('/fruit/size').first.text.strip
fruit.color = document.xpath('/fruit/color').first.text.strip
end
end
end
class FruitJSONParser < FruitParser
def parse(json)
attrs = JSON.parse(json)
build do |fruit|
fruit.name = attrs['name']
fruit.size = attrs['size']
fruit.color = attrs['color']
end
end
end
# -- Main program ----------------------------------------------------------
p = FruitJSONParser.new(FruitXMLBuilder)
puts p.parse('{"name":"Apple","size":"Big","color":"Red"}')
p = FruitXMLParser.new(FruitObjectBuilder)
puts p.parse('<fruit><name>Apple</name><size>Big</size><color>Red</color></fruit>')
p = FruitObjectParser.new(FruitJSONBuilder)
puts p.parse(Fruit.new(:name => 'Apple', :color => 'Red', :size => 'Big'))
| {
"pile_set_name": "StackExchange"
} |
Q:
Hide and display JFXPanel on Swing JFrame
I want to hide and show FXPanel controls in javaFx application in swing
I want on clicking a button FXPanel control should be hidden and on clicking other the control should be again visible it is being hidden not being visible again.
using the following code.
public class abc extends JFrame
{
JFXPanel fxpanel;
Container cp;
public abc()
{
cp=this.getContentPane();
cp.setLayout(null);
JButton b1= new JButton("Ok");
JButton b2= new JButton("hide");
cp.add(b1);
cp.add(b2);
b1.setBounds(20,50,50,50);
b2.setBounds(70,50,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
fxpanel= new JFXPanel();
cp.add(fxpanel);
fxpanel.setBounds(600,200,400,500);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("OK"))
{
fxpanel.setVisible(true);
}
if(ae.getActionCommand().equals("hide"))
{
fxpanel.hide();
}
Platform.runLater(new Runnable())
{
public void run()
{
init Fx(fxpanel);
}}
);
}
private static void initFX(final JFXPanel fxpanel)
{
Group group = ne Group();
Scene scene= new Scene(group);
fxpanel.setScene(scene);
WebView webview= new WebView();
group.getChildren().add(webview);
webview.setMinSize(500,500);
webview.setMaxSize(500,500);
eng=webview.getEngine();
File file= new File("d:/new folder/abc.html");
try
{
eng.load(file.toURI().toURL().toString());
}
catch(Exception ex)
{
}
}
public static void main(String args[])
{
abc f1= new abc();
f1.show();
}
}
A:
Aside from a number of typos, there's multiple issues with your code:
1) If you are using ActionEvent#getActionCommand to determine which button was clicked, you have to set the action command property on the button first. The action command ist not the same as the button's text.
2) You are adding both buttons with the same coordinates, hence one will not show.
3) Don't use the deprecated hide()-Method to hide the JFXPanel, use setVisisble(false)
Furthermore, a few general pointers:
4) Don't use null layout for a normal UI. Ever.
5) Read up on the java naming convention. This is not just me being picky, it will help you better understand other people's code and help other people maintain yours.
6) Invoke the code that displays your swing components from the EDT via SwingUtilities#invokeLater, just as you used the Platform class. Invoking swing from the main thread like you did will work most of the times, but induce occasional errors that will be hard to track.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can the value of a ConditionalWeakTable cause a memory leak?
If the value for an entry in a ConditionalWeakTable has a reference to its key, does it prevent the key from being garbage collected?
Let's say you have an interface and a decorator for that interface. The decorator holds a reference to what it decorates.
public interface IFoo
{
}
public class FooDecorator : IFoo
{
private readonly IFoo _foo;
public FooDecorator(IFoo foo)
{
_foo = foo;
}
}
And let's say that you have a extension method class that uses a ConditionalWeakTable<IFoo, FooDecorator>, so that each instance of IFoo can retrieve the same instance of FooDecorator each time the extension method is called.
public static class FooExtensions
{
private static readonly ConditionalWeakTable<IFoo, FooDecorator> _decorators =
new ConditionalWeakTable<IFoo, FooDecorator>();
public static IFoo GetDecorator(this IFoo foo)
{
return
foo as FooDecorator // don't decorate the decorator
?? _decorators.GetValue(foo , f => new FooDecorator(f));
}
}
Given:
that a FooDecorator exists as a value in the ConditionalWeakTable, retrievable by an instance of IFoo; and
that a FooDecorator holds a strong reference to the same instance of IFoo
Can the instance of IFoo ever be eligible for garbage collection? And if it not, is there a way I can use this pattern so that garbage collection is not prevented?
A:
The MSDN page specifically states that
However, in the ConditionalWeakTable class, adding a key/value pair to the table does not ensure that the key will persist, even if it can be reached directly from a value stored in the table ...
So it will not cause the kind of leak you worry about.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the most efficient way to implement mutable strings in C?
I'm currently implementing a very simple JSON parser in C and I would like to be able to use mutable strings (I can do it without mutable strings, however I would like to learn the best way of doing them anyway). My current method is as follows:
char * str = calloc(0, sizeof(char));
//The following is executed in a loop
int length = strlen(str);
str = realloc(str, sizeof(char) * (length + 2));
//I had to reallocate with +2 in order to ensure I still had a zero value at the end
str[length] = newChar;
str[length + 1] = 0;
I am comfortable with this approach, however it strikes me as a little inefficient given that I am always only appending one character each time (and for the sake of argument, I'm not doing any lookaheads to find the final length of my string). The alternative would be to use a linked list:
struct linked_string
{
char character;
struct linked_string * next;
}
Then, once I've finished processing I can find the length, allocate a char * of the appropriate length, and iterate through the linked list to create my string.
However, this approach seems memory inefficient, because I have to allocate memory for both each character and the pointer to the following character. Therefore my question is two-fold:
Is creating a linked list and then a C-string faster than reallocing the C-string each time?
If so, is the gained speed worth the greater memory overhead?
A:
The standard way for dynamic arrays, regardless of whether you store chars or something else, is to double the capacity when you grow it. (Technically, any multiple works, but doubling is easy and strikes a good balance between speed and memory.) You should also ditch the 0 terminator (add one at the end if you need to return a 0 terminated string) and keep track of the allocated size (also known as capacity) and the number of characters actually stored. Otherwise, your loop has quadratic time complexity by virtue of using strlen repeatedly (Shlemiel the painter's algorithm).
With these changes, time complexity is linear (amortized constant time per append operation) and practical performance is quite good for a variety of ugly low-level reasons.
The theoretical downside is that you use up to twice as much memory as strictly necessary, but the linked list needs at least five times as much memory for the same amount of characters (with 64 bit pointers, padding and typical malloc overhead, more like 24 or 32 times). It's not usually a problem in practice.
A:
No, linked lists are most certainly not "faster" (how and wherever you measure such a thing). This is a terrible overhead.
If you really find that your current approach is a bottleneck, you could always allocate or reallocate your strings in sizes of powers of 2. Then you would only have to do realloc when you cross such a boundary for the total size of the char array.
| {
"pile_set_name": "StackExchange"
} |
Q:
Counting in different bases
If you want to count over 8 bits, in base 2, the result is like this:
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 1;
0 0 0 0 0 0 1 0;
.....
1 1 1 1 1 1 1 1;
But how can you make an algorithm that counts - for each bit - based on a different bases, ex:
If the least significant bit is counted according to base 5 and the most significant one is on base 2, the result should look like:
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 1;
0 0 0 0 0 0 0 2;
0 0 0 0 0 0 0 3;
0 0 0 0 0 0 0 4;
1 0 0 0 0 0 0 0;
1 0 0 0 0 0 0 1;
1 0 0 0 0 0 0 2;
...
1 0 0 0 0 0 0 4;
Can you please give me the algorithm that generates these vectors?
A:
One algorithm for this problem is the kind of "ripple-carry" addition most students typically learn in kindergarten, except slightly modified. When you add two numbers, you do so digit-by-digit: first the ones place, then the tens place, then the hundreds place, etc. If you would ever had to write down a number larger than 10 (e.g. 7+8=15), then you write it down minus-10 and "carry" the 10 over to the next place, where you add it (it becomes a 1); this might "ripple" over many places (e.g. 999+1=1000). By repeatedly adding one using this algorithm, we can count up one-by-one.
It is important to clarify what we're after: what does it mean for different places to have different bases. If you allow places to have arbitrary number ranges, and stand for arbitrary numbers, then some bad things can happen: a number can be written in more than one way, and/or some decimal numbers cannot be written. Therefore we will limit ourselves to a "sane" scheme where if a place i has a base bi, that means the valid digits are 0,1,2,...,bi-1 (as usual, just like in decimal), and that digits in that place represents bi times the product of all bases on the right (bi-1 x bi-2 x ...). For example, if our bases were [10,10,10], the values of the digits would be [1000,100,10,1]; if our bases were [5,10,5], the values of the digits would be [250,50,5,1]
How to add 1 to a number:
Increment the least-significant digit (LSD)
Perform ripple-carry as follows:
Set the current place to the LSD
Repeat as long as the current place exceeds its allowed max digit:
Set the digit at the current place to 0
Advance the current place one to the left
Increment the number at the new place (now on the left)
Repeat the above algorithm until you have all numbers you desire.
Python:
from itertools import *
def multibaseCount(baseFunction):
currentDigits = [0]
while True:
yield currentDigits[::-1]
# add 1
currentDigits[0] += 1
# ripple-carry:
for place,digit in enumerate(currentDigits):
if currentDigits[place]>=baseFunction(place): # if exceeds max digit
currentDigits[place] = 0 # mod current digit by 10
if place==len(currentDigits)-1: # add new digit if doesn't exist
currentDigits += [0]
currentDigits[place+1] += 1 # add 1 to next digit
else: # doesn't exceed max digit; don't need to carry any more
break
Demo, where place n has base n+1:
>>> for digits in islice(multibaseCount(lambda n:n+1),30):
... print( ''.join(map(str,digits)).zfill(5) )
...
00000
00010
00100
00110
00200
00210
01000
01010
01100
01110
01200
01210
02000
02010
02100
02110
02200
02210
03000
03010
03100
03110
03200
03210
10000
10010
10100
10110
10200
10210
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting checkbox to be checked/unchecked depending on the column result in datalist
I have got 2 check box[isSold(bit), Offline(bit)] in the datalist , I want to set that check box to be checked or unckecked depending on the database result of that row. For instance if the product is sold , the sold column will be true , therefore the checkbox should be checked. I tried to do acheive the required result by using code below with no success:
<asp:DataList ID="dlEditCaravans" runat="server"
RepeatDirection="Vertical" DataKeyField="makeID" OnEditCommand="edit"
OnDeleteCommand="delete" ItemStyle-CssClass="dleditCaravans"
onitemcommand="dlEditCaravans_ItemCommand"
onitemdatabound="dlEditCaravans_ItemDataBound">
<ItemTemplate>
<div class="imgeditCaravan">
<asp:Image runat="server" ID="caravanImage" ImageUrl='<%#String.Format("/images/caravans/{0}", Eval("image")) %>' Height="80" Width="80" />
</div>
<div class="lblmakeCaravan">
<asp:Label ID="lblMake" runat="server" Text='<%#Eval("make") %>' CssClass="lblheader"></asp:Label>
<br />
<asp:Label ID="imgDesc" runat="server" CssClass="lblDescription" Text='<%#(Eval("description").ToString().Length>350)?Eval("description").ToString().Substring(0,50)+ "....":Eval("description").ToString() + "...." %>'></asp:Label>
<br />
<asp:Label ID="lblPrice" runat="server" Text='<%#"£ "+Eval("Price")%>'></asp:Label>
<br />
</div>
<div class="editImage">
<asp:ImageButton ID="edit" runat="server" CommandName="edit" ImageUrl="~/images/newsControls/edit.gif" ToolTip="Edit Caravan"/>
<asp:ImageButton ID="delete" runat="server" CommandName="delete" ImageUrl="~/images/newsControls/delete.gif" ToolTip="Delete Caravan"/>
<br /> <br />
<asp:Button ID="btnAddToFeature" runat="server" Text="Add To Feautured Caravans" CommandName="AddToCaravans" Enabled="false" Width="210" Height="30" ForeColor="#1D91BD" ToolTip="Add Caravan To Feautured Caravans"/><br /><br />
<asp:Button ID="btnRemoveFeature" runat="server" Text="Remove From Feautured Caravans" CommandName="RemoveToCaravans" Enabled="false" ToolTip="Remove from Featured Caravans" Width="210" Height="30" ForeColor="#1D91BD" />
<br /> <br />
<asp:CheckBox runat="server" ID="chkOffline" Checked='<%#Eval("offline") %>' /> <label>Set This Caravan in Offline mode</label>
</div>
</ItemTemplate>
<SeparatorTemplate>
<div class="descSeparator"></div>
</SeparatorTemplate>
</asp:DataList>
A:
First of all, this should work: Checked='<%#Eval("offline") %>', if it does not work, it must be a different problem.
Alternatively you can do the same in the ItemDataBound event. like..
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
DataRow dr = ((DataRowView)e.Item.DataItem).Row;
((CheckBox)e.Item.FindControl("chkOffline")).Checked = Convert.ToBoolean(dr["chkOffline"]);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Listing only the device with the highest RSSI
I am developing an android based application that is scanning for existing bluetooth enabled devices. So far I managed to get the name of the devices + the signal strength in dBm. And here comes my question. Is there any way to filter only the device with the strongest signal or in other words just to preview the closest device?
Thanks in advance
A:
I assume your RSSI values are of type int, if so why not use something similar to the following to determine your highest value:
int[] rssiValues = {20, 40, 45, 62, 85, 9, 12 };
int highest = rssiValues[0];
for (int index = 1; index < rssiValues.length; index ++) {
if (rssiValues[index] > highest) {
highest = rssiValues [index];
}
}
At the end of this loop highest will contain the closest RSSI or Bluetooth device. If you have your devices wrapped in some class you should be able to modify this code to compare your RSSI value.
| {
"pile_set_name": "StackExchange"
} |
Q:
New Cat Meows Constantly
My husband adopted a feral black cat a couple of days ago. He's an absolute sweetheart, only a little over one year old, but he meows constantly. Whether he's with us, playing, or in his room, he's almost always making noise and meowing. The only time he seems to stop is when he's asleep or eating.
We have him scheduled to see a vet soon to rule out any medical issues, and I've been trying to give him lots of play time and attention to see if it's a boredom thing, but he's pretty much just constantly making noise for the sake of it. He does play a fair bit, but he also seems indifferent towards us; not really scared like most new cats I've raised.
Any suggestions or ideas why he may be doing this? What can we do to mitigate it (nights have been very sleepless so far).
A:
Have you tried talking to him when he meows? He may just want some sort of vocal interaction with you. Some cats enjoy having "conversations" with their humans, and a short conversation will satisfy them for a while. You don't have to meow at him, unless you want to. Speaking normally is usually all that's required.
This approach can also help you learn to recognise his different vocalisations. He probably has one meow for when he wants to play, another for when he's just "checking in", another for when he's hungry, another to announce an accomplishment (I just killed a bug!) and so forth.
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular2: Open ngbPopover containing image delayed on hover
First of all: I created a plunkr to show the problem: http://plnkr.co/edit/5IhhqtofCvqqr5x9P0De?p=preview
I want to open a ngbPopover (with image) delayed on hovering an element.
I use (mouseover) and (mouseleave) in combination with triggers="manual". Inside the opening function i use setTimeout which triggers the popover opening. Everything works fine but not on the first execution. As you can see on the picture the popover is placed wrongly.
On the second, third, ... hover everything works fine. When i remove the timeout function it works, too, but that's not my goal.
A:
So, this is a tricky one! Before I suggest a work-around (as I'm not sure there is a way of "fixing" it), let me explain what is going on here.
In order to position elements properly we need to know exact size of an element to be positioned. In your particular case the exact size is only known after a browser loaded an image.
There are 2 basic ways of working-around the issue:
re-position popover after image has been loaded
give image a size upfront.
The problem with re-positioning popover after image load is that you would have to listen to <img>'s onload event and then force re-positioning. This is cumbersome and today's implementation of ng-bootstrap popover doesn't have any method of forcing re-positioning (although we could easily add one!).
What I would suggest instead is to give the <img> element initial size so when we position things the exact dimensions are known before image loads. Ex. width="200px" height="140px" like so:
<ng-template #popContent let-greeting="greeting">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ee/Crested_Tern_Tasmania_%28edit%29.jpg/1600px-Crested_Tern_Tasmania_%28edit%29.jpg"
width="200px"
height="140px">
</ng-template>
With the fixed dimensions of an image things start to work as expected: http://plnkr.co/edit/QUxBX1KCPVaAkIfBH0P8?p=preview
| {
"pile_set_name": "StackExchange"
} |
Q:
FFT Convolution - How to apply Kernel
I'm pretty new to Image Processing and found out that the FFT convolution speeds up the convolution with large kernel sizes a lot.
My question is, how can I apply a kernel to a image in frequency space when using kissFFT?
I already did the following:
//I have an image with RGB pixels and given width/height
const int dim[2] = {height, width}; // dimensions of fft
const int dimcount = 2; // number of dimensions. here 2
kiss_fftnd_cfg stf = kiss_fftnd_alloc(dim, dimcount, 0, 0, 0); // forward 2d
kiss_fftnd_cfg sti = kiss_fftnd_alloc(dim, dimcount, 1, 0, 0); // inverse 2d
kiss_fft_cpx *a = new kiss_fft_cpx[width * height];
kiss_fft_cpx *r = new kiss_fft_cpx[width * height];
kiss_fft_cpx *g = new kiss_fft_cpx[width * height];
kiss_fft_cpx *b = new kiss_fft_cpx[width * height];
kiss_fft_cpx *mask = new kiss_fft_cpx[width * height];
kiss_fft_cpx *outa = new kiss_fft_cpx[width * height];
kiss_fft_cpx *outr = new kiss_fft_cpx[width * height];
kiss_fft_cpx *outg = new kiss_fft_cpx[width * height];
kiss_fft_cpx *outb = new kiss_fft_cpx[width * height];
kiss_fft_cpx *outmask = new kiss_fft_cpx[width * height];
for(unsigned int i=0; i<height; i++) {
for(unsigned int l=0; l<width; l++) {
float red = intToFloat((int)Input(i,l)->Red);
float green = intToFloat((int)Input(i,l)->Green);
float blue = intToFloat((int)Input(i,l)->Blue);
int index = i * height + l;
a[index].r = 1.0;
r[index].r = red;
g[index].r = green;
b[index].r = blue;
}
}
kiss_fftnd(stf, a, outa);
kiss_fftnd(stf, r, outr);
kiss_fftnd(stf, g, outg);
kiss_fftnd(stf, b, outb);
kiss_fftnd(stf, mask, outmask);
kiss_fftnd(sti, outa, a);
kiss_fftnd(sti, outr, r);
kiss_fftnd(sti, outg, g);
When I set the rgb values again on an image I do get the original image back. So the transformation works.
What should I do now if I want to apply a kernel, for example
a 9x9 box blur (1/9, 1/9, ... 1/9).
I have read some things about Fast convolution, but they're all different, depending on the implementation of the FFT . Is there a kind of "list" what things I have to care before applying a filter ?
The way I think:
The imagesize must be a power of 2;
I must create a kernel, the same size as the image. Put the 9 middle values to 1/9, the rest to 0 and then transform this kernel into frequency domain, multiply the source image with it, then transform the source image back. But that doesn't really work :DD
A:
The convolution performed in the frequency domain is really a circular convolution. So when your non-zero elements of the kernel reach the edge of the picture it wraps around and includes the pixels from the other side of the picture, which is probably not what you want. To deal with this just zero pad the input with as many elements as you have non-zero elements in the kernel (actually one less will do). With a 3x3 kernel you need to add 3-1=2 zero pixels in each dimension.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make a click on an item in the global search provider (Quick Search Box) go to the correct Activity
I have an application that has the structure:
Activity A
Activity B
Activity C
In activity B I call startActivityForResult on Activity C.
In Activity C I have a search provider where the user can search addresses and then return them to activity B.
This works great, but when I introduce the search results in the Quick Search Box (Reference Link) then a click on the suggestion will go straight to Activity C. Calling finish on that activity will then not do what I want (returning to B with the result).
So any suggestions on how to rewrite this to work in both scenarios?
A:
You need to pass the result between activities
Activity C --> send the result to ---> Activity B.
how to use onActivityResult(..) if the activity is called from a menu
See my answer here. Its the same, mind the comments below.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regular Expression in C# for either empty, 0, or a length 5 digit. (Zip Code)
I'm stuck on this problem. I have an input field for a zip code, however, our database has a lot of records where the zip code is 0. I currently have a regular expression set on the field to ensure that the zip is either empty or is a 5 digit value.
Because this however, if you go to update a record that has the value set to "0", it triggers a validation message because it is not an empty string or a 5 digit string. I want to make it be able to accept all three of these states (empty, "0" or a 5 digit number).
(^\s{0,5}$)|(^\d{5}$) - This is what I've been using for the empty or 5 digit number, it seems to work fine.
(^?:(\s{0}$)|(^?:(0){1}$|\d{5})$) - I've tried this for the empty, "0" or 5 digit number, but it doesn't work. I really have next to no clue what's going on, I barely understand regular expressions. Help would be appreciated, thanks!
A:
I would go with:
(^([0]|[0-9]{5})$)
Where the input is 0 or any 5 number combination.
As pointed out in the comment, regex is for matching and you can't match when there is nothing
| {
"pile_set_name": "StackExchange"
} |
Q:
While using custom InfoWindow getting NullPointerException
I am using a custom InfoWindow in my app. I have two question related to it.
Is it possible to make multiline snippet in InfoWindow
Say am adding some data lets say I need to show LATTITUDE and LONGITUDE when I click on marker. Normally if u set these values in snippet they appear on same line. I would like to show them on two line. Is that possible
I googled about multiline snippet and couldn't find anything much useful so came up with the idea of customising InfoWindow.
2.Below show is my custom InfoWindow which gives me NullPointerException
Getting exception from try-catch loop. I followed some code I found while googleing but it's not working.
private class MyCustomInfoWindow implements InfoWindowAdapter{
private View view;
public MyCustomInfoWindow(){
}
@Override
public View getInfoContents(Marker markr) {
// TODO Auto-generated method stub
return null;
}
@Override
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
view = getLayoutInflater().inflate(R.layout.mycustom_infowindow, null);
TextView marker_heading = (TextView)findViewById(R.id.marker_heading);
try{
String m_heading = marker.getId();
marker_heading.setText(m_heading);
}
catch(Exception exx){
Toast.makeText(getApplicationContext(), "getInfoWindow Error is " + marker_heading.length(), Toast.LENGTH_LONG).show();
}
return view;
}
}
My custom
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/marker_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:typeface="serif"
android:textStyle="bold"
/>
</LinearLayout>
Using Google Maps V2
Could someone please tell me where am going wrong .
A:
Use
TextView marker_heading = (TextView)view.findViewById(R.id.marker_heading);
to initialize marker_heading TextView instance because TextView is inside mycustom_infowindow layout
| {
"pile_set_name": "StackExchange"
} |
Q:
Python XML-RPC server as a Windows service
I'm trying to create an XML-RPC server as a windows service.
The XML-RPC server is able to get and put files (like FTP) and
also execute commands via os.system() that the remote client
sends to it.
I'm trying the encapsulate the server in the windows service
event loop.
When creating the service there is no problem.
python.exe remoteServer.py --startup=auto install
Installing service XMLRPCServerService
Service installed
When starting the service there is no problem.
python.exe remoteServer.py start
Starting service XMLRPCServerService
When stopping the service there is no problem.
python.exe remoteServer.py stop
Stopping service XMLRPCServerService
When starting the service again there is a problem.
python.exe remoteServer.py start
Starting service XMLRPCServerService
Error starting service: An instance of the service is already running.
Looking at the process monitor, I see a process "pythonservice.exe" that is
still running.
Here are the contents of remoteServer.py:
#!/bin/python
# $Revision: 1.7 $
# $Author: dot $
# $Date: 2011/12/07 01:16:13 $
LISTEN_HOST='0.0.0.0'
LISTEN_PORT=8000
import os
import SocketServer
import BaseHTTPServer
import SimpleHTTPServer
import xmlrpclib
import SimpleXMLRPCServer
import socket
import httplib
import inspect
import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
class XMLRPCServer(BaseHTTPServer.HTTPServer,SimpleXMLRPCServer.SimpleXMLRPCDispatcher):
def __init__(self, server_address, HandlerClass, logRequests=True):
""" XML-RPC server. """
self.logRequests = logRequests
SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self,False,None)
SocketServer.BaseServer.__init__(self, server_address, HandlerClass)
self.socket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
self.server_bind()
self.server_activate()
class XMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
""" XML-RPC request handler class. """
def setup(self):
self.connection = self.request
self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
def do_POST(self):
""" Handles the HTTPS request.
It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly.
"""
try:
# get arguments
data = self.rfile.read(int(self.headers["content-length"]))
# In previous versions of SimpleXMLRPCServer, _dispatch
# could be overridden in this class, instead of in
# SimpleXMLRPCDispatcher. To maintain backwards compatibility,
# check to see if a subclass implements _dispatch and dispatch
# using that method if present.
response = self.server._marshaled_dispatch(
data, getattr(self, '_dispatch', None)
)
except:
# This should only happen if the module is buggy
# internal error, report as HTTP server error
self.send_response(500)
self.end_headers()
else:
# got a valid XML RPC response
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.send_header("Content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
# shut down the connection
self.wfile.flush()
self.connection.shutdown() # Modified here!
def XMLRPCServerGet(HandlerClass = XMLRPCRequestHandler,ServerClass = XMLRPCServer):
"""Test xml rpc over http server"""
class xmlrpc_registers:
def _listMethods(self):
return list_public_methods(self)
def _methodHelp(self, method):
f = getattr(self, method)
return inspect.getdoc(f)
def list(self, dir_name):
"""list(dir_name) => [<filenames>]
Returns a list containing the contents of the named directory.
"""
return os.listdir(dir_name)
def put(self,filename,filedata):
try:
with open(filename, "wb") as handle:
handle.write(filedata.data)
handle.close()
return True
except Exception,ex:
return 'error'
def get(self,filepath):
try:
handle = open(filepath)
return xmlrpclib.Binary(handle.read())
handle.close()
except:
return 'error'
def system(self, command):
result = os.system(command)
return result
server_address = (LISTEN_HOST, LISTEN_PORT) # (address, port)
server = ServerClass(server_address, HandlerClass)
server.register_introspection_functions()
server.register_instance(xmlrpc_registers())
#sa = server.socket.getsockname()
return server
#server.serve_forever()
#print "Serving HTTP on", sa[0], "port", sa[1]
#try:
# #print 'Use Control-C to exit'
# server.serve_forever()
#except KeyboardInterrupt:
# #print 'Exiting'
class XMLRPCServerService(win32serviceutil.ServiceFramework):
_svc_name_ = "XMLRPCServerService"
_svc_display_name_ = "XMLRPCServerService"
_svc_description_ = "Tests Python service framework by receiving and echoing messages over a named pipe"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
import servicemanager
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))
self.timeout = 100
server = XMLRPCServerGet()
#server.serve_forever()
while 1:
# Wait for service stop signal, if I timeout, loop again
rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
# Check to see if self.hWaitStop happened
if rc == win32event.WAIT_OBJECT_0:
# Stop signal encountered
server.shutdown()
servicemanager.LogInfoMsg("XMLRPCServerService - STOPPED")
break
else:
server.handle_request()
servicemanager.LogInfoMsg("XMLRPCServerService - is alive and well")
def ctrlHandler(ctrlType):
return True
if __name__ == '__main__':
win32api.SetConsoleCtrlHandler(ctrlHandler, True)
win32serviceutil.HandleCommandLine(XMLRPCServerService)
A:
It looks like you are missing a call to self.ReportServiceStatus(win32service.SERVICE_STOPPED) at the end of your SvcStop method.
A:
David K. Hess deserves credit for this one.
He suggested I add the following after line 142 in class XMLRPCServerService, def SvcStop:
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
Here is the final version for anyone interested:
#!/bin/python
# $Revision: 1.7 $
# $Author: dot $
# $Date: 2011/12/07 01:16:13 $
LISTEN_HOST='0.0.0.0'
LISTEN_PORT=8000
import os
import SocketServer
import BaseHTTPServer
import SimpleHTTPServer
import xmlrpclib
import SimpleXMLRPCServer
import socket
import httplib
import inspect
import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
class XMLRPCServer(BaseHTTPServer.HTTPServer,SimpleXMLRPCServer.SimpleXMLRPCDispatcher):
def __init__(self, server_address, HandlerClass, logRequests=True):
""" XML-RPC server. """
self.logRequests = logRequests
SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self,False,None)
SocketServer.BaseServer.__init__(self, server_address, HandlerClass)
self.socket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
self.server_bind()
self.server_activate()
class XMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
""" XML-RPC request handler class. """
def setup(self):
self.connection = self.request
self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
def do_POST(self):
""" Handles the HTTPS request.
It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly.
"""
try:
# get arguments
data = self.rfile.read(int(self.headers["content-length"]))
# In previous versions of SimpleXMLRPCServer, _dispatch
# could be overridden in this class, instead of in
# SimpleXMLRPCDispatcher. To maintain backwards compatibility,
# check to see if a subclass implements _dispatch and dispatch
# using that method if present.
response = self.server._marshaled_dispatch(
data, getattr(self, '_dispatch', None)
)
except:
# This should only happen if the module is buggy
# internal error, report as HTTP server error
self.send_response(500)
self.end_headers()
else:
# got a valid XML RPC response
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.send_header("Content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
# shut down the connection
self.wfile.flush()
self.connection.shutdown() # Modified here!
def XMLRPCServerGet(HandlerClass = XMLRPCRequestHandler,ServerClass = XMLRPCServer):
"""Test xml rpc over http server"""
class xmlrpc_registers:
def _listMethods(self):
return list_public_methods(self)
def _methodHelp(self, method):
f = getattr(self, method)
return inspect.getdoc(f)
def list(self, dir_name):
"""list(dir_name) => [<filenames>]
Returns a list containing the contents of the named directory.
"""
return os.listdir(dir_name)
def put(self,filename,filedata):
try:
with open(filename, "wb") as handle:
handle.write(filedata.data)
handle.close()
return True
except Exception,ex:
return 'error'
def get(self,filepath):
try:
handle = open(filepath)
return xmlrpclib.Binary(handle.read())
handle.close()
except:
return 'error'
def system(self, command):
result = os.system(command)
return result
server_address = (LISTEN_HOST, LISTEN_PORT) # (address, port)
server = ServerClass(server_address, HandlerClass)
server.register_introspection_functions()
server.register_instance(xmlrpc_registers())
#sa = server.socket.getsockname()
return server
#server.serve_forever()
#print "Serving HTTP on", sa[0], "port", sa[1]
#try:
# #print 'Use Control-C to exit'
# server.serve_forever()
#except KeyboardInterrupt:
# #print 'Exiting'
class XMLRPCServerService(win32serviceutil.ServiceFramework):
_svc_name_ = "XMLRPCServerService"
_svc_display_name_ = "XMLRPCServerService"
_svc_description_ = "Tests Python service framework by receiving and echoing messages over a named pipe"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
import servicemanager
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))
self.timeout = 100
server = XMLRPCServerGet()
#server.serve_forever()
while 1:
# Wait for service stop signal, if I timeout, loop again
rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
# Check to see if self.hWaitStop happened
if rc == win32event.WAIT_OBJECT_0:
# Stop signal encountered
server.shutdown()
servicemanager.LogInfoMsg("XMLRPCServerService - STOPPED")
break
else:
server.handle_request()
servicemanager.LogInfoMsg("XMLRPCServerService - is alive and well")
def ctrlHandler(ctrlType):
return True
if __name__ == '__main__':
win32api.SetConsoleCtrlHandler(ctrlHandler, True)
win32serviceutil.HandleCommandLine(XMLRPCServerService)
| {
"pile_set_name": "StackExchange"
} |
Q:
Associated Types in Swift
What are associated types in swift programming language? What are they used for?
As per swift programming language book:
When defining a protocol, it is sometimes useful to declare one or
more associated types as part of the protocol’s definition. An
associated type gives a placeholder name (or alias) to a type that is
used as part of the protocol. The actual type to use for that
associated type is not specified until the protocol is adopted.
Associated types are specified with the typealias keyword.
The above text is not very clear to me. It would help a lot if you can explain associated types with an example.
Also, why is it useful to declare an associated type as part of a protocol definition?
A:
You have a protocol that defines methods and perhaps properties that an implementing type must provide. Some of those methods/properties use or return objects of a different type to the type implementing the protocol. So, for instance, if you have a protocol that defines certain types of collections of objects, you might define an associated type which defines the elements of the collection.
So let's say I want a protocol to define a Stack, but a Stack of what? It doesn't matter, I just use an associated type to act as a place holder.
protocol Stack
{
// typealias Element - Swift 1
associatedtype Element // Swift 2+
func push(x: Element)
func pop() -> Element?
}
In the above Element is the type of whatever objects are in the stack. When I implement the stack, I use typealias to specify the concrete type of the stack elements.
class StackOfInt: Stack
{
typealias Element = Int // Not strictly necessary, can be inferred
var ints: [Int] = []
func push(x: Int)
{
ints.append(x)
}
func pop() -> Int?
{
var ret: Int?
if ints.count > 0
{
ret = ints.last
ints.removeLast()
}
return ret
}
}
In the above, I have defined a class that implements Stack and says that, for this class, Element is actually Int. Frequently, though, people leave out the typealias because the concrete type of Element can be inferred from the method implementations. e.g. the compiler can look at the implementation of push() and realise from the type of the parameter that Element == Int in this case.
| {
"pile_set_name": "StackExchange"
} |
Q:
struts 2.1 book?
Struts 2.1 is a major upgrade from the previous 2.0.X versions.
I have not been able to find any books for Struts2.1 or ref guides. There is a thread on Struts mailing list but I think Manning has canceled the publication Struts2.1 book
Does anyone know of Struts books being released that cover Struts2.1 in details?
A:
It appears that the Struts community does not agree that it is a major upgrade. At least they do not think anyone would like to pay to learn about the upgrade.
The best resource is likely to be a Struts 2.0 book and this upgrade guide.
| {
"pile_set_name": "StackExchange"
} |
Q:
Waiting for User login before executing code that uses User-Information
I am using Firebase in my Android-Application and using Auth and Realtime-DB. I want to set a value in the Database when I interact with the UI (Open Fragment when clicking item in BottomNavigationActivity), but I want the user to be Logged in before the Database gets accessed. I run the following code when my Fragment is initalized:
public static void setFoods(ArrayList<FoodItem> foods){
if(user != null){
DatabaseReference reference = database.getReference("users/" + user.getUid() + "/foods");
reference.setValue(foods);
}
}
The != null check makes sure that the User is logged in. But i want it to execute when the user variable changes, and not have to reopen the Fragment to load the list once the user is Logged in.
If anybody could tell me how you execute code once the value changes, I would be very happy. Thanks in Advance!
A:
I guess, you mean something like this:
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(getSubClassTAG(), "onAuthStateChanged: singed in: " + user.getUid());
} else {
Log.d(getSubClassTAG(), "onAuthStateChanged: signed out: ");
}
}
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Need clarification about mapping objects to database, annotations, and one to many relationships
Need some help understanding if I'm on the right track here and exactly what I need to do. Hope someone can chime in.
So I've got three tables, Job, Authorization, and Filter. Each Job must have one Authorization and one Filter. Of course, each Filter could be used by more than one job and the same goes for the Authorization. However, the Filters and Authorizations don't need to know what Jobs they are being used by.
So that is a one to many relationship on the part of the Filters and Authorizations I believe right? Or am I off track? How is this modeled in a database? I believe the Job table needs to have a foreign key field to the Filter and Authorization tables. Do the Filter and Authorization tables need foreign key fields themselves to Job?
Next, how do I model this in Java objects and then how do I set up the hibernate or java persistence annotations? I believe the Filter class looks like:
class Filter {
@OnetoMany
@JoinColumn(name="filterID")
private Job job;
}
and the Authorization class basically the same and then how would the Job class look? The thing that's really throwing me is that the Filter and Authorization classes don't need any knowledge of what Job they're associated with so I don't see the need for them to actually hold references to Job objects. Only the Job class needs to hold references to the Filter and Authorization objects. So do I really need the above code?
I'm hoping someone can help clarify all this for me as I can't seem to wrap my head around it. Databases are not my strong suit. Thanks.
A:
As far as I know, using a @OneToMany annotation is not very recommended in your situation. Maybe you may want the other side to own the relation.
Check this article out:
http://josian.wordpress.com/2006/09/09/hibernate-annotations-bidirectional-one-to-many/
So, to your question, no, you do not need the above code.
You need something like this:
class Job {
@Id
//stuff...
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn (name="authorization_id", nullable = false, updatable = false, insertable = false)
private Authorization authorization;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn (name="filter_id", nullable = false, updatable = false, insertable = false)
private Filter filter;
}
and on your Filter
@Entity
@Table(name="filter")
class Filter {
//some stuff, but no relation!
}
EDIT:
The @JoinColumn is just the name you want to appear in your Job table. By default, if you dont specify the join çolumn name, it is going to be {foreignTableName}_id. In the case of Authorizatrion, if you annotated it like this:
@Entity
@Table(name="foo")
class Authorization{
@Id
@column(name="auth_id")
private Long authId;
}
the default join column generated for you in the Job table will be
"foo_id" and will reference the
"auth_id" field in the
"foo" table.
TO your final comment:
Actually you don't need to put foreign keys in the db. In the Job Entity, the
@ManyToOne annotation already ensures the keys will be placed for you. The
@JoinColumn specifies the names of the foreign key. For example, if you want your foreign key name in the Job table to Authorization to be called 'authorization_fk', you would use
@JoinColumn('authorization_fk')
and this is how it is gonna be placed in your Job table.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.