Prevent client-side tampering when using Google Pay JavaScript API

Question: I am trying to integrate Google Pay into our online store using the Google Pay API, and in the tutorial, there is this snippet which set the amount to pay, and currency code in a JavaScript object like this:
paymentDataRequest.transactionInfo = {
  totalPriceStatus: 'FINAL',
  totalPrice: '123.45',
  currencyCode: 'USD'
};

This looks awfully insecure, in that anyone can tamper with the values on the client-side before eventually clicking on the "Buy With Google Pay" button.
Of course, I can also check that values eventually sent back from the payment gateway, and then flag the order as fraud, but I'd also like to prevent this as early into the process as I can, if possible..
Thanks.
Comment: https://stackoverflow.com/questions/3727332/prevent-tampering-with-client-side-geocoding-results
Comment: https://stackoverflow.com/questions/10494952/sniffing-and-tampering-requests-and-responses-of-web-sites-how-prevent
Comment: https://stackoverflow.com/questions/46675099/how-to-avoid-tampering-of-javascript-html-elements
Comment: https://stackoverflow.com/questions/22208349/is-there-a-way-to-stop-end-user-tampering-with-javascript-game-code-in-my-page
Answer:
I can also check that values eventually sent back from the payment gateway

This is the only approach that will work.

I'd also like to prevent this as early into the process as I can, if possible.

It isn't possible. The client belongs to the visitor and, ultimately, is completely under their control.
You can make it harder, with obfuscation, but that makes your code harder for you to debug and doesn't stop someone from just looking at the final HTTP requests and recreating them without using your code at all.
Answer: Any data written to a device is subject to be read. When referring to secret in the technological sense, this principle is more prominent on user-facing devices, because these are typically more exposed to other agents and individuals than machines that act as servers.
The transaction information you are passing to loadPaymentData never determines the amount that will finally be charged. What you get back from this call is a payment method that is encrypted with a key that only your processor has, and hence, the payment processor (on the server side) is the only agent who can access this information. The final request to issue the charge continues to happen through a secure call between your server and your processor's.
In essence, using Google Pay to retrieve payment information to issue a charge is equivalent to how it's done without Google Pay except for the fact that the payment information is never exposed on the client side (since the user does not need to type it in), and thus, the process occurs with an additional layer of security in this aspect.


Laravel 7 : Image intervention couldn't save into storage

Question: I had problems when uploading an image into storage. I used this one before :
<code>
        if ($files) {
          foreach ($files as $file) {
            $imageName = 'gambar_laporan_'.$i.'.'.$file->getClientOriginalExtension();
            $upload = Storage::put($filePath.$imageName, file_get_contents($file));

          }
        }

</code>
It works fine before i tried to resize the image using image intervention IO. So i changed my codes to this :
<code>$files = $request->file('gambar_laporan');

         if ($files) {
           foreach ($files as $file) {
             $imageSize = getimagesize($file);

             $newWidth = $imageSize[0] - ($imageSize[0] * 0.3);
             $newHeight = $imageSize[1] - ($imageSize[1] * 0.3);
             $image_resize = Image::make($file->getRealPath())->resize($newWidth, $newHeight);

             $imageName = 'gambar_laporan_'.$i.'.'.$file->getClientOriginalExtension();
             $upload = Storage::put($filePath.$imageName, file_get_contents($image_resize));

           }
         }
</code>
Then i have this problem
<code>file_get_contents(): Filename cannot be empty
</code>
What should i do? I cant find any questions that solves this error.
Answer: You can check with this code:
<code>        $file = $request->file('gambar_laporan');
        $image = Image::make($file);
        $extension = $filename->extension();
        $file = Str::random(40) . '.' . $extension;
        Storage::put('images' . $file, $image->orientate()->encode($extension), 'public');
        $image->resize(350, 350, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        })->save();

        return $file;
        // It will return the name of image.
</code>


Unable to push to github, Remote end hung up unexpectedly

Question: I'm trying to upload a relatively large Unreal engine 4 project through sourcecontrol on Github.
It uploads completely, and when it reaches 100% it fails giving me this error:
Writing objects: 100% (8901/8901), 11.30 GiB | 33.67 MiB/s
Writing objects: 100% (8901/8901), 11.32 GiB | 31.25 MiB/s, done.
Total 8901 (delta 632), reused 8579 (delta 403)
fatal: The remote end hung up unexpectedly
fatal: The remote end hung up unexpectedly
error: RPC failed; curl 56 Send failure: Connection was reset
Everything up-to-date

(The error was parsed as 4: The remote disconnected. Check your Internet connection and try again.)

My connection is fine, because I tried it several times, and it always fails at 100%.
I tried it with Sourcetree and Github Desktop, and it produces the same error.
Answer: Check first if this is a client setting issue:
cd /path/to/your/repository
git config http.postBuffer 524288000

(and you can increase that setting since Git 2.13)
Also make sure to not exceed a GitHub size limit.
Comment: I am definitely exceeding the size limit, My project is 11gb and the limit is 1gb apparently. Strange how it lets me upload to 100% and then decides to crash.

Thank you.
Comment: Ah yes, the size limit. Had me pulling out my hair. Thanks!
Comment: You just need to first go to main Directory to run this command
Answer: Had this issue recently, when I was using the HTTPs url of the repo for push, later switched to SSH and it works like expected. My Repo size was 500MB and using SSH fixed it for me.
Setting up SSH keys if you don't have one

create the SSH Key:
ssh-keygen -t rsa -b 4096 -C "email@example.com"

copy the key(everything) from the created public key file usually present in ".ssh/id_rsa.pub"

logon to github and add the public key under
settings->SSH_and_GPG_Keys->new_key

after adding the public SSH Key into Github, test the SSH connection using
ssh -vT firstname.lastname@example.com

Once you have your SSH ready.

Setup upstream(push) remote URL which will be SSH url of the repo instead of usual HTTPS url.
git remote add <remote-name> email@example.com:username/repo_name
Set your branches to use the new upstream url
git push --set-upstream <remote-name> <branch_name>
Push the large repository as usual
git push <remote-name> <branch_name>


Problem about C++ class (inheritance, variables scope and functions)

Question: I have a class that contains some data: class DATA
Now I would to create some functions that uses those data. I can do it easily by writing member functions like DATA::usedata();
Since there are hundreds of functions, I would to keep an order in my code, so I would like to have some "categories" (not sure of the correct name) like:
DATA data;
data.memory.free();
data.memory.allocate();
data.file.import();
data.whatever.foo();

where memory, file and whatever are the "categories" and free, allocate and foo are the functions.
I tried the inheritance way, but I got lost since I can not declare inside DATA a memory or file object, error C2079 occurs:  http://msdn.microsoft.com/en-us/library/9ekhdcxs%28VS.80%29.aspx
Since I am not a programmer please don't be too complicated and if you have an easier way I am all ears.
Comment: If you are not a programmer, C++ is probably not for you.
Comment: Hundreds is too much. Split your class up.
Comment: "Categories" are what classes are for in the first place.
Comment: @BlueRaja: Agree, maybe your DATA contains too much at the same time
Comment: @GMan: I agree with you.
Comment: @Luigi Giaccari: Why are you trying to accomplish this if you are not a programmer?
Answer: Give your data class some classes of its own, and let those classes refer to the data object that holds them. It sounds like you might have tried to do that already. If you got an error, then you were doing something else wrong.
struct DATA
{
  struct DataMemory
  {
    DATA& data;
    DataMemory(DATA& d): data(d) { }
    void free();
    void allocate();
  };
  struct DataFile
  {
    DATA& data;
    DataFile(DATA& d): data(d) { }
    void import();
  };
  struct DataWhatever
  {
    DATA& data;
    DataWhatever(DATA& d): data(d) { }
    void foo();
  };

  DataMemory memory;
  DataFile file;
  DataWhatever whatever;
  DATA(): memory(*this), file(*this), whatever(*this) { }
};

Each of the inner classes has a member that's a reference to the containing DATA object. They have constructors to allow that member to get assigned. The DATA class itself also has a constructor to initialize each of its members with a reference to itself.
You can now implement the functions and refer to any of the DATA object's members.
void DATA::DataMemory::free()
{
  data.whatever.foo();
}

The inner classes aren't required to be inner classes; they could be standalone top-level classes like DATA if you want, but I think nesting them helps show their interdependence.
Comment: Interesting. Me like it even if I don't have an immediate use for that "pattern".
Answer: The easiest way would be to do the categories just as a naming convention. If you replace the . with _ you don't need any "subobjects" and get:
data.memory_free();
data.memory_allocate();

data.file_import();

This way you basically have the same function names but avoid all the implementation problems of the subobject approach.
Comment: When you have hundreds of function in a single class and the information can be divided into specialized classes one should do so. Otherwise, it would be like writing thousands of lines of code in int main() {} when you can break the information in many smaller functions. It will be less of a mess to understand the code and it will force the person to write cleaner code. One should use the full potential of OOP and not just have a brick of information in one single class.
Comment: @Alerty: I don't think this gets much better if you only divide the functions into different "namespaces" that all work on the basic `data` object. To suggest how `Data` could be split up in a more OO design there really isn't enough information.
Answer: If you have a class that has hundreds of member functions, you almost certainly need to break that up into multiple classes.  To achieve the type of naming syntax that you're after you could use name spaces to group related classes into "categories."
Answer: class DATA
{
public:
    class CategoryA_Class
    {
        friend DATA;

    private:
        CategoryA_Class() { }

    public:
        bool GiveMeSomeInt() { return 1; }
    };

    class CategoryB_Class
    {
        friend DATA;

    private:
        CategoryB_Class() { }

    public:
        bool GiveMeSomeBool() { return true; }
    };

public:
    CategoryA_Class CategoryA;
    CategoryB_Class CategoryB;
};

int _tmain(int argc, _TCHAR* argv[])
{
    DATA mydata;

    int a = mydata.CategoryA.GiveMeSomeInt();
    bool b = mydata.CategoryB.GiveMeSomeBool();

    return 0;
}

Answer: It is normal to feel confuse when you have so many functions in one class. The trick is to break it all up so that the information is contained in smaller classes that inherits a parent class that has common functions and data to all children.
From what I see you already found a common name for the information. class DATA can be that parent class. Now, you need to break up the information into types of Data. In other words, you will have children classes that will be specialized in something. A quick way to divide the information is to create a diagram of a parent class linked with children classes.
Here is a small example of what you could do:
//parent class
template <class T> class Data
{
   T data_; //you could use an array like a std::vector or
            //use a stream

public:
//...
   void foo();
   T getData() const;
};

//child class
template <class T> class Memory
    : public Data
{
public:
   void free();
   void allocate(T data);
//...
};

//child class
template <class T> class File
    : public Data
{
public:
   T readFile(); //could read the contents of a
                 //file and save it in data_ (class member from parent class)

   void writeFile(); //could write data_
                     //(class member from parent class) to a file
//...
};

Also, here is documentation if you need help on the concept of inheritance.


How to detect a point above and below a region?

Question: I have this image:

Where the red dots are coordinates that divide the different letters of this Arabic word segment.
I want to detect the dots above or below the areas between the dots.
The dots are (from left to right) = [81,183;80,217;83,275;83,314]
Now there is a dot above the letter between [81,183] and [80,217]. Similarly there are dots above section between [80,217] and [83,275] and dots below region [83,275] and [83,314].
What I want to do is suppose a dot is detected above a coordinate then that coordinate must be deleted.
Would it be possible to detect these in Matlab?
edit: Here is the original image

The first image is just a crop showing my region of interest
Comment: Could you upload your original image somewhere and link it here? The one without the red encircled markers might be best. Asking for the original because the coordinates aren't matching when saving the image from here.
Comment: Out of curiosity, what does the word mean?
Comment: It's written Argentine in Arabic. :)
Comment: @Divakar You are right, sorry about that. I foolishly copied from the wrong matrix. I fixed the coordinates now and uploaded the original image
Answer: You can extract the coordinates of the individual objects with regionprops
Here is an example implementation:
im=rgb2gray(imread('https://i.stack.imgur.com/jic1X.jpg'));
P=regionprops(~im2bw(im), 'All');

Areas=cell2mat({P.Area});
Centroids=cell2mat({P.Centroid}');

Select only the points that have an area larger that 10 but smaller than 100:
Coord=Centroids(Areas< 100 & Areas > 10,:);

Monitor the dots found:
imshow(im);
hold on
for k=1:length(Coord)
    plot(Coord(k,1), Coord(k,2), 'ro');
    hold on
end

Result:

You can then sort the points with something like:
Aboves=Coord(Coord(:,2) < 80,:);
Belows=Coord(Coord(:,2) > 80,:);

From here, there are many ways of solving your problem, one option is the following:
dots=[81,183;80,217;83,275;83,314];

DetectDots=zeros(length(dots)-1, 1); % Creating a vector of zeros corresponding to the gaps between the elements in 'dots'
for k=1:size(dots,1)-1
    if ~isempty(find((Aboves(:,1) > dots(k,2) & Aboves(:,1) < dots(k+1,2)))) %*
        DetectDots(k)=1;
    elseif ~isempty(find((Belows(:,1) > dots(k,2) & Belows(:,1) < dots(k+1,2))))
        DetectDots(k)=-1;
    else
        DetectDots(k)=0;
    end

end

The result is a vector DetectDots with value [1,1,-1] in this case that indicates that there are dots above between the two first point, and between the second and third point, and dots below between the third and last point of the vector dots.
*find returns a logical array with ones where the condition is met. isempty checks if the output of find has at least one element. As a result the condition is one if there is at least one element in the array Aboves or Belows that meets the criteria. ~ is the logical NOT, hence ~= means not equal. & is the logical AND. Note also that the coordinates between images and arrays are inverted in matlab.
Comment: I was just pointing out, because I guess ultimately someone would do it :) I will wait for OP to respond on the query. +1 For the efforts so far and an almost correct answer!
Comment: @FarazKhan `~` is the logical NOT. Hence `~=` means not equal. The first selects elements of `Coord` that are non-zero and have a second coordinate smaller than 80. The second line returns ones when there is an element in `Above` that is between two points of the `dots` vector.  `&` is the logical AND.
Comment: @FarazKhan I admit that the first line was a bit confusing, I edited the code to make it more straightforward (I hope).
Comment: You could also mention about how different dots (the upper and lower ones) could be detected to be in between which letters.
Comment: Thanks for the edits. Curious though, shouldn't the comparison be done with codes? The comparison to be in between letters would be a bit complex.
Comment: @Divakar agreed, I don't have more time to invest at the moment, but if you write an answer with complementary information, you would surely get my vote.
Comment: Thank you. So if I apply this code to my original image(uploaded in edit) Wont it find the centroids of every connected components? And is the aim to locate the dots like this? Then how would I differentiate between all? The first image was cropped because some dots are desirable like the left most and right most dot in the uncropped image. I only want to see if a dot exists above or below the regions between successive red dots that I labelled. ~Thank you
Comment: @Jigg Thank you but this is not exactly what I wanted to achieve. There are desirable dots in there. For example the left most and right most dots are of no interest to me. only the dots between my initial red circles are what i want to detect. Thats why I cropped the image. What I want to do is suppose a dot is detected above a coordinate then that coordinate must be deleted. I'm sorry but I think I was not clear in the initial question. I'll add this target there
Comment: @Jigg Thank you. That is what I was looking for. Can you please possibly comment your edited code. I seem to easily understand the code above the display of coords but below that I am a bit confused. Thank you again for your help
Comment: Thank you @Jigg. I understand the functions being used, not just the conditions. Can you please tell me whats going on in ``Aboves=Coord(Coord(:,2) < 80 & Coord(:,2) ~=0,:);`` I never knew ``~`` could be used in Matlab. And also in ``find((Aboves(:,1) > dots(k,2) & Aboves(:,1) < dots(k+1,2)))`` You mentioned find returns if this condition is met. it is this condition that I do not understand. Thank you for your help


enabling button when all the fields are filled up

Question: I am using knockout.js for data binding.Actually there is a form which some fields accepting name,number,email etc.Suppose if any one of the field is not filled and the save button is pressed then that button goes to disabled state.Till now its working fine.
Now if I fill the empty fields then I want to enable that button again and I dont know how to do.Can any body please help me how to do?
The following is the js code
self.newPatient = ko.asyncCommand({

    execute: function (complete) {
        var isValid = $('#addPatientForm').parsley('validate');
        if (isValid) {
            var patientJson = ko.toJSON(self.patient());
            formdata.append("json", patientJson);
            //self.enableButton(false);
            var imagepath = $.ajax({
                url: projectUrl + "newPatient",
                type: "POST",
                data: formdata,
                processData: false,
                contentType: false,
                success: function (res) {
                    formdata = new FormData();
                    imagepath = res;
                    var length = self.patients().length;
                    var patient = self.patient();
                    //  self.enableButton(true);
                }
            });
            $('.alert-patient-success').show();
            self.patients.removeAll();
            self.getPatients();
            /* $.when(self.patients.push(self.patient()),self.patient(new Patient()),self.dirtyFlag1().reset(),$('#patientTabs a:last').tab('show'))
.always(complete);*/
        }
    },
    canExecute: function (isExecuting) {
        return !isExecuting && isDirty() && isValid();
    }
});

this is html code


View embedded in a NavigationView (where latter has navBar hidden) glitches every time it is pushed on to the View [SwiftUI]

Question: I have been struggling with this for the past hour mainly because all the solutions I have seen seem more hack-y than real solutions, and this is making me question the production readiness of NavigationBar in SwiftUI.
I have a MainView and a PushView, and I need to hide the navBar on both the Views.
However, this creates the following issues:
1)When the PushView is pushed onto the MainView, there is a glitch where the nav bar appears and then disappears.
2)Going back to MainView is now not possible because the back button in PushView is also now hidden.
What I want is my own button in PushView that pops this View and goes back to HomeView
What am I doing wrong:
struct HomeView: View {
    var body: some View {

        NavigationView {

            NavigationLink(destination: PushView()) {
                Text("PRESSME")
            }.navigationBarTitle("")
            .navigationBarHidden(true)

        }
    }
}

struct PushView: View {

    var body: some View {
        Text("Hello View Two")
    }
}

Answer: Yes, the NavBar is a bit buggy as you have already experienced yourself.
A clean solution which is not hacky in my opinion looks like this:
struct HomeView: View {
    var body: some View {

        NavigationView {

            NavigationLink(destination: PushView()) {
                Text("PRESSME")
            }.navigationBarTitle("")
                .navigationBarHidden(true)

        }
    }
}

struct PushView: View {
    @Environment(\.presentationMode) var presentationMode

    var btnBack : some View {
        Button(action: {
            self.presentationMode.wrappedValue.dismiss()
        }) {
            Image(systemName: "chevron.left")
        }
    }

    var body: some View {
        VStack {
            HStack {
                btnBack // Your custom back button.
                    .padding()
                Spacer()
            }
            Spacer()
            Text("Hello View Two")
            Spacer()
        }
        .navigationBarTitle("")
            .navigationBarHidden(true) // This hides the NavBar on PushView.
    }
}


TopHat 2 does not seem to recognize or use the designated output directory

Question: I am trying to set up a data analysis pipeline in TopHat. For some reason, I cannot seem to get the program to use my designated output directory. I have tried the following commands:
<code>--output-dir "/path" \
--output-dir /path \
-o "/path" \
-o /path \
</code>
However, all the files keep being written to ./tophat_out
Has anyone encountered a similar problem?
Answer: I ran into this problem too, specifying all options before the genome and sequence files solves this however.


Bounded sequence

Question: I'm currently learning for my math exam and I am stuck at the following problem:

If a real sequence $a_n$ has an upper and a lower boundary $s_u$ and $s_\ell$, then $s=\max\{s_u,s_\ell\}$ is a boundary. Find a counter-example.
  I need to give $a_n$, $s_u$ and $s_\ell$ so that $s$ is not a boundary.

I have got no idea what they want from me, because if a sequence of elements has a lower and upper boundary, how can the max of these two boundaries not be a boundary.
I'm lost, thanks in advance.
PS: I tried to translate it from German to English so please correct me if i got it wrong. I hope one can understand it.
In german:
Finden Sie ein Gegenbeispiel für die Behauptung "Ist sl eine untere und su eine obere Schranke, so ist s:=max{su,so} eine Schranke."
(Also: an, su und sl angeben, so dass obiges s keine Schranke ist)
Comment: What do you exactly mean by *boundary*? You mean a number that is greater than the absolute values of all $a_n$?
Comment: You probably mean $a_{n}$ has an upper bound of $s_{u}$ and a lower bound of $s_{\ell}$.  By $s$ being a boundary, do you mean a least upper bound?
Comment: You might consider adding the question (in German) below your post here.  Perhaps if another German speaker is here they can assist with the translation.
Comment: If my interpretation is correct, then $s$ is not a "boundary" just because you are not taking into account the fact that numbers can be negative. But that really appears to be just a trick, I hope there is something more serious here.
Comment: Of course numbers can be negative but due to the fact that *s* is is the max out so *su* and *so* it will still always be a bound/boundary
Or am i wrong?
Comment: @giomasce And, yes by boundary i meant a number that is greater than the absolute values of all *an*
Comment: Any lower bound is always smaller than any upper bound. So $s$ will always be $s_u$, independently of $s_\ell$. You probably wanted $s = \max\{|s_u|, |s_\ell|\}$.
Comment: yep that is what i thought as well. But we already proofed that *s=max{|su|,|sl|}* is always true in our lecture. And now i need to find a counter-example to the same statement without the absolute values.
Comment: What about something like $a_{n}=-1+\frac{1}{n}$ for $n\geq 1$.  Then $s_{u}=0$ is an upper bound and $s_{\ell}=-1$ is a lower bound.  $s=\max\{0, -1\}=0$ but $|a_{n}|>0=s$ for $n>1$.  (I'm not certain I understood the question right.)
Comment: well that would approve for every negative bounded sequence... somehow i can't imagine the problem to be that easy... meh... well i guess i'll ask my tutor and i'll post the answer as soon as i know. Thanks a lot
Answer: You are right, and the question is wrong. If $a$ is a lower bound for a sequence and $b$ is an upper bound, then $\max\{a,b\}=b$, which of course remains as an upper bound.

Bounded sequence


Stopping a webworker whilst its processing a large amount of data?

Question: I am wanting to use Web Workers to process image data in chunks and apply filters to the image data as working directly on the UI thread appears to be slow. (My question is not specific to image data processing in the grand scheme of things)
The main issue whilst I am coming up solutions to my issue is that if I was to split the image I am processing into chunks and then send that data to the Web Workers I would still like to be able to cancel the processing by sending another message to the web workers. It is my assumption though if I use a traditional loop (and not a recursive function that yields) to process the data that I will not be able to receive further messages until that process is completed (negating the usefulness of sending a cancel message).
Is this the case? I have not tried it as of yet but I would like to know if its worthwhile for me to somehow split this data further in the web worker itself so it can continue to receive further messages and process them.
If splitting it up is the best method, how would you go about essentially yielding? I assume it would be some sort of 1 millisecond timeout which then allows the event loop to process the incoming messages and then have my process function pick up where it left off, but if this isnt the way to do this, could someone suggest another?
Comment: Just use generator that yields every 100 iterations and is resumed by `setTimeout`.
Comment: Yes, that sounds fine. Of course, you can also [`.terminate()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/terminate) a worker, not sure what kind of cancellation you want to do and how often you need it.
Comment: I thought about using .terminate() but i think the overhead of recreating web workers would ruin the benefit of having them somewhat. Im thinking the cancel event may be called quite often because I want sliders and depending on user input if they change the values before its processed which is highly likely its going to slow it down.
Answer: You can use your main web-worker to spawn subworkers rather than "yeilding" ... so let the main web-worker you spawn for image processing handle both incoming messages from the main UI thread, as well as create chunks of data for image-processing tasks that it issues to it's own subworkers.  That way you can easily terminate or manage any child-workers depending on what messages come in from the main UI thread, and your main web-worker remains responsive at all times without blocking, needing to have some form of a "yield", or wait for some fixed timeout period before it can respond to messages again.


Minecraft: How can we repopulate a VANILLA world with MODDED ores?

Question: I'm currently stuck in the process of trying to finalize a modded world in Minecraft. I need to repopulate ALREADY CREATED chunks with ores from mods.
For more context:

We're trying to use a 1.7.10 Earth map. We found a couple, all of which look fine and okay.
We're also trying to use a 1.7.10 modpack
that is personalized to fit our Minecraft experience. It includes
simpler mods like ArchimedesShips and Flans as well as
worldgen-spawning stuff like Thermal Foundation, IC2, Tinker's
Construct, and Pam's HarvestCraft

Particularly, the combination of the above premises is something I can't do, but are exactly what I need to do. I'm fairly familiar with MCEdit, MultiMC, COFHCore, WorldEdit, etc., so any combination of such to produce the modded ores would be the appreciated. The closest I've gotten to such a world was using COFHCore to regen ores which kinda did it. Through some config file tampering I got Thermal Foundation ores to generate in the Vanilla Earth map. However, two problems arose: ONLY thermal foundation ores were regen-ing into the vanilla map, and it simply took too long and by the time I checked in (2 hours into regening) on how much has regened, only a part of India got all the cool new ores.
I know this might seem impossible, but I got close to what I was hoping for, so I know it's possible. I'm hoping that someone out there might know the answer or at least another step to finding it. This is a really cool idea and I would appreciate any help. Thank you.
NOTE All help is appreciated, but please don't ask me to delete chunks in MCEdit. I understand that I can delete chunks to get new chunks with modded stuff, but that's not what I'm looking for.
Comment: To anyone thinking that this is impossible: It's probably not, because chunk generation uses multiple steps, one of the later ones is replacing some stone with ores, setting trees, etc. So this is probably possible somehow.
Comment: @FabianRöling The problem is, if it's a map, then the chunks are already **fully** generated.
Comment: The way I read it, you don't need to play a specific map, but rather you just want the general layout of Earth. There's more mod-compatible ways to achieve that, TerrainControl being the first option that comes to mind. I also remember a mod that literally exists to produce an Earth-like world, I don't remember the name though.
Answer: Assuming that, for example, the Earth map has nothing relevant below level 65 (or however far down you need to go). Start any old map with all the relevant mods and allow it to generate sufficient chunks so that it is the same size as your earth map.
Copy everything from the generated world at say, level 60 and lower and copy it into you earth map at level 60 and down. Replacing the vanilla generated ores with the modded ones.
Its a hell of a lot of work, so you might create a sort of grid system. Coping 10 by 10 chunk areas at a time and deleting them (or cut and paste) from the generated world as you go to help you line them up.
You might also start by deleting everything level 60 and below so you can see your progress.
Answer: I, off the top of my head, recommend selecting a large area of the modded ores in WorldEdit, going over to the already loaded chunks, and manually pasting the ores around everywhere.  I'm sure there's a more efficient way of doing this, but this is probably the easiest way I can think of that doesn't require any other programs.  The command would be something like
//pos1 ~1000 ~-255 ~1000
//pos2 ~-1000 ~255 ~-1000
//paste
Make sure to paste it elsewhere, to avoid having a giant chunk of land in your world
Select the pasted chunk
//replace (all blocks other than your special ores) air
//copy
Then go back to the terrain and paste your structure (which should be all ore veins) with
//paste -a
This will paste only the ores and not disturb anything around them.  Not keeping the -a could paste all of the selected blocks, including air, and would thus create a massive cube of floating ore veins.
The only downside I can see with this method is there being floating ores inside caves.  Not sure what to do there.
Good luck!
Comment: Another option would be to `//replace` the stone with ores at the correct ratio. That gets rid of floating ores, at the cost of not forming natural veins.
Comment: Almost forgot: IIRC WorldEdit doesn't support relative coordinates due to the way its special coordinate wrapper is implemented.


Add Trailing Slash for MVC Application

Question: I'm building an application based on the MVC design pattern, and I want my URLS to be like: http://example.com/page/action/.  I successfully got it to work with the code below, but if the URL doesn't end with a slash, the application breaks.  I've searched all over, mostly Stack Overflow, but I haven't found a good answer that works with my code. I've tried to modify many of the answers others got, but that didn't work either.
Here is my latest code (that doesn't include things I've tried):
<code># Turn on Rewrite Engine
    Options +FollowSymLinks
    RewriteEngine On

    RewriteRule ^(.*) /$1/ [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)/(.*)/$ ./index.php?p=$1&a=$2 [PT]
</code>
I got a few ideas from:
Simple MVC mod-rewrite
I am new to mod_rewrite, but I don't understand why I can't get the code to add a trailing slash.  It looks correct.  Can someone help me out? Thanks!
Answer: <code>RewriteEngine on

RewriteBase /

RewriteCond %{REQUEST_URI} !/$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) $1/ [R=301,L,QSA]
</code>
Comment: Thanks for the fast response.  It worked perfectly!  I've been trying to figure this out for weeks...

Add Trailing Slash for MVC Application


How to hook up sauna heater wired for 3 wire 230v to US 240v?

Question: Purchased a sauna at Home Depot.  The heater that came with it is Advertised as 220v 20 amp.  My plan was to plug it into a 240v outlet I have in the garage (though after looking at my panel it is currently going to a 30 amp). When it arrived the heater had no plug on the end and only 3 wires.  The schematic included with the heater (BC 23 see picture) shows it is currently wired to 1. Ground 2. Neutral 3. L1 & L2 which are bridged.  From my research this is how it would be wired for European use.  My question is can I remove the 3 wire cord and the bridge and instead hook it up as 1. Ground 2. Neutral 3. L1 to 120 4. L2 to 120 so I can use a 4 wire US plug?  I plan to use an electrician to do the work but so far the 2 places I called didn't seem to know.  Appreciate any advice.
Comment: You're looking in the wrong section of the instructions.  When this thing got a UL/CSA listing, the instructions were approved *as part of that*.  The UL/CSA listing is only valid if installed according to instructions, which you must do per NEC 110.3(B).   That page of the instructions will be EN/FR because that's a Canadian requirement. Purely as a practical matter they often put ES (North American Context) there as well, which opens it to the rest of the continent + many installers are Spanish-first-language.
Comment: It might be possible to remove the jumper between L1/L2, but think this spa might be illegal to use or sell.  Does it have a UL mark on it?  If no instructions for a North American system, then just as easy to return it and get a proper one.
Comment: The cord coming out of the heater has a UL sticker on it.  It was delivered by freight on a pallet so it won't be an easy return.  I don't understand why Home Depot would be able to sell it if it wasn't legal to use.  On the webpage for Home Depot it says:ETL/CSA certified - meets all US and Canadian electrical safety standards - 220-Volt, 20 Amp plug
Comment: Will let the experts answer, but probably do the hook up as for BC23E 400v without the jumper.  Seems to be legal, but odd they don't have instructions for 240v systems.
Comment: I'm pretty sure if you hardwire this instead of using a plug you will be able to follow the 230V wiring below, with L1 going to L1, L2 going to N, and Ground going to G. That should be safe, requires less wire, and will eliminate the (likely) requirement for a GFCI.
Comment: I looked again at the instruction booklet and the posted schematic is the only one shown for the EN section.  There are a total of 14 languages for the instruction book (95 pages total 13 of which are in English).  FR has its' own separate listing.  So I'm not sure what's going on.
Answer:
My question is can I remove the 3 wire cord and the bridge and instead hook it up as 1. Ground 2. Neutral 3. L1 to 120 4. L2 to 120 so I can use a 4 wire US plug?

If you do that, you will likely end up with the heater running at a quarter of it's designed power.
Most likely for a US style 120/240 supply you need to leave the "L1 and L2" terminals connected together and connect them to one hot from your supply, connect the "N" terminal to the other hot from your supply and leave the neutral conductor from the supply disconnected.
Comment: Yes.  However, this should only be done if told to by the instructions, which UL or CSA will have *approved* as part of granting the machine a UL Listing.  OP may need to do a web search for the *American/Canadian* instructions.  The languages should be EN/FR on that document and possibly ES.


Where is the last riddler destructible on Founders' Island?

Question: I don't know if there's a game glitch or I'm missing something but I have completed every challenge and every riddle except the 15 "destructible a symbol of strength to overcome" on Founders Island and I cannot find it on the map or any help in walkthrough. Any help would be appreciated.
Thanks
Answer: Founders' Island can be a bit tricky when it comes to trophy locations. If you have beat up all of the Riddler informants and still don't see them on your map, it may mean you need to go underground. Some of the trophies for the Founders' Island portion are underground in the subway section of the map. Be sure to check there for all of the rest of the items
Here's also a video of where everything is:


AWS EC2 Instance - How to add a Load Balancer to an Instance Application that already has an Elastic IP and SSL?

Question: I have an Ubuntu 18.04 LTS EC2 Instance with a deployed Django application. The instance also has an elastic IP. The Django application already has a domain name mapped to it in nginx, and it also already has an SSL certificate mapped using certbot.
My questions are:

Do I need to add an HTTPS listener to the load balancer? If yes, do I use the SSL generated by certbot? How?
Do I need to change the IPV4 that is in the nginx config file and DNS record with the new IPV4 of the load balancer created?
Answer:
Do I need to add an HTTPS listener to the load balancer? If yes, do I use the SSL generated by certbot? How?

Yes, you would need to create a HTTPS listener and you need to use a certificate, you can import the same certificate you're using on nginx or get a new certificate from ACM (free), both will work as long as the subject/SAN are correct.

Do I need to change the IPV4 that is in the nginx config file and DNS record with the new IPV4 of the load balancer created?
ELB provided DNS name , the IP changes so you can't use IP address but after using ELB, you don't need elastic IP on EC2 instance , the communication between ELB and EC2 is on private IP so you can allow 0.0.0.0 in nginx and restrict ELB to make connections to ec2 instance, you will need to point your website to ELB DNS name eventually.
Comment: For #2, what will happen to the elastic IP that is currently associated with my instance after adding ELB? So you mean, I need to point my domain record to the new ELB DNS? For example, I have a Domain Name sample.net which points to my elastic ip, I need to change it to point to the new ELB DNS?
Comment: Yes, that how people will resolve to ELB and connect to it and elb neing proxy connects to your ec2 instance, careful with the changes :)


Grub not Showing Windows 7

Question: I recently installed Ubuntu to my harddrive and now I can only boot to Ubuntu, Windows 7 does not show up, please help.
Comment: Can you please include **everything you've tried** in the question?  This is to avoid people from taking the time and suggesting/answering the question, only to find out that you've already done it. You can always [edit] your question using the `edit` link right underneath it. Anywho, when you tried boot repair, it should have created a log file containing information and gave you a link. Can you please provide that link?
Comment: Welcome to Ask Ubuntu Tristin! Can you try running [boot-repair](https://help.ubuntu.com/community/Boot-Repair)?
Comment: Yes I have tried, It did not work.
Answer: Is this Ubuntu 12.04, 12.10, or 13.04?
Anyhow, open a terminal using Ctrl-Alt-T and run this command:
sudo update-grub | tee ~/update-grub.txt

You will need to type in your password. After that runs, try restarting. If it still doesn't work, give us the contents of the file called update-grub.txt located in your home directory.
Comment: That didnt work but thanks anyway, and I have nothing in that file

Grub not Showing Windows 7


Strange behaviour in item recommendation with MyMediaLite

Question: I'm working with the MyMediaLite's item recommendation tool and I'm trying to understand how can I do in order to generate a prediction file which consists only of test set's items.
Actually with the default options (--overlap-items) it generates a prediction file which contains both items that are present in the test set and someone which aren't present in it. This is really annoying simply because I need to obtain correct recommendation in order to generate the metrics for my recommender (I use an external tool in order to generate the metrics).
So I've tried the option "--in-test-items" which should use as candidate items only those present in the test set, but this is not the result that I obtain. Actually I'm working with the movielens 100k dataset which I've binarized following a specific strategy: I've assigned 1 to items which have as rating 4 or 5, otherwise 0.
I want to report here the command that I use in order to produce the recommendation in a implicit feedback situation(supposing that I'm trying to execute the test on the first split of the dataset):
item_recommendation --training-file=u1.base --test-file=u1.test --prediction-file=u1.mml_res --in-test-items --recommender=ItemKNN --predict-items-number=10
There is something incorrect in this command? Do I have to fix something?
Thank you in advance.
Alessandro Suglia
Answer: The question was answered in this e-mail thread: https://groups.google.com/forum/#!topic/mymedialite/Sm6RXehqrYE


Error while make install xnee

Question: I did the ./configure and make with root permission but I can't make install.
output:
Making install in libxnee
make[1]: Entering directory '/home/alex/xnee-3.19/libxnee'
Making install in src
make[2]: Entering directory '/home/alex/xnee-3.19/libxnee/src'
make[2]: Nothing to be done for 'install'.
make[2]: Leaving directory '/home/alex/xnee-3.19/libxnee/src'
Making install in test
make[2]: Entering directory '/home/alex/xnee-3.19/libxnee/test'
make[3]: Entering directory '/home/alex/xnee-3.19/libxnee/test'
 /bin/mkdir -p '/usr/local/lib'
 /bin/bash ../../libtool   --mode=install /usr/bin/install -c   libtestcb.la '/usr/local/lib'
libtool: install: /usr/bin/install -c .libs/libtestcb.lai /usr/local/lib/libtestcb.la
libtool: install: /usr/bin/install -c .libs/libtestcb.a /usr/local/lib/libtestcb.a
libtool: install: chmod 644 /usr/local/lib/libtestcb.a
libtool: install: ranlib /usr/local/lib/libtestcb.a
libtool: finish: PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/sbin" ldconfig -n /usr/local/lib
----------------------------------------------------------------------
Libraries have been installed in:
   /usr/local/lib

If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
   - add LIBDIR to the `LD_LIBRARY_PATH' environment variable
     during execution
   - add LIBDIR to the `LD_RUN_PATH' environment variable
     during linking
   - use the `-Wl,-rpath -Wl,LIBDIR' linker flag
   - have your system administrator add LIBDIR to `/etc/ld.so.conf'

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
----------------------------------------------------------------------
make[3]: Nothing to be done for 'install-data-am'.
make[3]: Leaving directory '/home/alex/xnee-3.19/libxnee/test'
make[2]: Leaving directory '/home/alex/xnee-3.19/libxnee/test'
make[2]: Entering directory '/home/alex/xnee-3.19/libxnee'
make[3]: Entering directory '/home/alex/xnee-3.19/libxnee'
make[3]: Nothing to be done for 'install-exec-am'.
make[3]: Nothing to be done for 'install-data-am'.
make[3]: Leaving directory '/home/alex/xnee-3.19/libxnee'
make[2]: Leaving directory '/home/alex/xnee-3.19/libxnee'
make[1]: Leaving directory '/home/alex/xnee-3.19/libxnee'
Making install in cnee
make[1]: Entering directory '/home/alex/xnee-3.19/cnee'
Making install in src
make[2]: Entering directory '/home/alex/xnee-3.19/cnee/src'
make  install-am
make[3]: Entering directory '/home/alex/xnee-3.19/cnee/src'
make[4]: Entering directory '/home/alex/xnee-3.19/cnee/src'
 /bin/mkdir -p '/usr/local/bin'
  /bin/bash ../../libtool   --mode=install /usr/bin/install -c cnee '/usr/local/bin'
libtool: install: /usr/bin/install -c cnee /usr/local/bin/cnee
 /bin/mkdir -p '/usr/local/share/man/man1'
 /usr/bin/install -c -m 644 cnee.1 '/usr/local/share/man/man1'
make[4]: Leaving directory '/home/alex/xnee-3.19/cnee/src'
make[3]: Leaving directory '/home/alex/xnee-3.19/cnee/src'
make[2]: Leaving directory '/home/alex/xnee-3.19/cnee/src'
make[2]: Entering directory '/home/alex/xnee-3.19/cnee'
make[3]: Entering directory '/home/alex/xnee-3.19/cnee'
make[3]: Nothing to be done for 'install-exec-am'.
make[3]: Nothing to be done for 'install-data-am'.
make[3]: Leaving directory '/home/alex/xnee-3.19/cnee'
make[2]: Leaving directory '/home/alex/xnee-3.19/cnee'
make[1]: Leaving directory '/home/alex/xnee-3.19/cnee'
Making install in gnee
make[1]: Entering directory '/home/alex/xnee-3.19/gnee'
Making install in src
make[2]: Entering directory '/home/alex/xnee-3.19/gnee/src'
gcc -DHAVE_CONFIG_H -I. -I../.. -DPACKAGE_DATA_DIR=\""/usr/local/share"\" -DPACKAGE_LOCALE_DIR=\""/usr/local//locale"\" -I"../../libxnee"/include -I../../        -DXNEE_XINPUT_SUPPORT  -g -O2 -MT gnee-main.o -MD -MP -MF .deps/gnee-main.Tpo -c -o gnee-main.o `test -f 'main.c' || echo './'`main.c
main.c:35:21: fatal error: gtk/gtk.h: No such file or directory
 #include <gtk/gtk.h>
                     ^
compilation terminated.
Makefile:475: recipe for target 'gnee-main.o' failed
make[2]: *** [gnee-main.o] Error 1
make[2]: Leaving directory '/home/alex/xnee-3.19/gnee/src'
Makefile:379: recipe for target 'install-recursive' failed
make[1]: *** [install-recursive] Error 1
make[1]: Leaving directory '/home/alex/xnee-3.19/gnee'
Makefile:430: recipe for target 'install-recursive' failed
make: *** [install-recursive] Error 1

Comment: It appears that your system doesn't have a gtk development package. Normally the `./configure` script would detect that and refuse to create the corresponding Makefiles, however it seems that in this case it is slipping through and allowing the build to fail later (possibly because it tries to use the deprecated `gtk-config` instead of `pkg-config`). Make sure the `libgtk2.0-dev` is installed and try again.
Comment: You have just stripped the important parts of the compile log.  Could you add few more lines before "compilation terminated"?
Answer: GNU Xnee can be installed from the default Ubuntu repositories. Open the terminal and type:
sudo apt-get install gnee cnee

GNU Xnee is a suite of programs that can record, replay and distribute user actions under the X11 environment. Think of it as a robot that can imitate the job you just did.
gnee: X event recorder/replayer - GUI flavor
cnee: X event recorder/replayer - command-line flavor
Answer: It might be due to the issue with configuration file setup so try with the below,
1) First check the source file,
tar xvf xnee-3.02.tar

2) Second check the Xnee directory,
cd xnee-3.02

After doing so please try with clean all and then try with installing again,
make clean all

make install

Hope this helps.
Comment: make clean all also failed...
Answer: You can install xnee without difficult compilations by the command:
sudo apt-get install libxnee0

It is in the Official Ubuntu Repository.

Error while make install xnee


My editor doesn't recognize a component with extension .vue "ChatApp.vue" in a laravel project

Question: My editor doesn't recognize a  component with extension .vue "ChatApp.vue" in a laravel project. Im using atom by the way.
All code is in grey instead of colored as the editor does with other parts and files of the laravel project.
<template>

Example Component

                        I'm an example component.

</template>

Comment: Does this answer your question? [How can I enable syntax highlighting for .vue files in Atom?](https://stackoverflow.com/questions/45227611/how-can-i-enable-syntax-highlighting-for-vue-files-in-atom)
Answer: I think what you are looking for is a syntax highlighter. Install either of these packages.
https://atom.io/packages/language-vue package to enable syntax highlighting to Vue components.
https://atom.io/packages/atom-beautify package. This will help in highlighting as well as indenting.


Normal distribution non linear transformation

Question: I have the following problem :
Given $X \sim N(\mu,\sigma^2)$ and $X' = h(X) = (\frac{x-\mu}{\sigma})^2$
Find $E[X']$ and $V[X']$.
My reasoning is as follow :
Since $X' \sim (\frac{x-\mu}{\sigma})^2$ if we take $Z \sim N(0,1)$ then $X' \sim Z^2$.
Also since $E[X'] = \int_{-\infty}^{\infty}x'f_{x'}(x')dx \sim \int_{-\infty}^{\infty}z^2f_{z}(z)dz$
Thus $E[X']$ is the same as the second, non centered, momentum of a normal standard distribution, is that correct?
Similarly $V[X'] = E(X'^2) - [E(X')]^2$ thus I can calculate the second momentum for $Z$ and it's mean to obtain $V[X']$
Answer: Your approach is correct but you have made some mistakes. $V(X')=E(X')^{2}-(EX')^{2}$ (not $(EX')^{2}-E(X')^{2}$).You will need the second moment and the fourth moment of $Z$ to find the variance.
Comment: Thanks for the correction, edited the question.
Answer: You are on the right track.
If $Z\sim N(0,1)$ then to be found are $\mathbb EZ^2$ and $\mathbb EZ^4-(\mathbb EZ^2)^2$.
Mistake in $V[X']$ (see answer of Kavi).
Comment: Thanks, edited.


Is there a way to keep traps constantly on?

Question: In terraria, there are multiple types of traps. My favorite being the flame trap. My question is, is there a way to make an electrical loop or a clock like in minecraft to keep the flame trap constantly on? Or any trap really, just as long as the trap reactivates constantly.
Also, I know that there are timers but I want to integrate the trap into my home security system; it is basically a switch that turns blocks on and off to block entrances as shown below and I can't have the timer constantly turn that on/off every 1/3/5 second(s)

The other switch (Blue and purple wiring) serve to open only two entrances/exits
Comment: You could just put two switches next to each other, one for walls, one for traps on timers.
Comment: @DomenikVanBuskirk The reason why I need it to be on one is so that once the doors have been closed, the traps activate and give extra protection to the house.
Answer: You want a timer or a crab engine (a statue-spawned crab trapped in a 1-high compartment with a pressure plate). Timers can be turned on and off just like a switch by right clicking them, so you can enable or disable your home security system whenever you like, or indeed you can use switches and other mechanisms to turn timers on/off.
Comment: @BakedPotato http://terraria.gamepedia.com/Crab_Engine and also http://terraria.wikia.com/wiki/Wire_Creations#Crab_Engine
Comment: can you add a picture with the circuitry?
Comment: @BakedPotato circuitry of what?
Comment: Can you show me the crab engine basically


get the first day of the month

Question: I initially started with getting few months back from current date
SELECT DATEADD(month, -3, getdate())

which gives me the date range from three months ago to today, as of today 9/26/2022, the code gave me 6/26/2022. I would like to get up to the first day of June which is 6/1/2022.
However, the following functions according to some googling returned error:
DATE_TRUNC(month,DATEADD(month, -3, getdate()))

or
DATETRUNC(month,DATEADD(month, -3, getdate()))

from
https://learn.microsoft.com/en-us/sql/t-sql/functions/datetrunc-transact-sql?view=sql-server-ver16
or the trunc_date.
Comment: Better idea: `DATEFROMPARTS( YEAR( SYSUTCDATETIME() ), MONTH( SYSUTCDATETIME ), 1, 0, 0, 0, 0 )`.
Comment: Also, avoid `GETDATE()`, instead you should be using UTC in databases - and _not_ using the server's local datetime.
Answer: Assuming you are resolving this only once and not on numerous records.
Example
SELECT DATEADD(month, -3, format(getdate(),'yyyy-MM-01'))

or
SELECT dateadd(month,datediff(month,0,getdate())-3,0)

Results
2022-06-01 00:00:00.000

Answer: What error are you getting? Did you see that DATETRUNC...

Applies to:  SQL Server 2022 (16.x) Preview

Meaning if you aren't running on a very recent preview build of SQL Server 2022, it's not going to work, and this is the error you should be seeing:

Msg 195, Level 15, State 10
'DATETRUNC' is not a recognized built-in function name.

Another way is to use EOMONTH() to get the first day of next month, then subtract 4 months instead of 3:
SELECT DATEADD(MONTH, -4, DATEADD(DAY, 1, EOMONTH(GETDATE())));

Or DATEFROMPARTS(), which is simpler (especially if you perform part of the calculation ahead of time):
DECLARE @d date = DATEADD(MONTH, -3, GETDATE());

SELECT DATEFROMPARTS(YEAR(@d), MONTH(@d), 1);

get the first day of the month


How to determine eigenvectors of symmetric circulant matrix {{A,B,B},{B,A,B},{B,B,A}}?

Question: I'm trying to find the eigenvectors for the matrix $$\begin{bmatrix} A & B & B \\ B & A & B \\ B & B & A \end{bmatrix} $$ .
I determined the eigenvalues to be $\lambda_1=\lambda_2=A-B$  and $\lambda_3=A+2B$. I also detrrmined one eigenvector to be $v_3=\frac{1}{\sqrt{3}}\begin{bmatrix} 1 \\1\\1 \end{bmatrix}$  .
But I'm having issues with detrrmining the remaining ones. For the first eigenvalue, the matrix used to determine eigenvector coefficients reduces to $$\begin{bmatrix} 1 & 1 & 1 \\ 0& 0 & 0\\ 0& 0 & 0 \end{bmatrix} $$.
From this I managed to extract some conditions for the coefficients, but I don't know how to determine eigenvectors that actually satisfy the eigenvalue equation. Conditions:
$$v_1+v_2+v_3=0$$
$$v_1\neq v_2\neq v_3\neq 0$$ $$v_1^2+v_2^2+v_3^2=1$$
Any help very appreciated.
Comment: See https://math.stackexchange.com/a/1521354/265466 for how to read a kernel basis from the rref. Otherwise, this is practically a duplicate of https://math.stackexchange.com/q/2177457/265466 and many other questions.
Answer: We can arbitrarily pick values for $v_1,v_2,v_3$ that satisfy $v_1+v_2+v_3=0$.
In particular we do not need them all to be different from $0$. We only need the vector to be different from the zero vector. And we don't need the vector to have length $1$ either, although we can normalize afterwards if we want to.
We can pick for instance $v_1=1$ and $v_3=0$, which means that $v_2=-1$. Just now we've found the eigenvector $(1,-1,0)$.


how to prove that $n(n+1)$ can't be square?

Question: Prove: for $n$ is positive integer, it's impossible that:
$$\exists k \in \mathbb Z, n(n+1)=k^{2}$$
I know that $(n,n+1)=1$, but the process seems odd using it.
Answer: $$n^2 < n(n+1) < (n+1)^2$$
Comment: This is exactly the solution that is shown in the duplicate version; we shouldn't re-answer duplicates.
Comment: @mathh, this is a basic, very-nice, simple answer which is more or less well-known. It could prefectly well be the poster did not even know there's a duplicate version (you posted 3 minutes after him) and even less that this is the answer there...
Comment: @DonAntonio I never implied that he copied anything, though.
Comment: Then why the "we shouldn't re-answer duplicates" comment, @mathh ?
Comment: @DonAntonio I meant that the exact same answer is already written and that we should avoid answering duplicates and post solutions in the original question instead. The answerer likely didn't know this is a duplicate, as you claim, though, in which case posting this answer could be reasonable, but we can't ignore the possibility that he knew this is a duplicate but wanted to become more popular and get some reputation by posting the answer instead. But, again, I'm not claiming he knew this is a duplicate.
Comment: right, I'm all for not answering duplicates, however: in this particular case your comment came after my answer. the link to the other question you gave is from over a month - I haven't seen this question and since the answer takes literally one line it just seems easier to type it than to look for other similar questions on mathSE.
Answer: Suppose for contradiction that there's some non zero $k$ such that $n(n+1)=k^2$
Then $(n-k)(n+k)=-n$
But one of the numbers $n-k$ or $n+k$ has absolute value > $|n|$.
This is a contradiction.
Comment: This answer would be a great addition to the original question.
Comment: Can't you just say $n$ and $n + 1$ are even and odd always but squares are always = even $\cdot$ even or odd $\cdot$ odd ?? (This is just proof sketch/idea, I just had to do this for homework and turned it in using my  argument here)
Answer: Below is a a solution that works much more generally than $\, n^2 < n(n+1) < (n+1)^2.\ $ Suppose that $\ n(n\!+\!1) = c^2\,$ in a UFD. Then, since $\,n,\,n\!+\!1\,$ are coprime, as in this proof we deduce that $\, n\!+\!1 = ua^2,\ n = u^{-1} b^2,\,$ for some $\,a,b,\,$ unit $\,u.\,$ So $\, 1 = (n\!+\!1)-n = ua^2\!-u^{-1}b^2,\,$ so scaling by $\,u\,$ yields $\, u = \bar a^2\! -b^2\! = (\bar a-b)(\bar a+b),\,\ \bar a = ua.\,$ Thus $\, \bar a+b = v,\ \bar a-b = v^{-1}\,$ for some unit $\,v,\,$ hence $\, \bar a = (v+v^{-1})/2,\,\ b = (v-v^{-1})/2.\ $
In UFDs like $\,\Bbb Z\,$ with finitely many units, there are only finitely many possibilities for the units $\,v,u\,$ hence the proof reduces to checking only finitely many cases.
Comment: But since $n$ and $n+1$ are coprime and make a square when one is multiplied by another, wouldn't it be a better argument to let $n+1=a^2$ and $n=b^2$ without the $u$?
Comment: How does the $u$ make the argument stronger (if it does) and why does the comprimeness of $n$ and $n+1$ let us deduce that $n+1=ua^2$ and $n=u^{-1}b^2$? Why couldn't we deduce that if they weren't coprime? Couldn't we just let $u$ be an integer such that $u\mid b^2$ in any case?
Comment: @mathh The unit factor is needed in general UFDs since, e.g. if $\,ab = c^2\,$ then also $\,(au)(bu^{-1}) = c^2.\,$ The linked answer gives a simple proof of the invoked lemma that works in any UFD (and for any power, not just squares).
Comment: @Downvoter If something is not clear then please feel welcome to ask questions and I will be happy to elaborate. This is much more to the essence of the matter from a divisibility viewpoint.
Answer: U can also see it this way
 n is integer
Arithematic mean will be greater than geometric mean
So
(n + n+1)/2 is greater than equal to [n(n+1)]^1/2
So (n+1/2)^2  is greater than equal to n(n+1)
So for any integer n , (n+1/2)^2 cannot be an integer
Now u may say that it would the maximum value
But u can see for attaining a lesser value u can only decrease n and n is always integer.
So it holds true.
Comment: Your inequality is undefined when $n\le -2$.
Comment: ya true ! but y is it so  ?I mean how did u deduce it ?
Comment: $\sqrt{n(n+1)}$is undefined when $n\le -2$. If you can't see why, solve the inequality $n(n+1)<0$. A square root of a negative number is undefined in the context of real numbers. And additionally, in general, the AM-GM (as well as all the other power mean inequalities) inequality is for positive numbers (about half of them can include $0$. AM-GM is correct for non-negative numbers; however, the harmonic mean is undefined when one of the numbers is zero).


Ubuntu server 14.04 Webmin installed

Question: I am running Ubuntu 14.04 server.  I am administering the domain from GoDaddy.  I would like to dump GoDaddy and use my Ubuntu server for everything including e mail and set up my own DNS from Ubuntu.  I am currently using DSN from my ISP.  I want to get stand alone as soon as possible.  Where should I start?
Answer: For dns you could start with bind. Bind is software to setup your own nameserver.
For email you could take a look at Dovecot for imap/pop3 and postfix for smtp. Alternatively you could take a look at exim.
If you are planning on serving websites you can take a look at apache or nginx. (there are a lot of alternatives, look for which best serve your specific need).
If you are hosting php, a lot of people go with the basic LAMP stack: Linux Apache Mysql/mariadb and php.
It will not be easy to learn all the settings for the software and the principles behind them all at once. But it is fun to do and very worthwile.
There are tons of tutorials on the web to install lamp with vhosts (if you want more then one domain on your server) and also some for bind.
Comment: I currently have LAMP installed and operational.  I am currently serving web content.  I have Webmin installed and wish to stick to it for configuration.  I now have a A record operational of abmail.archbrooks,us.  I have also submitted a new MX record but it has not propagated as of  now.
Comment: Keep in mind registrars might force you to a 2-name server setup - to provide a level of failover.  1&1, Gandi.net, and godaddy are examples of such registrars who complain...
Comment: In my particular situation I am stand alone.  The ISP does not become involved with anything I care to do with my server.  I have purchased this platform and I am free to make it do anything I am programmer enough to make happen.  I do not anticipate any complaints from the ISP at this time.  I will however keep you posted on all developments.

Ubuntu server 14.04 Webmin installed


Required_once file not routing correctly

Question: I am attempting to include a file, which I have done so successfully on the exact page which I am having issues now. For some reason the following calls are not working. I have tried all three methods.
require_once ("required_files/page-count.php");
require_once 'required_files/page-count.php';
include_once("required_files/page-count.php");

Initially I named the folder php instead of required_files and I received error messages, so I changed it thinking that php may have been a restricted folder name. Now since I have changed it, it appears it is still searching for the previous name I had, but it is no where within my code.
The errors:

Warning: require_once(php/page-count): failed to open stream: No such file or directory in /home4/public_html/account/required_files/page-count.php on line 40
Fatal error: require_once(): Failed opening required 'php/page-count' (include_path='.:/opt/php55/lib/php') in /home4/public_html/account/required_files/page-count.php on line 40

The home files is the file I am trying to include the file page-count.php file within.
Does anyone have any idea what is going on and why this won't work?

In required_files folder:
Comment: Is the folder listing you're showing for `account` or `public_html`?
Comment: @wogsland It is for `account`.
Comment: I know it appears I am still calling for `php/post-count.php`, but I am not and that is why I am so confused.
Comment: What's on line 40 of `page-count.php`?
Comment: @wogsland Right now it is a commented out line of code. Not sure why it is reading it. `//require_once ("required_files/page-count.php");`. The line I have uncommented is `include_once("required_files/page-count.php");` ....... I do not have the `php/post-count.php` anywhere on the page, not even commented out.
Comment: @wogsland It appears that whenever I do `include_once("required_files/page-count");` (leave out the .php) the page will load, but leave me with a warning that the page doesn't exist. Why do you think whenever I put php in the link it kills it off? I have other instances of `.php` and it works, such as: `require_once("fixDate.php");`
Answer: The /opt/php55/lib/php is the default path. It will try there if it can't find it anywhere else.
I would echo a test.php like this:
This will tell you if it's /home4/publc_html/ or /home4/public_html/account as your root directory.
It is good form to use $_SERVER['DOCUMENT_ROOT'] because your host may move you to a new server with a different home folder. This way it will always resolve to the correct place.
Comment:   in a test.php


Partial view doesn't get the object. always a null exception

Question: My partial view
@page
@model TechManagement.Models.ProjectTask

Call from my edit page
  @foreach (TechManagement.Models.ProjectTask task in Model.Project.Tasks)
            {
    <partial name="Task" model="@task">
}

same happens for
@Html.Partial("Task", (TechManagement.Models.ProjectTask)task)

Answer: Delete @page in you partial view.
Because @page makes the file into an MVC action.
Answer: TL&DR:  When creating a PARTIAL do NOT add a @page modifer
Explanation: A partial is considered a 'dumb' page, because it only accepts input from the caller.  Due to this limitation, the partial does NOT need any modifiers outside of the @model  being passed in.
Answer:
@page  <-- REMOVE THIS LINE!!!!!
@model TechManagement.Models.ProjectTask


Removing Paint from Enamel?

Question: My partner and I recently purchased a house, and it looks like the previous owners did a quick paint job covering some edges of the fixtures in the bathroom.
What would be the easiest and safest way to clean the paint from the enamel?
Comment: Is it latex or oil?
Comment: Dump some boiling water on it. If it wrinkles it is latex.
Comment: I'm making the assumption that toilets and sinks are coated in enamel.
Comment: @gbronner Is there a quick way for me to check?
Comment: The paint is indeed latex.
Answer: If it was paint from the walls, I'll take a stab in the dark and guess that they used the cheapest possible latex paint to get the place ready to sell.  Try scraping at it with a credit card, starting from the edge of the paint.
If it starts coming off, use the credit card to pick up a handful of cheap plastic putty knives and go at it. Most latex paints don't stick particularly well to enamel unless it's been pretty severely abraded, and cheap plastic putty knives won't damage it (metal will, or at very least leave marks).
Answer: The standard way is to use a nylon brush with some hot soapy water and scrub it off.
Apply masking tape on the wall to protect it, and score the paint with a razor. You may want to use a razor scraper as well, depending on how flat your fixtures are.
Alternatively, you could look into getting a steam gun, and using jets of steam to hit the paint on the fixtures.

Removing Paint from Enamel?


Connecting band/rim joist to floor joists on a cantilevered deck

Question: I'm building a deck. Joists are sitting on top of the beam and cantilever over the end of the beam a bit.
What is the appropriate way to connect the rim (end of the deck that is perpendicular to the joists) to the joists?   I've seen people toenail it to the joists, but my understanding is you shouldn't nail into the end grain of the joists.  Is there a connector built for this purpose (I'm thinking there is probably a 90 degree plate)?
Answer: As Tester101 mentioned, in this application there is close to no load on the rim joist, since your actual joists are supported by the beam. Nailing through the rim joist into the end of the other joists will be fine. I've built plenty of decks like this.
Here's a study that was done on end nailing, and the relevant recommendations:

Recommendations
Nails driven into the end grain of wood do resist both static
  and impact loads. However, additional research is required
  in several areas. Of the 4,723 data points on the relationship
  of specific gravity to nail withdrawal strength, only 294 data
  points were from tests of nails with a diameter larger than
  2.52 mm (0.099 in.). Therefore, research is needed on endgrain
  withdrawal capacity of nails with a diameter greater
  than 4.1 mm (0.163 mm) so that Equation (5) can be further
  developed.
Furthermore, none of the studies evaluated repetitive loading
  of nails from the end grain since joints in service typically
  do not experience strictly static or impact loading. Repetitive
  loading may cause end-grain withdrawal capacity to significantly
  decrease over time.
There is conflicting data on how threaded nails perform in
  comparison with smooth shank nails when withdrawn from
  the end grain. Three studies showed an increase in nail
  withdrawal capacity whereas one study showed a decrease.
  Since the use of threaded fasteners in construction is increasing,
  more research is needed to determine the effects of
  surface characteristics on end-grain withdrawal.
Finally, more research is needed to determine the long-term
  withdrawal strength of nails driven into end and side grain.
  The data in this report suggest that over time end-grain and
  side-grain withdrawal capacity may become equivalent.
  Very few test replicates measuring the effect of time delay
  on withdrawal strength were conducted, and more tests need
  to be run to clarify these limited observations.

If you still feel like you need more support, yes, you can find something like this:
at most hardware stores. If you're working with pressure treated lumber remember you will need galvanized plates and connectors.
Comment: ***NOTE:**  Do not use the band joist as part of the support structure for the railing, especially if you've end nailed it to the joists*
Comment: yes, good point. When doing this we would notch the posts for the railing into the deck and put blocking in behind the post, fastening it with lag bolts to both the joists and blocking.
Answer: It sounds like you need joist hangers

The advantage of these is the nails into the joists run across the grain, not in parallel to it (as they would if you end nailed them).
<code> Images and links for illustration only, not an endorsement of a product or source.
</code>
Comment: In this situation the band joist should have no load on it, it's just there to close of the joist bay. End nailing should be more than adequate.
Comment: Would you install them upside down, when attaching a band joist?
Comment: @Tester101 Not sure, but since the joists are fully supported by the beam (unlike when you use them on a ledger), that sounds right. The crossover strip provides further support beyond the shear strength of the side nails.
Comment: @Tester101 Probably true, but if the top edge of the rim is flush with the decking (as opposed to under it), there might be a small load if someone stepped on the edge. But not a big load or often.


One attribute storing likle array

Question: Please I really discouraged,
Is it possible to make a single entity like array attribute?
For example :
entity = person
attribute = courses
And the entity able to contain a few courses(attribute).
i have a many persons, and i need storing many courses on one person
and i don't know where to store them, and how store them
and after to get the specific person and show the all courses...
Comment: i have a many persons, and i need storing many courses on one person
and i don't know where to store them, and how store them

and after to get the specific person and show the all courses...
Answer: It would be a more common design to make both person and course entities and then have a many-to-many relationship between them.  That way, if something about a course changes, you don't have to make the change in every person's array.

One attribute storing likle array


Does the Black Box heal multiple times if it hits multiple people?

Question: Does the Soldier's Black Box heal multiple times for +15 a piece if it hits multiple people, or is it only +15 if it hits anybody at all?
Can this effect crit? (can any healing crit in TF2 or have I played WoW too long...)
Comment: Both (mutually exclusive) answers are posted, but for some reason the one that offers a testing method isn't voted as highly.  What is the correct answer?
Answer: Yes, you heal more if you hit multiple people. I just tested this.
However the GUI displays the +15 over each other.
If you want to try it yourself, I can recommand using tr_walkway. Just set constant resupply off and bot movement speed to zero.
Answer: Yes. The more people caught in the splash damage, the better.
The healing effect can't crit, but will heal the full amount even if you barely deal damage to them.
Comment: I agree with Dunhamzzz - If the black box hits anyone, regardless of how much damage it does (or how many people it hits) it will heal 15.
Comment: "It can't crit" Even now after Valve removed "No critical hits" from a bunch of weapons and replaced it with -25% damage?
Comment: @Powerlord I'm referring to the healing effect. Let me edit that clarification.
Comment: I don't think this is right, are you saying if your rocket hits 3 people, you'd get healed 45? Because I think you only get healed 15 regardless of *how many* people it hits.


" If condition" as one of the constraints to a Column Field?

Question: I have a Sales tax column in one of my SQL Table where Data is stored.
I was wondering  is it possible to place an constraint on the table itself for the Sales Tax
Column saying " if > June 2008 tax is 2 % " else "tax is 4 %"?
Should that come from stored procs related  to that Table?
Answer: Do you want the tax to be auto-populated?
Constraints only perform verification, not population of data, which can be done by stored procs or triggers.
Comment: I do not want it to be auto populated ,I want verification to be done.
Answer: You probably need to use a trigger rather than a constraint. An AFTER INSERT trigger should do the trick.
Comment: Since it appears a constraint can be written, it is better to put it in a constraint. Books Online even states that if you can use a trigger or a constraint it is better to use the constraint. Search for this in BOL to see what I mean
constraints [SQL Server], vs. DML triggers
Answer: If you want to make sure that the column 'tax' is 2 or 4 depending on the month (e.g., month 9 = September), then you could do this:
<code>ALTER TABLE SomeTable
   ADD CONSTRAINT CK_SalesTax
   CHECK ((MONTH(GETDATE()) = 9 AND SalesTax = 2) OR (MONTH(GETDATE()) != 9 AND SalesTax = 4))
</code>
Obviously, vary for your conditions. e.g., to test for dates after June 2008, it's a bit simpler.
<code>(GETDATE() >= '1 June 2008' AND SalesTax = 2)
</code>
You should be able to build this into a CHECK constraint of using a similar mechanism as I've dropped in the first example.
Note this only checks the value that put in to the table. It won't auto-populate. As other people have noted, if you want auto-population, you need a trigger.
Answer: You could use a constraint to achieve this effect...
pseudo-SQL...
<code>(YourDate >= '6/1/08' and YourTaxData = 0.02) or (YourTaxData = 0.04)
</code>
You might consider instead using a table to host the tax values and using your queries to pull the appropriate tax value for a given date/location.  That's more scalable than the constraint.
Comment: Without knowing what country he's in, I'd avoid using purely numeric dates -- is this the 6 January or 1 June? It'd be safer to name the months instead.
Comment: @rangerchris - I agree with you completely, just throwing out pseudo code to illustrate the constraint concept.  If it were actual code I would have used datediff... :)
Answer: here is a simple way you can alter or create a new table
<code> create table #test (
Date datetime,
amount money,
tax as case when date > '06/01/08' then convert(decimal(10,2),4.00) else convert(decimal(10,2),2.00) end,
)

insert into #test
select '05/01/08', 10.00

insert into #test
select '07/01/08', 10.00

select * from #test
</code>


What does it mean to be a Ninja Assassin?

Question: While playing Halo: The Master Chief Collection, I came across a mode in the Team Action Sack playlist called Ninja Assassins. It's a slayer type game in which the player is given a sniper rifle, an energy sword, and the boost armor ability, and the mini-map is disabled. The objective is to become the deadliest ninja, but all it is, is a team slayer game. At the bottom of the screen while playing however, there is a ninja level counter with 1-3 out of 3. This count goes up when you get a kill, but seems to have no real significance. Is it pointless or does it have a cause?
Answer: There are actually a couple of stats that get boosted depending on your Ninja Level.

Ninja Level 1

Shields recharge at a faster rate (2x)
Assassinations performed at a faster rate (2x)

Ninja Level 2

Shields recharge at a faster rate (2x)
Shields recharge sooner than normal (after 3 seconds)
Assassinations performed at a faster rate (3x)

Ninja Level 3

Shields recharge at a faster rate (2x)
Shields recharge sooner than normal (after 2 seconds)
Assassinations performed at a faster rate (4x)
Unlimited Thruster Pack energy

Source


Cannot convert partially known tensor in TensorFlow/TFLearn

Question: I'm a beginner to TensorFlow and still trying to figure out how it works, so I'm not sure if the error is a problem with my architecture or something more basic -- here I'm trying to train a siamese neural network (we feed a left and right input into left and right NN with identical weights, and try to map it to feature vectors that have small distance if the inputs are similar and large distance if the inputs are different).
The error I get occurs at the regression step:
  File "siamese.py", line 59, in <module>
    network = regression(y_pred, optimizer='adam',
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tflearn/models/dnn.py", line 63, in __init__
    best_val_accuracy=best_val_accuracy)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tflearn/helpers/trainer.py", line 120, in __init__
    clip_gradients)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tflearn/helpers/trainer.py", line 646, in initialize_training_ops
    ema_num_updates=self.training_steps)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tflearn/summaries.py", line 236, in add_loss_summaries
    loss_averages_op = loss_averages.apply([loss] + other_losses)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/training/moving_averages.py", line 292, in apply
    colocate_with_primary=(var.op.type == "Variable"))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/training/slot_creator.py", line 106, in create_zeros_slot
    val = array_ops.zeros(primary.get_shape().as_list(), dtype=dtype)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 1071, in zeros
    shape = ops.convert_to_tensor(shape, dtype=dtypes.int32, name="shape")
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 628, in convert_to_tensor
    ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/constant_op.py", line 198, in _tensor_shape_tensor_conversion_function
    "Cannot convert a partially known TensorShape to a Tensor: %s" % s)
ValueError: Cannot convert a partially known TensorShape to a Tensor: (?,)

I don't know how to resolve this problem if the first dimension needs to be None for the batch size (correct me if I'm wrong).
Relevant parts of the code are below:
BATCH_SIZE=100
def contrastive_loss(y_pred, y_true, margin=1.0):
    return tf.mul(1-y_true, tf.square(y_pred)) + tf.mul(y_true, tf.square(tf.maximum((margin-y_pred),0)))

## Load dataset
f = h5py.File('./data/paired_training_data.hdf','r')
X1 = f["train_X1"]
X2 = f["train_X2"]
Y = f["train_Y_paired"]

## Inputs: 1 example (phoneme pair), dropout probability
inp_sound1 = input_data(shape=[None, 1, N_MFCC_CHANNELS, N_IN_CHANNELS])
networkL = conv_1d(inp_sound1, reuse=None, scope="conv1d")
networkL = max_pool_1x6(networkL)
networkL = fully_connected(networkL, n_units=N_FULLY_CONN, activation='relu', scope="fc1")
networkL = dropout(networkL, .5) # unshared?
networkL = fully_connected(networkL, n_units=N_FULLY_CONN, activation='relu', scope="fc2")

inp_sound2 = input_data(shape=[None, 1, N_MFCC_CHANNELS, N_IN_CHANNELS])
networkR = conv_1d(inp_sound2, reuse=True, scope="conv1d")
networkR = max_pool_1x6(networkR)
networkR = fully_connected(networkR, n_units=N_FULLY_CONN, activation='relu', reuse=True, scope="fc1")
networkR = dropout(networkR, .5)
networkR = fully_connected(networkR, n_units=N_FULLY_CONN, activation='relu', reuse=True, scope="fc2")

l2_loss = tf.reduce_sum(tf.square(tf.sub(networkL, networkR)), 1)
y_pred = tf.sqrt(l2_loss)
#y_true = input_data(shape=[None])

## Training
network = regression(y_pred, optimizer='adam',
            loss=contrastive_loss, learning_rate=0.0001, to_one_hot=False)
model = tflearn.DNN(network, tensorboard_verbose=0)
model.fit([X1, X2], Y, n_epoch=10, batch_size=BATCH_SIZE, show_metric=True, validation_set=0.1)

Any help -- especially with understanding how to debug these issues on my own in the future -- would be greatly appreciated!
Comment: I would start by changing `reuse=None` to `reuse=True` (or `False`). You **can** force given `BATCH_SIZE`, substituting `None` with `BATCH_SIZE` everywhere.
Comment: @sygi I set the first layer `reuse=None` because I got an error that the scope "conv1d" doesn't exist yet -- the second layer does have `reuse=True`, though. Let me know if this is still the wrong way to do it.
Comment: Also, if I substitute `None` with `BATCH_SIZE`, TFLearn [automatically appends](https://github.com/tflearn/tflearn/blob/master/tflearn/layers/core.py#L73) a first dimension `None` (so that my 4D vector becomes 5D, and then it no longer works with the conv layer).
Comment: Try removing `None`, then? My guess it is that is always appends `None`, and if you have two it complains.
As far as `reuse` is concerned, this parameter expects bool (see [docs](http://tflearn.org/layers/conv/#convolution-1d)) -- it is possible that `None` will serve as `False`, but I'd change it to be sure it is not the problem.
Comment: Sadly, removing `None` still produces the same error.
Answer: It looks like TensorFlow cannot infer the shape of your contrastive_loss. Try to call set_shape in your contrastive_loss function if you know its output shape in advance:
def contrastive_loss(y_pred, y_true, margin=1.0):
  loss = tf.mul(1-y_true, tf.square(y_pred)) + tf.mul(y_true, tf.square(tf.maximum((margin-y_pred),0)))
  loss.set_shape([...])
  return loss

Comment: I tried setting the shape of the loss and the shape of `y_pred` (since it complained without it) to `[BATCH_SIZE,]`, but this causes more mismatches that I don't know how to resolve -- Adam/ScalarSummary throws an error that `tags and values not the same shape: [] != [100]`.
Comment: I guess the shape of `y_pred` would not be [BATCH_SIZE,], otherwise there is not dimension for the actual data.
Comment: Sorry, what do you mean? I assume it would just be a vector of BATCH_SIZE scalars (0-dimensional numbers)? `y_pred` just needs to be the distance between the vectors outputted by the left and right networks.
Comment: If it is a vector of BATCH_SIZE scalars, then its shape should be [BATCH_SIZE, 1]
Comment: It still has the same `Adam/ScalarSummary` error, now `[] != [100,1]`.


Make locally compiled programs request password graphically

Question: I have an application that I downloaded from my class' website for our custom avr robot and it requires root privileges to send our binaries to the robot via usb.
When I try to use it with sudo, the terminal says that the program was not found, even if it is in my path (and is found when not using sudo).
I've seen that programs like muon and other software updaters use policykit to request for password only when needed, after the software is launched. By using this I could launch the app normally then I would be prompted for my password to allow it to do its things.
How can I actually add this to our application? I can't find any documentation for the policykit, I don't even know if it is supposed to be in the sources or tied to the binaries...
Comment: Do you want to modify your applications source to use Polkit?
Comment: what happens when you run sudo with the absolute path of the binary as the argument?
Comment: See https://askubuntu.com/questions/78352/when-to-use-pkexec-vs-gksu-gksudo and https://askubuntu.com/questions/287845/how-to-configure-pkexec
Comment: @muru If this is how we add polkit then yes.
Comment: @tlund It works with the absolute path, I was just wondering how polkit can be added to a program and I thought it could be a good situation to test it.
Comment: @tlund: Could you please convert that to an answer so that schmucks like me who go around hunting for unanswered questions don't have to look at this one any more?  **;-)**  (And I'll upvote if you drop me a note and it's a good one too!)
Answer: The binary might be in YOUR path but not in roots path. Try using an absolut path with sudo:
<code>sudo /home/you/bin/some_binary
</code>
Comment: Upvoted! **;-)**


C++ to functional

Question: I am wondering how to do this in a functional programming language. Maybe F# or Haskell.
Can someone show me an example without using any function calls except for find and rfind?
This function finds the next slash using i as the num of slash (<0 for backwards).
size_t findSlash(const char *sz, size_t i)
{
    std::string s = sz;
    size_t a, b, c, n, ai = abs(i), pos=0;
    for (n=0; n<ai; n++)
    {
        if (i<0)
        {
            a = s.rfind("\\", pos);
            b = s.rfind("/", pos);
        }
        else
        {
            a = s.find("\\", pos);
            b = s.find("/", pos);
        }
        if (a==-1u)
        {
            if (b==-1u)
                return pos;
            c = b;
        }
        else if (b==-1u)
            c = a;
        else
            c = min(a, b);
        pos = c+1;
    }
    return c;
}

Comment: Can you explain what your c++ function is doing?
Comment: There are number of bugs in your code e.g., if i==0 then `c` is undefined; '`if (i<0)`' never happens due to you defined `i` as `size_t`.
Comment: So far I count at least 5 people asking you to clarify what this code does, so its not very likely that you'll get an accurate translation of the code to a functional style. Would you mind describing exactly what this function does?
Answer: Haskell:
import Data.List

findSlash :: String -> Int -> Int
findSlash str i = findIndices (\c -> c == '\\' || c == '/') str !! i

Handling the negative index (which is ugly 'cause you don't really want to do it):
findSlash :: String -> Int -> Int
findSlash str i =
    index (findIndices (\c -> c == '\\' || c == '/') str) i
          where index xs i | i  < 0 = (reverse xs) !! ((-i) - 1)
                           | i >= 0 = xs !! i

Handling errors:
findSlash :: String -> Int -> Maybe Int
findSlash str i = index i
    where xs = findIndices (\c -> c == '\\' || c == '/') str
          l = length xs
          index i
              | i <  0 && i < (-l) = Nothing
              | i >= 0 && i >= l   = Nothing
              | i <  0             = Just $ (reverse xs) !! ((-i) - 1)
              | i >= 0             = Just $ xs !! i

Now you can say:
map (findSlash "/foo/bar/baz") [-4..4]

and get:
-- -4        -3     -2     -1      0      1      2       3       4
[Nothing,Just 0,Just 4,Just 8,Just 0,Just 4,Just 8,Nothing,Nothing]

Anyway, handling the offset from the end makes the code pretty ugly, and ruins the possibility for lazy evaluation.  So I think most people would use the first one, perhaps with a bit of error-checking thrown in.  (Which also kills laziness, since length would force evaluation of the whole list.  You can use "drop" instead of "!!" to avoid errors AND to prevent evaluation of the entire result list, however.  TMTOWTDI.)
Comment: I am very confused by your definition of "index" in the last variant.  The four cases you list are equivalent to: i < 1, i >= 1, i == -1, i == 0.  Surely this is not what you intended.
Comment: That is the letter L, not a numeric one.
Answer: In first, your code is broken. size_t is unsigned type and never can be i<0.
In second, your code is ugly std library misuse and ineffective. There should be used regular expression library or such or use handcrafted scanner. Resulting code is far cleaner and faster. For example (I have not been using C for many years but below code crafted in 10 minutes works.):
size_t findSlash(const char *sz, int i)
{
    const char *s = sz;
    if (i<0) {
        for(;*s;s++);
        for(;;s--){
            if(s<sz) return -1;
            if((*s == '/') || (*s == '\\'))
                if(! ++i) break;
        }
    }
    else {
        for(;;s++){
            if(! *s) return -1;
            if((*s == '/') || (*s == '\\'))
                if(! i--) break;
        }
    }
    return s-sz;
}

I haven't used to write Haskell or F# but for example below code in Erlang should state as example how to do it in functional language:
findslash(L, I) when is_list(L), is_integer(I) ->
    if  I<0  ->
            case findslash(lists:reverse(L), -1*I - 1, 0) of
                none -> none;
                X -> length(L) - X - 1
            end;
        I>=0  -> findslash(L, I, 0)
    end.

findslash([H|_], 0, X) when H=:=$/; H=:=$\\ -> X;
findslash([H|T], I, X) when H=:=$/; H=:=$\\ ->
    findslash(T, I-1, X+1);
findslash([_|T], I, X) -> findslash(T, I, X+1);
findslash([], _, _) -> none.

My attempt in Haskell with error checking and keeps laziness for i>=0:
findSlash :: String -> Int -> Maybe Int
findSlash str i
  | i <  0 = reversed (_findSlash (reverse str) (-1*i-1) 0)
  | i >= 0 = _findSlash str i 0
    where
      reversed Nothing  = Nothing
      reversed (Just a) = Just ((length str) - a - 1)
      _findSlash (x:xs) i n
        | x == '/' || x == '\\' = if i==0 then Just n else _findSlash xs (i-1) (n+1)
        | True                  =                          _findSlash xs  i    (n+1)
      _findSlash []     _ _     = Nothing

Comment: Shouldn't it be `if (! --i) break;`?
Comment: the first slash corresponds to `i==1` otherwise you can't find the first slash from the end of a string. See http://stackoverflow.com/questions/548584/c-to-functional/550158#550158
Comment: Have you tried it? Just try, it works as usual in most of Perl or Python functions of same sort. i==0 is first from start, i==-1 is first from back.
Comment: You're right. I've confused indexing and counting. It is ubiquitous to use zero-based *indexing* in programming, but we usually use `1` when *counting* something. In this problem interpreting `i` as an *index* rather than *quantity of something* is more appropriate.
Answer: You can write a pure-functional code in pure C:
/** Return pointer to the `n`-th occurrence of any char from `chars` in `s`.

    Return NULL if it can't find the `n`-th occurrence.
    Start at the end of `s` if `n` is negative.
    `n` is zero-based.
*/
const char*
find_nth(const char* s, int n, const char* chars)
{
  if (n < 0) return rfind_nth(s, -(n+1), chars);
  if (! (s && *s)) return NULL;
  if (find(chars, *s)) return (n == 0) ? s : find_nth(s+1, n-1, chars);
  else return find_nth(s+1, n, chars);
}

Full program:
#include <string.h>

const char*
find(const char* s, char c)
{
  if (! (s && *s)) return NULL;
  return (*s == c) ? s : find(s + 1, c);
}

const char*
rfind_nth_range(const char* s, const char* end, size_t n, const char* chars)
{
  if (! (s && end && (end - s) > 0)) return NULL;
  if (find(chars, *(end - 1))) // `*(end-1)` is in `chars`
    return (n == 0) ? end - 1 : rfind_nth_range(s, end - 1, n-1, chars);
  else
    return rfind_nth_range(s, end - 1, n, chars);
}

const char*
rfind_nth(const char* s, size_t n, const char* chars)
{
  return rfind_nth_range(s, s + strlen(s), n, chars);
}

int
main(void)
{
  const char* const s = "ab/cd\\e";
  return !(find_nth(s, 1, "/\\") == (s+5));
}

Comment: That recursion is going to kill you in C.
Comment: The fact that you *can* do something doesn't tell you that it is a good idea to do it.
Answer: So, uh, what is this?  Does it just find the 'i'th slash (forward or backward) in the string (or the '-i'th from the end if i is negative)?  I am not sure if I interpreted it right just from reading the code.
In any case, it would be straightforward to port, but it is not clear what your goal/purpose is.
Comment: i mostly only want to see how it would look as its hard for me to wrap my head around
Comment: Well, the same algorithm would look like pretty much the same code (with slightly different syntax). A different algorithm to give the same results would be easier to read and look different, but that's true regardless of whether written in C++, F#, or Haskell or whatever. What do you want to learn?

C++ to functional