text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Java 8 function that takes a List and return a HashMap>
I am trying to create a function in Java 8 that takes a list as a parameter and returns a HashMap as a result.
I already did it in Java 7 but I want to do it by using Java 8 streams:
Here is the code in Java 7:
public static HashMap<String, List<Eleve>> getMentions(List<Eleve> liste){
HashMap<String, List<Eleve>> listeMentions = new HashMap<String, List<Eleve>>();
List<Eleve> noMention = new ArrayList<Eleve>();
List<Eleve> mentionAB = new ArrayList<Eleve>();
List<Eleve> mentionB = new ArrayList<Eleve>();
List<Eleve> mentionTB = new ArrayList<Eleve>();
for (Eleve eleve: liste) {
if (eleve.getAverage()>=12 && eleve.getAverage()<14) {mentionAB.add(eleve);}
else if(eleve.getAverage()>=14 && eleve.getAverage()<16) {mentionB.add(eleve);}
else if (eleve.getAverage()>=16) {mentionTB.add(eleve);}
else{noMention.add(eleve);}
}
listeMentions.put("No mention", noMention);
listeMentions.put("Mention AB", mentionAB);
listeMentions.put("Mention B", mentionB);
listeMentions.put("Mention TB", mentionTB);
return listeMentions;
}
I tried with the collect(Collectors.toMap) stream but I did not get the estimated outcome.
A:
You can create a method that accepts an int average and returns the corresponding group for that average.
public static String getGroup (int average) {
if (average >= 12 && average < 14) {
return "Mention AB";
} else if(average >= 14 && average < 16) {
return "Mention B";
} else if (average >= 16) {
return "Mention TB";
} else {
return "No mention";
}
}
Now you can use Collectors.groupingBy to group your instances by this criteria:
Map<String, List<Eleve>> listeMentions =
liste.stream()
.collect(Collectors.groupingBy(e -> getGroup(e.getAverage())));
Alternately, you can pass the Eleve instance to the getGroup() method, so the stream pipeline will become:
Map<String, List<Eleve>> listeMentions =
liste.stream()
.collect(Collectors.groupingBy(e -> getGroup(e)));
or, if you make getGroup() an instance method of Eleve (i.e public String getGroup() {...}):
Map<String, List<Eleve>> listeMentions =
liste.stream()
.collect(Collectors.groupingBy(Eleve::getGroup));
| {
"pile_set_name": "StackExchange"
} |
Q:
Length of sides of a triangle and area
Let $T$ be a triangle with sides of length $a,b,c$ and $T'$ a triangle with sides of length $a',b',c'$. If $a<a'$ and $b<b'$ and $c<c'$, is it true $Area(T)<Area(T')$?
I've tried to use Heron's formula, but I wasn't able to prove this.
A:
No, it's wrong! Try, $a=b=c=1$ and $a'=b'=100$ and $c'\rightarrow200^-$.
For example, $c'=199.9999999$ is valid.
| {
"pile_set_name": "StackExchange"
} |
Q:
Identification of a quadrilateral as a trapezoid, rectangle, or square
Yesterday I was tutoring a student, and the following question arose (number 76):
My student believed the answer to be J: square. I reasoned with her that the information given only allows us to conclude that the top and bottom sides are parallel, and that the bottom and right sides are congruent. That's not enough to be "more" than a trapezoid, so it's a trapezoid.
Now fast-forward to today. She is publicly humiliated in front of the class, and my reputation is called into question once the student claims to have been guided by a tutor. The teacher insists that the answer is J: square ("obviously"... no further proof was given).
Who is right? Is there a chance that we're both right?
How should I handle this? I told my student that I would email the teacher, but I'm not sure that's a good idea.
A:
Clearly the figure is a trapezoid because you can construct an infinite number of quadralaterals consistent with the given constraints so long as the vertical height $h$ obeys $0 < h \leq 9$ inches. Only one of those infinite number of figures is a square.
I would email the above statement to the teacher... but that's up to you.
As for the "politics" or "pedagogy" of drawing a square, but giving conditions that admit non-square quadralaterals... well, I'd take this as a learning opportunity. The solution teaches the students that of course any single drawing must be an example member of a solution set, but need not be every example of that set. In this case: a square is just a special case of a trapezoid.
The solution goes further and reveals that the vertexes (apparently) lie on a semi-circle... ("obvious" to a student). A good followup or "part b" question would be to prove this is the case.
A:
Of course, you are right. Send an email to the teacher with a concrete example, given that (s)he seems to be geometrically challenged. For instance, you could attach the following pictures with the email, which are both drawn to scale. You should also let him/her know that you need $5$ parameters to fix a quadrilateral uniquely. With just $4$ pieces of information as given in the question, there exists infinitely many possible quadrilaterals, even though all of them have to be trapezium, since the sum of adjacent angles being $180^{\circ}$ forces the pair of opposite sides to be parallel.
The first one is an exaggerated example where the trapezium satisfies all conditions but is nowhere close to a square, even visually.
The second one is an example where the trapezium visually looks like a square but is not a square.
Not only should you email the teacher, but you should also direct him/her to this math.stackexchange thread.
Good luck!
EDIT
Also, one might also try and explain to the teacher using the picture below that for the question only the first criterion is met, i.e., only one pair of opposite sides have been made parallel.
A:
FWIW, this question appears to come from a diagnostic test which can be perused at http://www.mathmatuch.com/presentations/diagnostic_test.pdf -- where the official answer is given as J (the square). So it's not just the teacher who is wrong.
(Remark: I found the site by googling on "identify the figure shown" and "trapezoid" then looking for "76" and "J" in the results.)
Update Feb. 17, 2020: The original link (above) is now dead. By googling again on "identify the figure shown" and "trapezoid," I did find another version of the diagnostic test at https://blevinshornets.org/teachers/wp-content/uploads/sites/6/2018/12/diagnostic_test-7th.pdf with the same error. Interestingly, a similar test can be found at http://stpatrickschoolstoneham.org/wp-content/uploads/2018/06/Rising-6th-grade-math-packet.pdf but problem 76 there is somewhat different and has no error.
| {
"pile_set_name": "StackExchange"
} |
Q:
R: Reclassify a raster stack through the range of the quantiles of each layer. Generic quantiles function ; layer by layer
I have a raster stack that contains terrain bends extracted with different neighborhood windows "crosc_nxn" (e.g. 3x3, 5x5, etc ...).
crosc_nxn <- raster::stack(path.files.list)
> crosc_nxn
class : RasterStack
dimensions : 170, 172, 29240, 5 (nrow, ncol, ncell, nlayers)
resolution : 30, 30 (x, y)
extent : 794418.4, 799578.4, 7400299, 7405399 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=22 +south +ellps=WGS84 +units=m +no_defs
names : crosc_3, crosc_5, crosc_9, crosc_11, crosc_15
I want to create a new stack containing only the extreme values of each layer using two quantile ranges ( <= 0.01 or 0.99 >=).
out_prob <- function(x, min= quantile(x, 0.01,na.rm=TRUE), max= quantile(x, 0.99, na.rm=TRUE)){ifelse(x <= min | x>= max , x, NA)}
range_calc <- calc(crosc_nxn, fun= out_prob)
range_over <- overlay(crosc_nxn, fun= out_prob)
It appears that calc applies the function to a certain pixel and traverses all layers to return the desired value. However I want my function to sweep all the pixels of the layer and then move on to the next one. I'm surprised that overlay has returned the same result.
On the other hand when specifying the quantile for a certain layer the result is consistent with my query, in that layer where I expressed the interval.
# calc quantile
> quantile(crosc_nxn, c(0.01, 0.99), na.rm=TRUE)
1% 99%
crosc_3 -0.001324438 0.001358304
crosc_5 -0.000933790 0.000937456
crosc_9 -0.000481476 0.000486876
crosc_11 -0.000356400 0.000362014
crosc_15 -0.000223900 0.000228338
# explicit range in function
out_prob_ex <- function(x) {ifelse(x <= -0.001324438 | x >= 0.001358304, x, NA)}
# generic
out_prob <- function(x, min= quantile(x, 0.01,na.rm=TRUE), max= quantile(x, 0.99, na.rm=TRUE)){ifelse(x <= min | x>= max , x, NA)}
quantile_generic <- overlay(crosc_nxn, fun= out_prob)
quantile_explicit <- overlay(crosc_nxn, fun= out_prob_ex)
# comparison using only the first stack layer
par(mfrow = c(2,2))
plot(outlier_generic[[1]], main= "generic formula")
plot(outlier_explicit[[1]], main= "explicit quantile")
hist(outlier_generic[[1]])
hist(outlier_explicit[[1]])
I need a generic function for each layer, without having to express the quantiles one by one. I thought overlay would do this and I can not figure it out. Someone has an explanation to help me see the way out.
A:
Lets make a test raster to make it easy to see what's going on:
> r = raster(matrix(1:100,10,10))
> plot(r)
The highest and lowest values are in the left and right columns, so we can see if we are selecting them properly.
This function takes a single raster and returns the parts of the raster that are outside the given quantiles, and NA elsewhere:
> extremes = function(r,q=c(0.01,0.99)){
qua = quantile(r[],q,na.rm=TRUE)
Q = r<qua[1] | r > qua[2]
Q[Q==0]=NA
r*Q
}
It works by computing the TRUE/FALSE raster that satisfies the condition, replacing FALSE (zero) with NA, and then multiplying by the raster values. That gives NA where FALSE and r values where TRUE. Test:
> plot(extremes(r, c(.2,.8)))
I'm using narrower quantile bands so I can see what's going on. With only 100 pixels I wouldnt see much with a 0.01 and 0.99 level. This looks good so far. Now let's construct a test stack:
> s = stack(list(r,r*2,r*3,r*4))
> plot(s)
To apply a function layer-wise, loop over layers with lapply and stack the returned layer list:
> exs = stack(lapply(1:nlayers(s), function(i){extremes(s[[i]], q=c(.2,.8))}))
> plot(exs)
Which I think is your final answer, once you've run it with your desired quantile levels.
| {
"pile_set_name": "StackExchange"
} |
Q:
control image loading in javascript/jquery?
I am creating an Image gallery and i want a few images to load when the next button is clicked.....
for example,
$("#next").css({cursor:"pointer"}).click(function(){
//load image1,image2,image3
});
HTML
<img src="image1.jpg"><img src="image2.jpg"><img src="image3.jpg">
i don't want to append them to a division, these image tags are already present in 'gallery' div tag... I just want to stop them from loading when the page loads at first and when the user clicks on next button theses images can load ...Thanks
A:
If the images elements are already in your markup, and they have the src attribute defined, the image files will be downloaded when the page starts loading.
You should either create the image elements programmatically or leave the src attribute empty on your markup, and then assign it when the user clicks next.
Option 1:
// on the click event...
var images = ['img1.jpg', 'img2.jpg', 'img3.jpg'],
gallery = $('#gallery');
$.each(images, function () {
$('<img/>').attr('src', this).appendTo(gallery);
});
Option 2:
Markup:
<img id="img1"/> <img id="img2"/> <img id="img3"/>
On the click event:
$('#img1').attr('src', 'image1.jpg');
$('#img2').attr('src', 'image2.jpg');
$('#img3').attr('src', 'image3.jpg');
Edit:
Another option comes to my mind when you talk about lazy loading.
Option 3:
You could remove the src attribute of your images, and store it using the $.data function, then in your click event, restore the image src to its original value, for example:
$(function () {
// put a "defaultImage" on all images of gallery
// and store the original src attribute
$('#gallery img').each(function () {
$(this).data('originalSrc', $(this).src).attr('src', 'defaultImage.jpg');
});
$("#next").click(function(){
$('#gallery img').each(function () {
// restore the original src attribute:
$(this).attr('src', $(this).data('originalSrc'));
});
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Asking the same question on MSE and MO
Under what circumstances is it acceptable to post the same question on Math Stack Exchange and on Math Overflow?
More specifically, I want to know if it is acceptable to duplicate the question if I have gotten no answers in here and some days have already passed. I understand that some questions might require more than a few days to be answered, but in the case of, say, a reference request I see no point in waiting.
A:
Sometimes you want to have pizza for dinner. And that's fine. You call the local pizza place, and you order pizza which is delivered to your house usually within 30 minutes.
What you don't do is neither call several pizza places and see which one gets first to your place; or call a falafel place, and order a large pizza with extra mushrooms.
When do you call a second pizza place? When you have waited 45 minutes and the delivery guy didn't show up with your pizza; or if you have given up on the pizza you might order a falafel instead.
What does this analogy teach us?
Asking a question online is like ordering a pizza. You ask on one place, asking at several places at once serves little more purpose than calling all five local pizzerias and ordering the same pizza, just because you're very hungry.
Sometimes, as Andres Caicedo remarks, your question is a pizza but for that purpose MathOverflow only sells falafel, so it has neither pizza nor mushrooms, to help you. Therefore depending on your question, it might not be suitable at all for MathOverflow.
If you are certain that the question is good for both sites, pick one, ask there, and let it sit for a while. What's a while? Say a week. If you placed a bounty at some point, let it sit through the bounty period and see what's going on. If all that failed to get you closer to an answer, either delete the question and post it on MathOverflow, or raise a flag and ask for it to be migrated there.
Be prepared for the possibility that your question is not welcomed there, and it will be downvoted, closed or migrated back to MSE. It may happen. Don't take it personally, you called to a vegetarian pizza place, and asked for sausage on your pizza, and they declined your order.
If you are not certain, you can always post a question on meta.MO and ask there. Explain the situation and ask whether or not this question is likely to be accepted well. If the response is positive, go ahead and repost/migrate. If not, try posting a bounty on your question here, try talking to people on the chat system. But remember not to overdo it, there's a fine line between asking people to help you, and harassing them with borderline spam.
That been said, of course there are possible merits for having two questions on two sites. But those should be aimed for receiving different answers. On MSE you may ask for a particular explanation for a particular solution, whereas on MO you might ask for a more general outline of different solutions (or references to them, and read yourself).
But in that case, don't forget to post cross-links in your questions, and be very clear that there are two questions and that they have different aim.
| {
"pile_set_name": "StackExchange"
} |
Q:
Click event to a Gwt-connector
I am trying to add click event to one of the widgets that use gwt-connector. Here is the code:
public class Diagrams extends Diagram implements HasClickHandlers{
public Diagrams(AbsolutePanel boundaryPanel) {
super(boundaryPanel);
}
@Override
public HandlerRegistration addClickHandler(ClickHandler handler) {
return addDomHandler(handler, ClickEvent.getType());
}
@Override
public void fireEvent(GwtEvent<?> event) {
}
}
Here Diagram is a gwt-connector class. Here is the link to the Diagram class and also link to GWT-Connector.
Question:
Am i doing anything wrong in the code while adding the clickhandler?
I am getting error saying that addDomHandler is undefined for the type Diagrams. are there limitations for adding click handlers?
Any input will be of great help.
Thank you.
A:
I was supposed to add the HasClickHandler to Shape class rather than Diagrm.
Its working fine now.
| {
"pile_set_name": "StackExchange"
} |
Q:
Amiga versus Atari ST computer introductions
I'm interested in the time, place and manner in which some historically important computers were introduced to the world. For example, the Macintosh was presented in January 1984 by Steve Jobs, first at the Apple shareholder meeting, then at a meeting of the Boston Computer Society.
Commodore introduced some important products at conventions: PET at West Coast Computer Faire 1977, CBM 8032 at NCC 1980, C64 at CES 1982. What was the format of these? Was it just 'walk up to the booth and take a look, and an employee will run through some of the features for you' or was there anything more elaborate, along the lines of the Macintosh introduction?
The Amiga was presented July 23, 1985, at the Lincoln Center, New York. Did they organize an event just for that, so that they could stage a more elaborate show than they could at a convention?
How did that compare with the debut of the Amiga's main rival, the Atari ST, at the Winter CES in January of 1985? Was that a 'walk up to the booth and take a look' affair, less elaborate than the Amiga?
Edit: Okay, that's two people perceiving the question as vague, so I'll make it more specific.
The Amiga apparently was introduced at its own special event, whereas the Atari ST was introduced at a convention, the Winter CES. Is it the case that the introduction of the Atari ST was therefore just a 'walk up to the booth and take a look' affair, whereas the Amiga could get a more elaborate stage presentation of the kind Steve Jobs liked to arrange, and this is why Commodore spent the extra money and risked the extra political capital on the special event?
A:
This question is a bit misleading as it seams to imply that a presentation at a trade show is always done in a 'small' booth somewhere hidden in a crowded hall. Maybe the originator never went to such? So the question may be rather:
Why do companies sometimes choose separate events over trade shows?
(Still not really Retrocomputing related)
'Boothes' on a trade show may be quite large. Sometimes companies fill whole convention halls with their single 'booth'. They are quite often way larger than any separate venue of the same company would be, as they transport communication over a longer duration as a single show and to a wider direct audience.
In addition, trade shows offer stage rooms/halls. This is where companies do such presentation events. Ofc, the machine will be also shown at the booth, regardless of size, after all, that's what a trade show is about. The stage events do the 'official' introduction. Such a stage show may be 'just a press conference' or again outclass any separate event in size as well as in style.
So doing an introduction within a trade show or separately is a marketing decision, and doesn't tell anything about the way it was done. It's all about how a marketing director sees the bigger chance to reach the target audience. Go with the convenience of a trade show and have a guaranteed crowd and a coverage among all trade publications and maybe beyond if show (and product) seems important enough for mainstream media (good PR preparation may help).
Conclusion: It's all about what goal marketing wants to reach
While Atari did go with a small presentation at Winter CES and a surprise introduction at Comdex, as they did not have any money to go beyond attending at all, hoping that the usual trade media would do the bidding, (New) Commodore did decide to go with a separate event targeted at main stream media and using showbiz glamour to attract them.
...and what budget they have :)
(Fun fact, a year later, in 1986, the Atari booth at CES was huge, while Commodores stand was quite small - Source: Compute! 75 in 8/86)
| {
"pile_set_name": "StackExchange"
} |
Q:
iPhone development, what UIKeyboard gives out just letters?
Is there a UIKeyboard that gives out just letters and nothing else? I tried out the alphabet one but it gives out numbers.
A:
You can't get a letters-only keyboard without subclassing UIKeyboard to create your own from scratch; but you can reject characters you don't want using a UITextFieldDelegate.
If string is anything other than a letter, return NO for this function:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
Here is an adaption of the answer here for your situation:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding Orthogonal Complement in $R^4$
I need to find the orthogonal complement in $\mathbb{R}^4$ of the space spanned by $(1,0,1,1)$ and $(-1,2,0,0)$. Here is what I am thinking:
Let's call $A$ the space spanned by $(1,0,1,1)$ and $(-1,2,0,0)$. A vector $v=(v_1,v_2,v_3,v_4)$ that exists in the orthogonal complement $A^\perp$ should satisfy
$$(v_1,v_2,v_3,v_4)\cdot (1,0,1,1) =0$$
and
$$ (v_1,v_2,v_3,v_4)\cdot (-1,2,0,0)=0$$
This means that $v_1+v_3+v_4=0$ and $-v_1+2v_2=0.$
Can someone give me a hint as to whether this thinking is correct? Should I now just try to find a basis for this space?
A:
Your approach is correct. Note that $$dim \Bbb R^4=4=dim A+dim A\perp$$ Therefore dim$A^\perp=2$ Solving the linear system we find that:$$v_1+v_3+v_4=0, v_1+2v_2=0$$ Therefore a generic vector of $A^\perp$ is equal : $v=(-v_3+v_4,-\frac {1}{2}(v_3+v_4),v_3,v_4)$. $A^\perp$ is spanned by $(-1,-\frac{1}{2},1,0)$ and $(-1,1,0,1)$
| {
"pile_set_name": "StackExchange"
} |
Q:
Evaluating 0xfb-0xfa
0xfb-0xfa
I have first turn to binary
0xfb=11111011
0xfa=11111010
-0xfa=00000101+1=00000110
Now 11111011+00000110=100000001 which is underflow, but it surely incorrect, where did I get it wrong?
A:
It is not clear whether the initial numbers are signed or unsigned. The results will be identical, but the reasoning is slightly different.
Assuming your initial numbers are unsigned, the initial conversion is incorrect.
Your data are 8 bits when coded in binary as unsigned.
If you want to convert them to 2s complement without truncation, you need an extra bit. So
+0xfb = 0 11111011
+0xfa = 0 11111010
-0xfa = 1 00000110
Now we can compute the addition
(1)
0xfb 0 11111011
-0xfa + 1 00000110
----------
0 00000001
We can notice that there is no overflow. There is a carry out, but we can just ignore it in 2s complement. And the sum of a positive and negative number cannot overflow.
Now, as the two MSB are equal, result can be shortened to 8 bits giving the obvious result of 1.
If initial numbers are signed, most your computation is correct. All the operations can be done on 8 bits. And the result will be on 8 bits.
(1)
0xfb 11111011
-0xfa + 00000110
----------
00000001
There is a carry out, but no over or underflow. The result is correct.
| {
"pile_set_name": "StackExchange"
} |
Q:
Minecraft Enchanting Power
Is there a certain pattern needed for enchantment tables so they get much more powerful since I tried bookshelves and the enchantments aren't much more powerful.
A:
Bookshelves need to be placed no more than two blocks away from the enchanting table horizontally, and must be vertically either on the same level as the table, or one level up.
Bookshelves increase the number of levels you can dump into an enchantment, increasing the chances that the enchantment you get is a good one. 15 bookshelves caps this effect.
It should look like this when finished.
| {
"pile_set_name": "StackExchange"
} |
Q:
Share upload locations MSM
Is there a way to share upload locations between MSM sites, or to sync the dirs for both sites?
If not, is there another module that can do this?
A:
If you have command line access on the server, you can setup a Symbolic Link:
http://www.wallpaperama.com/forums/linking-files-with-symbolic-links-linux-unix-shell-command-tutorial-guides-t479.html
Apparently you can also set up a Symbolic Link without command line access using PHP: http://perishablepress.com/use-php-to-create-symbolic-links-without-shell-access/
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot Convert From System.Windows.Forms.DialogResult To 'String' C#
C#
I am using visual studio, using windows forms, and get an error:
Cannot Convert From System.Windows.Forms.DialogResult To 'String'
I am trying to access the Minecraft file already in my computer and want to move files to a specific folder and I let the user choose what world they want to move the mod into but when I use System.IO.File.Move(datapack,DialogResult); and DialogResult is a variable which I made here: DialogResult DialogResult = folderBrowserDialog1.ShowDialog(); and the computer tries to convert DialogResult To a string for some reason and fails. so I looked up for a solution and found how to turn DialogResult into a string with this function DialogResult.ToString(); but comes up with the error.
This Is My Code: (My error is on line 29 System.IO.File.Move(datapack,DialogResult);)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string username = Interaction.InputBox("You can find your username in C:/Users/Your name", "", "Put User Name In Here");
string lastD = @"\AppData\Roaming\.minecraft\saves";
folderBrowserDialog1.SelectedPath = @"c:\users\" + username + lastD;
DialogResult DialogResult = folderBrowserDialog1.ShowDialog();
folderBrowserDialog1.ShowNewFolderButton = false;
string datapack = @"C:\Program Files (x86)\Mr Snout's Datapack Installer\Datapacks\Nether Reactor.zip";
DialogResult.ToString();
System.IO.File.Move(datapack,DialogResult);
}
private void button2_Click(object sender, EventArgs e)
{
panel1.BringToFront();
panel1.Show();
}
private void button3_Click(object sender, EventArgs e)
{
panel1.SendToBack();
panel1.Hide();
}
private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
}
}
}
A:
You have some confusion about what is DialogResult and what is its purpose. It is a enumeration DialogResult used to return the button pressed when a Dialog like FolderBrowserDialog is used. It is not the name of the folder selected by the user. This one is returned by the SelectedPath property.
So your code after getting the result from the dialog, should check if the user has pressed OK and then build the name of the destination file where you want to move your source file. This could be done extracting the file name from the source and combining it with the folder selected in the dialog.
private void button1_Click(object sender, EventArgs e)
{
string username = Interaction.InputBox("You can find your username in C:/Users/Your name", "", "Put User Name In Here");
string lastD = @"\AppData\Roaming\.minecraft\saves";
folderBrowserDialog1.SelectedPath = @"c:\users\" + username + lastD;
folderBrowserDialog1.ShowNewFolderButton = false;
DialogResult result = folderBrowserDialog1.ShowDialog();
if(result == DialogResult.OK)
{
string datapack = @"C:\Program Files (x86)\Mr Snout's Datapack Installer\Datapacks\Nether Reactor.zip";
string destFile = Path.Combine(folderBrowserDialog1.SelectedPath, Path.GetFilename(datapack));
System.IO.File.Move(datapack,destFile);
}
}
A:
The DialogResult doesn't return the path, but the result fx. (OK, FAILED)
Instead you use the folderBrowserDialog1 you made, that returns the path as shown:
System.IO.File.Move(datapack, folderBrowserDialog1.SelectedPath + "datapack.zip");
| {
"pile_set_name": "StackExchange"
} |
Q:
Number of solutions for $x^2 \equiv x \pmod m$
What is the number of solutions of $x^2 \equiv x \pmod m$ for any positive integer $m$?
A:
The problem is to count the roots of $x^2 - x \equiv 0 \pmod m$.
Exploring the problem for specific numbers of $m$ first, we see it can have:
$2$ roots mod $2$: 0,1
$4$ roots mod $6 = 2\cdot 3$: 0,1,3,4
$8$ roots mod $30 = 2\cdot 3\cdot 5$: 0,1,6,10,15,16,21,25,30
$16$ roots mod $210 = 2\cdot 3\cdot 5\cdot 7$
A good guess is it has $2^r$ roots, for some $r$ depending on $m$.
With some more exploring you can notice that:
There is $2$ roots modulo a prime power.
There is $2^r$ roots, where $r$ is the number of prime factors of $m$.
A degree $d$ polynomial can only have at most $d$ roots mod some prime $p$. It can have more roots than its degree modulo prime powers though. We need to prove that this special polynomial has exactly $2$ roots mod each prime power $p^k$.
Lemma $x^2-x \equiv 0$ has $2$ roots $\pmod {p^k}$.
proof: Clearly $x=0$ and $x=1$ are roots, as you have pointed out. We just need to show now that if $z$ is a root then $z=0$ or $z=1$. To prove that we can split into two cases: When $z|p^k$ and when $z$ is coprime to $p^k$. The coprime case is easy because $z$ is zero or invertible.
For the case $z|p^k$: Put $z = p^h$ (with $h < k$) and consider $$p^{2h} - p^h \equiv 0 \pmod {p^k}.$$ this is impossible of $2h \le k$ so suppose $2h > k$, we have $k < 2h < 2k$ and $p^{2h-k} \equiv p^k$ but this implies $2h-k = k$, so $2h = 2k$, but this contradicts $h < k$.
Secondly we can use the chinese remainder theorem to put together the $2$ roots mod each prime power of $m$ to get $2^r$ roots mod $m$.
Lemma If $a,b$ are coprime then if $P(x)$ has $m$ roots mod $a$ and $n$ roots mod $b$ then it has $mn$ roots mod $ab$.
proof: Label the roots mod $a$ as $\{r_i\}$ and the roots mod $b$ as $\{s_j\}$ then the roots mod $ab$ are $\{(r_i, s_j) \}$ of which there are $|\{r_i\}|\cdot|\{s_j\}| = nm$.
Putting these two lemmas together lets you conclude: There are $2^r$ roots, where $r$ is the number of prime factors of $m$.
| {
"pile_set_name": "StackExchange"
} |
Q:
(index out of bounds) I wrote a hangman game program with java
I am sure that there are many other problems with my program but I am currently stuck on this issue and focusing on solving this first.
My aim is to loop the game according to the number of inputted words while changing the game number.
My problem is that the "display banner" part kept looping until it is met with an error of "out of boundary".It displayed following when I inputted "java Hangman 123 test":
========
Game: 1
========
Game: 2
========
Game: 3
========
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Hangman.main(Hangman.java:121)
Here is my program:
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
public class Hangman {
//validation of raw questions
public static boolean isValidQuestion(String rawQuestion){
rawQuestion = rawQuestion.toUpperCase();
boolean vQuestion = true;
for(int i=0; i<rawQuestion.length(); i++){
char c = rawQuestion.charAt(i);
if(!(c>='A' && c<='Z'))
vQuestion = false;
}
return vQuestion;
}
//show invalid tries
public static String formatCharArray(char[] ca){
String output = "";
for(int i=0; i<ca.length; i++){
output += ca[i] + " ";
}
return output;
}
public static void main(String args[]){
if(args.length==0){
System.out.println("Usage: java Hangman word_to_guess [more_word_to_quess]...");
return;
}
List<String> validQuestions = new ArrayList<>();
for (int i = 0; i < args.length; i++){
String rawQuestion = args[i];
boolean b = isValidQuestion(rawQuestion);
if (b){
validQuestions.add(rawQuestion);
}else{
System.out.println("Error: " + rawQuestion + ", input must be a word consist of a-z or A-Z");
}
}
// store valid questions into an array
String questions[] = validQuestions.toArray(new String[validQuestions.size()]);
// shuffle the questions
for(int i=0; i<7; i++){
int x = (int)(Math.random()*validQuestions.size());
int y = (int)(Math.random()*validQuestions.size());
String temp = questions[x];
questions[x] = questions[y];
questions[y] = temp;
}
// game
// initiallize
int noInvalidTry = 0;
int count = 0;
char[] invalidTries = new char[6];
int j = 0;
char[] userGuess = new char[questions[j].length() ];
boolean isCorrect = false;
for(int i=0; i<invalidTries.length; i++){
invalidTries[i] = '_';
}
for(int k=0; k<userGuess.length; k++){
userGuess[k] = '_';
}
This is the part where I messed up.
// display banner
while( j<= args.length){
System.out.println( "========" );
System.out.println( "Game: " + ++j );
System.out.println("========");
}
above
// game loop
while( noInvalidTry<6 && count<questions[j].length() ){
Scanner sc= new Scanner(System.in);
System.out.print("Please input your guess: ");
String s = sc.nextLine().trim();
// check input length
while(s.length()==1 && isValidQuestion(s)){
//start guess
char inputChar = s.charAt(0);
inputChar = Character.toUpperCase(inputChar);
boolean c = false;
for(int i=0; i<questions[j].length(); i++){
if((s.equals(questions[j].charAt(i))) && (userGuess[i] == '_')){
//update userGuess
userGuess[i] = questions[j].charAt(i);
c = true;
count++;
System.out.println( "Good try!" );
// show status
System.out.printf("No of Invalid try: %d/6\t\tInvalid tries: ",noInvalidTry);
System.out.println( formatCharArray(invalidTries) );
}
}
if(!c){
noInvalidTry++;
System.out.println( "Oops..." );
// show status
System.out.printf("No of Invalid try: %d/6\t\tInvalid tries: ",noInvalidTry);
System.out.println( formatCharArray(invalidTries) );
}
}
}
if( noInvalidTry==6 && count<questions[j].length()){
System.out.println("Game over, the answer is " + questions[j] );
j=j++;
}
if( noInvalidTry<6 && count==questions[j].length()){
System.out.println("Congratulation!");
j=j++;
}
//final status
if(j==args.length){
double temp = 0;
double score = 0;
double total = args.length;
System.out.println("-------------------------------------------------------------------------------------------------------------------");
System.out.println("Summary");
System.out.println("-------------------------------------------------------------------------------------------------------------------");
while(j<=args.length && isCorrect ){
System.out.println(++j + ". " + questions[j] + "\t" + "Correct" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
temp++;
}
while(j<=args.length && !isCorrect) {
System.out.println(++j + ". " + questions[j] + "\t" + "Incorrect" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
}
score = temp/total;
System.out.println("Final result: " + score + " / 100 marks");
System.out.println("-------------------------------------------------------------------------------------------------------------------");
}
}
}
A:
if(j==args.length){
// ...
while(j<=args.length && isCorrect ){
System.out.println(++j + "" + questions[j] + "\t" + "Correct" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
temp++;
}
while(j<=args.length && !isCorrect) {
System.out.println(++j + ". " + questions[j] + "\t" + "Incorrect" + "\t" + count + "/" + questions[j].length() + " Correct guesses" + "\t" + noInvalidTry + "/" + questions[j].length() + " Incorrect guesses" );
}
if j is the array length, then questions[j] will raise an error (the last element is length-1).
But, even worse, you are still increasing j even more (the 2 j++ statements) !
They are also many other j++ in your while loop.
As a good practice to help you handle arrays : when you do some iteration on a value that is an index :
prefer for loops
loop for the correct values of your parameter (between 0 and length-1)
do not increase the array randomly, you should be sure that your array index (j) is increased once and only once for each iteration. To help you doing that, you should have only one line stating j++ or ++j in your loop, not some j++ at different places nested in some if blocks.
(that's why using a for loop is recommended : there is some place to do the j++, and you should not do it elsewhere without a very good reason.
Also, as stated in comments, you should learn to analyze your error (What is a stack trace, and how can I use it to debug my application errors?), and use debugging tools and go through your program step by step and see what you are doing with all your variables.
| {
"pile_set_name": "StackExchange"
} |
Q:
Formulário de perguntas com radio button retornando exibindo vazio
Boa noite,
Preciso fazer um sistema de perguntas (um questionario) exatamente como esse:
https://jsfiddle.net/hmana2sL/
Só que preciso que quanto as perguntas e as opções de respostas venham do banco.
Eu tentei dessa forma só que os radios estão saindo vazios, mais a consulta esta ok, e rodando-a no MySQL ela
retorna corretamente os dados, acho que pode ser algo com os loop's, alguém poderia me ajudar a encontrar o erro?:
Segue codigo:
<?php
//CONEXÃO
$servername = "127.0.0.1"; $username = "root"; $password = "root"; $dbname = "master";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//CONEXÃO
$QPergunta = "SELECT sug_perg_id AS ID_PERGUNTA, sug_perg_pergunta AS PERGUNTA FROM sugestoes_perguntas WHERE sug_perg_area = 3";
$QAvalicao = "SELECT sug_aval_id AS ID_AVALIACAO, sug_aval_desc AS DESCRICAO FROM sugestoes_avaliacao";
$RPergunta = $conn->query($QPergunta);
$RAvaliacao = $conn->query($sql);
while($row = $RPergunta->fetch_assoc()){
echo "PERGUNTA :".$row["PERGUNTA"];
echo"<br>";
while($row = $RAvaliacao->fetch_assoc()){
echo"<input type='radio' name='".$row["ID_PERGUNTA"]."' value='".$row["ID_AVALIACAO"]."'>".$row["DESCRICAO"];
echo"<br>";
}
}
//FINALIZA CONEXÃO
$conn->close();
//FINALIZA CONEXÃO
?>
A:
<?php
//CONEXÃO
$servername = "127.0.0.1"; $username = "root"; $password = "root"; $dbname = "master";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//CONEXÃO
$QPergunta = "SELECT sug_perg_id AS ID_PERGUNTA, sug_perg_pergunta AS PERGUNTA FROM sugestoes_perguntas WHERE sug_perg_area = 3";
$QAvalicao = "SELECT sug_aval_id AS ID_AVALIACAO, sug_aval_desc AS DESCRICAO FROM sugestoes_avaliacao";
$RPergunta = $conn->query($QPergunta);
$RAvaliacao = $conn->query($QAvalicao);
$Repostas = [];
while($Repostas[] = $RAvaliacao->fetch_assoc());
while($row_pergunta = $RPergunta->fetch_assoc()){
echo "PERGUNTA :".$row["PERGUNTA"];
echo"<br>";
foreach ($Repostas as $row_resposta) {
echo"<input type='radio' name='".$row_pergunta["ID_PERGUNTA"]."' value='".$row_resposta["ID_AVALIACAO"]."'>".$row_resposta["DESCRICAO"];
echo"<br>";
}
}
//FINALIZA CONEXÃO
$conn->close();
//FINALIZA CONEXÃO
?>
Isso provavelmemte irá resolver seu problema.
A variável $sql não existe, foi troquei por $QAvalicao;
O segundo problema é o seguinte, você fez somente uma chamada de banco para pegar as respostas. Quando o primeiro while sai do primeiro registro isso significa que o segundo while (mais interno) já leu todos os registros de respostas, então depois da primeira pergunta, não haverá respostas.
Assim, desta forma eu guardei os registros de respostas em uma variavel:
$Repostas = [];
while($Repostas[] = $RAvaliacao->fetch_assoc());
E Depois para cada registro de Pergunta percorro esta variável com o foreach;
Terceiro erro, a variável $row estava se repetindo e quando erá chamada pelo segundo while em $row["ID_PERGUNTA"] ela iria retorna um valor vazio, pois nesse ponto do código a variável $row só tinha os dados da resposta e não da pergunta.
Para isso renomeei as variáveis para $row_pergunta e $row_resposta.
Especificar o nome de cara variável precisamente com o nome mais próximo do que era guarda é uma ótima pratica de código. Ajuda a você entender um código depois de muito tempo sem ver ele e ainda ajuda em projetos em equipe.
Ps:
while($Repostas[] = $RAvaliacao->fetch_assoc());
Este While não esta vazio, ele esta preenchendo a variável $Respostas com os registros das respostas. Apesar de a pessoa no comentário abaixo não perceber, o comando dentro da condicional do while esta atribuindo o fetch ao $Repostas[].
Ao usar a expressão [] em um array o php criar um novo índice e atribui o valor a ele. A atribuição retorna este valor ao condicional do while. quando essa atribuição for null, o while para.
Espero ter ajudado.
| {
"pile_set_name": "StackExchange"
} |
Q:
When can I remove 301 error?
I recently change a domain name of one of my site.
This is how I did it.
Buy new hosting with new domain name.
Move that content and database to new hosting
Do 301 redirection to new domain
My old hosting account will be expired just after 4 months. Should I renew it just for these redirection part? I mean, we need to use these 301 redirection lifetime? Or can we just remove it after a few months?
A:
It depends.
Do you just want the new domain to be indexed within the search results
instead of the old domain?
Or do you have important backlinks to the
old domain which you want to redirect to the new domain?
If first case: Wait until the search results are updated with the new domain.
Second case: Either you change the target URLs from your important backlinks on the referring sites or you will lose the backlinks after the expiration of your hosting contract.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Javascript, HTML, JQuery & CSS how can I set a variable depending on a HTML Select OnChange, do calculations and update instantly?
I am building a pool pump calculator. My html onchange works perfectly, but I am having trouble passing which Div is active into my Javascript If Else and updating the outputs for each Else. Note that not all features seem to work on JSFiddle, but they work perfectly on a live page.
Here's what I want it to do: (Please see JSFiddle at the bottom for updated version of the demo!)
Depending on the users selection using a HTML Select onChange, a certain Div is displayed using display:block;. Divs from the other selection options are set to display:none; in CSS so they are then hidden and only the correct Div is displayed for each selection. This is the Pool Shape. A variable needs to be set which I am naming PoolShape and I have attempt to make the results of this a String with the Results of "Rectangle", "Oval", "Round" or "Oblong", again depending on the Select onChange.
I am then wanting to add into my Javascript an If Else so that if PoolShape = "Rectangle" then do some calculations, else if PoolShape = "Oval" then do differenet calculations etc for the Results on Tab 3 (Calc-Tab-3).
And finally, there is a DropDown box on the Results Tab 3 (Calc-Tab-3) which will alter one variable in the calculation by calling the function UpdateComparisonPump(); which again searches for the PoolShape and recalculates this section using the newly selected DropDown option StandardPumpSize.
All other calculations on the tabs work fine, apart from this whole PoolShape If Else scenario.
Any help is appreciated.
Here is the HTML I am using: (Please see JSFiddle at the bottom for updated version of the code!)
<span>
What is the shape of your pool:
<label class="radio-container"><input onchange="change('Rectangle-container');RectangleContainerChange();" type="radio" name="radio" id="RectangleCheck" checked="checked"><span class="radio-checkmark"></span>Rectangle
</label><label class="radio-container"><input onchange="change('Oval-container');OvalContainerChange();" type="radio" name="radio" id="OvalCheck"><span class="radio-checkmark"></span>Oval</label><label class="radio-container"><input onchange="change('Round-container');RoundContainerChange();" type="radio" name="radio" id="RoundCheck"><span class="radio-checkmark"></span>Round</label><label class="radio-container"><input onchange="change('Oblong-container');OblongContainerChange();" type="radio" name="radio" id="OblongCheck"><span class="radio-checkmark"></span>Custom Oblong</label>
</span>
<div id="Rectangle-container">
Length of your pool in feet: <input type="number" class="tabinput" id="Length" min="1">
Width of your pool in feet: <input type="number" class="tabinput" id="Width" min="1">
Depth of your pool in feet: <input type="number" class="tabinput" id="Depth" min="1">
</div>
<div id="Oval-container">
Half the length of your pool in feet: <input type="number" class="tabinput" id="HalfLength" min="1">
Half the width of your pool in feet: <input type="number" class="tabinput" id="HalfWidth" min="1">
Depth of your pool in feet: <input type="number" class="tabinput" id="OvalDepth" min="1">
</div>
<div id="Round-container">
Radius of your pool in feet: <input type="number" class="tabinput" id="RoundRadius" min="1">
Depth of your pool in feet: <input type="number" class="tabinput" id="RoundDepth" min="1">
</div>
<div id="Oblong-container">
Small diameter of your pool in feet: <input type="number" class="tabinput" id="SmallDiameter" min="1">
Large diameter of your pool in feet: <input type="number" class="tabinput" id="LargeDiameter" min="1">
Length of your pool in feet: <input type="number" class="tabinput" id="OblongLength" min="1">
</div>
<input type="button" class="CalcButtons" onclick="document.getElementById('Calc-Tab-1').style.display='none';document.getElementById('Calc-Tab-2').style.display='block';" value="Next">
</div>
<div id="Calc-Tab-2" class="CalcTabs">
<h3 class="CalcHeaders">Energy Consumption</h3>
<span>What are the voltage, ampage and kilowatt per hour of your pump?</span>
Volts: <input type="number" class="tabinput" id="Volts" min="1">
Amps: <input type="number" class="tabinput" id="Amps" min="1">
Cost per kWh: <input type="number" class="tabinput" id="CostPerKwh" min="1">
<span>How many hours do you run your pump for: <span class="slideOutputValueHours" id="myHoursRan">7</span> Hours
<input type="range" class="slideInputValueHours slider" id="slideRangeHours" value="7" min="1" max="24" step="1" oninput="myHoursPumpIsRunFunction()">
<input type="button" class="CalcButtons" onclick="document.getElementById('Calc-Tab-2').style.display='none';document.getElementById('Calc-Tab-1').style.display='block';" value="Previous">
<input type="button" class="CalcButtons" onclick="GetTheResults();" value="Calculate Results">
</div>
<div id="Calc-Tab-3" class="CalcTabs">
<h3 class="CalcHeaders">Results & Savings</h3>
<strong>Your pools total expenditures</strong>
Total kWh per day: <span id="ResultsKwhPerDay"></span> KWh per day
Total Cost per day: <span id="ResultsCostPerDay"></span> Thai Baht
Total Cost per month: <span id="ResultsCostPerMonth"></span> Thai Baht based on 30 days
Total Cost per year: <span id="ResultsCostPerYear"></span> Thai Baht per year
<strong>The amount of liters in your pool</strong>
Total liters in your pool: <span id="ResultsTotalLiters"></span> Liters
<strong>The run-time of your pool</strong>
Liters per hour: <span id="ResultsLitersPerHour"></span> Per hour
Time to complete 1 turnover: <span id="ResultsTurnoverTime"></span> Hour
Total turnovers per 24 hour: <span id="ResultsTotalTurnovers"></span> Turnovers
<strong>And here are your savings compared to a <select id="StandardPumpSize" onchange="UpdateComparisonPump()"><option value="1.26">.75hp standard pump</option><option value="1.72">1hp standard pump</option><option value="2.14">1.5hp standard pump</option><option selected value="2.25">2hp standard pump</option><option value="2.62">2.5hp standard pump</option><option value="3.17">3hp standard pump</option><option value="3.5">3.5hp standard pump</option><option value="4">4hp standard pump</option><option value="4.5">4.5hp standard pump</option><option value="5">5hp standard pump</option><option value="5.5">5.5hp standard pump</option><option value="1">variable speed pump</option></select></strong>
Savings per day: <span id="ResultsSavingsPerDay"></span> Thai Baht
Savings per month: <span id="ResultsSavingsPerMonth"></span> Thai Baht
Savings per year: <span id="ResultsSavingsPerYear"></span> Thai Baht
Percentage saved per year: <span id="ResultsSavingsPercentage"></span>% Saved!
</div>
Here are my Javascript and variables being used throughout: (Please see JSFiddle at the bottom for updated version of the code!)
<script>
function GetTheResults() {
var PoolShape = "Rectangle";
var Volts = parseInt(document.getElementById('Volts').value);
var Amps = parseInt(document.getElementById('Amps').value);
var HoursPumpIsRan = parseInt(document.getElementById('slideRangeHours').value);
var KwhPerDay = (Volts * Amps) / 1000 * HoursPumpIsRan;
var CostPerKwh = parseInt( document.getElementById('CostPerKwh').value);
var CostPerDay = KwhPerDay * CostPerKwh;
var CostPerMonth = CostPerDay * 30;
var CostPerYear = CostPerDay * 365;
var Length = parseInt(document.getElementById('Length').value);
var Width = parseInt(document.getElementById('Width').value);
var Depth = parseInt(document.getElementById('Depth').value);
var RectangleTotalLiters = Length * Width * Depth * 7.48;
var HalfLength = parseInt(document.getElementById('HalfLength').value);
var HalfWidth = parseInt(document.getElementById('HalfWidth').value);
var OvalDepth = parseInt(document.getElementById('OvalDepth').value);
var OvalTotalLiters = HalfLength * HalfWidth * 3.14 * 7.48;
var RoundRadius = parseInt(document.getElementById('RoundRadius').value);
var RoundDepth = parseInt(document.getElementById('RoundDepth').value);
var RoundTotalLiters = RoundRadius * RoundRadius * RoundDepth * 7.48;
var SmallDiameter = parseInt(document.getElementById('SmallDiameter').value);
var LargeDiameter = parseInt(document.getElementById('LargeDiameter').value);
var OblongLength = parseInt(document.getElementById('OblongLength').value);
var OblongTotalLiters = SmallDiameter * LargeDiameter * OblongLength * 3.142 * 7.48;
var FlowRate = parseInt(document.getElementById('FlowRate').value);
var LitersPerHour = FlowRate * 60;
var RectangleTurnoverTime = RectangleTotalLiters / LitersPerHour;
var OvalTurnoverTime = OvalTotalLiters / LitersPerHour;
var RoundTurnoverTime = RoundTotalLiters / LitersPerHour;
var OblongTurnoverTime = OblongTotalLiters / LitersPerHour;
var RectangleTotalTurnovers = 24 / RectangleTurnoverTime;
var OvalTotalTurnovers = 24 / OvalTurnoverTime;
var RoundTotalTurnovers = 24 / RoundTurnoverTime;
var OblongTotalTurnovers = 24 / OblongTurnoverTime;
var StandardPumpSize = parseInt(document.getElementById('StandardPumpSize').value);
var StandardCostPerYear = StandardPumpSize * myHoursRan * CostPerkWh * 365;
var SavingsPerYear = StandardCostPerYear - CostPerYear;
var SavingsPerMonth = SavingsPerYear / 12;
var SavingsPerDay = SavingsPerYear / 365;
var SavingsPercentage = SavingsPerYear / StandardCostPerYear * 100;
/* IF ELSE to define which radio button is selected, and if x is selected then provide the correct output */
if (PoolShape == "Rectangle") {
document.getElementById("ResultsTotalLiters").innerHTML = RectangleTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = RectangleTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = RectangleTotalTurnovers;
}
Else if (PoolShape == "Oval") {
document.getElementById("ResultsTotalLiters").innerHTML = OvalTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = OvalTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = OvalTotalTurnovers;
}
Else if (PoolShape == "Round") {
document.getElementById("ResultsTotalLiters").innerHTML = RoundTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = RoundTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = RoundTotalTurnovers;
}
Else if (PoolShape == "Oblong") {
document.getElementById("ResultsTotalLiters").innerHTML = OblongTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = OblongTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = OblongTotalTurnovers;
}
document.getElementById("ResultsLitersPerHour").innerHTML = LitersPerHour;
document.getElementById("ResultsSavingsPerDay").innerHTML = SavingsPerDay;
document.getElementById("ResultsSavingsPerMonth").innerHTML = SavingsPerMonth;
document.getElementById("ResultsSavingsPerYear").innerHTML = SavingsPerYear;
document.getElementById("ResultsSavingsPercentage").innerHTML = SavingsPercentage;
}
</script>
<script>
/* This sets the PoolShape string from our radio button selections */
Function RectangleContainerChange() {
PoolShape == "Rectangle";
}
Function OvalContainerChange() {
PoolShape == "Oval";
}
Function RoundContainerChange() {
PoolShape == "Round";
}
Function OblongContainerChange() {
PoolShape == "Oblong";
}
</script>
<script>
/* This updates the Comparison with the Select Onchange from the Dropdown which should be a live comparison in addition to the initial comparison in GetTheResults() */
Function UpdateComparisonPump() {
if (PoolShape == "Rectangle") {
document.getElementById("ResultsTotalLiters").innerHTML = RectangleTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = RectangleTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = RectangleTotalTurnovers;
}
Else if (PoolShape == "Oval") {
document.getElementById("ResultsTotalLiters").innerHTML = OvalTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = OvalTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = OvalTotalTurnovers;
}
Else if (PoolShape == "Round") {
document.getElementById("ResultsTotalLiters").innerHTML = RoundTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = RoundTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = RoundTotalTurnovers;
}
Else if (PoolShape == "Oblong") {
document.getElementById("ResultsTotalLiters").innerHTML = OblongTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = OblongTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = OblongTotalTurnovers;
}
document.getElementById("ResultsSavingsPerDay").innerHTML = SavingsPerDay;
document.getElementById("ResultsSavingsPerMonth").innerHTML = SavingsPerMonth;
document.getElementById("ResultsSavingsPerYear").innerHTML = SavingsPerYear;
document.getElementById("ResultsSavingsPercentage").innerHTML = SavingsPercentage;
}
</script>
And here is some CSS to help display everything: (Please see JSFiddle at the bottom for updated version of the code!)
/*--------------------------------------------------------------
Only displays the first Tab on load
--------------------------------------------------------------*/
.Calc-Tab-1 {
display:block;
}
/*--------------------------------------------------------------
Hide the other tabs on load
--------------------------------------------------------------*/
.Calc-Tab-2,
.Calc-Tab-3 {
display:none;
}
/*--------------------------------------------------------------
Calculator preferences
--------------------------------------------------------------*/
.CalcButtons {
margin-bottom: 1em!important;
}
.CalcHeaders {
margin-top: 1em!important;
}
#Calc-Tab-1,
#Calc-Tab-2,
#Calc-Tab-3 {
padding: 10px;
}
/*--------------------------------------------------------------
Calculator - Hide Pool Shape Divs
--------------------------------------------------------------*/
#Oval-container,
#Round-container,
#Oblong-container {
display: none;
}
/*--------------------------------------------------------------
Calculator - Tabs display
--------------------------------------------------------------*/
#Calc-Tab-1,
#Calc-Tab-2,
#Calc-Tab-3 {
display: none;
}
.CalcTabs {
background: #f9f9f9 !important;
border-radius: 20px !important;
padding: 15px !important;
}
/*--------------------------------------------------------------
Calculator form slider
--------------------------------------------------------------*/
.slidecontainer {
width: 100%;
}
.slider {
-webkit-appearance: none;
width: 80%;
height: 15px;
border-radius: 5px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider:hover {
opacity: 1;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border-radius: 50%;
background: #01ace4;
cursor: pointer;
}
.slider::-webkit-slider-thumb:hover {
background: #266ee4;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
border-radius: 50%;
background: #01ace4;
cursor: pointer;
}
.slider::-moz-range-thumb:hover {
background: #266ee4;
}
/*--------------------------------------------------------------
Calculator replace default radio button
--------------------------------------------------------------*/
/* Hide the browser's default radio button */
.radio-container {
display: inline-block;
position: relative;
padding-left: 40px;
padding-right: 40px;
margin-top: 12px;
margin-bottom: 12px;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.radio-container input {
position: absolute;
opacity: 0;
cursor: pointer;
}
/*--------------------------------------------------------------
Colors the radio buttons
--------------------------------------------------------------*/
/* Create a custom radio button */
.radio-checkmark {
position: absolute;
top: 0;
left: 10px;
margin-right: 10px;
height: 25px;
width: 25px;
background-color: #d3d3d3;
opacity: 0.7;
border-radius: 50%;
}
/*On mouse-over, add a grey background color */
.radio-container:hover input ~ .radio-checkmark {
background-color: #ccc;
opacity: 1;
}
/*When the radio button is checked, add a blue background */
.radio-container input:checked ~ .radio-checkmark {
background-color: #01ace4;
}
/*When the radio button is checked and hovered, add a dark blue circle */
.radio-container input:checked~.radio-checkmark:hover {
background-color: #266ee4 !important;
opacity: 1;
}
Please click link below to view the calculator on live page:
View calculator on live page
Update as of 20/09/2018 16.48pm (GMT +7)
The code is now too long for this page so I have input this into a JSFiddle and can be viewed here with the Javascript Load type set to Body as advised:
https://jsfiddle.net/Dayley/kfz0w7ud/32/
I could still do with some help on this to clarify why it works great on JSFiddle but not on the live page. I still have not figured this out since 23/07/2018! The code is a simple Copy & Paste from the above link, and with added <script> and </script> before and after the script content. Everything else is exact!
Any helps appreciated!
A:
There have many errors in your code i.e some grammatical and some syntacticals. I have corrected some portions of your code. Please check
function GetTheResults() {
var PoolShape = "Rectangle";
var Volts = parseInt(document.getElementById('Volts').value);
var Amps = parseInt(document.getElementById('Amps').value);
var HoursPumpIsRan = parseInt(document.getElementById('slideRangeHours').value);
var KwhPerDay = (Volts * Amps) / 1000 * HoursPumpIsRan;
var CostPerKwh = parseInt( document.getElementById('CostPerKwh').value);
var CostPerDay = KwhPerDay * CostPerKwh;
var CostPerMonth = CostPerDay * 30;
var CostPerYear = CostPerDay * 365;
var Length = parseInt(document.getElementById('Length').value);
var Width = parseInt(document.getElementById('Width').value);
var Depth = parseInt(document.getElementById('Depth').value);
var RectangleTotalLiters = Length * Width * Depth * 7.48;
var HalfLength = parseInt(document.getElementById('HalfLength').value);
var HalfWidth = parseInt(document.getElementById('HalfWidth').value);
var OvalDepth = parseInt(document.getElementById('OvalDepth').value);
var OvalTotalLiters = HalfLength * HalfWidth * 3.14 * 7.48;
var RoundRadius = parseInt(document.getElementById('RoundRadius').value);
var RoundDepth = parseInt(document.getElementById('RoundDepth').value);
var RoundTotalLiters = RoundRadius * RoundRadius * RoundDepth * 7.48;
var SmallDiameter = parseInt(document.getElementById('SmallDiameter').value);
var LargeDiameter = parseInt(document.getElementById('LargeDiameter').value);
var OblongLength = parseInt(document.getElementById('OblongLength').value);
var OblongTotalLiters = SmallDiameter * LargeDiameter * OblongLength * 3.142 * 7.48;
var FlowRate = parseInt(document.getElementById('FlowRate').value);
var LitersPerHour = FlowRate * 60;
var RectangleTurnoverTime = RectangleTotalLiters / LitersPerHour;
var OvalTurnoverTime = OvalTotalLiters / LitersPerHour;
var RoundTurnoverTime = RoundTotalLiters / LitersPerHour;
var OblongTurnoverTime = OblongTotalLiters / LitersPerHour;
var RectangleTotalTurnovers = 24 / RectangleTurnoverTime;
var OvalTotalTurnovers = 24 / OvalTurnoverTime;
var RoundTotalTurnovers = 24 / RoundTurnoverTime;
var OblongTotalTurnovers = 24 / OblongTurnoverTime;
var StandardPumpSize = parseInt(document.getElementById('StandardPumpSize').value);
var StandardCostPerYear = StandardPumpSize * myHoursRan * CostPerkWh * 365;
var SavingsPerYear = StandardCostPerYear - CostPerYear;
var SavingsPerMonth = SavingsPerYear / 12;
var SavingsPerDay = SavingsPerYear / 365;
var SavingsPercentage = SavingsPerYear / StandardCostPerYear * 100;
/* IF ELSE to define which radio button is selected, and if x is selected then provide the correct output */
console.log(PoolShape);
if (PoolShape == "Rectangle") {
document.getElementById("ResultsTotalLiters").innerHTML = RectangleTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = RectangleTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = RectangleTotalTurnovers;
}
else if (PoolShape == "Oval") {
document.getElementById("ResultsTotalLiters").innerHTML = OvalTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = OvalTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = OvalTotalTurnovers;
}
else if (PoolShape == "Round") {
document.getElementById("ResultsTotalLiters").innerHTML = RoundTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = RoundTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = RoundTotalTurnovers;
}
else if (PoolShape == "Oblong") {
document.getElementById("ResultsTotalLiters").innerHTML = OblongTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = OblongTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = OblongTotalTurnovers;
}
document.getElementById("ResultsLitersPerHour").innerHTML = LitersPerHour;
document.getElementById("ResultsSavingsPerDay").innerHTML = SavingsPerDay;
document.getElementById("ResultsSavingsPerMonth").innerHTML = SavingsPerMonth;
document.getElementById("ResultsSavingsPerYear").innerHTML = SavingsPerYear;
document.getElementById("ResultsSavingsPercentage").innerHTML = SavingsPercentage;
}
/* This sets the PoolShape string from our radio button selections */
function ContainerChange(shape) {
PoolShape = shape;
if (PoolShape == "Rectangle") {
document.getElementById('Rectangle-container').style.display='block';
document.getElementById('Oval-container').style.display='none';
document.getElementById('Round-container').style.display='none';
document.getElementById('Oblong-container').style.display='none';
}
else if (PoolShape == "Oval") {
document.getElementById('Rectangle-container').style.display='none';
document.getElementById('Oval-container').style.display='block';
document.getElementById('Round-container').style.display='none';
document.getElementById('Oblong-container').style.display='none';
}
else if (PoolShape == "Round") {
document.getElementById('Rectangle-container').style.display='none';
document.getElementById('Oval-container').style.display='none';
document.getElementById('Round-container').style.display='block';
document.getElementById('Oblong-container').style.display='none';
}
else if (PoolShape == "Oblong") {
document.getElementById('Rectangle-container').style.display='none';
document.getElementById('Oval-container').style.display='none';
document.getElementById('Round-container').style.display='none';
document.getElementById('Oblong-container').style.display='block';
}
}
/* This updates the Comparison with the Select Onchange from the Dropdown which should be a live comparison in addition to the initial comparison in GetTheResults() */
function UpdateComparisonPump() {
if (PoolShape == "Rectangle") {
document.getElementById("ResultsTotalLiters").innerHTML = RectangleTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = RectangleTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = RectangleTotalTurnovers;
}
else if (PoolShape == "Oval") {
document.getElementById("ResultsTotalLiters").innerHTML = OvalTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = OvalTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = OvalTotalTurnovers;
}
else if (PoolShape == "Round") {
document.getElementById("ResultsTotalLiters").innerHTML = RoundTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = RoundTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = RoundTotalTurnovers;
}
else if (PoolShape == "Oblong") {
document.getElementById("ResultsTotalLiters").innerHTML = OblongTotalLiters;
document.getElementById("ResultsTurnoverTime").innerHTML = OblongTurnoverTime;
document.getElementById("ResultsTotalTurnovers").innerHTML = OblongTotalTurnovers;
}
document.getElementById("ResultsSavingsPerDay").innerHTML = SavingsPerDay;
document.getElementById("ResultsSavingsPerMonth").innerHTML = SavingsPerMonth;
document.getElementById("ResultsSavingsPerYear").innerHTML = SavingsPerYear;
document.getElementById("ResultsSavingsPercentage").innerHTML = SavingsPercentage;
}
/*--------------------------------------------------------------
Only displays the first Tab on load
--------------------------------------------------------------*/
.Calc-Tab-1 {
display:block;
}
/*--------------------------------------------------------------
Hide the other tabs on load
--------------------------------------------------------------*/
.Calc-Tab-2, .Calc-Tab-3 {
display:none;
}
/*--------------------------------------------------------------
Calculator preferences
--------------------------------------------------------------*/
.CalcButtons {
margin-bottom: 1em!important;
}
.CalcHeaders {
margin-top: 1em!important;
}
#Calc-Tab-1, #Calc-Tab-2, #Calc-Tab-3 {
padding: 10px;
}
/*--------------------------------------------------------------
Calculator - Hide Pool Shape Divs
--------------------------------------------------------------*/
#Rectangle-container, #Oval-container, #Round-container, #Oblong-container {
display: none;
}
/*--------------------------------------------------------------
Calculator - Tabs display
--------------------------------------------------------------*/
#Calc-Tab-1, #Calc-Tab-2, #Calc-Tab-3 {
display: none;
}
.CalcTabs {
background: #f9f9f9 !important;
border-radius: 20px !important;
padding: 15px !important;
}
/*--------------------------------------------------------------
Calculator form slider
--------------------------------------------------------------*/
.slidecontainer {
width: 100%;
}
.slider {
-webkit-appearance: none;
width: 80%;
height: 15px;
border-radius: 5px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider:hover {
opacity: 1;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border-radius: 50%;
background: #01ace4;
cursor: pointer;
}
.slider::-webkit-slider-thumb:hover {
background: #266ee4;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
border-radius: 50%;
background: #01ace4;
cursor: pointer;
}
.slider::-moz-range-thumb:hover {
background: #266ee4;
}
/*--------------------------------------------------------------
Calculator replace default radio button
--------------------------------------------------------------*/
/* Hide the browser's default radio button */
.radio-container {
display: inline-block;
position: relative;
padding-left: 40px;
padding-right: 40px;
margin-top: 12px;
margin-bottom: 12px;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.radio-container input {
position: absolute;
opacity: 0;
cursor: pointer;
}
/*--------------------------------------------------------------
Colors the radio buttons
--------------------------------------------------------------*/
/* Create a custom radio button */
.radio-checkmark {
position: absolute;
top: 0;
left: 10px;
margin-right: 10px;
height: 25px;
width: 25px;
background-color: #d3d3d3;
opacity: 0.7;
border-radius: 50%;
}
/*On mouse-over, add a grey background color */
.radio-container:hover input ~ .radio-checkmark {
background-color: #ccc;
opacity: 1;
}
/*When the radio button is checked, add a blue background */
.radio-container input:checked ~ .radio-checkmark {
background-color: #01ace4;
}
/*When the radio button is checked and hovered, add a dark blue circle */
.radio-container input:checked~.radio-checkmark:hover {
background-color: #266ee4 !important;
opacity: 1;
}
<div id="Calc-Tab-1" class="CalcTabs" style="display:block;">
<span> What is the shape of your pool:
<label class="radio-container">
<input onchange="ContainerChange('Rectangle');" type="radio" name="radio" id="RectangleCheck" checked="checked">
<span class="radio-checkmark"></span>Rectangle </label>
<label class="radio-container">
<input onchange="ContainerChange('Oval');" type="radio" name="radio" id="OvalCheck">
<span class="radio-checkmark"></span>Oval</label>
<label class="radio-container">
<input onchange="ContainerChange('Round');" type="radio" name="radio" id="RoundCheck">
<span class="radio-checkmark"></span>Round</label>
<label class="radio-container">
<input onchange="ContainerChange('Oblong');" type="radio" name="radio" id="OblongCheck">
<span class="radio-checkmark"></span>Custom Oblong</label>
</span>
<div id="Rectangle-container" style="display:block;"> Length of your pool in feet:
<input type="number" class="tabinput" id="Length" min="1">
Width of your pool in feet:
<input type="number" class="tabinput" id="Width" min="1">
Depth of your pool in feet:
<input type="number" class="tabinput" id="Depth" min="1">
</div>
<div id="Oval-container"> Half the length of your pool in feet:
<input type="number" class="tabinput" id="HalfLength" min="1">
Half the width of your pool in feet:
<input type="number" class="tabinput" id="HalfWidth" min="1">
Depth of your pool in feet:
<input type="number" class="tabinput" id="OvalDepth" min="1">
</div>
<div id="Round-container"> Radius of your pool in feet:
<input type="number" class="tabinput" id="RoundRadius" min="1">
Depth of your pool in feet:
<input type="number" class="tabinput" id="RoundDepth" min="1">
</div>
<div id="Oblong-container"> Small diameter of your pool in feet:
<input type="number" class="tabinput" id="SmallDiameter" min="1">
Large diameter of your pool in feet:
<input type="number" class="tabinput" id="LargeDiameter" min="1">
Length of your pool in feet:
<input type="number" class="tabinput" id="OblongLength" min="1">
</div>
<input type="button" class="CalcButtons" onclick="document.getElementById('Calc-Tab-1').style.display='none';document.getElementById('Calc-Tab-2').style.display='block';" value="Next">
</div>
<div id="Calc-Tab-2" class="CalcTabs">
<h3 class="CalcHeaders">Energy Consumption</h3>
<span>What are the voltage, ampage and kilowatt per hour of your pump?</span> Volts:
<input type="number" class="tabinput" id="Volts" min="1">
Amps:
<input type="number" class="tabinput" id="Amps" min="1">
Cost per kWh:
<input type="number" class="tabinput" id="CostPerKwh" min="1">
<span>How many hours do you run your pump for: <span class="slideOutputValueHours" id="myHoursRan">7</span> Hours
<input type="range" class="slideInputValueHours slider" id="slideRangeHours" value="7" min="1" max="24" step="1" oninput="myHoursPumpIsRunFunction()">
<input type="button" class="CalcButtons" onclick="document.getElementById('Calc-Tab-2').style.display='none';document.getElementById('Calc-Tab-1').style.display='block';" value="Previous">
<input type="button" class="CalcButtons" onclick="GetTheResults();" value="Calculate Results">
</div>
<div id="Calc-Tab-3" class="CalcTabs">
<h3 class="CalcHeaders">Results & Savings</h3>
<strong>Your pools total expenditures</strong> Total kWh per day: <span id="ResultsKwhPerDay"></span> KWh per day
Total Cost per day: <span id="ResultsCostPerDay"></span> Thai Baht
Total Cost per month: <span id="ResultsCostPerMonth"></span> Thai Baht based on 30 days
Total Cost per year: <span id="ResultsCostPerYear"></span> Thai Baht per year <strong>The amount of liters in your pool</strong> Total liters in your pool: <span id="ResultsTotalLiters"></span> Liters <strong>The run-time of your pool</strong> Liters per hour: <span id="ResultsLitersPerHour"></span> Per hour
Time to complete 1 turnover: <span id="ResultsTurnoverTime"></span> Hour
Total turnovers per 24 hour: <span id="ResultsTotalTurnovers"></span> Turnovers <strong>And here are your savings compared to a
<select id="StandardPumpSize" onchange="UpdateComparisonPump()">
<option value="1.26">.75hp standard pump</option>
<option value="1.72">1hp standard pump</option>
<option value="2.14">1.5hp standard pump</option>
<option selected value="2.25">2hp standard pump</option>
<option value="2.62">2.5hp standard pump</option>
<option value="3.17">3hp standard pump</option>
<option value="3.5">3.5hp standard pump</option>
<option value="4">4hp standard pump</option>
<option value="4.5">4.5hp standard pump</option>
<option value="5">5hp standard pump</option>
<option value="5.5">5.5hp standard pump</option>
<option value="1">variable speed pump</option>
</select>
</strong> Savings per day: <span id="ResultsSavingsPerDay"></span> Thai Baht
Savings per month: <span id="ResultsSavingsPerMonth"></span> Thai Baht
Savings per year: <span id="ResultsSavingsPerYear"></span> Thai Baht
Percentage saved per year: <span id="ResultsSavingsPercentage"></span>% Saved! </div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Reduce bit-depth of PNG files from the command line
What command or series of commands could I execute from the CLI to recursively traverse a directory tree and reduce the bit-depth of all PNG files within that tree from 24bpp to 16bpp? Commands should preserve the alpha layer and should not increase the file size of the PNGs - in fact a decrease would be preferable.
I have an OSX based system at my disposal and am familiar with the find command so am really more keen to to locate a suitable PNG utility command.
A:
Install fink
Say "fink install imagemagick" (might be "ImageMagick")
"convert -depth 16 old/foo.png new/foo.png"
If that did what you want, wrap it in a find call and be happy. If not, say "convert -help" and RTF-ImageMagick-M. :)
Optional: "fink install pngcrush" and run that as a second pass after the convert pass.
A:
AFAIK the only PNG format that supports the alpha layer is PNG-24; Reducing the PNG to another format may require specifying a transparent color in a CLUT, which will not give you the output you want.
From the feature list on PNG's website:
8- and 16-bit-per-sample (that is, 24- and 48-bit) truecolor support
full alpha transparency in 8- and 16-bit modes, not just simple on-off transparency like GIF
... which I read to mean that anything other than PNG-24 or PNG-48 does not support full alpha transparency.
| {
"pile_set_name": "StackExchange"
} |
Q:
ASP.NET MVC and ADO.NET Entity Framework
I have a problem that I cannot solve without some advice. I'm developing an ASP.NET MVC application and I'm using ADO.NET EF to connect to the database. My problem is that I don't know if business logic of my app should use entities created by EF or should I create one more abstraction layer and separate EF entities from my business logic objects (and develop some converters between those object types). Or maybe I'm totally wrong and I should do it differently? How? Which solution would be best practice?
A:
This absolutely depends on your application, its scope and its requirements. Introducing abstraction layers just for layers' sake means introducing complexity and indirection, where often it doesn't really get you anywhere. For the overuse of layered architecture the term Lasagna Software is currently being introduced - replacing the infamous Spaghetti Software.
To make this clear, I'm not proposing against abstraction layers. Using them just highly depends on your specific requirements.
I'd start with a simple architecture and add layers as required to ensure testability and maintainability. The current version Entity Framework (4.1 as of this writing) allows working with POCOs and the DbContext pretty much resembles the Repository and Unit of Work patterns. These out-of-the-box features might be sufficient for a start in most cases.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to return a C-style array of integers in Objective-C?
How to return a C-style array of integers from an Objective-C method? This is what my code looks like so far:
Function call:
maze = [amaze getMaze];
Function:
-(int*) getMaze{
return maze;
}
I just started writing in Objective-C today so this is all new to me.
A:
In C if you need to return an array from a function, you need to allocate memory for it using malloc and then return the pointer pointing to the newly allocated memory.
Once you're done working with this memory you need to free it.
Something like:
#include <stdlib.h> /* need this include at top for malloc and free */
int* foo(int size)
{
int* out = malloc(sizeof(int) * size); /* need to get the size of the int type and multiply it
* by the number of integers we would like to return */
return out; /* returning pointer to the function calling foo().
* Don't forget to free the memory allocated with malloc */
}
int main()
{
... /* some code here */
int* int_ptr = foo(25); /* int_ptr now points to the memory allocated in foo */
... /* some more code */
free(int_ptr); /* we're done with this, let's free it */
...
return 0;
}
This is as C style as it gets :) There are probably other (arguably more suitable) ways to do this in Objective C. However, as Objective C is considered a strict superset of C, this would also work.
If I may further expand on the need to do this by pointers. C-style arrays allocated in a function are considered local, once the function is out of scope they are automatically cleaned up.
As pointed out by another poster, returning a standard array (e.g. int arr[10];) from a function is a bad idea as by the time the array is returned it no longer exists.
In C we get around this problem by allocating memory dynamically using malloc and having a pointer that points to that memory returned.
However unless you free this memory adequately, you may introduce a memory leak or some other nasty behavior (e.g. free-ing a malloc-ed pointer twice will produce unwanted results).
A:
Given you explicitly ask about C-style arrays no suggestions here that you should use NSArray etc.
You cannot return a C-style array directly (see below) as a value in Objective-C (or C or C++), you can return a reference to such an array.
Types such as int, double and struct x can all be passed by value - that is the actual bits representing the value are passed around. Other things; such as C-style arrays, dynamically allocated memory, Objective-C style objects, etc.; are all passed by reference - that is a reference to a location in memory that contains the actual bits the represent the value is passed around.
So to return a C-style array from a function/method you can:
Dynamically (malloc et al) an array and return the reference to the allocated memory;
Pass in a reference to an already existing array and have the function fill it up; or
Wrap the array up as a struct...
The normal choices are (1) or (2) - note you cannot return a reference to a stack allocated array, as in:
int *thisIsInvalid()
{
int myValues[5];
...
return myValues; // will not work, the type is correct but once function
// returns myValues no longer exists.
}
If you really want to return a (small) array by value you can actually do it using (3). Remember that struct values are passed by value. So the following will work:
typedef struct
{
int array[5];
} fiveInts;
fiveInts thisIsValid()
{
fiveInts myValues;
...
myValues.array[3] = ...; // etc.
...
return myValues;
}
(Note that there is no overhead from wrapping the array inside a struct when it comes to reading/writing the array - the cost in the above is copying all the values back - hence only advised for small arrays!)
HTH
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery cross browser opacity (fadeTo) IE 7 & 8 png
I know this topic has been addressed several times here, however my problem is different (or possibly I missed it somewhere?).
My issue is that I need a cross browser way to set opacity and have it not show a black background on the transparent pngs (IE7 and 8).
Several here suggested:
$(this).fadeTo(0, 0.5);
however like I said above.. it displays black on the png.
Thanks.
A:
I don't think this has anything to do with fadeTo, which is about the overall opacity of an element. Basically, what you have to do is get IE to understand the alpha channel of PNGs at all so it understands the bits that should be transparent, which requires some IE-specific CSS:
img {
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(...);
}
Details (just a couple of links; but if you search for "IE" "png" "transparency" you'll find a huge amount of information):
MS KB#294714
Transparent PNGs in IE6 (applies to later versions as well)
| {
"pile_set_name": "StackExchange"
} |
Q:
Are all HTML elements unique?
I was busy making a JavaScript code that allows me to make GUI page elements to have custom context menus, when I thought about checking to see if an element exists in order to make a context menu for it.
function element_exists(el){
var tagName=el.tagName;
var exists=0;
for(var a=0;a<document.getElementsByTagName(tagName).length;a++){
if(document.getElementsByTagName(tagName)[a]==el){
exists=1;
}
}
return exists;
}
In this code, I pass a reference to a DOM element object (which is stored from earlier).
Let's say that it was stored, but since then I removed the element itself from the document.
I'm using Chrome Canary, and even if I edit the page through the console and make a new element with the exact same tag name and ID, it returns false. Would it return true if it had the same innerText and innerHTML?
If not, is this a standard in all web browsers (old and new)?
Just curious because I could eliminate some unnecessary code if they're all unique.
A:
I'm pretty sure the answer is no; each element is unique, regardless of whether they have similar values (including "id").
This might provide you some insight into how element garbage collection works in Chrome. I'm not sure how the other browsers respond though.
http://www.html5rocks.com/en/tutorials/memory/effectivemanagement/
It outlines some tools that might be useful to test your theory.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fibonacci in python cant run the code receiving syntax error or other
enter image description hereIm try to run this code to get fibonacci numbers in range 1-11
def fibonacci(n):
if n == 1 or n == 2
return 1
return fibonacci(n-1) + fibonacci(n-2)
for i in range (1, 11):
print(fibonacci(i))
but im getting :
**Traceback (most recent call last):
File "python", line 2
if n == 1 or n ==2
^
SyntaxError: invalid syntax**
In this video tutorial the guy doing the same-thing and getting result
i dont understand - https://www.youtube.com/watch?v=Cz476EsH1Lc&t=3s 3:10
version is 2.7.6
Now im getting :
IndentationError: expected an indented block - solved
Now im trying to print only the value of fibonacci = 11 and it's failing i get no result
def fibonacci (n) :
if n == 1 or n ==2:
return 1
return fibonacci (n-1) + fibonacci(n-2)
print (fibonacci (11))
A:
If you've copied your code exactly (besides formatting – indentation is very important in python) then the problem is the missing : after n==2.
It should look something like this:
def fibonacci (n):
if n == 1 or n == 2: # the colon is missing here.
return 1
return fibonacci(n-1) + fibonacci(n-2)
...
A:
Your error is stating that you missed : in the if statement. Also your indentation is not correct.
if n == 1 or n ==2: # focus on ':' at the end.
| {
"pile_set_name": "StackExchange"
} |
Q:
android-if condition doesn't work
I have an android application and I have two EditTexts.
The user inputs 'distance' and 'time.
I made an if statement to show an error message if the user didn't filled one of the two inputs:
String strDistance,strTime;
strDistance=edtDistance.getText().toString();
strTime=edtTime.getText().toString();
if(strDistance==null||strTime==null){
txtError.setText("Please insert the distance and time");
}
else{
calculateLogic();
app.setFare(fare);
Intent intent=new Intent(MainActivity.this,Fare.class);
startActivity(intent);
}
It works fine if I filled the two inputs.
But when I fill only one of them, the application stops working (I don't get my error message)...
A:
Try following this one:-
if(strDistance.equals("")||strTime.equals("") {
txtError.setText("Please insert the distance and time");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Matching across Multiple documents with ElasticSearch
I am relatively new to ElasticSearch. I am using it as a search platform for pdf documents. I break the PDFs into text-pages and enter each one as an elasticSearch record with it's corresponding page ID, parent info, etc.
What I'm finding difficult is matching a given query not only to a single document in ES, but making it match any document with the same parent ID. So if two terms are searched, if the terms existed on page 1 and 7 of the actual PDF document (2 separate entries into ES), I want to match this result.
Essentially my goal is to be able to search through the multiple pages of a single PDF, matching happening on any of the document-pages in the PDF, and to return a list of matching PDF documents for the search result, instead of matching "pages"
A:
It's somewhat tricky. First of all, you will have to split your query into terms yourself. Having a list of terms (let's say foo, bar and baz, you can create a bool query against type representing PDFs (parent type) that would look like this:
{
"bool" : {
"must" : [{
"has_child" : {
"type": "page",
"query": {
"match": {
"page_body": "foo"
}
}
}
}, {
"has_child" : {
"type": "page",
"query": {
"match": {
"page_body": "bar"
}
}
}
}, {
"has_child" : {
"type": "page",
"query": {
"match": {
"page_body": "baz"
}
}
}
}]
}
}
This query will find you all PDFs that contain at least one page with each term.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery autocomplete UI Widget- Perform jQuery select event on dynamically created table row element
I have a working jQuery autocomplete being performed on the text input of a table data element, txtRow1. The text data is remote, from a mysql database, and is returned by JSON as 'value' for the text input. The returned data includes another piece of text, which, via a select event within the autocomplete, is populated to the adjacent table data element tickerRow1.
With help from the SO community, the autocomplete is now live and working on all text input elements of a dynamically created table (so txtRow1 to txtRowN). There is javascript code to create and name the table elements txtRoxN + 1 and tickerRowN + 1.
However, I have a problem with the select event for the id of tickerRowN. Because it changes every time I add a row, I don't know how to call the select event for the specific id of the table data in question.
I have done a lot of searching around but as I am new to this, the only functions I have been able to find manipulate the element data when you know the id already. This id is dynamically created and so I don't know how to build the syntax.
Thankyou for your time.
UPDATE: with huge thanks to JK, the following example works. I now know about jsFiddle and will try to use this for all further questions. The following code works for my dynamic example, but I don't know why. Sigh.
jsFiddle working example
A:
function getRowId(acInput){
//set prefix, get row number
var rowPrefix = 'txtRow';
var rowNum = acInput.attr("id").substring((rowPrefix.length));
return rowNum;
}
$("#txtRow1").autocomplete({
source: states,
minLength: 2,
select: function(event, ui) {
var tickerRow = "#tickerRow" + getRowId($(this));
//set ticker input
$(tickerRow).val(ui.item.label);
}
});
http://jsfiddle.net/jensbits/BjqNz/
| {
"pile_set_name": "StackExchange"
} |
Q:
Handling frequent database writes triggered by asp.net page
I need to store some data in a SQL Server database every time someone opens or refreshes a page of a website made in asp.net.
Should I try to buffer the inserts, writing them to the DB all together every X time, or is it acceptable to write them one by one?
I know I should provide some data about how many views I expect but the one who is supposed to tell me this has no idea... Here I'm just asking if there's any kind of best practice about handling frequent writes to a DB from an asp site. It's not a problem (logic wise) if the information insertion is delayed.
A:
Personally, but I don't think this is merely opinion, I would start off doing what was simplest and seemed most natural, without worrying about optimizations.
So if the server side page render event (probably not the actual event name) seems like a natural place to insert some records I would do just that.
If you're doing this on multiple pages then you might want to centralize the inserts using some sort of filter that all requests pass through (probably not the right term for asp.net either, but you get the idea).
Later on, if it turns out that doing this is introducing an unacceptable amount of latency, you can introduce some asynchronous way to update the database, perhaps a message queue or some of the c# ansync constructs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mean Independence and uncorrelated vs independence
If we are given 2 RV's X and Y and find that they are both mean independent and uncorrelated, is it suffice to say that they are independent or are they any situations that this is not true? (Given that their expectations exist)
A:
The standard counterexample for "uncorrelated normals are not necessarily independent" works. Let $X$ be $N(0,1)$ and $Z$ be an independent coinflip $\pm 1,$ and let $Y=XZ.$ $X$ and $Y$ are mean-independent: $$E(X\mid Y) = E(Y\mid X) = E(X)=E(Y)=0.$$ (For instance $E(Y\mid X) = XP(Z=1)+(-X)P(Z=-1) = 0.)$
But they are not independent, since, e.g. $E(|Y|\mid X) = X$ which is generally not equal to $E(|Y|).$
| {
"pile_set_name": "StackExchange"
} |
Q:
Basic concept/principle of ECommerce Site
Is there any short tutorial which explain the basic principles/concept and Database design of an Ecommerce Website?
A:
Are you looking for a technical solution for building an Ecommerce Website ? I'd advise you to use a builtin solution designed for this purpose, here are some best-of :
http://woork.blogspot.com/2009/01/8-interesting-cms-for-e-commerce.html
http://www.ilovecolors.com.ar/ecommerce-cms-open-source-commercial/
(if you choose to use Joomla!) http://www.web3mantra.com/2011/01/24/20-joomla-ecommerce-templates/
Were you looking for tips ?
http://uxdesign.smashingmagazine.com/2009/10/08/15-common-mistakes-in-e-commerce-design-and-how-to-avoid-them/
Regards,
Max
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if MotionEvent.ACTION_UP is out of the imageview
The user will touch a image and it is important that if he left his finger up in that image or not
i tried with writing a onTouchListner() and after that using swich case but i don't know how to continue
image.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
}
return true;
}
});
thank's in advance
A:
I found my answer through this link but i change it to this:
private Rect rect; // Variable rect to hold the bounds of the view
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) {
// User moved outside bounds
}
break;
case MotionEvent.ACTION_DOWN:
rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
break;
}
return false;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Mathematica Dashing "Up and down"
Is there any reason that underlies mathematica's way of presenting this graph
ListPlot[
Table[{x, x*01}, {x, -5, 5, .08}],
PlotStyle -> White,
Filling -> 0,
FillingStyle -> {Dashed, Brown}]
While the dashing is present for the part of the graph above the zero boundary, another part of the graph has the filling that is solid.
Am I doing something wrong?
A:
Not that wrong. Mathematica is interpreting your filling style as being Dashed below zero and Brown above. You just need another pair of braces, like so:
ListPlot[Table[{x, x*01}, {x, -5, 5, .08}], PlotStyle -> White,
Filling -> 0, FillingStyle -> {{Dashed, Brown}}]
Hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
captureOutput function isn't called using setSampleBufferDelegate
I'm starting to develop an iOS app and this is my first SO post. I'm trying to implement a UI view which can show the preview video of the rear camera and process the captured frames. My preview layer works perfectly and I can see the picture display in my UI view. However, the captureOutput function is never called.
I have searched online for silimar issues and solutions for a while and tried to tweak different things including the output, connection, and dispatch queue settings, but none has worked. Can anyone help me out or share some insights and directions? Thanks a lot in advance!
Here is my code, I'm using Xcode 11 beta with iOS 10 as build target.
class ThreeDScanningViewController: UIViewController,
AVCaptureVideoDataOutputSampleBufferDelegate {
@IBOutlet weak var imageView: UIImageView!
var session : AVCaptureSession!
var device : AVCaptureDevice!
var output : AVCaptureVideoDataOutput!
var previewLayer : AVCaptureVideoPreviewLayer!
override func viewDidLoad() {
super.viewDidLoad()
//NotificationCenter.default.addObserver(self, selector: #selector(self.startedNotif), name: NSNotification.name.CaptureSessionDidStartRunningNotification, object: nil)
func initCamera() -> Bool {
session = AVCaptureSession()
session.sessionPreset = AVCaptureSession.Preset.medium
let devices = AVCaptureDevice.devices()
for d in devices {
if ((d as AnyObject).position == AVCaptureDevice.Position.back) {
device = d as! AVCaptureDevice
}
}
if device == nil {
return false
}
do {
// Set up the input
let input : AVCaptureDeviceInput!
try input = AVCaptureDeviceInput(device: device)
if session.canAddInput(input) {
session.addInput(input)
} else {
return false
}
// Set up the device
try device.lockForConfiguration()
device.activeVideoMinFrameDuration = CMTimeMake(1, 15)
device.unlockForConfiguration()
// Set up the preview layer
previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer.frame = imageView.bounds
imageView.layer.addSublayer(previewLayer)
// Set up the output
output = AVCaptureVideoDataOutput()
output.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString) as String: kCVPixelFormatType_32BGRA]
let queue = DispatchQueue(label: "myqueue")
output!.setSampleBufferDelegate(self, queue: queue)
output.alwaysDiscardsLateVideoFrames = true
if session.canAddOutput(output) {
session.addOutput(output)
} else {
return false
}
for connection in output.connections {
if let conn = connection as? AVCaptureConnection {
if conn.isVideoOrientationSupported {
conn.videoOrientation = AVCaptureVideoOrientation.portrait
}
}
}
session.startRunning()
} catch let error as NSError {
print(error)
return false
}
return true
}
func captureOutput (captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
print("captureOutput!\n");
DispatchQueue.main.async(execute: {
// Do stuff
})
}
}
Here are some links I've looked into, none is relevant to solve my issue:
AVCaptureVideoDataOutput captureOutput not being called
ios capturing image using AVFramework
AVCaptureDeviceOutput not calling delegate method captureOutput
iOS: captureOutput:didOutputSampleBuffer:fromConnection is NOT called
didOutputSampleBuffer delegate not called
A:
I have finally managed to find the cause of the issue. You need to make sure to use the correct function signature for the captureOutput function for the Swift 3 syntax.
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection)
NOT
func captureOutput(_ output: AVCaptureOutput, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection)
I was using older version of the Swift syntax and the compiler did not warn me of the issue! After correcting the function signatures, the captureOutput function gets called beautifully:-)
A:
From Swift 4:
func captureOutput(_ captureOutput: AVCaptureOutput!,
didOutputMetadataObjects metadataObjects: [Any]!, from connection:
AVCaptureConnection!)
won't be called as it no longer exists.
It has been changed to the following :
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection)
A:
If previous answers cannot solve your problem for swift 4 and newer, correct the function name by add public can fix the problem.
public func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {}
| {
"pile_set_name": "StackExchange"
} |
Q:
Mysql not selecting null values
I have the following query:
SELECT * FROM table
WHERE orderdate >= "2015-12-01"
AND orderdate <= "2015-12-31"
AND values > 0
AND orders <> 'Returned'
The problem is that the query doesn't return the rows where the orders column is NULL and I can't figure out why.
A:
This is the sql language. Mysql doesn't consider NULL as value. So if you want to include NULL we must specify that.
SELECT * FROM table
WHERE orderdate >= "2015-12-01"
AND orderdate <= "2015-12-31"
AND values > 0
AND (orders <> 'Returned' or orders is null)
| {
"pile_set_name": "StackExchange"
} |
Q:
how to validate array two dimensional in laravel
hy.. I have using laravel 4 and my quetion
how I can validate input array two dimensional
for ex in my view :
<input type="text" name="result_test[numeric][]">
<input type="text" name="result_test[non_numeric][]">
A:
in controller :
$this->validate([
'result_test.numeric' => 'validation|rules'
]);
same in request
$rules = [
'result_test.numeric' => 'validation|rules'
]
not shure about laravel 4 , but in laravel 5 + it works like this
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting NoClassDefFoundError while using JGit in eclipse luna
I recently download eclipse luna and installed the EGit plugin through Eclipse. I can see the download jar files in eclipse/plugins folder. I then added the JGit jar file to my build path and I can see the class files inside my Referenced Libraries folder.
However, when I run the project I get the following error
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.eclipse.jgit.util.FS.<clinit>(FS.java:112)
at org.eclipse.jgit.lib.BaseRepositoryBuilder.setupWorkTree(BaseRepositoryBuilder.java:620)
at org.eclipse.jgit.lib.BaseRepositoryBuilder.setup(BaseRepositoryBuilder.java:556)
at org.eclipse.jgit.storage.file.FileRepositoryBuilder.build(FileRepositoryBuilder.java:92)
at org.eclipse.jgit.storage.file.FileRepositoryBuilder.create(FileRepositoryBuilder.java:110)
at upload_gen.Launcher.main(Launcher.java:16)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 6 more
I googled the problem which said that it might be because my classpath doesn't include the jar file. But when I check the the classpath tab in "run | run configuration" it seems to be including the jar file. I also checked the .classpath file in the root folder which looks like this
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry exported="true" kind="lib" path="lib/org.eclipse.jgit_3.7.0.201502260915-r.jar"/>
<classpathentry kind="var" path="JGIT_JARS"/>
<classpathentry kind="output" path="bin"/>
</classpath>
I also tried adding the JGit jar file in the lib folder in the root of my project as you can see in the above .classpath file.
In short, I tried adding the jar file externally as well as internally but I'm still getting the error. I also tried referencing the jar file using a class variable but that doesn't work either. Also there are no errors while compiling the project, getting error only when the project is run.
A:
You probably need to add a slf4j jar to the libraries in Eclipse.
| {
"pile_set_name": "StackExchange"
} |
Q:
The downvote issue and the stupid rivalry
I asked a question recently, and found that most of the people viewing the question are really appreciating the question. Even the answer is well written and got some votes.
I was quite surprised to find out that someone came and downvoted the question and the best answer in quick succession for no reason - he thinks he's smart and may know everything. Is there any way to find out these smarties?
A:
There are people out there who don't like homework-type questions. They will probably down-vote such questions, even if you observe that it is generally well received by the community. That is how the system works.
Voting is nothing personal, it is about the content. Don't take (make) it personal.
There is no way to find out who voted how; and there shouldn't be. Users are encouraged to leave a comment when down-voting, but it is not mandatory.
I enjoy being able to down-vote posts I don't care for without worrying about retaliation. And I really enjoy being able to leave honest comments without worrying that they'll be justifiably interpreted as evidence that I've down-voted. I would not like to see the two systems linked. – Shog9♦ Jun 28 '09 at 19:36
This system has (more or less and with a few bumps) worked for quite some time now. There have been multiple (attempts at) changes over the years. I welcome you to explore meta.se and perhaps post your suggestions there.
Over the time there also have been multiple posts of users who are unhappy with down-votes. Most of them use language which is not really appreciative of our be nice policy. Maybe you would like to check your post, if there was any way to improve upon its wording.
Please always keep in mind that each and everyone is offering their free time on this site. Treat people with respect, do what you would expect other users to do, and view posts objectively as content and not a s opinions. If you're nice you will be helped and welcomed, if you're rubbing users the wrong way, you will be ignored.
| {
"pile_set_name": "StackExchange"
} |
Q:
Could not load 'active_record/connection_adapters/sqlite3_adapter'. in win7 64bit
Ruby version:ruby 2.1.3p242 (2014-09-19 revision 47630) [x64-mingw32]
Rails version:Rails 4.1.6
Windows :win7 64bit
sqlite3-1.3.9-x64-mingw32.gemspec has changed to s.require_paths= ["lib/sqlite3_native"]
sqlite3.dll in Ruby/Bin,and Gemfile's sqlite3 version is same as Gemfile.lock's,rails server is ok,but when visit the website it returns this error:
Could not load 'active_record/connection_adapters/sqlite3_adapter'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.
infos:
activesupport (4.1.6) lib/active_support/dependencies.rb:247:in require'
activesupport (4.1.6) lib/active_support/dependencies.rb:247:inblock in require'
activesupport (4.1.6) lib/active_support/dependencies.rb:232:in load_dependency'
activesupport (4.1.6) lib/active_support/dependencies.rb:247:inrequire'
activerecord (4.1.6) lib/active_record/connection_adapters/sqlite3_adapter.rbin <top (required)>'
activesupport (4.1.6) lib/active_support/dependencies.rb:247:inrequire'
activesupport (4.1.6) lib/active_support/dependencies.rb:247:in block in require'
activesupport (4.1.6) lib/active_support/dependencies.rb:232:inload_dependency'
activesupport (4.1.6) lib/active_support/dependencies.rb:247:in require'
activerecord (4.1.6) lib/active_record/connection_adapters/connection_specification.rb:188:inspec'
activerecord (4.1.6) lib/active_record/connection_handling.rb:50:in establish_connection'
activerecord (4.1.6) lib/active_record/railtie.rb:129:inblock (2 levels) in class:Railtie'
activesupport (4.1.6) lib/active_support/lazy_load_hooks.rb:38:in instance_eval'
activesupport (4.1.6) lib/active_support/lazy_load_hooks.rb:38:inexecute_hook'
activesupport (4.1.6) lib/active_support/lazy_load_hooks.rb:45:in block in run_load_hooks'
activesupport (4.1.6) lib/active_support/lazy_load_hooks.rb:44:ineach'
activesupport (4.1.6) lib/active_support/lazy_load_hooks.rb:44:in run_load_hooks'
activerecord (4.1.6) lib/active_record/base.rb:326:inmodule:ActiveRecord'
activerecord (4.1.6) lib/active_record/base.rb:23:in <top (required)>'
activerecord (4.1.6) lib/active_record/connection_adapters/abstract/connection_pool.rb:628:inrescue in call'
activerecord (4.1.6) lib/active_record/connection_adapters/abstract/connection_pool.rb:619:in call'
activerecord (4.1.6) lib/active_record/migration.rb:380:incall'
actionpack (4.1.6) lib/action_dispatch/middleware/callbacks.rb:29:in block in call'
activesupport (4.1.6) lib/active_support/callbacks.rb:82:inrun_callbacks'
actionpack (4.1.6) lib/action_dispatch/middleware/callbacks.rb:27:in call'
actionpack (4.1.6) lib/action_dispatch/middleware/reloader.rb:73:incall'
actionpack (4.1.6) lib/action_dispatch/middleware/remote_ip.rb:76:in call'
actionpack (4.1.6) lib/action_dispatch/middleware/debug_exceptions.rb:17:incall'
actionpack (4.1.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in call'
railties (4.1.6) lib/rails/rack/logger.rb:38:incall_app'
railties (4.1.6) lib/rails/rack/logger.rb:20:in block in call'
activesupport (4.1.6) lib/active_support/tagged_logging.rb:68:inblock in tagged'
activesupport (4.1.6) lib/active_support/tagged_logging.rb:26:in tagged'
activesupport (4.1.6) lib/active_support/tagged_logging.rb:68:intagged'
railties (4.1.6) lib/rails/rack/logger.rb:20:in call'
actionpack (4.1.6) lib/action_dispatch/middleware/request_id.rb:21:incall'
rack (1.5.2) lib/rack/methodoverride.rb:21:in call'
rack (1.5.2) lib/rack/runtime.rb:17:incall'
activesupport (4.1.6) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in call'
rack (1.5.2) lib/rack/lock.rb:17:incall'
actionpack (4.1.6) lib/action_dispatch/middleware/static.rb:64:in call'
rack (1.5.2) lib/rack/sendfile.rb:112:incall'
railties (4.1.6) lib/rails/engine.rb:514:in call'
railties (4.1.6) lib/rails/application.rb:144:incall'
rack (1.5.2) lib/rack/lock.rb:17:in call'
rack (1.5.2) lib/rack/content_length.rb:14:incall'
rack (1.5.2) lib/rack/handler/webrick.rb:60:in service'
E:/Tool/Ruby21-x64/lib/ruby/2.1.0/webrick/httpserver.rb:138:inservice'
E:/Tool/Ruby21-x64/lib/ruby/2.1.0/webrick/httpserver.rb:94:in run'
E:/Tool/Ruby21-x64/lib/ruby/2.1.0/webrick/server.rb:295:inblock in start_thread'
A:
My resolution (Win7 x64) was to uninstall all unnecessary versions of sqlite3. I had 1.3.9, 1.3.10 and 1.3.11 installed, so I removed .9 and .10 and updated my gemfile to use .11.
gem uninstall sqlite3
bundle install
With 1.3.11 I did not need to apply the s.require_paths=["lib/sqlite3_native"] hack that you mentioned.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamically assigning var to json
I have a variable var locations in a .ts file and wish to have this equal to a json object in the same folder. In other words the .json file changes every 5 seconds an I need the variable to update. I assume that he rxjs observable is they way to go. I have tried
ngOnInit() {
timer(0, 7000).pipe(
switchMap( _ => this.hawkerservice.fetchNews()
)).pipe(
map((ret:any) => {
this.locations = ret
})
).subscribe();
}
Now this works well except .fetchNews() pull is over a port with:
export class MapjsonService{
theUrl = 'http://localhost:8000/locations.json';
constructor(private http: HttpClient) { }
fetchNews(): Observable<any>{
return this.http.get(this.theUrl)
}
}
So my question is what is the best way to do this without passing the json object over a port. Namely, just getting it locally.
thx
A:
Well it is as simple as that. Your file is just another resource, which is hosted either locally or on server. You indeed need http to access it, because it is hosted.
Contradicting to your point, you can not simply run your application also without using http, even though it is hosted locally. Same is applicable for json file aswell.
You need http to access the file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Lifting a computation from the State monad into the RWS monad
I structure a computation around the use of the RWS (Reader+Writer+State) monad:
newtype Problem a = Problem { unProblem :: RWS MyEnv MyLog MyState a }
deriving ({- lots of typeclasses -})
The computation is built step by step by assembling elementary computations of the form
foo :: a -> Problem b
Sometimes, however, the subcomputations do not need the full power of the RWS monad. For instance, consider
bar :: c -> State MyState d
I would like to use bar as a part of a larger computation in the context of the Problem monad. I can see three ways of doing this, none of which seems very elegant to me.
Manually unwrap the the State computation and rewrap it in the RWS monad:
baz :: a -> RWS MyEnv MyLog MyState c
baz x = do temp <- foo x
initialState <- get
let (finalResult, finalState) = runState (bar temp) initialState
put finalState
return finalResult
Modify the type signature of bar by lifting it into the Problem monad. This has the downside that the new type signature does not explicitly promise that bar is independent of MyEnv and logs nothing to MyLog.
Replace the RWS monad by an explicit ReaderT MyEnv WriterT MyLog State MyState monad stack. This allows me to concisely lift.lift the bar subcomputation into the full monad; however, this trick will not work e.g. for a subcomputation of the form c -> Reader MyEnv d.
Is there a cleaner way to compose foo and bar? I have a hunch that a few clever definitions of type-class instances might do the trick, but I can't see exactly how to proceed.
A:
I assume you are using mtl (if you aren't, consider doing so - the libraries are mostly compatible, except for what follows). You can derive instances of MonadReader MyEnv, MonadWriter MyLog, and MonadState MyState. Then, you can use these to generalize your functions over any monad stack that has these sort of constraints.
{-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses, FlexibleContexts #-}
import Control.Monad.RWS
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.State
newtype Problem a = Problem { unProblem :: RWS MyEnv MyLog MyState a }
deriving (Functor, Applicative, Monad,
MonadReader MyEnv, MonadWriter MyLog, MonadState MyState)
From your example, maybe bar only needs to know that there is some state MyState, so you can give it signature
bar :: MonadState MyState m => c -> m d
bar = ...
Then, even for foo, which might need the full RWS capabilities, you could write
foo :: (MonadState MyState m, MonadReader MyEnv m, MonadWriter MyLog m) => a -> m b
foo = ...
Then, you can mix and match these to your liking:
baz :: Problem ()
baz = foo 2 >> bar "hi" >> return ()
Now, why is this useful in general? It boils down to the flexibility of your monad "stack". If tomorrow you decide that you don't actually need RWS but only State, you can refactor Problem accordingly and bar (which only ever needed state in the first place) will continue to work without any changes.
In general, I try to avoid using WriterT, StateT, RWST etc inside auxiliary functions like foo or bar. Opt to keep your code there as generic and implementation-independent as possible using the typeclasses MonadWriter, MonadState, MonadReader, etc. Then, you only have to use WriterT, StateT, RWST once inside your code: when you actually "run" your monad.
Side note about transformers
If you are using transformers, none of this works. That isn't necessarily a bad thing: mtl, by virtue of always being able to "find" components (like state or writer) has some problems.
| {
"pile_set_name": "StackExchange"
} |
Q:
how should i intepret RGB colors in directx/opengl?
so, there are many different color spaces that go by the name RGB. some are linear, and some are gamma. and i'm assuming that which one is being used varies from monitor to monitor.
which one should i interpret the rgb values in a directx or opengl shader as?
is there a 'safe' color space that i can assume a typical user will be using? like, is there a RGB space that everyone in the gaming industry assumes their users will be using?
or is there a way to detect what color space the monitor is using?
i need to know so that i can convert to and from standard color spaces like CIE XYZ. it's fine if it's a little wrong, but i'd like to be as close as possible for typical hardware.
A:
Without further provision the colors going into OpenGL go right through to the monitor, with just the video gamma ramp applied. All color operations in OpenGL are linear.
However OpenGL does provide special sRGB texture formats which linearize textures colors from colorspace first before doing color operations. To complement this there are also sRGB framebuffer formats supported.
Also see these for further info http://www.g-truc.net/post-0263.html and http://www.arcsynthesis.org/gltut/Texturing/Tut16%20Free%20Gamma%20Correction.html
Of course for some applications sRGB is a unfit color space (to small, to low fidelity at 8 bit). In those situations I'd recommend "raw color" OpenGL image and framebuffer formats and perform the color transformations in the shader. Use some contact color space (XYZ is very fit for this) with some HDR image format (i.e. 10 or more bits per channel) for textures (assuming R=X, G=Y, B=Z). Render to a off-screen framebuffer object and in a final post processing step transform from the XYZ framebuffer to the screen color space.
or is there a way to detect what color space the monitor is using?
OpenGL doesn't deal with device management. You'll have to use the OS's facilities to determine the output device's color profile.
| {
"pile_set_name": "StackExchange"
} |
Q:
LINQtoCRM and DynamicEntity
I found LINQtoCRM (http://linqtocrm.codeplex.com/) and I started playing with it. It's nice, but before I get carried away I found there appears to be a showstopper: I can't figure out how to query against DynamicEntities (so I can query against my custom entities). Can someone confirm if this is currently impossible? Or give an example of how one would go about it?
This works:
var res = from c in p.Linq<task>()
select c;
string msg = "";
foreach (task dyn in res.ToList<task>())
{
msg += dyn.ToString();
}
If you s/task/DynamicEntity/ it no longer works :) Just want to confirm it's currently undoable before I go write lots more boilerplate...
edit: angle brackets
A:
(I implemented the original version of LinqtoCRM and I'm still a maintainer).
I do not believe dynamic entities are supported. There is some related discussion on the forum. Maybe give XrmLinq a try.
| {
"pile_set_name": "StackExchange"
} |
Q:
In what order were the Servants summoned for the 5th Holy Grail War?
I know that Assassin was summoned after Caster, and in most cases, Saber is the last Servant to be summoned. (The exception is in Heaven's Feel if you count True Assassin's appearance as a separate summoning).
However, I am wondering about the order of summoning of all the Servants, and if possible, the approximate times in which they were summoned.
In the visual novel, the date is shown during cutscenes, and I am quite sure that Saber was summoned on the night of 29th of February 2004, as I remember that the date changed from 29/2 into 1/3 after Shirou returned home with Saber. This can be used to approximate when the Servants were summoned.
A:
All of these are explained in the visual novels of Fate/stay night and Fate/hollow ataraxia.
First to be summoned was Berserker, two months before Saber.
Second to be summoned was Caster, one month before Saber.
Rider, Assassin and Lancer are summoned at around the same time, around ten days or so before Saber.
Archer is summoned two days before Saber.
By the way, Saber was summoned during the night between February 2nd and February 3rd.
| {
"pile_set_name": "StackExchange"
} |
Q:
What debugger tools do you use to look at contents of a STL container (on linux)
I use gdb (actually DDD), and getting an element out of container is impossible. So I typically end up rolling my own loop for debugging purposes...
What do you do?
A:
Qt Creator is capable of visualizing both Qt containers and STL containers.
There's ongoing work to get GDB to support pretty printing on its own. So far it hasn't made it into any official releases yet, but Fedora 11 shipped it already.
| {
"pile_set_name": "StackExchange"
} |
Q:
Erro Failure[INSTALL_FAILED_INVALID_URI] no GCC
Eu já fiz de tudo, instalei o GCC C4droid pelo Google Store, já instalei o Android Terminal Emulator e também já root ei e liberei o acesso ao $su.
Porem quando eu tento instalar o GCC usando o comando PM install GCC ele aparece escrito pkg: gcc; Failure[INSTALL_FAILED_INVALID_URI].
Se alguém souber de alguma solução.
apt-get e o site sobre instalação do NDK e SDk no site da Android não da certo.
A:
Certa vez tive o mesmo problema ao instalar um APK pelo shell android.
Primeiro erro que eu consegui foi: INSTALL_FAILED_INVALID_URI
$ pm install myApp.apk
pkg: myApp.apk
Failure [INSTALL_FAILED_INVALID_URI]
Isso é porque você precisa dar o caminho completo para o apk, como:
$ pm install /sdcard/myApp.apk
Faça o seguinte:
Refactor -> Rename
Project -> Clean
Crie uma cópia "limpa" do seu projeto.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you escape raw HTML in Go?
I have managed to output text using the following line:
fmt.Fprintf(w, "<p>some text</p>")
But this will literally output the HTML tags. How do you output it so it can safely be included in HTML like you would with echo in PHP?
A:
fmt.Fprintf() has no knowledge of HTML syntax: it outputs raw data without escaping it (it may do some formatting but that is not escaping).
You don't use it correctly though: its second parameter is a format string, so you should call it rather like this:
fmt.Fprintf(w, "%s", "<p>some text</p>")
Else if your text contains some format-specific special characters, you will not get the expected result.
What you want is to escape HTML code so it can be safely included in HTML documents/pages. For that you get excellent support from the html/template package which provides you a powerful template engine where automatic escaping functionality being just one feature.
Here's a simple example how to achieve what you want:
w := os.Stdout
text := "<p>some text</p>"
fmt.Fprintf(w, "%s\n", text)
tt := `{{.}}`
t := template.Must(template.New("test").Parse(tt))
t.Execute(w, text)
Output (try it on the Go Playground):
<p>some text</p>
<p>some text</p>
Also note that if you only want to escape some HTML code, there is a template.HTMLEscaper() function for that:
fmt.Println(template.HTMLEscaper(text))
Output:
<p>some text</p>
| {
"pile_set_name": "StackExchange"
} |
Q:
SAXParser | parse xml data via vector to db
Edit: Not totally solved!
How I can add every entry to db. I want to add Data1, Data2, Data3 and so on to a new column.
In my actual code, down below, parsing data from the XML in res/raw works like a charm. But I cant get it from a URL. Which I'am doing wrong?
I want to parse data from an XML on the net. The XML looks like:
<entrys>
<entry>
<data1>a number</data1>
<data2>a name</data2>
<data3>a webUrl</data3>
<data4>a streamUrl</data4>
<data5>a logoUrl</data5>
</entry>
<entry>
<data1>other number</data1>
<data2>other name</data2>
<data3>other webUrl</data3>
<data4>other streamUrl</data4>
<data5>other logoUrl</data5>
</entry>
<-- more entrys like this, up to one number defined in another xml -->
</entrys>
If I parse it on my way (the code below), I only get the last entry data.
The problem is, I want every entry (and its data) in my db. How can I achieve it?
class ParsedExampleDataSet {
private String data1;
private String data2;
private String data3;
private String data4;
private String data5;
public String toString() {
return "entry ID: " + data1 + "entry Name: "
+ data2 + "entry webUrl: " + data3
+ "entry streamUrl: " + data4
+ "entry Logo: " + data5;
}
public String getdata1() { return data1; }
public void setdata1(String data1) { this.data1 = data1; }
public String getdata2() { return data2; }
public void setdata2(String data2) { this.data2 = data2; }
public String getdata3() { return data3; }
public void setdata3(String data3) { this.data3 = data3; }
public String getdata4() { return data4; }
public String getdata5() { return data5; }
public void setdata4(String data4) {
this.data4 = data4;
}
public void setdata5(String data5) {
this.data5 = data5;
}
}
class ContentHandler extends DefaultHandler {
private enum Tags {
entry, data1, data2, data3, data4, data5, entrys
}
private boolean in_entryTag = false;
private boolean in_entrys = false; //opened at document start, closed at document end
private boolean in_entry = false; //opened at new entry, closed after entry completet
private boolean in_data1 = false; //the entry id
private boolean in_data2 = false; //entry Name
private boolean in_data3 = false; //entry weburl
private boolean in_data4 = false; //entry streamUrl
private boolean in_data5 = false; // Url to entry logo
private ParsedExampleDataSet DataSet;
private Vector<ParsedExampleDataSet> MyParsedExampleDataSets;
public ContentHandler() {
super();
this.MyParsedExampleDataSets = new Vector<ParsedExampleDataSet>();
}
public Vector<ParsedExampleDataSet> getParsedExampleDataSets() {
return this.MyParsedExampleDataSets;
}
public void startDocument() throws SAXException { }
public void endDocument() throws SAXException { }
public void startElement(String n, String l, String q, Attributes a) {
switch(Tags.valueOf(l)) {
case entry:
in_entryTag = true;
DataSet = new ParsedExampleDataSet();
break;
case data1:
in_data1 = true;
break;
case data2:
in_data2 = true;
break;
case data3:
in_data3 = true;
break;
case data4:
in_data4 = true;
break;
case data5:
in_data5 = true;
break;
case entrys:
break;
}
}
public void endElement(String n, String l, String q) {
switch(Tags.valueOf(l)) {
case entry:
in_entryTag = false;
MyParsedExampleDataSets.add(DataSet);
break;
case data1:
in_data1 = false;
break;
case data2:
in_data2 = false;
break;
case data3:
in_data3 = false;
break;
case data4:
in_data4 = false;
break;
case data5:
in_data5 = false;
break;
case entrys:
break;
}
}
public void characters(char ch[], int start, int length) {
if(this.in_data1){
DataSet.setdata1(new String(ch, start, length));
}else if(this.in_data2) {
DataSet.setdata2(new String(ch, start, length));
}else if(this.in_data3) {
DataSet.setdata3(new String(ch, start, length));
}else if(this.in_data4) {
DataSet.setdata4(new String(ch, start, length));
}else if(this.in_data5) {
DataSet.setdata5(new String(ch, start, length));
}
}
}
public class XMLparserSample extends Activity {
private TextView myTextView;
private static final String TAG = XMLparserSample.class.getSimpleName();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Vector<ParsedExampleDataSet> test = read(getResources().openRawResource(R.raw.sample));
String text = "";
for(int i=0; i < test.size(); i++)
text += test.get(i).toString();
myTextView = (TextView) findViewById(R.id.tv);
myTextView.setText(text);
Log.d(TAG, "vector = " + test);
}
public Vector<ParsedExampleDataSet> read(InputStream in) {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp;
try {
sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
ContentHandler ch = new ContentHandler();
xr.setContentHandler(ch);
xr.parse(new InputSource(in));
return ch.getParsedExampleDataSets();
} catch (ParserConfigurationException e) {
} catch (SAXException e) {
} catch (IOException e) {}
return null;
}
}
A:
Please look into your code into application
case entrys:
MyParsedExampleDataSets.add(DataSet);
break;
here entrys tag will end only one time in full document. So place this code into entry tag like this:
public void endElement(String n, String l, String q) {
switch(Tags.valueOf(l)) {
case entry:
in_entryTag = false;
MyParsedExampleDataSets.add(DataSet);
break;
case data1:
in_data1 = false;
break;
case data2:
in_data2 = false;
break;
case data3:
in_data3 = false;
break;
case data4:
in_data4 = false;
break;
case data5:
in_data5 = false;
break;
case entrys:
break;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Output To a Text Box
This is going to sound really stupid, but I'm taking a class in C# where we are skipping around the book and working only from a console application. We were given an exercise to build sentences in strings based on arrays of articles, nouns, verbs, and prepositions, and capitalize the first letter in the first word of the string. The kicker is, it wants the output to a text box. That wouldn't be a problem except
a) we have bypassed all chapters regarding GUIs (that will come in the next quarter's C# class), and
b) I have checked the book and even Stack Overflow and other online sources, but couldn't figure it out.
Unfortunately, my instructor chose not to discuss this exercise in class last night. Since he and I aren't on the same page (not a dislike, more of a chemistry thing), I'm trying to figure this out on my own. And the deadline for turning this in has passed, so I'm only asking for personal edification at this point.
So, here's the code I created. I wrote it for output to a console just to show I had the basic mechanism of the problem. I know I have to create a separate form with a text box inside a GUI window, but I couldn't figure out how to send the output to a text box rather than a console.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _16._4_StoryWriter
{
class StoryWriter
{
static void Main(string[] args)
{
string[] articles = { "the", "a", "one", "some", "any" };
string[] nouns = { "boy", "girl", "dog", "town", "car" };
string[] verbs = { "drove", "jumped", "ran", "walked", "skipped" };
string[] preps = { "to", "from", "over", "under", "on" };
string articleStory = "";
string nounStory = "";
string verbStory = "";
string prepStory = "";
Random random = new Random();
for (int counter = 1; counter <= 10; ++counter)
{
int randomNext = random.Next(5);
articleStory = articles[randomNext];
randomNext = random.Next(5);
nounStory = nouns[randomNext];
randomNext = random.Next(5);
verbStory = verbs[randomNext];
randomNext = random.Next(5);
prepStory = preps[randomNext];
Console.WriteLine(UppercaseFirst(articleStory) + " " + nounStory + " " + verbStory + " " + prepStory + ".");
} // End For
Console.Read();
} // End Main
static string UppercaseFirst(string s) // Borrowed from dotnetperls.com tutorial for making first letter uppercase
{
if (string.IsNullOrEmpty(s)) // Checks for an empty string
{
return string.Empty;
}
char[] a = s.ToCharArray(); // Creates array of characters from a string
a[0] = char.ToUpper(a[0]); // Selects value of zeroth position and changes to upper case
return new string(a); // Passes new string back
} // End method
} // End Class
} // End Namespace
A:
To create a Windows Forms Application project Start Visual Studio
2010.
On the File menu, point to New, and then select Project.
The New Project dialog box appears.
In the Installed Templates pane, expand Visual Basic or Visual C#, and
then select Windows.
Above the middle pane, select the target framework from the drop-down
list.
In the middle pane, select the Windows Forms Application template.
NoteNote The Windows Forms Application template in the .NET Framework
4 targets the Client Profile by default.
In the Name text box, specify a name for the project.
In the Location text box, specify a folder to save the project. Click
OK.
The Windows Forms Designer opens and displays Form1 of the project.
SOURCE
Then drag textbox from toolbox and place it on the form.
Double click anywhere on the form, except for textbox, which will open code behind form and you will be in form load event.
Add:
textBox1.Text = "Your text to put in textbox";
in:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "Your text to put in textbox";
}
press F5
Youtube Form
Youtube textbox
| {
"pile_set_name": "StackExchange"
} |
Q:
Plot mask on top of grayscale image MATLAB
I'm running an algorithm to segment part of an image using morphological operations.
I end up with a 2D binary image that represents the segmentation results. Namely, the mask. My question is how to plot the original image and the mask overlay in color on top of it.
Thank you.
A:
You can use imoverlay written by Steve Eddins.
In addition, you can check these blog posts by him:
Image visualization using transparency
Image overlay using transparency
| {
"pile_set_name": "StackExchange"
} |
Q:
Hide navigation drawer when user presses back button
I've followed Google's official developer tutorials here to create a navigation drawer.
At the moment, everything works fine, except for when the user uses the native back button Android provides at the bottom of the screen (along with the home and recent app buttons). If the user navigates back using this native back button, the navigation drawer will still be open. If the user instead navigates back using the ActionBar, the navigation drawer will be closed like I want it to be.
My code is nearly identical to the official tutorials, except for how I handle the user selecting an item on the drawer:
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView parent, View view, int position, long id)
{
switch(position)
{
case 0:
{
Intent intent = new Intent(MainActivity.this, NextActivity.class);
startActivity(intent);
}
}
}
});
How can I have the navigation drawer be closed when the user navigates back using the native back button? Any advice appreciated. Thanks!
A:
You have to override onBackPressed(). From the docs :
Called when the activity has detected the user's press of the back
key. The default implementation simply finishes the current activity,
but you can override this to do whatever you want.
So you can have code like this :
@Override
public void onBackPressed() {
if (this.drawerLayout.isDrawerOpen(GravityCompat.START)) {
this.drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
If is open this method closes it, else falls back to the default behavior.
A:
You need to override onBackPressed() in your activity and check for the condition where the navigation drawer is open. If it is open, then close it, else do a normal back pressed method. Here is some code mixed with some pseudocode to help you:
@Override
public void onBackPressed(){
if(drawer.isDrawerOpen()){ //replace this with actual function which returns if the drawer is open
drawer.close(); // replace this with actual function which closes drawer
}
else{
super.onBackPressed();
}
}
To replace the pseudocode look in the documentation for the drawer. I know both those methods exist.
A:
UPDATE:
As of support library 24.0.0 this is possible without any workarounds. Two new openDrawer and closeDrawer methods have been added to DrawerLayout that allow the drawer to be opened or closed with no animation.
You can now use openDrawer(drawerView, false) and closeDrawer(drawerView, false) to open and close the drawer with no delay.
If you call startActivity() without calling closeDrawer(), the drawer will be left open in that instance of the activity when you navigate back to it using the back button. Calling closeDrawer() when you call startActivity() has several issues, ranging from choppy animation to a long perceptual delay, depending on which workaround you use. So I agree the best approach is to just call startActivity() and then close the drawer upon return.
To make this work nicely, you need a way to close the drawer without a close animation when navigating back to the activity with the back button. (A relatively wasteful workaround would be to just force the activity to recreate() when navigating back, but it's possible to solve this without doing that.)
You also need to make sure you only close the drawer if you're returning after navigating, and not after an orientation change, but that's easy.
Details
(You can skip past this explanation if you just want to see the code.)
Although calling closeDrawer() from onCreate() will make the drawer start out closed without any animation, the same is not true from onResume(). Calling closeDrawer() from onResume() will close the drawer with an animation that is momentarily visible to the user. DrawerLayout doesn't provide any method to close the drawer without that animation, but it's possible to extend it in order to add one.
Closing the drawer actually just slides it off the screen, so you can effectively skip the animation by moving the drawer directly to its "closed" position. The translation direction will vary according to the gravity (whether it's a left or right drawer), and the exact position depends on the size of the drawer once it's laid out with all its children.
However, simply moving it isn't quite enough, as DrawerLayout keeps some internal state in extended LayoutParams that it uses to know whether the drawer is open. If you just move the drawer off screen, it won't know that it's closed, and that will cause other problems. (For example, the drawer will reappear on the next orientation change.)
Since you're compiling the support library into your app, you can create a class in the android.support.v4.widget package to gain access to its default (package-private) parts, or extend DrawerLayout without copying over any of the other classes it needs. This will also reduce the burden of updating your code with future changes to the support library. (It's always best to insulate your code from implementation details as much as possible.) You can use moveDrawerToOffset() to move the drawer, and set the LayoutParams so it will know that the drawer is closed.
Code
This is the code that'll skip the animation:
// move drawer directly to the closed position
moveDrawerToOffset(drawerView, 0.f);
// set internal state so DrawerLayout knows it's closed
final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
lp.onScreen = 0.f;
lp.knownOpen = false;
invalidate();
Note: if you just call moveDrawerToOffset() without changing the LayoutParams, the drawer will move back to its open position on the next orientation change.
Option 1 (use existing DrawerLayout)
This approach adds a utility class to the support.v4 package to gain access to the package-private parts we need inside DrawerLayout.
Place this class into /src/android/support/v4/widget/:
package android.support.v4.widget;
import android.support.annotation.IntDef;
import android.support.v4.view.GravityCompat;
import android.view.Gravity;
import android.view.View;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class Support4Widget {
/** @hide */
@IntDef({Gravity.LEFT, Gravity.RIGHT, GravityCompat.START, GravityCompat.END})
@Retention(RetentionPolicy.SOURCE)
private @interface EdgeGravity {}
public static void setDrawerClosed(DrawerLayout drawerLayout, @EdgeGravity int gravity) {
final View drawerView = drawerLayout.findDrawerWithGravity(gravity);
if (drawerView == null) {
throw new IllegalArgumentException("No drawer view found with gravity " +
DrawerLayout.gravityToString(gravity));
}
// move drawer directly to the closed position
drawerLayout.moveDrawerToOffset(drawerView, 0.f);
// set internal state so DrawerLayout knows it's closed
final DrawerLayout.LayoutParams lp = (DrawerLayout.LayoutParams) drawerView.getLayoutParams();
lp.onScreen = 0.f;
lp.knownOpen = false;
drawerLayout.invalidate();
}
}
Set a boolean in your activity when you navigate away, indicating the drawer should be closed:
public static final String CLOSE_NAV_DRAWER = "CLOSE_NAV_DRAWER";
private boolean mCloseNavDrawer;
@Override
public void onCreate(Bundle savedInstanceState) {
// ...
if (savedInstanceState != null) {
mCloseNavDrawer = savedInstanceState.getBoolean(CLOSE_NAV_DRAWER);
}
}
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// ...
startActivity(intent);
mCloseNavDrawer = true;
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(CLOSE_NAV_DRAWER, mCloseNavDrawer);
super.onSaveInstanceState(savedInstanceState);
}
...and use the setDrawerClosed() method to shut the drawer in onResume() with no animation:
@Overrid6e
protected void onResume() {
super.onResume();
if(mCloseNavDrawer && mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
Support4Widget.setDrawerClosed(mDrawerLayout, GravityCompat.START);
mCloseNavDrawer = false;
}
}
Option 2 (extend from DrawerLayout)
This approach extends DrawerLayout to add a setDrawerClosed() method.
Place this class into /src/android/support/v4/widget/:
package android.support.v4.widget;
import android.content.Context;
import android.support.annotation.IntDef;
import android.support.v4.view.GravityCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class CustomDrawerLayout extends DrawerLayout {
/** @hide */
@IntDef({Gravity.LEFT, Gravity.RIGHT, GravityCompat.START, GravityCompat.END})
@Retention(RetentionPolicy.SOURCE)
private @interface EdgeGravity {}
public CustomDrawerLayout(Context context) {
super(context);
}
public CustomDrawerLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setDrawerClosed(View drawerView) {
if (!isDrawerView(drawerView)) {
throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer");
}
// move drawer directly to the closed position
moveDrawerToOffset(drawerView, 0.f);
// set internal state so DrawerLayout knows it's closed
final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
lp.onScreen = 0.f;
lp.knownOpen = false;
invalidate();
}
public void setDrawerClosed(@EdgeGravity int gravity) {
final View drawerView = findDrawerWithGravity(gravity);
if (drawerView == null) {
throw new IllegalArgumentException("No drawer view found with gravity " +
gravityToString(gravity));
}
// move drawer directly to the closed position
moveDrawerToOffset(drawerView, 0.f);
// set internal state so DrawerLayout knows it's closed
final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
lp.onScreen = 0.f;
lp.knownOpen = false;
invalidate();
}
}
Use CustomDrawerLayout instead of DrawerLayout in your activity layouts:
<android.support.v4.widget.CustomDrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
...and set a boolean in your activity when you navigate away, indicating the drawer should be closed:
public static final String CLOSE_NAV_DRAWER = "CLOSE_NAV_DRAWER";
private boolean mCloseNavDrawer;
@Override
public void onCreate(Bundle savedInstanceState) {
// ...
if (savedInstanceState != null) {
mCloseNavDrawer = savedInstanceState.getBoolean(CLOSE_NAV_DRAWER);
}
}
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// ...
startActivity(intent);
mCloseNavDrawer = true;
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(CLOSE_NAV_DRAWER, mCloseNavDrawer);
super.onSaveInstanceState(savedInstanceState);
}
...and use the setDrawerClosed() method to shut the drawer in onResume() with no animation:
@Overrid6e
protected void onResume() {
super.onResume();
if(mCloseNavDrawer && mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.setDrawerClosed(GravityCompat.START);
mCloseNavDrawer = false;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get parts of a string via regular expressions in Kotlin or Java?
Suppose you have a string http://server.com/s123456 and want to get 123456 from it. Or http://server.com/s123456&a=100 and get 123456, 100. Many different situations where you want to have parts of a string.
In order to match strings I use regular expressions.
@Test
fun test() {
val text = "http://server.com/s123456" // Source string.
val reg = "^http://server.com/s\\d+\$".toRegex()
assertEquals(true, reg.matches(text))
// Try to split the string with findAll().
val a: Sequence<MatchResult> = reg.findAll(text, 0)
val names = a.map { it.groupValues[0] }.joinToString()
println(names) // http://server.com/s123456
}
But it doesn't split the source string into chars and digits, just prints: http://server.com/s123456. Is there a way to write a mask, so that we can retrieve numbers (or any other parts) from the string?
A:
You need to use capture group around the the part that you interested. Use this "^http://server.com/s(\\d+)\$" and use it.groupValues[1].
| {
"pile_set_name": "StackExchange"
} |
Q:
What does it really mean by "Kafka partitions are immutable"?
In all the Kafka tutorials I've read so far they all mentioned "Kafka partitions are immutable". However, I also read from this site https://towardsdatascience.com/log-compacted-topics-in-apache-kafka-b1aa1e4665a7 that from time to time, Kafka will remove older messages in the partition (depending on the retention time you set in the log-compact command). You can see from the screenshot below that data within the partition has clearly changed after removing the duplicate Keys in the partition:
So my question is what exactly does it mean to say "Kafka partitions are immutable"?
A:
Tha Kafka partitions are defined as "immutable" referring to the fact that a producer can just append messages to a partition itself and not changing the value for an existing one (i.e. with the same key). The partition itself is a commit log working just in append mode from a producer point of view.
Of course, it means that without any kind of mechanisms like deletion (by retention time) and compaction, the partition size could grow endlessly.
At this point you could think .. "so it's not immutable!" as you mentioned.
Well, as I said the immutability is from a producer's point of view. Deletion and compaction are administrative operations.
For example, deleting records is also possible using the Admin Client API ... but we are always talking about administrative stuff, not producer/consumer related stuff.
If you think about compaction and how it works, the producer initially sends, for example, a message with key = A and payload = "Hello". After a while in order to "update" the value, it sends a new message with same key = A and payload = "Hi" ... but actually it's a really new message appended at the end of the partition log; it will be the compaction thread in the broker doing the work of deleting the old message with "Hello" payload leaving just the new one.
In the same way a producer can send the message with key = A and payload = null. It's the way for actually deleting the message (null is called "tombstone"). Anyway the producer is still appending a new message to the partition; it's always the compaction thread which will delete the last message with key = A when it saw the tombstone.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extracting all the changesets in an area path using Python
I am using the TFSAPI in python. I am able to extract all the changesets associated with a work item but if a chnageset is not associated with any work item I am not getting it. Is there any way I can get all the changesets in an area path?
A:
You can changesets that not linked to a work item with this code:
from tfs import TFSAPI
user="username"
password="password"
# Use DefaultCollection
client = TFSAPI("https://tfs-server-url:8080/tfs/", project="DefaultCollection/ProjectName", user=user, password=password)
# Get changesets from 1000 to 1002
changesets = client.get_changesets(from_=1000, to_=1002)
# Get just a particular changeset
changeset = client.get_changeset(1000)
| {
"pile_set_name": "StackExchange"
} |
Q:
Couldn't find an element with uiautomatorviewer and appium
I tried to automate scripts for Android app using uiautomatorviewer and running appium version 1.6.3, framework TESTNG
Here My code, all element are well found, but only the last one with index = 2 it's visible on uiautomatorviewer (see the picture)
All elemnt with index 0 and 1 are found ok ! only the last one.
I'm using the same logic just changing the index with 2
@Test(priority = 1)
public void SignIn() throws InterruptedException {
System.out.println("newlook-tutoriel");
/*
* boolean ispresent = driver.findElement(By.id("skip")).isDisplayed();
* if (ispresent == true) { driver.findElement(By.id("skip")).click();
* System.out.println("Tutorials are present"+ispresent); } else
* System.err.println("Tutorials aren't present ! "+ispresent);
*/
System.out.println("newlook-welcome");
driver.findElement(By.id("btn_signin_welcome")).click();
System.out.println("newlook-Me connecter");
driver.findElement(By.id("input_email")).sendKeys(
"[email protected]");
System.out.println(driver.findElement(By.id("input_password"))
.getClass());
// Thread.sleep(5000);
driver.hideKeyboard();
driver.findElement(By.id("input_password")).sendKeys("00000000");
// Thread.sleep(5000);
driver.hideKeyboard();
driver.findElement(By.id("btn_signin")).click();
Thread.sleep(5000);
System.out.println("connected !!!!");
System.out.println(driver.findElement(By.xpath(".//@class='android.widget.TextView'")).getText());
System.out.println("Bienvenue"+driver.findElement(By.xpath("//*[@class='android.widget.TextView' and @index='0']")).getText());
System.out.println("Emna"+driver.findElement(By.xpath("//*[@class='android.widget.TextView' and @index='1']")).getText());
System.out.println("répondez....." + driver.findElement(By.xpath("//*[@class='android.widget.TextView' and @index='2']")).getText());
driver.findElement(By.xpath("//*[@class='android.widget.Button']")).click();
}
Here appium log
[debug] [AndroidBootstrap] Sending command to android: {"cmd":"action","action":"find","params":{"strategy":"xpath","selector":"//*[@class='android.widget.TextView' and @index='2']","context":"","multiple":false}}
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"action","action":"find","params":{"strategy":"xpath","selector":"//*[@class='android.widget.TextView' and @index='2']","context":"","multiple":false}}
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type ACTION
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command action: find
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Finding '//*[@class='android.widget.TextView' and @index='2']' using 'XPATH' with the contextId: '' multiple: false
[AndroidBootstrap] [BOOTSTRAP LOG] [debug] Returning result: {"status":7,"value":"Could not find an element using supplied strategy. "}
A:
I still don't know the reson but i resolve it by this way :
driver.findElements(By.className("android.widget.TextView")).get(2).getText();
| {
"pile_set_name": "StackExchange"
} |
Q:
I18n with_translation and where condition
I'm trying to run a query on table Testimonials which has a Translation Table TestimonialTranslations.
The Following query works like a charm:
Testimonial.with_translations(I18n.locale).where(:id => params[:id]).first
When I change the query to:
Testimonial.with_translations(I18n.locale).where(:alias => "test").first
It doesn't return any values?
A record exists where the where class is true:
=> [#<Testimonial id: 1, title: "Test", person: "", image_uid: nil, content: "<p>zfzefzfLorem ipsum dolor sit amet, consectetur a...", interest_group: "", created_at: "2015-01-15 11:48:11", updated_at: "2015-01-15 11:48:11", job: "", overview: true, content_short: "<p>Lorem ipsum dolor sit amet, consectetur adipisci...", hidden: false, hide_image: false, alias: "test">]
I know 100% sure that the language is "nl" and that it returns a query when I run:
Testimonial.with_translations(I18n.locale)
These are my specs:
ruby 1.9.3p550 (2014-10-27 revision 48165) [x86_64-darwin13.4.0]
Rails 3.2.19
EDIT 1:
I'm going to leave this open for a while but as far as I can see it is not possible to add a where to the with_translations query that will go and look in the translation table.
With this knowledge I will need to do 2 querys.
A:
Did you try with with_translated_attribute ?
| {
"pile_set_name": "StackExchange"
} |
Q:
How secure is the "Authentication from Scratch" from Railscasts?
I'm weighing the pros and cons of using "Authentication from Scratch" (as implemented in this Railscast) vs. using Devise.
I'm using a custom datastore, so using Devise isn't as simple as just following the README. It would require writing a custom ORM adaptor, which is far from trivial.
Given all this, the Railscast Auth from scratch seems much easier to implement.
So how secure is it?
Update: I should have pointed out that I'm using Parse.com as my datastore. This means they take care of hashing passwords and constraining uniqueness of usernames.
A:
They both work by using bcrypt to generate a salted hash of the password, the only difference is that devise (by default) uses a higher cost for the hash (i.e. it would take more cpu cycles to brute force it), but of course you could easily add that to the railscast code, so roughly equivalent in that respect.
The railscast version does seem to be vulnerable to timing attacks as just doing == won't give you a constant time compare operation. In a nutshell a timing attack works because a password where the hash was completely wrong would take less time for == to reject than a password where first half of the bytes were correct (and so == had to consider more bytes before bailing). It may seem that any such difference would be erased by noise from variations in network latency and so on but people have mounted real attacks to recover keys using these approaches.
You could obviously borrow the secure compare bit from devise though, but it does go to show that there are non obvious issues involved.
Obviously devise gives you a lot more than just authentication!
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I retrieve the features of the last step in backward regression in R
I am using backward regression to do the feature selection in R. After the backward feature selection is run I get a series of outputs starting from the initial set of features.
Start AIC 6811.87
Step AIC 6809.88
Step AIC 6807.99
Step AIC 6807.63
I would like take the features of the last step with the minimum AIC and pass it into another model.
model.aic.backward <- step(fullModel, direction = "backward", trace = 1)
When I try to print the terms by using the below command
print(attr(model.aic.backward$terms,"term.labels"))
I still get the initial set of features which was fed into the model. Please suggest how can I achieve this.
Thank you
A:
The model given by step is the "optimal" model, not the initial model.
Here is an illustrative example:
# Linear data generating process
set.seed(1)
n <- 100
X <- matrix(rnorm(n*5),nrow=n)
betas <- c(-1.5,2,0,-2,0,0)
y <- cbind(rep(1,n), X) %*% betas + 0.5*rnorm(n)
dtset <- data.frame(y, X)
# Initial full model
lmfit <- lm(y~., data=dtset)
# Backward selection
model.aic.backward <- step(lmfit, direction = "backward", trace = 1)
Here is the output of step
Start: AIC=-137.45
y ~ X1 + X2 + X3 + X4 + X5
Df Sum of Sq RSS AIC
- X2 1 0.01 22.44 -139.41
- X5 1 0.11 22.54 -138.97
- X4 1 0.22 22.66 -138.47
<none> 22.44 -137.44
- X1 1 294.14 316.57 125.24
- X3 1 422.44 444.87 159.26
Step: AIC=-139.41
y ~ X1 + X3 + X4 + X5
Df Sum of Sq RSS AIC
- X5 1 0.12 22.56 -140.89
- X4 1 0.22 22.66 -140.45
<none> 22.44 -139.41
- X1 1 294.37 316.82 123.32
- X3 1 423.21 445.65 157.44
Step: AIC=-140.89
y ~ X1 + X3 + X4
Df Sum of Sq RSS AIC
- X4 1 0.23 22.79 -141.89
<none> 22.56 -140.89
- X1 1 299.18 321.74 122.86
- X3 1 423.79 446.35 155.59
Step: AIC=-141.89
y ~ X1 + X3
Df Sum of Sq RSS AIC
<none> 22.79 -141.89
- X1 1 300.89 323.67 121.46
- X3 1 431.38 454.17 155.33
and here the model inside the model.aic.backward object:
summary(model.aic.backward)
############
Call:
lm(formula = y ~ X1 + X3, data = dtset)
Residuals:
Min 1Q Median 3Q Max
-1.2168 -0.3057 -0.0047 0.3693 1.0416
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -1.51531 0.04885 -31.02 <2e-16 ***
X1 1.94126 0.05424 35.79 <2e-16 ***
X3 -2.01862 0.04711 -42.85 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.4847 on 97 degrees of freedom
Multiple R-squared: 0.9693, Adjusted R-squared: 0.9687
F-statistic: 1531 on 2 and 97 DF, p-value: < 2.2e-16
This is the model after backward selection, not the initial model.
Hope this can help you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does CORS not seem to work with POST?
Mozilla's own specification says simple GET or POST should be natively CORS's without preflighting but so far every POST attempt I've made has resulted in an OPTIONS header going out. When I change it from POST to get the code immediately sends a proper GET request so the cross site part is working fine.
Here's a slimmed down sample of what I'm doing in firefox:
var destinationUrl = 'http://imaginarydevelopment.com/postURL';
var invocation = new XMLHttpRequest();
if (invocation) {
invocation.open('POST', destinationUrl, true);
//tried with and without this line
//invocation.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
invocation.onreadystatechange = (function Handler() {
if (invocation.readyState == 4)
alert('Request made');
});
invocation.send(/* tried with and without data*/);
}
Here's what I already had working in chrome and IE:
var destinationUrl = 'http://imaginarydevelopment.com/postURL';
var destination = { url: destinationUrl, type: 'POST', success: AjaxSuccess, error: AjaxError,
dataType: 'text', contentType: 'application/x-www-form-urlencoded'
};
destination.data = { 'rows': rowList, 'token': token };
$jq.ajax(destination);
A:
well, I don't know what all contentTypes actually work but text/plain does on all 3 browsers:
var destination = { url: destinationUrl, type: 'POST', success: AjaxSuccess, error: AjaxError,
contentType: 'text/plain'
};
var postData={ 'anArray': theArray, 'token': token };
destination.data=JSON.stringify(postData);
$jq.ajax(destination);
However so far I haven't figured out what's stopping the request from doing anything besides running the success method even when a 505 code is returned. Adding a response header of Access-Control-Allow-Origin: * solved the browser not wanting to read the return data.
| {
"pile_set_name": "StackExchange"
} |
Q:
¿Cómo comprobar dos fechas TimeStamp en Java Android?
Estoy intentando crear un validador de fechas en Java, la actual con una obtenida de un json y que está en formato TimeStamp 2016-01-18 18:12:56
Para obtener los milisegundos de la fecha actual utilizo lo siguiente
public static long GetCurrentTimeStamp() {
Date date= new Date();
return date.getTime();
}
public static long ConvertTimeStampToDecimal(String fecha) {
//Me falta convertir TimeStamp a Milisegundos
}
long DateNowDecimal = GetCurrentTimeStamp();
String TimeStampDB = "2016-01-18 18:12:56";
me falta como convertir el contenido de TimeStampDB a milisegundos para luego comprobar si es inferior o superior a la de actual, para determinar si actualizar datos o no
A:
Solucionado!
Con la respuesta de @Jose Antonio Dura Olmos añado el siguiente código para la solución.
El final no uso lo de obtener los milisegundos de la fecha actual ya que siempre se estaría actualizando.
Función GetTimeStamp()
public static long GetTimeStamp(String TimeStampDB) {
Date fechaConvertida = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
fechaConvertida = dateFormat.parse(TimeStampDB);
} catch(Exception e) {
System.out.println("Error occurred"+ e.getMessage());
}
return fechaConvertida.getTime();
}
Dependencias
import java.util.Date;
import java.util.*;
import java.text.*;
Código de testeo:
long localJsonDate = GetTimeStamp("2016-01-10 23:00:12");
long remoteJsondate = GetTimeStamp("2016-01-18 18:12:56");
System.out.println("now Date: " + String.valueOf(localJsonDate));
System.out.println("JSON Date: " + String.valueOf(remoteJsondate));
if (remoteJsondate > localJsonDate) {
//Se debe actualizar datos
System.out.println("Necesita actualizar datos...");
} else {
System.out.println("Datos actualizados!");
}
Resultado:
Se debe actualizar datos ya que la fecha del JSON remoto es superior a la última del JSON local
| {
"pile_set_name": "StackExchange"
} |
Q:
React: axios post request with both params and body
Currently I have an axios post request that works fine for sending the data to Spring Boot backend. But it just wraps single list of data to json and sends it as requested body:
Example:
sendAllData(data) {
return axios.post(API_URL + "receiveData", JSON.stringify(data),
{ headers: { "Content-Type": "application/json; charset=UTF-8" },
}).then(response=> console.log("repsonse", response.status)) // is 201
}
And it receives it on backend:
@RequestMapping(path = "/receiveData", method = RequestMethod.POST)
public ResponseEntity<Void> receiveData(@RequestBody Collection<ActivePOJO> activitePOJOS) {
//DO WORK WITH activePOJOS DATA
return new ResponseEntity<>(HttpStatus.CREATED);
}
However, apart from that information, I also need to send some other info like user.id (as example), so I need my backend to receive something like this:
public ResponseEntity<Void> receiveData(@RequestBody Collection<ActivitePOJO> activePOJOS, Long userID)
But I don't know which way should I prepare axios post for something like that. Should I use params instead of body?
A:
You can use params and body together in a request with axios. To send userID as a param:
sendAllData(data) {
return axios.post(API_URL + "receiveData", JSON.stringify(data),
{ headers: { "Content-Type": "application/json; charset=UTF-8" },
params: { userID: 1 }, //Add userID as a param
}).then(response=> console.log("repsonse", response.status)) // is 201
And receive userID in controller with @RequestParam annotation:
public ResponseEntity<Void> receiveData(@RequestBody Collection<ActivitePOJO> activePOJOS, @RequestParam("userID") Long userID){
// here you can access userID value sent from axios
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Наследовние
Добрый! Начал изучать тему наследования на python, в книге был пример:
#класс с конструктором
class Square:
width = 0
height = 0
def area(self): #каждый метод должен принемать хотя бы один параметр (self) что бы получить ссылку на самого себя
return self.width * self.height
def __init__(self, width, height): #констурктор класса, self самособой обязателен
self.width = width
self.height = height
sq = Square(100, 40)
print(sq.area())
#Наследование
class Cube(Square):
z = 0
def __init__(self, width, height, z):
Square.__init__(self, width, height)
self.z = z
def volume(self):
return self.area(self) * self.z
c = Cube(100,40,5)
a = c.area()
print(a)
v = c.volume()
print(c)
Во время выполнения происходит ошибка:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-25-80ae5ab1a692> in <module>()
25 print(a)
26
---> 27 v = c.volume()
28 print(c)
<ipython-input-25-80ae5ab1a692> in volume(self)
19 self.z = z
20 def volume(self):
---> 21 return self.area(self) * self.z
22
23 c = Cube(100,40,5)
TypeError: area() takes 1 positional argument but 2 were given
Прошу объяснить почему не работает
return self.area(self) * self.z
Если не сложно то максимально подробного, для максимального понимания процессов проходящих внутри
A:
class Square:
width = 0
height = 0
def area(self): #каждый метод должен принемать хотя бы один параметр (self) что бы получить ссылку на самого себя
return self.width * self.height
def __init__(self, width, height): #констурктор класса, self самособой обязателен
self.width = width
self.height = height
sq = Square(100, 40)
print(sq.area())
#Наследование
class Cube(Square):
z = 0
def __init__(self, width, height, z):
Square.__init__(self, width, height)
self.z = z
def volume(self):
return self.area() * self.z
c = Cube(100,40,5)
a = c.area()
print(a)
v = c.volume()
print(v)
4000 4000 20000
Неточность - вывод с а не v. И вызов area - не надо снова передавать self
| {
"pile_set_name": "StackExchange"
} |
Q:
Maintaining a chat between user and agent using Google Actions
I am creating an app using Dialogflow and Actions on Google Node.js library.
The logic I am trying to implement is as follows:
User says: Initiate chat.
That user request triggers my webhook which then supplies the agent response.
User replies back to the agent - this is the tricky part because the user reply can be anything, thus the wrong Intent or the Fallback Intent can be triggered.
Is there a way to allow for the unpredictability of a user's response and to keep conversation going between user and agent? In another words, always trigger the same Intent (Chat Intent) regardless of what the user says?
A:
In Dialogflow, you can configure the Default Fallback Intent to connect to web fulfillment. In your fulfillment, you can then route the user's query to your webhook and process a response however you'd want.
| {
"pile_set_name": "StackExchange"
} |
Q:
What happens if I exceed the limits of Heroku Add On free-tier
I'm relatively new to Heroku. I need to integrate my app with elasticsearch by using one of the add ons provided, such as Searchbox.
The free tier for searchbox has a storage limit of 5mb.
If I exceed this limit will I be charged automatically for my usage or will it just cap itself and ask me to either change to a paid tier or delete some stuff.
I don't want to be charged unnecessarily for just a development instance.
Thanks
A:
It will just cap itself. In order for Heroku to charge you, you have to explicitly change to a paid tier.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the meaning of "^" in the CPU window of the Immunity debugger?
I can't figure out the meaning of ^ in the CPU window of the immunity debugger. What does it mean?
A:
Looks like it shows the direction of the jump (backwards in this case).
| {
"pile_set_name": "StackExchange"
} |
Q:
The import com.badlogic cannot be resolved in Java Project Libgdx Setup
I've just tried to setup Libgdx to start making games, i followed this tutorial https://www.youtube.com/watch?v=S9fs1PVTyUc&feature=youtu.be
in conjunction with the libgdx grdale setup. However an error shows up in the Java project which says:
The import com.badlogic cannot be resolved
I am using Eclipse for Java IDE. I believe I have the Android SDK installed. I think it may be to do with the setup but i think the latest updates are there and i tried deleting '.m2'ccahe, which is not there any more btw after i deleted it (not been replaced), but this didnt work. Any ideas?
heres my code for the java proect:
import com.badlogic.gmx.Game;
public class GameMain extends Game{
}//'com.badlogic 'gets an error and so does 'Game'
A:
The issue you are encountering is your eclipse project "CreateGame" is not setup correctly. It is missing the files needed to use libgdx.
Possible Solutions:
Use the libgdx project setup tool and then follow the instructions here to import the project to eclipse. (easy)
Add the missing library files to the project (hard)
Also make sure your game code is going into the game-core project as this project is used by each platform you are targeting.
| {
"pile_set_name": "StackExchange"
} |
Q:
Show that $(x^2-yz)^3+(y^2-zx)^3+(z^2-xy)^3-3(x^2-yz)(y^2-zx)(z^2-xy)$ is a perfect square and find its square root.
Show that $(x^2-yz)^3+(y^2-zx)^3+(z^2-xy)^3-3(x^2-yz)(y^2-zx)(z^2-xy)$ is a perfect square and find its square root.
My work:
Let, $x^2-yz=a,y^2-zx=b,z^2-xy=c$. So, we can have,
$a^3+b^3+c^3-3abc=(a+b+c)(a^2+b^2+c^2-ab-bc-ca)$
$(a+b+c)(a^2+b^2+c^2-ab-bc-ca)=\dfrac12[(x-y)^2+(y-z)^2+(z-x)^2]\cdot\dfrac12[(a-b)^2+(b-c)^2+(c-a)^2]$
Now, I got into a mess. I have got two products with sum of three squares which I cannot manage nor can I show this to be a perfect square. Please help.
A:
HINT:
$$(x^2-yz)^3-(x^2-yz)(y^2-zx)(z^2-xy)$$
$$=(x^2-yz)[(x^2-yz)^2-(y^2-zx)(z^2-xy)]$$
$$=(x^2-yz)x(x^3+y^3+z^3-3xyz)$$
$$=(x^3-xyz)\underbrace{(x^3+y^3+z^3-3xyz)}$$
As the terms under the brace is symmetric wrt $x,y,z$
we shall reach at the similar expressions from
$$(y^2-zx)^3-(x^2-yz)(y^2-zx)(z^2-xy)$$ and $$(z^2-xy)^3-(x^2-yz)(y^2-zx)(z^2-xy)$$
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the black slag formed when sterling silver is melted with borax?
What is the black graphite looking slag that is formed when sterling silver is melted with borax? Is there a way to remove it from the surface of the sterling silver? It appears to be indestructible!
The melting is related to jewelry casting. All melting was done in an electric Ney muffle furnace. Here is a melting dish with some half-melted buttons of sterling silver.
I can't remember why I didn't completely melt this. I assume the green is salts of copper from the sterling silver. Notice how the black slag erodes the walls of the melting dish.
Here is a closeup of the erosion.
This erosion property ate through the bottom of my furnace! UGGG! It'll be $600 to replace the muffle. I heated to 1,900 Fahrenheit for about one hour and this is what I saw when I opened the furnace to get the crucible with the molten sterling silver, but with glowing white-orange light.
Here I have the crucible laying on its side next to the hole.
Here is a close up of the hole and in one of the images I'm lighting it up with a flashlight. I'd say it's about 1.5 inches in diameter and 1.5 inches deep. There are 2.25 Ozt of sterling silver down in the hole somewhere because the eroding black slag ate holes through the wall of my crucible.
A closeup of the erosion in front of the main hole. These two erosion spots were from the previous melt cycle with the same crucible. I saw that the black slag was penetrating the crucible but I figure it was just minute capillary action and it'd be ok. Notice that the black slag seems to be working like a catalytic reaction because the amount of borax in the crucible is only about the volume of one grain of white rice. These two depressions were not depressions at the end of the previous melt cycle they were just flat black areas of the same size and shape.
Here is a view on the outside of the crucible. I assume one of those holes is where the silver leaked out.
A view inside the crucible. In person, the black slag has a metallic sheen to it. It is very similar to the dark grey metallic sheen of graphite.
What is this black slag?
A:
"Indestructible" by what means exactly? How did you try to "destroy" it? Provided that sterling alloy is an alloy of silver and copper, the first guess is that your slag is primarily a copper (II) oxide. Depending on the actual composition of the alloy, it may contain other 3d-metal oxides. The formation of borates (not of silver, but of less noble metals) cannot be excluded, for borax is frequently used as a constituent of the high-temperature fluxes for spectroscopic and calorimetric applications. To what extent the borates are formed depends on the temperature and duration of your melting experiment.
You should be able to dissolve your slug in a boiling mineral acid of your choice. Personally, I'd try the $\ce{HCl}$ solution, or $\ce{HNO3}$ if you do not care that silver dissolves as well.
The following may be irrelevant to the question asked, but, based on my experience and some textbooks, people first try to purify silver and then melt the pure metal, not the other way around. The methods of purification are aplenty, but most of them are based on dissolving the silver-containing alloy in $\ce{HNO3}$. Then $\ce{AgNO3}$ can be transformed into $\ce{AgCl}$, which, in turn, can be reduced by metallic zinc in acidic environment or formaldehyde - in basic.
A:
Voffch mentioned that borax is a flux. Quite true; borax beads are used for determination of various metals, and copper or silver would give characteristic colors, like green and whatever silver gives. Fluxes are also solvents for metal oxides, like the refractory material of the crucible. While molten alloys should be containable by refractory crucibles (I'm surprised by blacksmith37's comment!), if the crucible is not properly chosen, I suppose it just might not do its job of containing the molten metal.
The borax was probably added to provide a cover for the molten alloy, but was too powerful a solvent for the crucible. There are many materials for crucibles, such as clay, alumina, graphite, and silicon carbide. There are many articles on the internet which address the specific issue of melting silver and sterling silver. Perhaps a better crucible would allow the use of borax (recommended for silver) or a different flux could be chosen.
The black slag has been called fire-burnt copper, an oxide which is very hard product when cooled; probably also combined with the borax.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which is the fastest way to find a member of a subgroup with known size modulo prime $P$, with know factorization of $P-1$?->$x$ with $x^s \mod P = 1$
Assuming you know the factorization of used prime $P-1$
$P-1 = s \cdot f_2\cdot f_3...f_i$
Now you want to find a member of a subgroup $\mathbb{Z}_s$.
This means any $x$ with
$x^s \equiv 1 \mod P $
Naive way whould be selecting a random value $x$, compute $x^s$ and check if it is equal to $1$.
Another way I found online:
transform to disc. log
This first first computes a prime root $g$ of $P$. With this you can rewrite the equation:
$x^s \equiv (g^k)^s \equiv (g^s)^k \mod P$
And computes a $k$ with Shanks' baby-step giant-step algorithm.
Is that the best/fastest way to go? Does it help if $s$ is a prime?
Is there a faster way if you are allowed to change $s$ and $P$ as well?
e.g. instead finding $x$ look for a fitting P' instead. For this fix $x$ to any number of choice $x_{const}$ and search for a $P'=s \cdot f +1$
$x_{const}^s \equiv 1 \mod P' $
(Trivial $x$ like $x = 1+n \cdot P$ do not count here)
A:
Is that the best/fastest way to go?
Well, unless you give some criteria, whether it's the best is unanswerable. However, it might not be the fastest; you could just note that $k = f_2 \cdot f_3 \cdot … \cdot f_i$ and skip the baby-step-giant-step algorithm entirely.
In addition, if all you want is a random element of the subgroup, you don't need to find a generator. Instead, all you need to do is select a random value $r \in [1, P-1]$, and compute $x = r^k \bmod P$ (using the above definition of $k$); if $x \ne 1$ (true with probability $1 - 1/s$), that's what you're looking for.
BTW: why do you think you need $x$ to be a prime?
| {
"pile_set_name": "StackExchange"
} |
Q:
Default numeric format in Excel
I have a web app that exports reports to Excel. It does this by sending the HTML of the report table to the clipboard, and then pasting it into Excel. Quick and dirty. And it comes through fairly well. Numbers are formatted as numbers, dates as dates, and so on.
But the reports have negative numbers formatted to use parentheses rather than a minus sign, and when this is pasted into Excel, it changes to a minus sign. You can see this in action simply by typing (200) into Notepad, and then selecting it, copying it, and pasting it into a cell in an Excel spreadsheet. It will come through as -200.
My users would like to have it display as (200). And I can use automation from Javascript to manually format selected cells. But that's slow. Is there any way to get Excel to change its default numeric format?
A:
If you're pasting HTML-formatted data in the form of a table into Excel, then you can include css styles to control how the cell contents are displayed.
See (e.g.) : http://cosicimiento.blogspot.com/2008/11/styling-excel-cells-with-mso-number.html
VBA example:
Sub Formatting()
Dim html As String, d As New DataObject
html = "<table><tr><td>(200)</td></tr>" & _
"<tr><td style='mso-number-format:\@'>(200)</td></tr></table>"
d.SetText html
d.PutInClipboard
End Sub
HTML example: CSS Formatting for Excel Web Query
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any relation between connectedness of metrizible spaces and their completeness
I'm new to topology and apologize if my questions might be trivial.
I'm wondering about the causality relation between connected and complete metric spaces. I do wanna know whether the following statements are theorems:
1. If (X,T) is a connected metrizible topological space, then (X,d) (where d is the metric inducing T) is a complete metric space.
2. If (X,d) is a complete metric space, then the topological space (X,T) induced by (X,d) is connected.
Of course these two satements are the converse of each other.
A:
The answer to both questions is negative. The space $\mathbb{R}\setminus(-1,1)$, with its usual metric, is complete, but disconnected. And $(-1,1)$, with its usual metric, is connected but not complete.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to avoid toddlers on a long-distance plane flight?
I have recently taken a London - San Francisco (12 hour) flight, with a toddler in the seat directly behind me. His parents actively encouraged the kid to speak out in that typical proto-speech, while reading out from books. For 12 hours.
One might think that the industrial-strength earplugs I always carry with me would have helped. One would be very, very wrong.
What specific steps can I take in all of my future flights so that this experience will never, ever repeat itself?
A:
To avoid disturbance from small children, you can use a multi-pronged approach:
first, try to choose flights that are more of a hassle for parents. Generally this means night flights - some parents may be sure their child will sleep (and not bother you) but others are worried the child will not sleep and will cry. So they take a daytime flight and are willing to entertain them for the length of the flight
second, try to minimize the impact of the child on you. Buy a more expensive ticket - first, business, even economy plus. Children are of course allowed in the more expensive zones, but they are in substantially fewer numbers. In some cases these children are experienced and quiet flyers, accompanying parents who have been kept awake by other people's children in the past. And do what you can to improve things at whatever seat you have. Bring noise cancelling headphones in addition to earplugs, for example. Bring some sort of music you can play that will drown out the repetitive reading.
third, try to react in the moment in some way that is more positive than sitting in your seat seething. Go for a walk. Strike up a conversation elsewhere on the plane. Turn around and interact with the child, such as playing peek a boo over the back of your seat. It's probably likely to be quieter than the reading and even endear you to the parents. Tell the child your name and ask theirs, and smile. If in a few hours you want to ask the parents if there's a quieter form of entertainment available, you won't be the grumpy gus in the next row, you'll be the toddler's airplane friend.
fourth, try to be realistic. No toddler does anything for 12 hours. They nap, they eat and drink, and so on. Focusing on the behavior that irritates you, to the extent you genuinely recall that it took the entire flight time, leaves you with a bad cloud around you that can take days to shake. When the noise starts, tell yourself it won't last the whole flight. Do something positive, listen to something, take yourself away from the noise. When the noise stops, be grateful, even if it's just a short respite.
And finally, when you leave the plane, be grateful that you are now done with that child and don't have to hear the noise or put in any effort to try to prevent bedlam. The parents will still be on duty for hours more today, and for another few decades in general. Count your blessings!
A:
For $160,000, you can hire a private jet for London - LAX return which is a similar trip length to that of London to San Francisco. This aircraft seats 13 making the trip approximately $12,300 each if you could find 12 other people to share it with. That's a similar price to paying for fully flexible first class.
For that you typically get a private terminal, minimal security, ability to take almost as much luggage as you wish, and an aircraft that will wait for you and take off whenever you want. You also guarantee to be sharing the aircraft with people of your choice.
The OP specifically asks "how to avoid toddlers". This question and similar questions, such as how do I avoid drunks, people who snore or sitting next to someone with bad body odor, or why should babies be allowed in first class, typically end up with the canonical answer that you should fly in a private jet. When you are taking a form of public transport, inevitably you are going to come across a disagreeable situation or disagreeable passengers.
On almost any airline (apart from, I think, one exception), babies and young children are allowed in all cabins including First and Business class. Children under a certain age are not allowed in the exit row, but they are allowed in front of, behind and in the bulkhead adjacent to the exit row. There are many parents who can afford to travel in Business and First and you see young children in these every day. Some parents prefer an overnight flight to a day flight in order to get the children to sleep more quickly. In summary, you can almost never be guaranteed to more than one seat away from a toddler.
If the OP had said he'd had an uncomfortable flight and asked what's the best way with dealing with noise on an aircraft, I would have provided an answer responding to that question, rather than the question that the OP did ask.
A:
Toddlers cannot be seated in exit rows.
If you are able to select your seat, choose one that has an exit row behind it. You may lose the ability to recline your seat, but you are guaranteed that there will not be a toddler behind you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento 2: Fetching last generated invoice
In Magento 1, I can fetch the invoice details like,
$orderObject = Mage::getModel('sales/order')->load($orderId);
$invoiceCollection = $orderObject->getInvoiceCollection();
foreach($invoiceCollection as $invoice):
$invoiceId = $invoice->getId();
endforeach;
How can I do the same in Magento 2?
A:
you need to inject Sales Collection Factory class,
protected $order;
public function __construct(
.....
\Magento\Sales\Model\Order $order,
.......
) {
...
$this->order = $order;
........
parent::__construct($context, $data);
}
public function getInvoiceDetails($order_id){
$orderdetails = $this->order->load($order_id);
$orderdetails->getGrandTotal(); //you can get the grandtotal like this
foreach ($orderdetails->getInvoiceCollection() as $invoice)
{
$invoice_id = $invoice->getIncrementId();
}
}
and then you can use the function getInvoiceDetails in your template file
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Save Textboxt.Text as file name?
What's wrong with this code?
I need to add textbox13.text (the value of it is in number) as the file name and how can I add an option which checks if the file already exists if so show an option saying replace or cancel when I press my save button.
So far here is the code :
Dim i As Integer = 0
Dim filepath As String = IO.Path.Combine("D:\Logs", Textbox13.Text + i.ToString() + ".txt")
Using sw As New StreamWriter(filepath)
sw.WriteLine(TextBox13.Text)
sw.WriteLine(TextBox1.Text)
sw.WriteLine(TextBox2.Text)
sw.WriteLine(TextBox3.Text)
sw.WriteLine(TextBox4.Text)
sw.WriteLine(TextBox5.Text)
sw.WriteLine(TextBox7.Text)
sw.WriteLine(TextBox9.Text)
sw.WriteLine(TextBox10.Text)
sw.WriteLine(TextBox11.Text)
sw.WriteLine(TextBox12.Text)
This is from Form1
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Form2.WriteTextBoxTextToLabel(TextBox1.Text)
Form2.WriteTextBoxTextToTextbox(TextBox1.Text)
End Sub
This is from form2
Public Sub WriteTextBoxTextToLabel(ByVal Txt As String)
lblPD.Text = Txt
End Sub
Public Sub WriteTextBoxTextToTextbox(ByVal Txt As String)
TextBox13.Text = Txt
End Sub
Private Sub TextBox13_TextChanged(sender As Object, e As EventArgs) Handles TextBox13.TextChanged
TextBox13.Text = lblPD.Text
End Sub
A:
You can add the following logic before creating the StreamWriter:
if system.io.file.exists(filepath) then
' The file exists
else
' The file does not exist
end if
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem with Bash script: 'declare: not found'
I had a script which was running fine but when I ran it today, it says declare: not found. I am using bash shell and path at the starting of the script is correct.
Two flagged lines in my script are as follows:
declare -a RESPONSE
RESPONSE=($RESULT)
It also says ( is unexpected but I guess that is coming up because of the first error.
Worth mentioning point is when I type in declare directly works fine.
declare | grep USER shows
USER=ashfame
USERNAME=ashfame
values="$SVN_BASH_USERNAME";
So, whats wrong here?
A:
Are you using sh instead of bash? sh (linked to dash) does not support declare keyword, nor the syntax
VAR=(list)
for initializing arrays.
A:
I suspect that your "shebang" line (the optional first line of the file) is referencing sh instead of bash. It should be
#!/bin/bash
for bash scripts. If the first line of your script is
#!/bin/sh
then that would indicate that a strictly bourne-compatible shell is to be used; in the case of Ubuntu, dash is used. In many other distributions, this does not cause a problem, because they link /bin/sh to /bin/bash; however ubuntu links to /bin/dash in order to allow system scripts to run more rapidly.
The declare builtin is one of bash's many extensions to the Bourne shell script specification; dash just implements that specification without extensions.
A:
How to reproduce the above error:
I'm using Ubuntu 14.04 64 bit. Put this code in a file:
#!/bin/sh
declare -i FOOBAR=12;
echo $FOOBAR;
Run it like this:
el@apollo:~$ ./06.sh
./test.sh: 2: ./test.sh: declare: not found
To fix it, do this instead:
#!/bin/bash
declare -i FOOBAR=12;
echo $FOOBAR;
Prints:
el@apollo:~$ ./06.sh
12
| {
"pile_set_name": "StackExchange"
} |
Q:
Instantiating class from string wont really work in php
Ive just started learning namespaces. If I do this:
$a = new Devices\Desktop();
this works. But I have dynamic class names, so I have to do it from a variable.
$a = 'Devices\Desktop';
$a = new $a();
this is not working, although its the same. The class is not found. Why?
A:
Going out on a limb:
namespace Foo;
class Bar { }
new Bar;
$bar = 'Bar';
new $bar;
This won't work. String class names are always absolute, they're not resolved relative to the current namespace (because you can pass strings from one namespace to another, which should it resolve against then?). To make those two instantiations equivalent, you need to use a fully qualified class name:
$bar = 'Foo\Bar';
The __NAMESPACE__ constant can be useful here:
$bar = __NAMESPACE__ . '\Bar';
| {
"pile_set_name": "StackExchange"
} |
Q:
Cosmos DB - Indexing Policy Settings
I am using the azure cli in order to set my indexing policy. I am using the following JSON:
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{
"path": "/ttl/?",
"indexes": [
{
"kind": "Range",
"dataType": "Number",
"precision": -1
}
]
}
],
"excludedPaths": [
{
"path": "/*"
}
]
}
The script reports no errors have occurred, however when I log into the portal and look at the indexing policy, it shows the following:
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{
"path": "/ttl/?",
"indexes": [
{
"kind": "Range",
"dataType": "Number",
"precision": -1
},
{
"kind": "Range",
"dataType": "String",
"precision": -1
}
]
}
],
"excludedPaths": [
{
"path": "/*"
},
{
"path": "/\"_etag\"/?"
}
]
}
The portal settings include an extra excludedPath and index, so I am not sure if this is intentional or I am doing something wrong. Or are the two equivalent?
Any help would be great!
A:
Since indexing v2 came out the default indexing will add range for both strings and numbers and it will also automatically exclude the ETag.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't show class with interface properties in PropertyGrid
Currently i'm trying to configure some of my classes through the PropertyGrid. Now i have some problems about showing the value (the right side within the grid) if the class provides the property as an interface. I thought, cause the grid uses reflection it would take the real type and uses it's normal ways on showing the value within the grid. For a demonstration simply take the class hierarchy below and create a simple form with a PropertyGrid and put the object into it by calling
propertyGrid1.SelectedObject = new MyContainerClass();
Here are the classes:
public class MyContainerClass
{
// Simple properties that should be shown in the PropertyGrid
public MyInterface MyInterface { get; set; }
public MyClass MyClass { get; set; }
public object AsObject { get; set; }
public MyContainerClass()
{
// Create one instance of MyClass
var myClass = new MyClass();
// Put the instance into both properties
// (cause MyClass implements MyInterface)
MyClass = myClass;
MyInterface = myClass;
// and show it if it is declared as "object"
AsObject = myClass;
}
}
// Some kind of interface i'd like to show in the PropertyGrid.
public interface MyInterface
{
string Name { get; set; }
}
// A class that also implements the interface
// and uses some kind of TypeConverter
[TypeConverter(typeof(ExpandableObjectConverter))]
public class MyClass : MyInterface
{
// Create an instance and put something meaningful into the property.
public MyClass()
{
Name = "MyName";
}
public string Name { get; set; }
// Override ToString() to get something shown
// as value in the PropertyGrid.
public override string ToString()
{
return "Overridden ToString(): " + Name;
}
}
As you can see the container uses the same object in all three properties, but within the grid you'll see the ToString() text on the class property and on the object property, but nothing on the interface property. Also the TypeConverter is only used on the property that uses the exact type.
PropertyGrid showing MyContainer http://image-upload.de/image/O2CC5e/9558e4e179.png
Exists there any way to let the PropertyGrid showing the ToString() result of the class behind the interface property?
A:
Finally i solved this problem for the most cases:
The problem occurs, cause the PropertyDescriptor returns within its Converter property normally the correct converter or at least the base class TypeConverter which will at least call ToString() for visualization. In case of a property that is defined as an interface the property grid will get a ReferenceConverter, but by looking into the remarks section
The ReferenceConverter is typically used within the context of sited components or a design environment. Without a component site or a usable ITypeDescriptorContext, this converter is of little use.
We really seem to have a little use for it. Fortunately i'm already using my own PropertyDescriptor, so all i had to do was to override the Converter property of my descriptor and change to the following:
public override TypeConverter Converter
{
get
{
var converter = base.Converter;
// If the property of the class is a interface, the default implementation
// of PropertyDescriptor will return a ReferenceConverter, but that doesn't
// work as expected (normally the right site will stay empty).
// Instead we'll return a TypeConverter, that works on the concrete type
// and returns at least the ToString() result of the given type.
if (_OriginalPropertyDescriptor.PropertyType.IsInterface)
{
if (converter.GetType() == typeof(ReferenceConverter))
{
converter = _InterfaceConverter;
}
}
return converter;
}
}
The explicit check for the ReferenceConverter is needed, cause it could be possible that the user defined its own TypeEditor through an attribute on the property, which will be automatically respected by the base implementation. It would only lead to problems if someone would explicit say through the attribute, that he likes the ReferenceConverter, but i don't think that case has to be handled (but could be by checking the attributes of the PropertyDescriptor).
| {
"pile_set_name": "StackExchange"
} |
Q:
Kafka 0.8 All Good & rocks! .... Kafka 0.7 not able to make it happen
Kafka 0.8 works great. I am able to use CLI as well as write my own producers/consumers!
Checking Zookeeper... and I see all the topics and partitions created successfully for 0.8.
Kafka 0.7 does not work!
Why Kafka 0.7? I am using Kafka Spout from Storm which is made for Kafka 0.7.
First I just want to run CLI based producer/consumer for Kafka 0.7, which I am unable to. I carry out the following steps:
I delete all the topics/partitions etc. in Zookeeper that were created from my Kafka 0.8
I change the dataDir in zoo.cfg to point to different location.
Now I start the kafka server 0.7. It starts successfully. However I don’t know why it again registers the broker topics I deleted?
Now I start the Kafka Producer :
bin/kafka-console-producer.sh --zookeeper localhost:2181 --topic topicime
& it starts successfully:
[2013-06-28 14:06:05,521] INFO zookeeper state changed (SyncConnected) (org.I0Itec.zkclient.ZkClient)
[2013-06-28 14:06:05,606] INFO Creating async producer for broker id = 0 at 0:0 (kafka.producer.ProducerPool)
Time to send some messages & oops I get this error:
[2013-06-28 14:07:19,650] INFO Disconnecting from 0:0 (kafka.producer.SyncProducer)
[2013-06-28 14:07:19,653] ERROR Connection attempt to 0:0 failed, next attempt in 1 ms (kafka.producer.SyncProducer)
java.net.ConnectException: Connection refused
at sun.nio.ch.Net.connect0(Native Method)
at sun.nio.ch.Net.connect(Net.java:364)
at sun.nio.ch.Net.connect(Net.java:356)
at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:623)
at kafka.producer.SyncProducer.connect(SyncProducer.scala:173)
at kafka.producer.SyncProducer.getOrMakeConnection(SyncProducer.scala:196)
at kafka.producer.SyncProducer.send(SyncProducer.scala:92)
at kafka.producer.SyncProducer.multiSend(SyncProducer.scala:135)
at kafka.producer.async.DefaultEventHandler.send(DefaultEventHandler.scala:58)
at kafka.producer.async.DefaultEventHandler.handle(DefaultEventHandler.scala:44)
at kafka.producer.async.ProducerSendThread.tryToHandle(ProducerSendThread.scala:116)
at scala.collection.immutable.Stream.foreach(Stream.scala:254)
at kafka.producer.async.ProducerSendThread.processEvents(ProducerSendThread.scala:70)
at kafka.producer.async.ProducerSendThread.run(ProducerSendThread.scala:41)
Note that Zookeeper is already running.
Any help would really be appreciated.
EDIT:
I don't even see the topic being created in zookeeper. I am running the following command:
bin/kafka-console-producer.sh --zookeeper localhost:2181 --topic topicime
After the command everything is fine & I get the following message:
[2013-06-28 14:30:17,614] INFO Session establishment complete on server localhost/127.0.0.1:2181, sessionid = 0x13f805c6673004b, negotiated timeout = 6000 (org.apache.zookeeper.ClientCnxn)
[2013-06-28 14:30:17,615] INFO zookeeper state changed (SyncConnected) (org.I0Itec.zkclient.ZkClient)
[2013-06-28 14:30:17,700] INFO Creating async producer for broker id = 0 at 0:0 (kafka.producer.ProducerPool)
However now when i type a string to send I get the above error (Connection refused!)
A:
INFO Disconnecting from 0:0 (kafka.producer.SyncProducer)
The above line has the error hidden in it. 0:0 is not a valid host and port. The solution is to explicitly set the host ip to be registered in Zookeeper by setting the "hostname" property in server.properties.
| {
"pile_set_name": "StackExchange"
} |
Q:
Verify if has only a specified parameter in request - Laravel
Is it possible to check in laravel, if only a specific field is filled in a request?
Like this: if($request->filledOnly('email)){}
If possible how to do that?
A:
You can use the has() method, and you can call it like this:
if($request->has('email'))){
//do one thing
} else {
//do another
}
Edit:
If you want to check for a situation in which only one input is set, you can do something like this:
Assuming your other inputs are name, phone, address, you can check if any of them are set by calling hasAny on your $request:
if (!$request->hasAny['name', 'phone', 'address'])
{
//now we know none of them are set
//check if email is set:
if ($request->has('email')
{
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change values in a dataframe Python
I've searched for an answer for the past 30 min, but the only solutions are either for a single column or in R. I have a dataset in which I want to change the ('Y/N') values to 1 and 0 respectively. I feel like copying and pasting the code below 17 times is very inefficient.
df.loc[df.infants == 'n', 'infants'] = 0
df.loc[df.infants == 'y', 'infants'] = 1
df.loc[df.infants == '?', 'infants'] = 1
My solution is the following. This doesn't cause an error, but the values in the dataframe doesn't change. I'm assuming I need to do something like df = df_new. But how to do this?
for coln in df:
for value in coln:
if value == 'y':
value = '1'
elif value == 'n':
value = '0'
else:
value = '1'
EDIT: There are 17 columns in this dataset, but there is another dataset I'm hoping to tackle which contains 56 columns.
republican n y n.1 y.1 y.2 y.3 n.2 n.3 n.4 y.4 ? y.5 y.6 y.7 n.5 y.8
0 republican n y n y y y n n n n n y y y n ?
1 democrat ? y y ? y y n n n n y n y y n n
2 democrat n y y n ? y n n n n y n y n n y
3 democrat y y y n y y n n n n y ? y y y y
4 democrat n y y n y y n n n n n n y y y y
A:
This should work:
for col in df.columns():
df.loc[df[col] == 'n', col] = 0
df.loc[df[col] == 'y', col] = 1
df.loc[df[col] == '?', col] = 1
A:
I think simpliest is use replace by dict:
np.random.seed(100)
df = pd.DataFrame(np.random.choice(['n','y','?'], size=(5,5)),
columns=list('ABCDE'))
print (df)
A B C D E
0 n n n ? ?
1 n ? y ? ?
2 ? ? y n n
3 n n ? n y
4 y ? ? n n
d = {'n':0,'y':1,'?':1}
df = df.replace(d)
print (df)
A B C D E
0 0 0 0 1 1
1 0 1 1 1 1
2 1 1 1 0 0
3 0 0 1 0 1
4 1 1 1 0 0
A:
This should do:
df.infants = df.infants.map({ 'Y' : 1, 'N' : 0})
| {
"pile_set_name": "StackExchange"
} |
Q:
Head First Java, Chapter 16, Be The Compiler exercise query
I have just finished reading chapter 16 of Head First Java, which is about collections and the use of generics. There is a "Be the compiler" exercise at the end of the chapter that gives 9 lines of code and the challenge is to say which lines of code will compile successfully. The lines of code given are as follows:-
ArrayList<Dog> dogs1 = new ArrayList<Animal>();
ArrayList<Animal> animals1 = new ArrayList<Dog>();
List<Animal> list = new ArrayList<Animal>();
ArrayList<Dog> dogs = new ArrayList<Dog>(); //The book says this line will not compile
ArrayList<Animal> animals = dogs;
List<Dog> dogList = dogs;
ArrayList<Object> objects = new ArrayList<Object>();
List<Object> ObjList = objects;
ArrayList<Object> objs = new ArrayList<Dog>();
The solution states that the 3rd, 6th, 7th and 8th lines will compile but when I try to compile the lines of code myself I find that the 4th line also compiles successfully. What is more, the 6th line of code relies on the 4th line of code compiling as it references the ArrayList from line 4!
I was wondering if anyone else that has done this "Be the compiler" exercise noticed this issue while completing it or if anyone can has any idea as to why the authors would have left the fourth line of code out of the solutions even though it compiles fine.
Thanks a lot in advance for any help you can give.
A:
The 4th line should compile. If you look at the Confirmed Errata for Head First Java, it's there:
| {
"pile_set_name": "StackExchange"
} |
Q:
Norm of a block of matrix operator
Let $(\mathcal{H}_1,\langle \cdot\mid \cdot\rangle_1), (\mathcal{H}_2,\langle \cdot\mid \cdot\rangle_2), \cdots, (\mathcal{H}_d,\langle \cdot\mid \cdot\rangle_d)$ be complex Hilbert spaces and let $\mathbb{H}=\oplus_{i=1}^d\mathcal{H}_k$.
Let $\mathbb{T}= (T_{ij})_{d \times d}$ be an operator matrix on $\mathcal{B}(\oplus_{i=1}^d\mathcal{H}_k)$ and $\tilde{\mathbb{T}} = (\|T_{ij} \|_{\mathcal{B}(\mathcal{H}_j,\mathcal{H}_i)})_{d\times d}$ its block-norm matrix.
Why
$$\|\mathbb{T}\|_{\mathcal{B}(\oplus_{i=1}^d\mathcal{H}_k)} \leq \| \tilde{\mathbb{T}} \|?$$
Attempt: Let $x=(x_1,\cdots,x_d)\in \oplus_{i=1}^d\mathcal{H}_k$. Then,
$$
\|\mathbb{T}x\|^2=\sum_k\left\|\sum_jT_{kj}x_j\right\|_k^2\leq\sum_k\left(\sum_j\|T_{kj}\|_{\mathcal{B}(\mathcal{H}_j,\mathcal{H}_k)}\,\|x_j\|_j\right)^2
.
$$
On the other hand,
$$\| \tilde{\mathbb{T}} \|=\sup_{\|x\|_{\mathbb{R}^d}}\| \tilde{\mathbb{T}}x\|.$$
For all $x=(x_1,\cdots,x_d)\in \mathbb{R}^d$ we have
$$
\|\tilde{\mathbb{T}}x\|^2=\sum_k\left|\sum_j\|T_{kj}\|x_j\right|^2.
$$
A:
You're almost there!
Given $x = (x_1,\dots,x_d) \in \Bbb H$, let $\tilde x$ denote $(\|x_1\|,\dots,\|x_d\|) \in \Bbb R^d$; note that $\|\tilde x\| = \|x\|$.
It suffices to show that we always have $\|\Bbb Tx\| \leq \|\tilde {\Bbb T}\|\, \|x\|$. Indeed, we have
$$
\|\mathbb{T}x\|^2=\sum_k\left\|\sum_jT_{kj}x_j\right\|_k^2\leq\sum_k\left(\sum_j\|T_{kj}\|_{\mathcal{B}(\mathcal{H}_j,\mathcal{H}_k)}\,\|x_j\|_j\right)^2\\
= \left\| \tilde {\Bbb T} \ \tilde x
\right\|^2 \leq \|\tilde {\Bbb T}\|^2\|\tilde x\|^2 = \|\tilde {\Bbb T}\|^2 \| x\|^2.
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
sed replace with special characters
I'm having some problems with sed where I need the replacement has a special regex character in it.
I've seen answers on stackoverflow, but none seem to work for my problem.
I'm trying to replace the date in a variable as follows:
date=$(date "+%d/%m/%Y %H:%M")
echo "DATE" | sed -e "s/\bDATE/${date}/g;"
However, I receive the following error:
sed: -e expression #1, char 15: unknown option to `s'
A:
If you simply change the delimiter, it suffices to make your expression work.
date=$(date "+%d/%m/%Y %H:%M")
echo "DATE" | sed -e "s|\bDATE|${date}|g"
| {
"pile_set_name": "StackExchange"
} |
Q:
A group of odd order has no non-identity elements which are conjugate to their inverse.
I want some verification for my proof to a homework problem. (Is it correct? Is there a simpler way to do this?)
Let $G$ be a finite group of odd order and suppose there is an element $g$ that is conjugate to its own inverse. In other words, there is $h \neq e$ such that $h^{-1}gh = g^{-1}$. We will show $g=e$ by supposing it's not and finding a contradiction.
We see that $gh = hg^{-1}$ and $hg = g^{-1}h$. This means given any word composed of $g$, $h$, $g^{-1}$, and $h^{-1}$, we can always "push" the $g^r$'s to one side and the $h^s$'s to the other, giving us a canonical spelling $g^rh^s$. That is to say, $\langle g, h\rangle \cong \langle g \rangle \oplus \langle h \rangle$.
By Lagrange, finding any non-trivial even subgroup will prove that $|G|$ was even after all, giving us the desired contradiction. Since both $\langle g \rangle$ and $\langle h \rangle$ are nontrivial, neither may be even. But if that is the case, then they are both odd, and $\langle g \rangle \oplus \langle h \rangle \cong \langle g, h \rangle$ is now non-trivial even.
EDIT Critical error at the end. The order of the direct sum is the product, not the sum.
A:
HINT: Note that $gh=hg^{-1}$. What is $(gh)^2$?
| {
"pile_set_name": "StackExchange"
} |
Q:
How do does that work in jquery
IF NOT mouseover/-enter/click on div "menu" THEN do stuff ELSE do other stuff?
I dont know the jquery equivalent,
is there one for that?
Thanks!
A:
Just leave the not away and exchange do stuff with do other stuff.
| {
"pile_set_name": "StackExchange"
} |
Q:
Short caption fig.scap in knitr not working?
I understood that using fig.scap should provide a short label for use with the table of figures, but it doesn't, it uses the long label. Any ideas? Rstudio Version 0.98.1091.
---
output:
pdf_document:
fig_caption: yes
---
\listoffigures
```{r, fig.cap="long caption",fig.scap="short"}
plot(1:4)
```
A:
This option was originally designed for .Rnw documents only. It does not apply to .Rmd documents. However, you can trigger LaTeX output for plots in R Markdown by specifying any of the chunk options out.width, out.height, and fig.align. For example,
---
graphics: yes
output:
pdf_document:
fig_caption: yes
---
\listoffigures
```{r, fig.cap="long caption", fig.scap="short", fig.align='center'}
plot(1:4)
```
Note you need knitr >= 1.8 (currently on CRAN) and Pandoc >= 1.13.1 (see comments below). The YAML metadata graphics: yes makes sure Pandoc is aware of graphics output in the document (it is too technical to explain here).
Update: With knitr >= v1.26.4, no special treatment (such as fig.align = 'center') is needed; using fig.scap will generate the correct LaTeX output. Since someone else has asked the same question again, I just decided to fix the issue on Github, and you will need
remotes::install_github('yihui/knitr')
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional Label in R without Loops
I'm trying to find out the best (best as in performance) to having a data frame of the form getting a new column called "Season" with each of the four seasons of the year:
MON DAY YEAR
1 1 1 2010
2 1 1 2010
3 1 1 2010
4 1 1 2010
5 1 1 2010
6 1 1 2010
One straightforward to do this is create a loop conditioned on the MON and DAY column and assign the value one by one but I think there is a better way to do this. I've seen on other posts suggestions for ifelse or := or apply but most of the problem stated is just binary or the value can be assigned based on a given single function f based on the parameters.
In my situation I believe a vector containing the four stations labels and somehow the conditions would suffice but I don't see how to put everything together. My situation resembles more of a switch case.
A:
I'll start by giving a simple answer then I'll delve into the details.
I quick way to do this would be to check the values of MON and DAY and output the correct season. This is trivial :
f=function(m,d){
if(m==12 && d>=21) i=3
else if(m>9 || (m==9 && d>=21)) i=2
else if(m>6 || (m==6 && d>=21)) i=1
else if(m>3 || (m==3 && d>=21)) i=0
else i=3
}
This f function, given a day and a month, will return an integer corresponding to the season (it doesn't matter much if it's an integer or a string ; integer only allows to save a bit of memory but it's a technicality).
Now you want to apply it to your data.frame. No need to use a loop for this ; we'll use mapply. d will be our simulated data.frame. We'll factor the output to have nice season names.
d=data.frame(MON=rep(1:12,each=30),DAY=rep(1:30,12),YEAR=2012))
d$SEA=factor(
mapply(f,d$MON,d$DAY),
levels=0:3,
labels=c("Spring","Summer","Autumn","Winter")
)
There you have it !
I realize seasons don't always change a 21st. If you need fine tuning, you should define a 3-dimension array as a global variable to store the accurate days. Given a season and a year, you could access the corresponding day and replace the "21"s in the f function with the right calls (you would obviously add a third argument for the year).
About the things you mentionned in your question :
ifelse is the "functionnal" way to make a conditionnal test. On atomic variables it's only slightly better than the conditionnal statements but it is vectorized, meaning that if the argument is a vector, it will loop itself on its elements. I'm not familiar with it but it's the way to got for an optimized solution
mapply is derived from sapply of the "apply family" and allows to call a function with several arguments on vector (see ?mapply)
I don't think := is a standard operator in R, which brings me to my next point :
data.table ! It's a package that provides a new structure that extends data.frame for fast computing and typing (among other things). := is an operator in that package and allows to define new columns. In our case you could write d[,SEA:=mapply(f,MON,DAY)] if d is a data.table.
If you really care about performance, I can't insist enough on using data.table as it is a major improvement if you have a lot of data. I don't know if it would really impact time computing with the solution I proposed though.
| {
"pile_set_name": "StackExchange"
} |
Q:
Compare: JMX vs JMS
I thought JMX was a specification and JMS was more like an implementation. I was asked the difference between the two and the questioner disagreed with this. I read about it and understood both are specifications. And saw "JMX is a monitoring spec, not a publish/subscribe spec.You could beat it
into a publish/subscribe model but that is more what JMS is supposed to do
for you." What does this exactly mean? And what is their difference and when to go for one or the other and both.
A:
Quoting from Wikipedia.
"The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients."
In simple terms: it is for passing messages.
"Java Management Extensions (JMX) is a Java technology that supplies tools for managing and monitoring applications, system objects, devices (such as printers) and service-oriented networks."
In simple terms: it is for monitoring things.
What is their difference and when to go for one or the other and both.
If you read the above, that should be self evident.
You would use JMS when you are building an system that needs (reliable, robust, resilient) message passing between different components (typically) on different computers.
You would JMX when you are implementing monitoring for your system.
(Obviously there are alternatives for both.)
I saw "JMX is a monitoring spec, not a publish/subscribe spec. You could beat it into a publish/subscribe model but that is more what JMS is supposed to do for you." What does this exactly mean?
It is difficult without seeing the context, but I think this is a response to someone else suggesting the JMX could be used to support publish-subscribe ... for something. And the guy who wrote this seems to be saying "bad idea: use JMS".
Taken out of context, it is pretty meaningless. I'd advise not trying to extract deep meaning ....
| {
"pile_set_name": "StackExchange"
} |
Q:
Performance advantages using OpenGL Loader Generator over GLEW?
Title pretty much explains it all. I first heard of the OpenGL Loader Generator project yesterday while browsing Stack and I checked it out to investigate what advantages it presents over GLEW. On the project website they state that:
This loader generation system is used to create OpenGL headers and
loading code for your specific needs. Rather than getting every
extension and core enumerator/function all in one massive header, you
get only what you actually want and ask for.
While I understand that this approach is definitely more succinct than GLEW, I do not understand how this approach improves compilation time, application performance, or interaction with OpenGL drivers. Furthermore, it seems that the process of using it requires more maintenance as you have to regenerate the extension source every time you need to utilize an additional extension. I have never noticed any performance hit when using GLEW (compared to not using it) so I am curious as to why the developers of this project feel they had a problem to address. Am I missing something?
A:
In the interest of full disclosure, I wrote the OpenGL Loader Generator.
While I understand that this approach is definitely more succinct than GLEW, I do not understand how this approach improves compilation time, application performance, or interaction with OpenGL drivers.
It's an OpenGL function loading library. With the possible exception of the inline forwarding functions in the "Function CPP" style, it's just calling function pointers. Just like GLEW.
The only possible performance difference between the two is in the time it takes to load those functions (ie: the initialization routine). And since that's an initialization function, its one-time performance is irrelevant unless it's decidedly slow.
In short, it is not the tool's purpose to improve "application performance, or interaction with OpenGL drivers". It exists to have clean headers that contain exactly and only the parts of OpenGL you intend to use. Also, it lets you easily use GLEW or GLee-style function initialization, as you see fit.
As for "compilation time" performance, I imagine that it's cheaper to compile a 100KB header than an 800KB one. But since neither GLEW nor my tool use advanced C++ techniques like metaprogramming or templates, odds are pretty good that any compile-time savings will be minimal.
Furthermore, it seems that the process of using it requires more maintenance as you have to regenerate the extension source every time you need to utilize an additional extension.
That's certainly one way to use the tool. Another way to use the tool is to figure out ahead of time what extensions are appropriate for you and just use them.
Generally speaking, when you write real OpenGL applications, you write that code against a specific OpenGL version. This version is dictated to you by the minimum hardware you want to support. If you want to support everything from outdated Intel 945 "GPUs" to the latest high-end stuff from AMD and NVIDIA, you have to write against GL 1.4 (maybe 2.1, if you're feeling really brave and are willing to do lots of testing against Intel drivers). If you want to support more recent hardware, you would write your code against one of the OpenGL 3.x versions, 3.1 depending on how much support you want to give Intel GPUs.
From there, you decide which optional features of later versions, or just hardware-specific features, you intend to support. You have a list of stuff that you intend to use, so you check those extensions and conditionally use or not use it as needed.
That's what this tool is for: when you have settled on a specific set of extensions and OpenGL version. If you want to be more flexible, you could just generate a header that includes more extensions, even if you don't use them. Or you can use GLEW; my tool is an option, not a requirement.
The tool is not meant to be everything for everyone. It's meant to be for people who know what they want, who want to have headers that don't include kilobytes of crap extensions that they will never use.
It's also good for auto-completion and the like. With a clean header, you have to sift through far less junk you have no intention of ever calling. Oh, and it helps prevent you from accidentally using something from an extension you forgot to check for. Because it's not in your header, any attempts to call such functions or use those enums will result in a compiler error.
The other thing that this is good for is ease of use. Just look at how many questions there are on this site about GLEW and "unresolved externals". This comes up, in part, because GLEW can be compiled as a static or dynamic library. So you have to use a #define in your code to switch between them (on Windows). That's bad.
With the generator, you just stick the header and source in your regular build. No library to build or link with. Just a couple extra headers and source files.
Those are the reasons why I wrote the tool.
| {
"pile_set_name": "StackExchange"
} |
Q:
ignoring file lib.a, file was built for archive which is not the architecture being linked (x86_64)
I'm trying to code a printf clone. I've built a library file called "libftprintf.a" but when I try to use it, I get the following error, on Mac OSX 10.8.5:
ld: warning: ignoring file ./libftprintf.a, file was built for archive which is not the architecture being linked (x86_64): ./libftprintf.a
Strangely this works fine (but I need only one lib called libftprintf, so this is not acceptable):
gcc -Wall -Wextra -Werror -I libft/includes/ -o ft_printf_test.bin -L libft -lft -L. -lftprintf ft_printf_test.c
I suspect I have misused the ar command to link both libs together. But I don't se my mistake yet.
What could be the cause of that?
Everything seems to compile just fine until I try to use the libftprintf.a file with the make test command. I've searched for a solution on Google, but most answers relate to XCode only. According to lipo -info, the files are x86_64.
My GCC version:
$> gcc --version
Configured with: --prefix=/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin12.5.0
Thread model: posix
Below is the full output of my makefile, for reference.
$> make re
make -C libft clean
rm -f src/ft_arrdel.o src/ft_atoi.o src/ft_bzero.o src/ft_isalnum.o src/ft_isalpha.o src/ft_isascii.o src/ft_isdigit.o src/ft_islower.o src/ft_isprint.o src/ft_isupper.o src/ft_itoa.o src/ft_lstadd.o src/ft_lstdel.o src/ft_lstdelone.o src/ft_lstiter.o src/ft_lstmap.o src/ft_lstnew.o src/ft_lstpush.o src/ft_malloc.o src/ft_memalloc.o src/ft_memccpy.o src/ft_memchr.o src/ft_memcmp.o src/ft_memcpy.o src/ft_memdel.o src/ft_memmove.o src/ft_memset.o src/ft_putchar.o src/ft_putchar_fd.o src/ft_putendl.o src/ft_putendl_fd.o src/ft_putnbr.o src/ft_putnbr_fd.o src/ft_putstr.o src/ft_putstr_fd.o src/ft_strcat.o src/ft_strchr.o src/ft_strclr.o src/ft_strcmp.o src/ft_strcpy.o src/ft_strdel.o src/ft_strdup.o src/ft_strequ.o src/ft_striter.o src/ft_striteri.o src/ft_strjoin.o src/ft_strlcat.o src/ft_strlen.o src/ft_strmap.o src/ft_strmapi.o src/ft_strncat.o src/ft_strncmp.o src/ft_strncpy.o src/ft_strnequ.o src/ft_strnew.o src/ft_strnstr.o src/ft_strrchr.o src/ft_strrev.o src/ft_strsplit.o src/ft_strstr.o src/ft_strsub.o src/ft_strtrim.o src/ft_tolower.o src/ft_toupper.o src/get_next_line.o
rm -f ft_printf.o
make -C libft fclean
rm -f src/ft_arrdel.o src/ft_atoi.o src/ft_bzero.o src/ft_isalnum.o src/ft_isalpha.o src/ft_isascii.o src/ft_isdigit.o src/ft_islower.o src/ft_isprint.o src/ft_isupper.o src/ft_itoa.o src/ft_lstadd.o src/ft_lstdel.o src/ft_lstdelone.o src/ft_lstiter.o src/ft_lstmap.o src/ft_lstnew.o src/ft_lstpush.o src/ft_malloc.o src/ft_memalloc.o src/ft_memccpy.o src/ft_memchr.o src/ft_memcmp.o src/ft_memcpy.o src/ft_memdel.o src/ft_memmove.o src/ft_memset.o src/ft_putchar.o src/ft_putchar_fd.o src/ft_putendl.o src/ft_putendl_fd.o src/ft_putnbr.o src/ft_putnbr_fd.o src/ft_putstr.o src/ft_putstr_fd.o src/ft_strcat.o src/ft_strchr.o src/ft_strclr.o src/ft_strcmp.o src/ft_strcpy.o src/ft_strdel.o src/ft_strdup.o src/ft_strequ.o src/ft_striter.o src/ft_striteri.o src/ft_strjoin.o src/ft_strlcat.o src/ft_strlen.o src/ft_strmap.o src/ft_strmapi.o src/ft_strncat.o src/ft_strncmp.o src/ft_strncpy.o src/ft_strnequ.o src/ft_strnew.o src/ft_strnstr.o src/ft_strrchr.o src/ft_strrev.o src/ft_strsplit.o src/ft_strstr.o src/ft_strsub.o src/ft_strtrim.o src/ft_tolower.o src/ft_toupper.o src/get_next_line.o
rm -f libft.a
rm -f libftprintf.a
rm -Rf ft_printf_test.bin*
gcc -Wall -Wextra -Werror -I libft/includes/ -c ft_printf.c -o ft_printf.o
make -C libft
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_arrdel.c -o src/ft_arrdel.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_atoi.c -o src/ft_atoi.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_bzero.c -o src/ft_bzero.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_isalnum.c -o src/ft_isalnum.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_isalpha.c -o src/ft_isalpha.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_isascii.c -o src/ft_isascii.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_isdigit.c -o src/ft_isdigit.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_islower.c -o src/ft_islower.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_isprint.c -o src/ft_isprint.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_isupper.c -o src/ft_isupper.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_itoa.c -o src/ft_itoa.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_lstadd.c -o src/ft_lstadd.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_lstdel.c -o src/ft_lstdel.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_lstdelone.c -o src/ft_lstdelone.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_lstiter.c -o src/ft_lstiter.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_lstmap.c -o src/ft_lstmap.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_lstnew.c -o src/ft_lstnew.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_lstpush.c -o src/ft_lstpush.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_malloc.c -o src/ft_malloc.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_memalloc.c -o src/ft_memalloc.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_memccpy.c -o src/ft_memccpy.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_memchr.c -o src/ft_memchr.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_memcmp.c -o src/ft_memcmp.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_memcpy.c -o src/ft_memcpy.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_memdel.c -o src/ft_memdel.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_memmove.c -o src/ft_memmove.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_memset.c -o src/ft_memset.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_putchar.c -o src/ft_putchar.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_putchar_fd.c -o src/ft_putchar_fd.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_putendl.c -o src/ft_putendl.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_putendl_fd.c -o src/ft_putendl_fd.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_putnbr.c -o src/ft_putnbr.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_putnbr_fd.c -o src/ft_putnbr_fd.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_putstr.c -o src/ft_putstr.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_putstr_fd.c -o src/ft_putstr_fd.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strcat.c -o src/ft_strcat.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strchr.c -o src/ft_strchr.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strclr.c -o src/ft_strclr.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strcmp.c -o src/ft_strcmp.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strcpy.c -o src/ft_strcpy.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strdel.c -o src/ft_strdel.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strdup.c -o src/ft_strdup.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strequ.c -o src/ft_strequ.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_striter.c -o src/ft_striter.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_striteri.c -o src/ft_striteri.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strjoin.c -o src/ft_strjoin.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strlcat.c -o src/ft_strlcat.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strlen.c -o src/ft_strlen.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strmap.c -o src/ft_strmap.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strmapi.c -o src/ft_strmapi.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strncat.c -o src/ft_strncat.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strncmp.c -o src/ft_strncmp.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strncpy.c -o src/ft_strncpy.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strnequ.c -o src/ft_strnequ.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strnew.c -o src/ft_strnew.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strnstr.c -o src/ft_strnstr.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strrchr.c -o src/ft_strrchr.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strrev.c -o src/ft_strrev.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strsplit.c -o src/ft_strsplit.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strstr.c -o src/ft_strstr.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strsub.c -o src/ft_strsub.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_strtrim.c -o src/ft_strtrim.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_tolower.c -o src/ft_tolower.o
gcc -g -Wall -Wextra -Werror -I includes -c src/ft_toupper.c -o src/ft_toupper.o
gcc -g -Wall -Wextra -Werror -I includes -c src/get_next_line.c -o src/get_next_line.o
ar -rsv libft.a src/ft_arrdel.o src/ft_atoi.o src/ft_bzero.o src/ft_isalnum.o src/ft_isalpha.o src/ft_isascii.o src/ft_isdigit.o src/ft_islower.o src/ft_isprint.o src/ft_isupper.o src/ft_itoa.o src/ft_lstadd.o src/ft_lstdel.o src/ft_lstdelone.o src/ft_lstiter.o src/ft_lstmap.o src/ft_lstnew.o src/ft_lstpush.o src/ft_malloc.o src/ft_memalloc.o src/ft_memccpy.o src/ft_memchr.o src/ft_memcmp.o src/ft_memcpy.o src/ft_memdel.o src/ft_memmove.o src/ft_memset.o src/ft_putchar.o src/ft_putchar_fd.o src/ft_putendl.o src/ft_putendl_fd.o src/ft_putnbr.o src/ft_putnbr_fd.o src/ft_putstr.o src/ft_putstr_fd.o src/ft_strcat.o src/ft_strchr.o src/ft_strclr.o src/ft_strcmp.o src/ft_strcpy.o src/ft_strdel.o src/ft_strdup.o src/ft_strequ.o src/ft_striter.o src/ft_striteri.o src/ft_strjoin.o src/ft_strlcat.o src/ft_strlen.o src/ft_strmap.o src/ft_strmapi.o src/ft_strncat.o src/ft_strncmp.o src/ft_strncpy.o src/ft_strnequ.o src/ft_strnew.o src/ft_strnstr.o src/ft_strrchr.o src/ft_strrev.o src/ft_strsplit.o src/ft_strstr.o src/ft_strsub.o src/ft_strtrim.o src/ft_tolower.o src/ft_toupper.o src/get_next_line.o
ar: creating archive libft.a
a - src/ft_arrdel.o
a - src/ft_atoi.o
a - src/ft_bzero.o
a - src/ft_isalnum.o
a - src/ft_isalpha.o
a - src/ft_isascii.o
a - src/ft_isdigit.o
a - src/ft_islower.o
a - src/ft_isprint.o
a - src/ft_isupper.o
a - src/ft_itoa.o
a - src/ft_lstadd.o
a - src/ft_lstdel.o
a - src/ft_lstdelone.o
a - src/ft_lstiter.o
a - src/ft_lstmap.o
a - src/ft_lstnew.o
a - src/ft_lstpush.o
a - src/ft_malloc.o
a - src/ft_memalloc.o
a - src/ft_memccpy.o
a - src/ft_memchr.o
a - src/ft_memcmp.o
a - src/ft_memcpy.o
a - src/ft_memdel.o
a - src/ft_memmove.o
a - src/ft_memset.o
a - src/ft_putchar.o
a - src/ft_putchar_fd.o
a - src/ft_putendl.o
a - src/ft_putendl_fd.o
a - src/ft_putnbr.o
a - src/ft_putnbr_fd.o
a - src/ft_putstr.o
a - src/ft_putstr_fd.o
a - src/ft_strcat.o
a - src/ft_strchr.o
a - src/ft_strclr.o
a - src/ft_strcmp.o
a - src/ft_strcpy.o
a - src/ft_strdel.o
a - src/ft_strdup.o
a - src/ft_strequ.o
a - src/ft_striter.o
a - src/ft_striteri.o
a - src/ft_strjoin.o
a - src/ft_strlcat.o
a - src/ft_strlen.o
a - src/ft_strmap.o
a - src/ft_strmapi.o
a - src/ft_strncat.o
a - src/ft_strncmp.o
a - src/ft_strncpy.o
a - src/ft_strnequ.o
a - src/ft_strnew.o
a - src/ft_strnstr.o
a - src/ft_strrchr.o
a - src/ft_strrev.o
a - src/ft_strsplit.o
a - src/ft_strstr.o
a - src/ft_strsub.o
a - src/ft_strtrim.o
a - src/ft_tolower.o
a - src/ft_toupper.o
a - src/get_next_line.o
ar -rsv libftprintf.a libft/libft.a ft_printf.o
ar: creating archive libftprintf.a
a - libft/libft.a
a - ft_printf.o
ranlib libftprintf.a
$> make test
gcc -Wall -Wextra -Werror -I libft/includes/ -L. -lftprintf -o ft_printf_test.bin ft_printf_test.c
ld: warning: ignoring file ./libftprintf.a, file was built for archive which is not the architecture being linked (x86_64): ./libftprintf.a
Undefined symbols for architecture x86_64:
"_ft_printf_string", referenced from:
_test_printf_percent in ft_printf_test-jTXeph.o
"_ft_strcmp", referenced from:
_test_printf_percent in ft_printf_test-jTXeph.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [test] Error 1
[ ckleines ~/Projects/2013-2014/Algo-1/printf ] $> lipo -info libft/libft.a
input file libft/libft.a is not a fat file
Non-fat file: libft/libft.a is architecture: x86_64
[ ckleines ~/Projects/2013-2014/Algo-1/printf ] $> lipo -info libftprintf.a
input file libftprintf.a is not a fat file
Non-fat file: libftprintf.a is architecture: x86_64
[ ckleines ~/Projects/2013-2014/Algo-1/printf ] $> lipo -info ft_printf.o
Non-fat file: ft_printf.o is architecture: x86_64
A:
Use libtool -static -o instead of ar.
Static library link issue with Mac OS X: symbol(s) not found for architecture x86_64
A:
I've found a slightly dirty but working solution for now. I extract the libft/libft.a archive in a temporary directory. Link the new library with the extracted .o files and then remove the temporary directory.
$(NAME): $(OBJ) $(HEADER)
make -C libft
mkdir libft_o && cd libft_o && ar -x ../libft/libft.a && cd ..
$(AR) $(NAME) libft_o/*.o $(OBJ)
rm -Rf libft_o
ranlib $(NAME)
The drawback being that if an object file from libft at some point has the same name than one from the printf files, it will overwrite things. But that's not likely to happen.
| {
"pile_set_name": "StackExchange"
} |
Q:
Change img src path by using NG-Model on tag
I'm new to AngularJS, I've started learning it since yesterday.
My HTML code:
<select ng-model="myImage">
<option selected disabled>Make selection</option>
<option value="earth">Earth</option>
<option value="moon">Moon</option>
<option value="sun">Sun</option>
</select>
{{myImage}}
<img ng-src="{{myImage}}">
My JavaScript code:
(function() {
app = angular.module('app', []);
app.controller("imgController", function($scope) {
function getImageIdOrName(param) {
var imageNames = ["earth", "moon", "sun"];
if (typeof param === "number") {
return imageNames[param - 1];
}
if (typeof param === "string") {
for (var i = 0; i <= imageNames.length; i++) {
if (imageNames[i] == param) {
return pad((i+1), 3);
}
}
}
}
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
$scope.myImage = "img/" + getImageIdOrName($scope.myImage) + "png";
});
}());
I'm trying to display the image which is selected in the <select> tag, the images are named like:
001.png (Earth)
002.png (Moon)
003.png (Sun)
I know that I can fix this, by doing it like:
<select ng-model="myImage">
<option selected disabled>Make selection</option>
<option value="001">Earth</option>
<option value="002">Moon</option>
<option value="003">Sun</option>
</select>
<img ng-src="img/{{myImage}}.png">
But what I really want to do is to pass names in the value of <option> instead of image IDs and then I want to use my getImageIdOrName(param) function to convert the name into ID and use the id for <img> tag's src attribute.
I've tried doing the following in my controller: $scope.myImage = "img/" + getImageIdOrName($scope.myImage) + "png";
But that doesn't seem to work, the ng-model is returning the selected value of <option> instead of doing$scope.myImage = "img/" + getImageIdOrName($scope.myImage) + "png";
Can somebody tell me what I'm doing wrong and show me a solution for this?
A:
All you need is
<img ng-src="img/{{getImageIdOrName()}}.png">
Your code doesn't make much sense, because it initializes $scope.myImageonly once, when the controller is instanciated. You need to get a new value each time the selection changes, and the easiest way to do that is to call the function from the view, as shown above.
Another option is to use ng-change on the select in order to invoke a function that changes the value of myImage every time the selection changes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extending the hyperbolic splitting on $\Lambda$ to a neighborhood of $\Lambda$
Let $M$ be a compact Riemannian manifold and let $f:M→M$ a diffeomorphism. Let $\Lambda\subset M$ be a compact invariant subset of $M$. We say that $\Lambda $ is a hyperbolic set for $f$ when there are constants $C>0$ and $0<\lambda<1$ and an invariant decomposition $T_{\Lambda}M=E^s_{\Lambda}\oplus E^u_{\Lambda}$ such that
$\|Df^n_{x}v\|\leq C\lambda^n\|v\|$ $~~\forall n\geq 0$ and $\forall v\in E^s_{x}$
$\|Df^{-n}_{x}v\|\leq C\lambda^n\|v\|$ $~~\forall n\geq 0$ and $\forall v\in E^u_{x}$
$Df_xE^s_x=E^s_{f(x)}$ and $Df_xE^u_x=E^u_{f(x)}$ $\forall x\in \Lambda.$
I'm currently reading basic texts on hyperbolic dynamics. An argument that appears repeatedly to these long texts says it is possible extending the hyperbolic splitting on $\Lambda$ to a neighborhood of $\Lambda $. In other words there is a neighborhood $U$ of $\Lambda$ where we get a decomposition $T_U=E^s_U\oplus E_U^u$ which still hold $(1)$ and $(2)$ (Possibly with $\lambda $ slightly higher), and possibly not holding $(3).$ Roughly speaking: "Hyperbolicity is an open property".
However all authors treat this statement as if it were obvious, is not commented on the appropriate details, which makes me think that this may be a corollary of a classical result. I wish someone would explain to me some standard or not way to do this.
A:
One relatively straightforward way is to use cone families. First, note that by passing to an adapted metric it is possible to assume that $C=1$. (This is a standard argument whose details should appear in the texts you are reading.) In particular, you have the one-step expansion properties $\|Df(v^u)\| \geq \lambda^{-1}\|v^u\|$ and $\|Df(v^s)\|\leq \lambda \|v^s\|$ for every $v^{u,s}\in E^{u,s}_x$.
Next, note that the hyperbolicity conditions on $\Lambda$ imply the existence of invariant cone families $K^{u,s}_x$. These can be defined by fixing $\gamma>0$ and putting $K^u_x = \{ v^u + v^s \mid v^{u,s} \in E^{u,s}_x, \|v^s\| < \gamma \|v^u\|\}$, and similarly for $K^s_x$ with the roles of $u,s$ reversed. A direct computation using the one-step expansion properties above shows that if $\gamma$ is chosen sufficiently small, then $\overline{Df(K_x^u)} \subset K_{f(x)}^u$ and $\overline{Df^{-1}(K_x^s)} \subset K_{f^{-1}(x)}^s$ for $x\in \Lambda$ and that moreover the one-step expansion holds for all $v^{u,s}\in K_x^{u,s}$ if $\lambda$ is replaced by some $\lambda'\in (\lambda,1)$.
It is straightforward to see that the existence of cones with the above properties is an open condition: given that the above conditions hold for $K_x^{u,s}$ with $x\in \Lambda$, extend the cones continuously to $x$ in a neighbourhood of $\Lambda$, and for a sufficiently small neighbourhood this continuous extension will have the same property because each of the properties above is stable under small perturbations.
Now once you have the cones on a neighbourhood $U$, you just need to get invariant subspaces $E^{u,s}_x \subset K^{u,s}_x$, and everything follows. Let's do $E^s$: the case $E^u$ is similar. Let $J = \{n\geq 0 \mid f^n(x)\in U\}$, and define $E_x^s$ to be any subspace of the appropriate dimension contained in the intersection $\bigcap_{n\in J} Df^{-n}(\overline{K_{f^nx}^s})$. Note that the sets in the intersection are compact and nested, so the intersection is nonempty even if $J=\mathbb{N}$. Take a similar intersection with $n\leq 0$ to define $E_x^u$.
Edit: Here is a clarification of how to extend the cones to a neighbourhood. Let $\tilde U$ be a small neighbourhood of some part of the attractor $\Lambda$ -- in particular, assume $\tilde U$ is small enough so that the tangent bundle $T\tilde U$ is homeomorphic to $\tilde U \times \mathbb{R}^d$. Then the subspaces $E_x^u$ on $\Lambda \cap \tilde U$ are given by a continuous function $\Lambda \cap \tilde U \to (\mathbb{R}^d)^u$, where $u$ is the dimension of the unstable subspace -- this function takes $x$ to a set of $u$ vectors forming a basis for $E_x^u$. By the Tietze extension theorem, this can be extended continuously to the neighbourhood $\tilde U$. The procedure for $E_x^s$ is analogous. This gives an extension of $E_x^{u,s}$, and hence $K_x^{u,s}$, to $\tilde U$. Cover $\Lambda$ with finitely many such neighbourhoods, enumerate them as $\tilde U_i$ for $i=1,\dots, n$, and extend first to $\tilde U_1$, then $\tilde U_2$, and so on.
This describes how to extend the cones. For the claim that the conditions on the cones extend, the key tool is the topological fact that if $\phi\colon X\to Y$ is continuous and $X'\subset X, Y'\subset Y$ are closed sets such that $\phi(X')\subset Y'$, then for every open set $Z\supset Y'$, there is an open set $V\supset X'$ such that $\phi(V) \subset Z$.
First we use this to get the expansion/contraction condition. Let $\chi(x) = \sup\{ \|Df_x(v)\| \mid v\in K_x^s, \|v\|=1\}$. Note that $\chi$ is continuous on $U$ and $\chi(x)\leq \lambda'$ for all $x\in \Lambda$. Thus for all $\lambda''\in (\lambda', 1)$, there is a neighbourhood $\hat U \subset U$ of $\Lambda$ such that $\chi(x) \leq \lambda''$ for all $x\in \hat U$. Expansion properties for $K_x^u$ follow similarly.
Finally, invariance. Extend $E_x^{u,s}$ as described above. Given $x\in U$ and $\gamma>0$ Let $K_x^u(\gamma)$ be the cone around $E_x^u$ of width $\gamma$, as in the second paragraph. Then on $\Lambda$, uniform expansion/contraction together with invariance of $E_x^{u,s}$ shows that there are $0<\gamma'<\gamma$ such that $Df(K_x^u(\gamma)) \subset K_{fx}^u(\gamma')$ for all $x\in \Lambda$. Because $Df$ and $x\mapsto K_x^u$ are continuous, and because $K_{fx}^u(\gamma)$ contains a neighbourhood of $K_{fx}^u(\gamma')$, the topological lemma shows that $\overline{Df(K_x^u(\gamma))} \subset K_{fx}^u(\gamma)$ for all $x$ in a sufficiently small neighbourhood of $\Lambda$. The invariance property for $K_x^s$ is similar.
| {
"pile_set_name": "StackExchange"
} |
Q:
compute a conditional expectation
We define $S(t) = \sum\limits_{i = 1}^{N(t)} {{e^{ - r{U_i}}}{X_i}}$ with $N(t)$ a poisson process, $U_i$ is a sequence of i.i.d. random variables having $U(0,1)$ distribution, $X_i$ are iid.
$X_i$ and $U_i$ are independant
I have to compute $E(S(t))$ and $var(S(t))$
This is what i did:
$E(S(t)) = E\left( {E\left( {\sum\limits_{i = 1}^{N(t)} {{e^{ - r{T_i}}}{X_i}} \left| {N(t) = n} \right.} \right)} \right)$
I am stuck here
A:
What you have done is a very good start. You just need to use linearity of expectation and using i.i.d. assumption. Suppose that $\overline{X^2}$ is the second moment of $X$ and $\mu_X$ its mean. Suppose that $\phi(t)$ is the moment generating function of $U$.
First see that the conditional expectation is evaluated as :
$$
E\left( {\sum\limits_{i = 1}^{N(t)} {{e^{ - r{U_i}}}{X_i}} \left| {N(t) = n} \right.} \right)=nE(e^{-r{U_i}}{X_i})=n\mu_X\phi(-r)
$$
where $N(t)=n$ is then entered into expectation:
$$
E(S(t)) = \mu_X\phi(-r)E(N(t))=\mu_X\phi(-r)\lambda t.
$$
Similarly, second moment of $S(t)$ can be calculated:
$$
E(S(t)^2|N(t)=n) = n\overline{X^2}\phi(-2r)+n(n-1) \mu_X^2\phi^2(-r)
$$
Therefore, the second moment is obtained as:
$$
E(S(t)^2)=\overline{X^2}\phi(-2r)\lambda t+(\lambda t)^2 \mu_X^2\phi^2(-r).
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
C# console app hangs when removed from Visual Studio directory
I'm attempting to publish a C# console application, and I'm following this advice. However, when I copy my Debug folder in my Visual Studio project directory and paste it to my desktop, the program no longer runs. Instead, it hangs and doesn't even execute the Console.WriteLine command on the first line. Here is my debug folder:
Any clues as to what might be the problem?
A:
Do you have any anti-virus installed? I had this problem, and the root cause was that my anti-virus would always block any binary file which is being executed from a path which is not white-listed by my anti-virus (I'm using Avast). So, I had to white-list those directories where I would build my executable files. Since then, had no problem with executing the files.
| {
"pile_set_name": "StackExchange"
} |
Q:
Density of $H^{1/2}(\partial \Omega)$ in $L_2(\partial\Omega)$
Hi,
i know that the following statement is used extensively, but i cannot find a proof anywhere:
For $\Omega$ a Lipschitz domain with boundary $\Gamma$, the space $H^{1/2}(\Gamma)$ is dense in $L_2(\Gamma)$.
Here, the space $H^{1/2}(\Gamma)$ is defined as the trace space, i.e. as $\gamma_0(H^1(\Omega))$, where $\gamma_0$ is the trace operator.
I read that one has to use density of $C^\infty(\overline\Omega)$ in $H^1(\Omega)$, but i dont see how - i can't extend an $L_2(\Gamma)$ function to a function in $H^1(\Omega)$ in a bounded way, right?
I tried Google and looked in all the books I have access to, but didn't find a proof.
Does anyone have a hint?
Thanks,
Mike
A:
Lipschitz continuous functions on $\Gamma$ are dense in $L^2(\Gamma)$ and are contained in $H^{1/2}(\Gamma)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the frame of open sets in a topological space or locale really have all meets?
According to the nLab article on locales, a frame has all meets by the adjoint functor theorem:
This seems a bit strange to me, since it's well-known that an infinite intersection of open subsets is not necessarily open.
Is the assertion on nLab true? If so, what open set do we get from $\wedge_{n=1}^\infty (-1/n,1/n)$ in the frame of opens on $\mathbb{R}$? Is it just the initial object (empty set)?
A:
Let's forget about frames and look at spaces. If $\{U_i:i\in I\}$ is a collection of open sets in a space $\mathcal{X}$, then there is a largest open set contained in each $U_i$, namely $int(\bigcap_{i\in I}U_i)$. So viewed as a poset, the set of open subsets of $\mathcal{X}$ is a complete lattice with sups being given by unions and infs being given by interiors of intersections.
But in some sense the presence of infinite meets is "coincidental" - we only really care about finite meets. This gets to the issue of how we define "homomorphism" - arbitrary meets happen to exist, but we don't care about preserving them.
| {
"pile_set_name": "StackExchange"
} |
Q:
Use Dynasty DynamoDB Query in Alexa Response
I am using Dynasty in my Nodejs Alexa Skill Service, run on AWS Lambda, to query DynamoDB. Due to the structure of the API, I am unable to use a query's result in my Alexa response. In the code below, the callback passed to 'then' is run after the handler returns, so 'name' is never assigned. How can I use information obtained in the query callback in my response?
const dynasty = require('dynasty')(credentials);
const myIntentHandler = {
canHandle(input) {
return input.requestEnvelope.request.intent.name === 'MyIntent';
},
handle(input) {
const userId = input.requestEnvelope.session.user.userId;
const users = dynasty.table('user');
var name;
users.find(userId).then(function(user) {
if(user) {
name = user.name;
} else {
...
}
});
return input.responseBuilder.speak('Hello ' + name).getResponse();
}
};
A:
The Alexa SDK for NodeJS v2 supports promises in handlers.
So, from you handler you return a promise, chained off of the Dynasty query promise.
const dynasty = require('dynasty')(credentials);
const myIntentHandler = {
canHandle(input) {
return input.requestEnvelope.request.intent.name === 'MyIntent';
},
handle(input) {
const userId = input.requestEnvelope.session.user.userId;
const users = dynasty.table('user');
var name;
return new Promise((resolve, reject) => {
users.find(userId).then(function(user) {
if(user) {
name = user.name;
let response
= input.responseBuilder
.speak('Hello ' + name)
.getResponse();
resolve(response);
} else {
...
// handle this case
// and resolve(..) or reject(..)
}
});
});
}
};
| {
"pile_set_name": "StackExchange"
} |
Q:
c - Fuga de memoria en realloc
llevo dos días con una fuga de memoria en un realloc y no encuentro el problema.
Aquí os adjunto el código:
#include "palabra.h"
Palabra * palabraNueva(){
Palabra* pal = NULL;
pal = (Palabra*)malloc(sizeof(Palabra));
if(pal == NULL){
printf("Error en la reserva de la palabra\n");
return NULL;
}
pal->tamano = 0;
pal->contenido = (char**)malloc(sizeof(char*)*pal->tamano);
if(pal->contenido == NULL){
printf("Error al reservar memoria a la coleccion de letras\n");
}
return pal;
}
void palabraElimina(Palabra * p_p){
int i;
if(p_p->tamano != 0 ){
for(i=0 ; i < p_p->tamano; i++){
free(p_p->contenido[i]);
}
free(p_p->contenido);
}
free(p_p);
}
Palabra * palabraInsertaLetra(Palabra * p_p, char * letra){
int longitud;
int tam = 0;
if(letra == NULL){
printf("Letra vacia, Error\n");
return NULL;
}
longitud = p_p->tamano;
tam = strlen(letra) + 1;
p_p->contenido=(char**)realloc(p_p->contenido,sizeof(char*)*(longitud+1));
p_p->contenido[longitud] = (char*)malloc(sizeof(char)*tam);
if(p_p->contenido == NULL){
printf("Error en la reserva de memoria de la copia de la letra\n");
return NULL;
}
strcpy(p_p->contenido[longitud], letra);
p_p->tamano++;
return p_p;
}
void palabraImprime(FILE * fd, Palabra * p_p){
int i;
if(p_p == NULL){
printf("Palabra a NULL a la hora de imprimir palabra\n");
return;
}
fprintf(fd, "[(%d) ", p_p->tamano);
for(i=0;i<p_p->tamano;i++){
if(i==p_p->tamano-1){
fprintf(fd, "%s ",p_p->contenido[i]);
} else {
fprintf(fd, "%s ",p_p->contenido[i]);
}
}
fprintf(fd,"]\n");
return;
}
int palabraTamano(Palabra * p_p){
if(p_p == NULL){
printf("Palabra a NULL a la hora de devolver el tamano de la palabra\n");
return -1;
}
return p_p->tamano;
}
char * palabraQuitaInicio(Palabra * p_p){
char* letraQuitada;
if(p_p == NULL){
printf("Palabra null a la hora de quitar letra\n");
return NULL;
}
letraQuitada = p_p->contenido[0];
p_p->contenido++;
p_p->tamano--;
return letraQuitada;
}
Y aquí el main del programa:
#include "palabra.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
Palabra * pal;
int i;
char letra [20];
char * letrai;
pal = palabraNueva();
for (i=0; i < argc-1; i++)
{
sprintf(letra,"l_%d_%s",i,argv[1+i]);
palabraInsertaLetra(pal,letra);
fprintf(stdout,"pal_%d:\n",i);
palabraImprime(stdout,pal);
fprintf(stdout,"\n");
}
while ( palabraTamano(pal) > 0 )
{
fprintf(stdout,
"QUITAMOS %s DE LA PALABRA QUE QUEDA ASI:\n",letrai=palabraQuitaInicio(pal));
palabraImprime(stdout,pal);
free(letrai);
}
palabraElimina(pal);
return 0;
}
El error de valgrind os lo adjunto aquí abajo:
==3097== HEAP SUMMARY:
==3097== in use at exit: 208 bytes in 1 blocks
==3097== total heap usage: 54 allocs, 53 frees, 2,996 bytes allocated
==3097==
==3097== 208 bytes in 1 blocks are definitely lost in loss record 1 of 1
==3097== at 0x4C2CE8E: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3097== by 0x400B2A: palabraInsertaLetra (palabra.c:51)
==3097== by 0x4008EB: main (main.c:15)
==3097==
==3097== LEAK SUMMARY:
==3097== definitely lost: 208 bytes in 1 blocks
==3097== indirectly lost: 0 bytes in 0 blocks
==3097== possibly lost: 0 bytes in 0 blocks
==3097== still reachable: 0 bytes in 0 blocks
==3097== suppressed: 0 bytes in 0 blocks
==3097==
==3097== For counts of detected and suppressed errors, rerun with: -v
==3097== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Gracias de antemano!
A:
Hasta donde alcanzan mis matemáticas, x*0=0, luego este código:
pal->tamano = 0;
pal->contenido = (char**)malloc(sizeof(char*)*pal->tamano);
De primeras no pinta demasiado bien. En la primera línea inicializas pal->tamano a 0 y después calculas la cantidad de memoria a reservar a partir de dicho valor...
De hecho si miramos la documentación al respecto vemos que pedirle a malloc 0 bytes no es buena idea:
If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.
Así que, confirmado, esa reserva de memoria no está bien hecha. Deberías esperarte a que pal->tamano tuviese un valor positivo antes de llamar a malloc
| {
"pile_set_name": "StackExchange"
} |
Q:
How to cluster objects (without coordinates)
I have a list of opaque objects. I am only able to calculate the distance between them (not true, just setting the conditions for the problem):
class Thing {
public double DistanceTo(Thing other);
}
I would like to cluster these objects. I would like to control the number of clusters and I would like for "close" objects to be in the same cluster:
List<Cluster> cluster(int numClusters, List<Thing> things);
Can anyone suggest (and link to ;-)) some clustering algorithms (the simpler, the better!) or libraries that can help me?
Clarification Most clustering algorithms require that the objects be laid out in some N-dimensional space. This space is used to find "centroids" of clusters. In my case, I do not know what N is, nor do I know how to extract a coordinate system from the objects. All I know is how far apart 2 objects are. I would like to find a good clustering algorithm that uses only that information.
Imagine that you are clustering based upon the "smell" of an object. You don't know how to lay "smells out" on a 2D plane, but you do know whether two smells are similar or not.
A:
I think you are looking for K-Medoids. It's like K-means in that you specify the number of clusters, K, in advance, but it doesn't require that you have a notion of "averaging" the objects you're clustering like K-means does.
Instead, every cluster has a representative medoid, which is the member of the cluster closest to the middle. You could think of it as a version of K-means that finds "medians" instead of "means". All you need is a distance metric to cluster things, and I've used this in some of my own work for exactly the same reasons you cite.
Naive K-medoids is not the fastest algorithm, but there are fast variants that are probably good enough for your purposes. Here are descriptions of the algorithms and links to the documentation for their implementations in R:
PAM is the basic O(n^2) implementation of K-medoids.
CLARA is a much faster, sampled version of PAM. It works by clustering randomly sampled subset of objects with PAM and grouping the entire set of objects based on the subset. You should still be able to get very good clusterings fast with this.
If you need more information, here's a paper that gives an overview of these and other K-medoids methods.
A:
Here's an outline for a clustering algorithm that doesn't have the K-means requirement of finding a centroid.
Determine the distance between all objects. Record the n most separate objects. [finds roots of our clusters, time O(n^2)]
Assign each of these n random points to n new distinct clusters.
For every other object:[assign objects to clusters, time O(n^2)]
For each cluster:
Calculate the average distance from a cluster to that object by averaging the distance of each object in the cluster to the object.
Assign the object to the closest cluster.
This algorithm will certainly cluster the objects. But its runtime is O(n^2). Plus it is guided by those first n points chosen.
Can anyone improve upon this (better runtime perf, less dependent upon initial choices)? I would love to see your ideas.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.