Method called on render without click react native

Question: I am having an issue where a method is being called automatically on render in my react native application. Here are the snippets:
static navigationOptions = ({navigation}) => {
    return {
        headerTitle: 'Network',
        headerRight: () => (
            <View style={{flexDirection: 'row'}}>
            <Button
                title='Invite'
                color='#ccc'
                onPress={() => navigation.navigate('InviteUser')}
            />
                <Button
                    title='Search'
                    color='#ccc'
                    onPress={() => navigation.state.params.handleSearch}
                />
            </View>
            ),
    };
};

componentDidMount() {
    this.state = {
        dataSource:[],
    };
    this.props.navigation.setParams({ handleSearch: this.getNearbyUsers(user_id, auth_token)})
}

It's happening specifically for the search button. Invite works fine. I am pretty new to RN still, so can anyone give some help please?
Edit* added getNearbyUser():
getNearbyUsers(user_id, auth_token) {
    console.log('Get Users: id:' + user_id);
    let formData = new FormData();
    formData.append('user_id', user_id);
    formData.append('auth_token', auth_token);
    fetch("https://{url}", {
        method: 'POST',
        header: {
            Accept: 'application/json',
            'Content-Type': 'multipart/form-data'
        },
        body: formData
        //JSON.stringify({'user_id': user_id, 'auth_token': auth_token})//, 'latitude': 33.0296843, 'longitude': -96.7059628})
    }).then(response => response.json())
        .then((responseJson) => {
            // console.log(responseJson.users[0])
            this.createSearchList(responseJson.users)
        }).catch((error) => {
            console.log('Local Network Error: ' + error)
    })
}

Answer: Change
this.props.navigation.setParams({ handleSearch: this.getNearbyUsers(user_id, auth_token)})

To
this.props.navigation.setParams({ handleSearch: () => this.getNearbyUsers(user_id, auth_token)})

Comment: I had tried that before, but when I do that the click doesn't work at all.
Comment: If you follow the code I posted, and then for the button OnPress do : onPress={navigation.state.params.handleSearch} does it work?
Comment: I tried that too, and it crashes with error TypeError: undefined is not an object (evaluating 'navigation.state.params.handlerSearch')
Comment: can you post your getNearbyUsers function
Comment: Added it to the original post, I changed the URL so I don't give that info out. Otherwise exactly as I have in code
Comment: can you set it to be an arrow function instead?
Comment: What is an arrow function?
Comment: Ok, did a quick search of what that is, and it seems to have solved it. Thanks


jQuery | Submit Form with Span

Question: I'm wanting to have the span within my form have the same "submit" behaviour as the input type="submit".
Please note I cannot use AJAX for this as the third party provider does not support an AJAX submission hence there being an input type="submit"
Most searches return using the submit() method however, this doesn't work?
JSFIDDLE DEMO
HTML
<form method="post" action="http://www.google.com">
    <input type="text" placeholder="Name">
    Span submit
    <input type="submit">
</form>

jQuery
$(document).ready(function(){
    var spanSubmit = $('.submit-span');

    spanSubmit.on('click', function() {
        $(this).submit();
    });
});

Comment: Could you just hide your  with CSS and then link your $('span).on('click') to the $('#sb').click()?
Answer: Your $(this) in your jQuery code is not referring to the form, but the  element itself. Therefore, you can use DOM transversal to seek/search for the parent <form> element:
$(document).ready(function(){
    var spanSubmit = $('.submit-span');

    spanSubmit.on('click', function() {
        $(this).closest('form').submit();
        // Will also work, but might fail if nesting is changed:
        // $(this).parent().submit();
    });
});

Here's a proof-of-concept fiddle, where I used an alert to listen to the submit event to verify that form submission is indeed called :)
Answer: Why don't you submit the form element in the click handler?
    $(document).ready(function(){
    var spanSubmit = $('.submit-span');

    spanSubmit.on('click', function() {
        $(this).closest('form').submit();
    });
});

Answer: Here you are calling the submit event on the span (which doesn't have such an event.
spanSubmit.on('click', function() {
  $(this).submit();
});

You need to call this event on the form:
spanSubmit.on('click', function() {
  $(this).closest('form').submit();
});

Answer: You should trigger the native JavaScript submit event on the form element:
$(document).ready(function(){
    var spanSubmit = $('.submit-span');

    spanSubmit.on('click', function() {
        $(this).closest('form')[0].submit();
    });
});

jQuery | Submit Form with Span


How to determine if a 20 amp breaker can be upgraded to 30 amp

Question: I recently purchased my first home and the breaker the electric clothes dryer is connected to is 20 amp.  I was told it should be 30 amp by a home inspector but foolishly did not have the seller correct it.  If I run the dryer on its highest heat setting it will trip the breaker so I would like to swap out the 20 for a 30.  How can I tell if the wiring and such is adequate for 30 amps?
Location: North-eastern U.S.
Comment: This is an unusual situation, so tread carefully. Unless you can conclusively determine that the circuit is capable of 30 amps from end-to-end, you should not change the breaker. It's an important safety device.
Comment: If it is easy to do; I would just replace that cable as the outer jacket is deteriorating, and may not be adequately grounded to modern standards.
Comment: Modern standards nec 2014 250.114 then follow instructions on dryer to install a 4 wire cord.
Answer: It depends upon two things:

The gauge (thickness) of the wire; and
The length of the wire.

For 30 amp, a typical household installation requires 10 gauge:

To measure it you'll need to use a wire gauge measurement tool on an uninsulated piece of the wire:

You can get these on Amazon
Comment: That color chart above is completely useless. It is not on par with the NEC and other codes for residential AC wiring. That is for 12V wiring such as landscape lighting and automotive wiring.
Comment: Virtually wire and cable has the gauge printed on the outside, that would be an easier way to tell.
Comment: Looking at the picture presented, I am curious - do you think the printing will be legible, if you can find it at all without stripping the wire more than it's already been stripped (as in permanently installed...)
Comment: I couldn't read anything on the wire to see what gauge it is.  Since it is in an unfinished basement I suppose I'll just run new wire.
Comment: Fair enough - chart removed.
Comment: You need to go by the material of the wire, as well. Copper can hold more current then aluminum. I don't know the popularity of one vs the other.
Comment: For completeness, that particular drop from the ceiling to the outlet "should" be conduit protected or armored (BX) wire.  Pretty common but against code :-/
Answer: The easiest and surest way to determine the gauge is to look at the bare wire itself, either in the outlet, or more easily in the service panel where it goes into the breaker.  It is almost certainly one of 14, 12, or 10 gauge wire.
If you haven't worked with much electrical wire, then sighting its diameter it won't be as easy, so simply compare it to a known gauge wire, perhaps in the other breakers.  Or go to your local electrical supply store or big box retailer and look and feel the wires.  Maybe even buy a foot of each to keep as reference.
Comment: You'll also want to make sure the same size wire runs the entire length of the circuit.
Answer: A cloths dryer needs to be fed by a 30 amp circuit through at least#10 awg copper wire (I don't recommend aluminum) if you do find that the wire you have is#10 ga. Copper make sure that it has 3#10 conductors and is not using the very small bonding conductor that old romex like that usually has for the neutral.
Answer: Check the wire gauge before replacing. I had an old Victorian and similar wire was 10-gauge copper, some of the best wire in the house; I wrapped the exterior in wide electrical tape.
Also, your breaker should be dedicated ONLY to the dryer, even if that is not the code in your area. This makes swapping out the wire and breaker fairly straightforward, and if it is 10-gauge, swapping out the breaker is incredibly easy. Just have to turn off the power main to the whole house, which is usually at the top of the breaker box.
Good luck!
Comment: how do you check / verify that it's 10 gauge wire?
Answer: Why not just run the dryer for a few months and see if the 20 amp breaker trips?  If not, then 20 amps will do fine.  It's possible that your dryer doesn't pull more than 20 amps.
20 amps times 220 volts means a maximum of 4400 watts.  If you look at the back of your dryer it may indicate the wattage it consumes.
If the line isn't buried behind a wall, it probably would be easy just to replace your existing line with 10 ga copper conduit.  I suspect it's a straight shot from outlet to panel with no junctions.  It should take a pro less than 30 minutes.
Comment: OP already said the breaker trips when dryer is on "high".
Comment: Wallyk: no you are not too conservative the dryer outlet is a 30 amp device it needs to be fed by a 30 amp circuit with the correct wire.
Comment: Hardly anywhere in the U.S. gets 220 volts.  It is likely to be 230 in the northeast and wherever there is heavily loaded transmission.  The rest of North America gets 240 volts.  Also, a 20 amp circuit is not rated for 20 amps continuously.  There is a 20% derating so 16 amps is all that can be used.  16 amps times 240 volts is 3,840 watts.
Comment: I am in the Northeast (NY State). My household voltage is consistently 240-250V. Also, a household dryer would NOT be considered a continuous load. This is not to say if the cable is 10 that the breaker should not be changed to 30A. It should.
Comment: @SpeedyPetey:  You are correct.  I thought the definition of *continuous* was 30 minutes or more.  [This says](http://www.flashcardmachine.com/nec-2008-definitions.html) it is *A load where the maximum current is expected to continue for 3 hours or more.*  I have been overly conservative in my electrical work.


What mining resource will make the most money? Elite Dangerous

Question: I'm core mining in an Asp Scout.  Been doing pretty good, made three runs with an average profit of 2,000,000 credits per run, mining one asteroid per run.  I've pretty much figured out the mechanics of core mining, but I am trying to figure out which resources I should be searching for.  So far I've mined Platinum and Rhodplumsite.  Those are pretty good, but I'm hoping to make more than 2 mil a run (not sure if that's possible with my current ship).  Which resource is worth the most (that i can get core mining) and where can i get it?
Answer: The most profitable core mining material is either Void Opals or Low Temperature Diamonds. Void opals are commonly found around Icy rings. There are worth upwards of 650k per ton. My mining Clipper averages 220mil per void run, as an example of the potential gains you can have by focusing on a single material.
Mining one asteroid and calling it quits is a very inefficient way of mining, continue to search until your cargo bay is full or you run out of limpets. Below is a full guide created by another CMDR that will help get things going in the right direction, what to look for, and additional tips.
o7
Comment: yeah, before you posted this I made the most I've made in one haul, 9 mil.  I mined Alexandrite and Void Opals, but I'm not sure i get it.  The galactic average for Alexandrite was about 200,000, and the Void Opals around 100,000 if i remember correctly,  so why are the Void Opals worth more?  I'm currently docked at Col 285 Sector CC-K A38-2 1, because I heard it's a great spot for diamond mining.
Comment: Ok, I mined 14 low temp diamonds, but their average value is only 106,000.  Why are they the best?
Comment: the value of minerals vary drastically. check something like INARA https://inara.cz/galaxy-commodity/10250/ regularly and jump to where void opals are in a boom state. the system where it is mined usually won't be where you sell.
Comment: Use [edtools](https://edtools.cc/miner) to find out what system pays best for the minerals you mined. Try to strike a balance between price and distance.
Also consider selling to Fleet Carriers parked in the system. They may pay under-market rates, but they often sell limpets too, meaning you can get back to mining a whole lot quicker and yield better profit/hour.
Comment: Also, if you like and use the edtools, consider helping the community and run the [EDMC](https://github.com/EDCD/EDMarketConnector/wiki) while you play E:D.


plus predefined functor for concatenation in c++?

Question: It looks like plus() predefined functor should work for strings as it devolves to using the operator+. However this does not compile.
   string one="one", two="two";
   string result=std::plus<string>(one,two);

Why?
Comment: It doesn't work for string for the same reason it wouldn't work for int. You're using it incorrectly.
Comment: Obviously because there's no `main` and missing includes. But in all seriousness, your question would definitely be better if you [edit]ed it to include a [mcve] (i.e. add the includes, chuck in a `main`) AND show the actual error the compiler gives you. Doing so would help people wanting to help you.
Comment: Not at all a duplicate, but [this](https://stackoverflow.com/questions/35568541/how-stdtransform-and-stdplus-work-together) should actually answer your question
Comment: it does not. Somebody has to actually answer this one.
Comment: ah, oh. my bad. Sorry. Thank you!
Comment: Possible duplicate of [How std::transform and std::plus work together?](https://stackoverflow.com/questions/35568541/how-stdtransform-and-stdplus-work-together)
Answer: std::plus is a function object and has to be used in the same manner you would use other function objects.
Minimal example:
#include <iostream>
#include <string>
#include <functional>

int main()
{
    std::string one="one";
    std::string two="two";
    std::string result=std::plus<std::string>()("one","two"); //a temp function object created.
    std::cout << result;

}

See demo here.
Answer: std::plus is a functor, which means you need to create an object of it:
auto adder = std::plus<>{};
auto result = adder(one, two); // result is onetwo

For this reason, you'd never use this as you have: you'd always just simply write one + two.
But it does mean you can use this in the same way you'd use std::greater and the likes: by passing it as a functor which will apply to some container, rather than needing to write your own lambda to add things together.
See What are C++ functors and their uses? for more on functors.


Unable to compile fileExporter view modifier in SwiftUI

Question: I'm having some challenges in creating an export functionality for my hobby project.
I want to be able to export my data in JSON format. According to the FileDocument capabilities, this should be just what I'm looking for.
I gathered my FileDocument and after setting the view modifier of .fileExporter and filling in the right information, it does not compile.
My code looks like this:
struct YourData: View {
    @ObservedObject var manager = Manager.shared
    @State private var isShowingFileExporter = false
    private var document: FileDocument? {
      manager.retrieveData()
    }
    var body: some View {
      List {
        Text("Import Data")
        Text("Export Data")
          .onTapGesture {
            isShowingFileExporter = true
          }
      }
      .navigationTitle("Manage Your Data")
      .navigationBarTitleDisplayMode(.inline)
      .fileExporter(
        isPresented: $isShowingFileExporter,
        document: document,
        contentType: .json,
        onCompletion: { result in
          switch result {
          case let .success(url):
            print("Data saved to: \(url)")
            isShowingFileExporter = false
          case let .failure(error):
            print("Data failed to save with error: \(error.localizedDescription)")
            isShowingFileExporter = false
          }
        }
      )
    }
}

The compile error states: no exact matches in call to instance method 'fileExporter'
Am I missing an import or something? I only import SwiftUI and UniformTypeIdentifiers.
Any tips greatly appreciated.
Answer: The .fileExporter expects concrete type of document (not a protocol FileDocument), so it should be provided
struct YourData: View {
    @ObservedObject var manager = Manager.shared
    @State private var isShowingFileExporter = false
    private var document: YourFileDocument? {             // << here !!


Should a Haskell parser allow Unicode digits in numeric literals?

Question: As an exercise, I am writing a parser for Haskell from scratch. In making the lexer, I noticed the following rules on the Haskell 2010 Report:

digit     → ascDigit | uniDigit
ascDigit  →   0 | 1 | … | 9
uniDigit  →   any Unicode decimal digit
octit →   0 | 1 | … | 7
hexit →   digit | A | … | F | a | … | f
decimal →   digit{digit}
octal →   octit{octit}
hexadecimal   →   hexit{hexit}
integer →   decimal  |    0o octal | 0O octal  |  0x hexadecimal | 0X hexadecimal
float →   decimal . decimal [exponent]  | decimal exponent
exponent  →   (e | E) [+ | -] decimal

Decimal and hexadecimal literals, along with float literals, are all based on digit, which admits any Unicode decimal digit, instead of ascDigit, which admits only the basic digits 0-9 from ASCII. Strangely, octal is based on octit, which instead only admits the ASCII digits 0-7. I would guess that these "Unicode decimal digit"s are any Unicode codepoints with the "Nd" General Category. However, this includes characters such as the Full-Width digits 0-9 and the Devanagari numerals ०-९. I can see why it might be desirable to allow these in identifiers, but I can see no benefit whatsoever for allowing one to write ९0 for the literal 90.
GHC seems to agree with me. When I try to compile this file,
module DigitTest where
x1 = 1

it spits out this error.
digitTest1.hs:2:6: error: lexical error at character '\65297'
  |
2 | x1 = 1
  |      ^

However, this file
module DigitTest where
x1 = 1

compiles just fine. Am I reading the language specification incorrectly? Is GHC's (sensible) behavior actually correct, or does it technically go against the specification in the Report? I can find no mention of this anywhere.
Comment: Funny. I suspect this came about something like "Ok, so literals just consist of ASCII digits, easy." "No hang on, let's think of internationalisation, Unicode... they also have other digit symbols, right?" "Oh yeah, eh, never dealt with that... but ok, let's insert a clause for that..." "Great." ...and then it was just forgotten and nobody actually bothered ever implementing it, or noticed that it doesn't make sense to allow mixing different families of digit.
Comment: Yikes. Yeah, don't bother with this.
Answer: In the GHC source code file compiler/parser/Lexer.x, you can find the following code:
ascdigit  = 0-9
$unidigit  = \x03 -- Trick Alex into handling Unicode. See [Unicode in Alex].
$decdigit  = $ascdigit -- for now, should really be $digit (ToDo)
$digit     = [$ascdigit $unidigit]
...
$binit     = 0-1
$octit     = 0-7
$hexit     = [$decdigit A-F a-f]
...
@numspc       = _*                   -- numeric spacer (#14473)
@decimal      = $decdigit(@numspc $decdigit)*
@binary       = $binit(@numspc $binit)*
@octal        = $octit(@numspc $octit)*
@hexadecimal  = $hexit(@numspc $hexit)*
@exponent     = @numspc [eE] [\-\+]? @decimal
@bin_exponent = @numspc [pP] [\-\+]? @decimal

Here, $decdigit is used for parsing decimal and hexadecimal literals (and their floating point variants), while $digit is used for the "numeric" part of alphanumeric identifiers.  The "ToDo" note makes it clear that this is a recognized deviation of GHC from the language standard.
So, you're reading the spec correctly, and GHC is semi-intentionally violating the spec.  There's an open ticket that suggests at least documenting the deviation, but I don't think anyone's expressed any interest in fixing it.
Comment: All three of the deviations listed there are quite reasonable. I can see why there isn't a demand to "fix" them.


send stream from WCF service ready for printing

Question: consider the following idea:
There can be X amount of client applications that need to print labels with differing layouts. There is one server with a WCF service app which contains all the layout logic of those labels.
The service gets called with parameters and returns an Image object which the client can send to an attached printer.
My mind blocks on the idea of returning an image and then draw that on a Graphics object needed for printing.
Normally generating the Image to print happens in the context of the printer so a good size of the image is generated.
void print(object sender, PrintPageEventArgs ev)
{
    Graphics g = ev.Graphics;
    g.DrawString() // etc
}

But how should the WCF service generate its image so the client can just call
Graphics g = ev.Graphics;
g.DrawImage(service.GenerateLabel(), 0, 0);

I hope Im clear
Answer: You should still be able to use GDI+ (Graphics class) in the server environment. If your only concern is the image size, consider using Metafile instead of bitmap, which is a pretty compact and resolution-independent format (you set the DPI).
Comment: You could also look at [XPS](http://stackoverflow.com/questions/321168/how-to-create-an-xps-document-in-a-wcf-service-to-store-and-return) if you want a higher level of document format abstraction, but that'd probably take a lot more code to render and print.


Reverse Binary Numbers 4/8 test succeds

Question: My task is to  write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11. Where the input contains a single line with an integer N, 1≤N≤1000000000.
I have to pass 8 tests, so far I've only passed 4/8. An input could be 13 where the expected is 11.
Sample input
13

Sample output
11

To clarify I do not get the output from the tests, only the results of them.
Any thoughts on how I can update the code?
public class Reversebinary
{
    public static void Main()
    {
        //Convert Decimal to binary
        int num;
        string binary, reversed;

        //Read integer value from console
        num = int.Parse(Console.ReadLine());
        //Console.WriteLine(num);
        if (num > 1 && num < 1000000000)
        {
            //Convert the integer value to string binary
            binary = Convert.ToString(num, 2);

            //reverse string binary
            reversed = reverseString(binary);

            //Console.WriteLine("binary: " + binary);
            //Convert reversed string binary to int32 and print out
            Console.WriteLine(Convert.ToInt32(reversed, 2));
        }
        else
            Console.WriteLine("Number is not between 1 or 1000000000");

    }

    static string reverseString(string str)
    {
        return new string(str.Reverse().ToArray());
    }
}

EDIT1: clarification of the tests.
EDIT2: please understand I just want your opinion on the code so I can alter to it to succed the tests. I am not asking for you to provide me code.
EDIT3: Problem solved, I passed the tests after including greater/lesser or equals operator. Thanks for all your inputs.
Comment: What are the tests? Where does your output deviate? There are several things missing from this question. Is it a homework assignment?
Comment: *I have to pass 8 tests, so far i've only passed 4/8* This bit needs some clarification I think. What tests fail? You need to post some examples of input, expected output and actual output
Comment: You need to make sure you have a "try-catch" statement on "num = int.Parse(Console.ReadLine());" because otherwise your program will crash whenever you give an input that isn't an integer
Comment: Well i do not get more information from the tests other than the results of them failing or not. The input is a number and the output is a number reversed in binary!
Comment: So, you don't know what numbers are being tested? You are only being told that you pass 4 out of 8 tests?
Comment: @Rariolu Ah! yes can't forget try-catch, thanks for the advice.
Comment: @JarrettRobertson Exactly, but this time i cleared the tests by including greater/lesser than or equal operator and i passed all the 8 tests. I guess i wasn't that far from problem.
Answer: At least, numbers are in 1≤N≤1000000000 and you are not considering 1 and 1000000000.
if (num >= 1 && num <= 1000000000)
        {
            //Convert the integer value to string binary
            binary = Convert.ToString(num, 2);

            //reverse string binary
            reversed = reverseString(binary);

            //Console.WriteLine("binary: " + binary);
            //Convert reversed string binary to int32 and print out
            Console.WriteLine(Convert.ToInt32(reversed, 2));
        }

Also, you can use int.TryParse instead of int.Parse to avoid exceptions.
So your if condition should look like this
    int num = 0;
    if (int.TryParse(Console.ReadLine(), out num) && num >= 1 && num <= 1000000000)
    {
         ...
    }

Answer: Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Reversebinary
{
    class Reversebinary
    {
        static byte[] reverseBinary = new byte[] {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
        static void Main(string[] args)
        {
            //Convert Decimal to binary
            int num;
            int reversed;

            //Read integer value from console
            num = int.Parse(Console.ReadLine());

            if (num >= 0 && num <= 15)
            {

                //reverse string binary
                reversed = reverseBinary[num];

                Console.WriteLine(reversed.ToString("x2"));
            }
            else
                Console.WriteLine("Number is not between 0 and 15");

        }

    }
}

Reverse Binary Numbers 4/8 test succeds


Base Types Limitations in Multi-Precision Libraries

Question: Good afternoon,
Supposing that available memory isn't a constraint, what is the point of having a multi-precision integer library if by storing it's "digits" in an ulong[] array you are limited to about, say, (2^64)^(ulong.MaxValue)? I know this is already a pretty big value, but isn't a multi-precision library supposed to be able to represent numbers greater than that one?
Edit: this question isn't even specific to .NET because of the 2Gb limit. I am talking about languages in general.
Thank you very much.
Comment: An array with 42 elements is enough for everything.
Answer: The point is that there are plenty of applications which will need numbers bigger than (say) a 64 or 128 bit integer, but won't need numbers bigger than that enormous theoretically one. That's a pretty wide space of numbers.
It's like asking why we have long when that's got a limit - and the answer is because there are situations where int has too small a range, but the range of long is okay.
Have you considered just how big that "pretty big" number really is? Consider the estimate of "number of atoms in the universe" as 1080. That won't fit in a long, but it would fit in a "relatively small" arbitrary precision integer. If you need to take into account numbers which are larger than 217,179,869,176 you should probably think about a different representation.


Fourier expansions of Eisenstein series as a Poincare series for the Fuchsian group

Question: In Miyake's book, Modular Forms, Ch 2.6, thm 2.6.9, there is a statement which relate to Fourier expansion of the Eisenstein series.
Let $\Gamma$ be a Fuchsian group, $\chi$ a character of $\Gamma$ of finite order, and $k$ an integer. We suppose $\chi(-1)=(-1)^k$ if $-1 \in \Gamma$. Let $\Lambda$ be a subgroup of $\Gamma$, and $\phi$ be a meromorphic function of $\mathbb{H}$ which is a seed function for a the Poincare series. We write the Poincare series by
$$
F(z)=F_k(z;\phi,\chi,\Lambda,\Gamma)=\sum_{\gamma \in \Lambda \setminus \Gamma} \overline{\chi(\gamma)} (\phi|_k \gamma)(z).
$$
Let $x$ be a cusp and $\sigma \in SL_2(\mathbb{R})$ satisfies $\sigma(x)=\infty$, and $h$ be a cusp width of $x$. Take $\phi_m(z)=j(\sigma,z)^{-k}e^{2\pi i m \sigma z/h}$, $\Lambda=\Gamma_x$, and take $\chi$ which satisfies
$$
\chi(\gamma)j(\sigma \gamma \sigma^{-1},z)^k =1
$$
for $\gamma \in \Gamma_x$. If $m=0$, then $F(z)=F_k(z;\phi_0,\chi,\Gamma_x,\Gamma)$ is called the Eisenstein series.

Theorem. Suppose $k\geq 3$. If $m=0$, then $F(z)=F_k(z;\phi_0,\chi,\Gamma_0,\Gamma) \in M_k(\Gamma,\chi).$ It has the Fourier expansion at $x$ of the form
$$
(F|_k \sigma^{-1})(z)=1+\sum_{n=1}^{\infty} a_n e^{2\pi i n z/h},
$$
and vanishes at all cusps which are inequivalent to $x$.

But I don't know why the Fourier coefficient $a_0$ is $1$.
Here is my attempt.
$$
a_0=\frac{1}{h}\int_{z_0}^{z_0+h} (F|_k \sigma^{-1})(z) dz
$$
$$
=\frac{1}{h}\int_{z_0}^{z_0+h}F_k(z;1,\chi^{\sigma},\sigma\Gamma_x \sigma^{-1} ,\sigma \Gamma \sigma^{-1}) dz,
$$
where $\chi^{\sigma}(\sigma \gamma \sigma^{-1})=\chi(\gamma)$, and the above integral is
$$
=\frac{1}{h}\int_{z_0}^{z_0+h}\sum_{\gamma \in \Gamma_x \setminus \Gamma } \chi(\gamma)^{-1}j(\sigma \gamma \sigma^{-1},z)^{-k} dz.
$$
The last integral must be 1, and if $\gamma \in \Gamma_x$, we know that $\chi(\gamma)j(\sigma \gamma \sigma^{-1},z)^k=1$. But I don't know about the other $\gamma$.
Answer: It seems that you started off well enough. Maybe for clarity, note that we may get rid of $\sigma$, assume that $x = \infty$ and what one really wants to show is that for all characters $\chi$ of finite order, which acts trivially on $\Gamma_{\infty}$ we have
$$
I = \int_{z_0}^{z_0+h} \sum_{1 \ne \gamma \in \Gamma_{\infty} \backslash \Gamma} \chi(\gamma) j(\gamma, z)^{-k} dz = 0
$$
One could do that directly (see below), but in fact Miyake already does that in the course of proving Theorem 2.6.7. I would first like to draw your attention to condition (v), right before the theorem. Note that for $\phi = 1$, if
$\sigma^{-1} = \left( \begin{array}[cc] aa & b \\ c & d \end{array} \right)$, then we get different bounds when $c = 0$ and when $c \ne 0$.
Namely, for $c = 0$, we have $\varepsilon = 0$, but for $c \ne 0$, we have the much stronger $\varepsilon = k$.
Now, consider again the functions $\phi_{\alpha}$ in the proof of Theorem 2.6.7.
In this case, $\alpha$ runs over a set of representatives for
$\Gamma_{\infty} \backslash \Gamma / \Gamma_{\infty}$ .
Note that the lower left entry of a matrix (the one we call $c$) is the same for all elements of the double coset. Moreover, an element with $c = 0$ must be in $\Gamma_{\infty}$. Therefore, for any nontrivial $\alpha$, we have $c \ne 0$, and the stronger bound, implying that for any element $\alpha \beta$ in the double coset, this is the case, and so by the same proof as in that of Theorem 2.6.7, we see that $\phi_{\alpha}$ vanishes at $\infty$ for all $\alpha \ne \Gamma_{\infty}$.
Since $F(z) = \sum_{\alpha} \phi_{\alpha} (z)$ (see 2.6.6), we see that at $\infty$ the value of $F$ coincides with that of $\phi_1 = 1$.
(*) If you would really like to evaluate the integral, here is one way to proceed:
\begin{align*}
I &= \int_{\Gamma_{\infty} \backslash \mathbb{R}} \sum_{1 \ne \alpha \in  \Gamma_{\infty} \backslash \Gamma / \Gamma_{\infty}}
\sum_{\beta \in \Gamma_{\infty} \alpha \backslash \Gamma} \chi(\alpha \beta) j(\alpha \beta, z)^{-k} dz \\
&= \sum_{1 \ne \alpha \in  \Gamma_{\infty} \backslash \Gamma / \Gamma_{\infty}}
\chi(\alpha) \int_{\Gamma_{\infty} \backslash \mathbb{R}} \sum_{\beta \in (\alpha^{-1} \Gamma_{\infty} \alpha \cap \Gamma_{\infty}) \backslash \Gamma_{\infty}} j(\alpha, \beta z)^{-k} dz \\
&= \sum_{1 \ne \alpha \in  \Gamma_{\infty} \backslash \Gamma / \Gamma_{\infty}}
\chi(\alpha) \int_{(\alpha^{-1} \Gamma_{\infty} \alpha \cap \Gamma_{\infty})  \backslash \mathbb{R}} j(\alpha, z)^{-k} dz = 0.
\end{align*}
Here we have used that $\chi(\beta) = 1$ for $\beta \in \Gamma_{\infty}$, that $j(\alpha \beta, z) = j(\alpha, \beta z) j(\beta, z)$, that $j(\beta, z) = 1$ for $\beta \in \Gamma_{\infty}$, that the integral $\int j(\alpha,z)^{-k} dz$ converges for $\alpha \notin \Gamma_{\infty}$, and that the sum $\sum \chi(\alpha)$ vanishes. This only works when $\chi$ is non-trivial due to convergence issues, but it gives a rough idea of what one should do.
Comment: Thank you for the answer!


Why do some LED lights go dim while others go out completely?

Question: When dimming LED lights with an LED dimmer, why do the LED lights at the end of a string of lights go off when LED lights at the beginning of a string of lights go dim but stay lit?
This application is in a kitchen. The LED dimmers were a Lutron Diva C.L Single-Pole/3-Way CFL/LED Dimmer White purchased at Menards. The LED bulbs were Exclusive EcoSmart 60-Watt Equivalent A19 Non-Dimmable LED Light Bulb Daylight (4-Pack)Model#  B7A19A60WUL34 purchased at Home Depot. One dimmer controlled 4 bulbs from one location. When dimmed, the 2 bulbs in the string of lights closest to the dimmer did dim to a minimum but the 2 bulbs in the string of lights farthest from the dimmer shut off completely. The other dimmer controlled 8 bulbs from one location. When dimmed, the 6 bulbs in the string of lights closest to the dimmer did dim to a minimum but the 2 bulbs in the string of lights farthest from the dimmer shut off completely. All of the bulbs used were exactly the same. Perhaps the bulbs were not compatible with the dimmers. Originally I purchased the dimmers at Menards closer to my office. I installed the dimmers using the existing LED bulbs, not knowing they were the kind that would not dim. I then purchased the LED dimmable bulbs from Home Depot closer to home.
Comment: Hi, Russ. You now have [two](https://diy.stackexchange.com/users/97701/russ-wunderlich) separate [accounts](https://diy.stackexchange.com/users/97702/russ); please use the SE contact form to request that they be merged.
Comment: Can you provide more details about the application? This sounds like it might be a better fit for the Electrical Engineering SE, if you're talking about consumer electronics instead of residential LED lighting. The answer also depends on the type of dimmer you're using.
Comment: @HariGanti, *use of consumer electronics* is specifically [off-topic at EE.SE](https://electronics.stackexchange.com/help/on-topic).
Comment: @brhans "except when designing these products or modifying their electronics for other uses." Hobbyist electronics questions are pretty common there, including plenty of questions about LED strips, and this question leads me to believe it fits within the scope of "designing" or "modifying." Understandably, it's not about how to turn on your cell phone
Answer: Because it's not enough to have an LED rated dimmer.  You also need dimmer-rated LEDs.
What's happening is the dimmer needs to power itself.  Some dimmers power themselves by using a neutral wire.  But those which don't, power themselves by leaking a small amount of current through the light bulbs.  Historically, incandescent bulbs didn't mind that.  However, the more efficient LEDs see a small trickle of power as a command to "come on slightly".  Many LEDs made for dimming have an extra circuit to cope with this.
You should also check your dimmer to see if it has a "hard off setting". Some dimmers have a smooth range in the dimming zone, but if you push harder, you will click past a detent, and into a "hard off" setting.  That setting is to allow you to safely change light bulbs without getting nailed.
Answer: The short answer without getting into the electrical engineering aspect is that not all LED bulbs are created equal, even if they say "dimmable" on them. There are literally thousands of variations on the electronics inside that make them work; what's called the "driver", which is an AC to DC power supply that provides low voltage DC for the LEDs themselves. But everyone has their own "secret sauce" so to speak on how to make those power supplies. So the effects of a dimmer, and what TYPE of dimmer, have different effects on different bulbs. The best advice if you don't want to live with this is to always use the EXACT same LED bulbs on any dimmed circuit; brand name, model, rating everything exactly the same.


How to explain this operator associativity?

Question: According to this table, ++ has right to left associativity. So, I run this code:
int a = 5;
++a + ++a * ++a

and expect the expression to be 50 (as 8 + 7 * 6, increment starts from right to left). But the expression is evaluated from left to right (6 + 7 * 8) by Eclipse, and gives result as 62. I am new to this associativity in Java, and must be missing something obvious. Please help me understand this strange behavior.
EDIT: Thank you for your answers, but I have one more question now. It is that, as seen from @bizclop's code and tree answer, it is obvious that the associativity for ++ doesn't matter. Then, is there any use case for this associativity of ++/--?
Comment: Associativity != precedence. Precedence comes first, associativity is only used to resolve cases where the operators have the same precedence.
Comment: I can't think of an example where the associativity of the `++`/`--` operators matters, there probably isn't one.
Answer: There are two different things mixed up here: expression parsing and expression evaluation.
Let's start with the expression: ++a + ++a * ++a. What do we first have to do with it? Since operators + and * need two operands and ++ needs one, we have to figure out which operand goes with which operation. This is the expression parsing step, where precedence/associativity are applied.

++ has the highest precedence, so we can rewrite our expression as (++a) + (++a) * (++a)
Next up it's *, so again we can add parentheses: (++a) + ((++a) * (++a))
And lastly we have +, the lowest precedence of all, so for the sake of symmetry we can write:  ((++a) + ((++a) * (++a)))

Note that we can represent this neatly as a tree:
   +
  / \
++   *
 |   | \
 a  ++ ++
     |  |
     a  a

So this is our evaluation tree based on precedence and associativity.

Note that in this case associativity didn't matter at all as all the operators
  had different precedence. Had our expression been 4 - 1 - 3 + 2, it
  would've been important to use associativity to reach (((4 - 1) - 3) + 2), as + and - have the same precedence.

Now comes the next step, evaluation. Evaluation always happens from left to right (even for assignments, though the rules are a bit quirky), but it happens left-to-right using the tree we've just built.

So first of all we start evaluating the + operator, as it's on the top.
We then go one level down to the left, as we evaluate the ++a on the left side of the + operator, (6)
then we go to the right and start evaluating the * operation.
The way we do it is to evaluate the second ++a, (7)
then the third ++a (8)
and then we multiply the result of steps 4 and 5 (this is the * operation evaluated), (56)
and finally we add the result of step 6 to the result of step 2 (62)

...and we're done.
TL;DR: Precedence and associativity determine where to put parentheses but evaluation is always left-to-right.

15.7. Evaluation Order
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
Comment: Excellent! Exactly what I needed. I will always evaluate all expressions using this tree method!
Comment: I have one more query, I edited the question for that. Please see.
Answer: It is because multiplication operator * has higher precedence over the addition + operator.
The computation will be ++a + (++a * ++a) = 6 + 7 * 8
Comment: Thanks for your answer! I have one more query, I edited the question for that. Please see.


Angular-repeat display column IF equal to a value

Question: I am using angularJS to display my result set into a table, that is filterable with totals etc. I was wondering if it would be possible to display a value based on another value if it is = to something. here is an example:

     {{c.type}}	 //expects either 'fixed' or 'hourly'
     {{c.fixed_rate}}
     {{c.hourly_rate}}

Therfore are you able to only display the fixed value if type is fixed, and hourly if the type is hourly without using any JQuery to hide elements?
My mind is kind of stumped on this as I am just a few months in with angular.
Data is pulled from a database* so if there is an SQL option I am all for it.
Comment: have you looked into `ng-if`?
Comment: @Claies I have not yet thanks for the suggestion! Going to look at the docs now, would I be able to inject this right into the repeat?
Answer: You could do something like this:

     {{c.type}}
     {{c.fixed_rate}}
     {{c.hourly_rate}}

If you want to filter by only those two values, add this function to your controller:
$scope.filterHourlyOrFixed = function (item) {
    return item.type === 'fixed' || item.type === 'hourly';
};

If you do not want to filter by the value, remove | filter: filterHourlyOrFixed from the ng-repeat.
Also, when you have some time, do a little reading through the docs for ngIf, ngShow, ngHide, and ngFilter. You'll probably be using these repeated.  Also, pay attention to the differences in how ng-if, ng-show, and ng-hide manipulate the DOM to achieve similiar results.
The differences are subtle, but important.
Comment: This is working perfectly, I did not know this was possible and will make future tasks MUCH easier. Thanks again, and to everyone else for the swift replies. Cheers
Comment: Excellent. Glad it helped. Take a look at the docs I just added to the answer when you have a chance.  There are a few different ways to achieve this with `ng-if`, `ng-switch`, `ng-show` and `ng-hide`.
Answer: Use ng-if to remove or recreate parts of the DOM based on an expression.  for example:

     {{c.type}}	 //expects either 'fixed' or 'hourly'
     {{c.fixed_rate}}
     {{c.hourly_rate}}

You could also use a filter, if you are rendering identical DOM but want to exclude certain elements.
Answer: You could try something like this:

     Fixed
     Hourly
     {{c.fixed_rate}}
     {{c.hourly_rate}}

Hope this helps!
http://embed.plnkr.co/Wes1Uf1OCCmKYa5wTP5s/preview


Integrate $\int_{-\infty}^{\infty} \frac{e^{2020x}-e^{x}}{x\left(e^{2020x}+1\right)\left(e^x+1\right)} \mathop{dx}$

Question: A challenge problem says integrate $$\int_{-\infty}^{\infty} \frac{e^{2020x}-e^{x}}{x\left(e^{2020x}+1\right)\left(e^x+1\right)} \mathop{dx}$$
I thought $u=-x$ helps but I get $I$ so it is even.  I also try partial fraction to $$\int_{-\infty}^{\infty} -\frac{1}{x\left(e^{2020x}+1\right)} + \frac{1}{x\left(e^{x}+1\right)} \mathop{dx}$$
Now what?  Help please thanks
Comment: [WA](https://www.wolframalpha.com/input/?i=integral_%28-%E2%88%9E%29%5E%E2%88%9E+%28-e%5Ex+%2B+e%5E%282020+x%29%29%2F%28%281+%2B+e%5Ex%29+%281+%2B+e%5E%282020+x%29%29+x%29+dx) gives no closed form
Answer: Instead of trying to use partial fraction decomposition, how about try to introduce a parameter, $a$, inside the integral?  Sometimes when there are integrals with strange numbers, like $2020$ in this case, the integral can be generalized.
$$I(a)=\int_{-\infty}^{\infty} \frac{e^{ax}-e^x}{x\left(e^{ax}+1\right) \left(e^x+1\right)} \; \mathrm{d}x$$
Now, factor out the terms independent of $a$, and differentiate both sides with respect to $a$:
\begin{align*}
I'(a)&=\int_{-\infty}^{\infty} \frac{1}{x \left(e^x+1\right)} \cdot \frac{x e^{ax}\left(e^{ax}+1\right)-xe^{ax}\left(e^{ax}-e^x\right)}{{\left(e^{ax}+1\right)}^2} \; \mathrm{d}x \\
&=\int_{-\infty}^{\infty} \frac{e^{ax}}{{\left(e^{ax}+1\right)}^2} \; \mathrm{d}x \\
&=-\frac{1}{a\left(e^{ax}+1\right)} \bigg \rvert_{-\infty}^{\infty} \\
&=\frac{1}{a}\\
\end{align*}
Integrate both sides with respect to $a$:
$$I(a)=\ln{a}+C$$
Notice that  $I(1)=0$.
$$0=\ln{1}+C \implies C=0$$
Therefore, the integral you posted evaluates to:
$$I(2020)=\boxed{\ln{2020}}$$
Comment: @sai-kartik [this on brilliant.org](https://brilliant.org/wiki/differentiate-through-the-integral/) is an excellent resource.
Comment: Could you please explain why differentiation inside the integral was valid? How can we be sure we can do this kind of differentiation?
Comment: @AndrewChin I know about the Leibniz rule, but I must have got confused in its application here. Thanks for the resource though !
Comment: Thank you @Ty. I like solution
Comment: Very nice user and student :-)
Comment: Very elegant. +1 from me.
Answer: Let $f(x) =\frac1{e^x+1}$. Then
\begin{align}
&\int_{-\infty}^{\infty} \frac{e^{2020x}-e^{x}}{x\left(e^{2020x}+1\right)\left(e^x+1\right)} \mathop{dx}\\
= & \>2\int_{0}^{\infty} \frac{e^{2020x}-e^{x}} {x\left(e^{2020x}+1\right)\left(e^x+1\right)} \mathop{dx} \\
= & \>2\int_{0}^{\infty} \frac{f(x)-f(2020x)}x dx \\
= & \>2[f(0)-f(\infty)] \ln \frac{2020}1\\
=&\> \ln 2020
\end{align}
where the Frullani integral is applied.


Why is useEffect not being triggered?

Question: I have a functional component that is supposed to be a running clock:
import React,{useState,useEffect} from 'react';
import 'materialize-css/dist/css/materialize.min.css';
import { parseTime } from '../../Utils/utils'

const MainClock = (props) => {
    const [timeString, setTimeString] = useState(parseTime(new Date(), true));
    function tick(){
        console.log("TICK:" + timeString)
        setTimeString(parseTime(new Date(), true));
    };

    useEffect(()=>{console.log("rendered!");setTimeout(tick,500);},[timeString]);
    return (

{timeString}

    );
}

export default MainClock;

But for some reason it is only being rendered twice and the console output is:
rendered!
TICK:14:56:21
rendered!
TICK:14:56:22

Why isn't useeffect being called after the second render?
Any help is welcomed!
Edit: If it helps, this is parseTime:
const parseTime = (timeDate, withSeconds=false) =>{
    let time = timeDate.getHours()<10 ? `0${timeDate.getHours()}`:`${timeDate.getHours()}`;
    time+=":";
    time+= timeDate.getMinutes()<10 ? `0${timeDate.getMinutes()}`:`${timeDate.getMinutes()}`;
    if(withSeconds){
        time+=":";
        time+=timeDate.getSeconds()<10 ? `0${timeDate.getSeconds()}`:`${timeDate.getSeconds()}`;
    }
    return time;
}

Comment: yes, without parseTime, i can see continuously prints
Comment: ah, i found the error, just try to update the setTimeout interval not 500.
Comment: whta's wrong here? i expect "rendered! TICK: ..." will be displayed per 500ms continuously.
Comment: @WilliamWang That's the problem. It's not displaying "rendered! TICK: ..."  continuously but only twice.
Comment: i checked and it works properly.
Comment: what does parseTime do?
Comment: just remove the parseTime and try
Comment: @WilliamWang `parseTime` returns a formatted hh:mm:ss string to a given Date object. I'm really not sure what is going on if you say it works properly for you. Does your console output continuously prints new "TICK!..."?
Comment: there is no problem.
Comment: can you attach your whole codebase into the jsfiddle so that i can see your wrong result?
Comment: @WilliamWang I'm afraid not since it's private project. I've added parseTime since he's somehow the culprit.
Answer: Problem is the use of setTimeout and the use of low delay, i.e 500ms for the timeout. If you log the return value of parseTime, you will notice that between the two calls, it returns the same time string, so state never updates, leading to the component never re-rendering and hence useEffect never executes again to set another setTimeout.
Solution
Increase the timeout delay or check the return value of the parseTime function and if its the same as the one in the state, call this function again.
Moreover, its more appropriate to use setInterval here instead of setTimeout because setInterval will only need to be called once and it will call the tick function repeatedly until the interval is cancelled. If you use setTimeout, then you will need to call setTimeout again and again to schedule a new tick function call.
Comment: Wouldn't using `setInterval` create multiple stacking Intervals after every render? And why would I need to add tick to the dependency array if tick is updating a variable that's already in the dependency array?
Comment: I think setTimeout is correct rather than setInterval because setInterval always repeatedly call the tick function.
Comment: @MaorMagori share the code of `parseTime` and i will add more explanation of why the problems occurs and how it can be solved or share a reproducible example on codesandbox.
Comment: @Yousaf Added. Is parseTime what's causing the problem?
Answer: As I indicated above, it is the problem of the short setTimeout timing value - 500ms.
To make it work, you need to use setInterval
const MainClock = (props) => {
    const [timeString, setTimeString] = useState(parseTime(new Date(), true));
    function tick(){
        console.log("TICK:" + timeString)
        setTimeString(parseTime(new Date(), true));
    };

    useEffect(() => {
      setInterval(tick, 500);
    }, []);
    useEffect(()=>{console.log("rendered!");},[timeString]);
    return (

{timeString}

    );
}

Comment: You missed the dependency array of `useEffect` hook. You only want the `useEffect` to run only once and you should also use the cleanup function to cancel the `setInterval`.

Why is useEffect not being triggered?


Show that $\cap_{k\in \mathbb{N}}[-\frac{1}{k},k+1]$ is a closed set

Question: I know that a subset $M$ of a metric space $(X,d)$ is open if it contains a ball about each of it points, and closed it its complement is open.
But how would I show that the set $\cap_{k\in \mathbb{N}}[-\frac{1}{k},k+1]$ in $(\mathbb{R},|.|)$ is closed and not open?
Comment: Do you know in generality that the intersection of closed sets is closed?
Comment: The set has a much simpler description.  Ask yourself: Which positive numbers are in the set?  Which negative numbers are in the set?  Is $0$ in the set?  abatkai raises a good point, but in this case it is useful to have a more concrete description first.
Comment: Identify in a picture the intervals $[-1/k,k+1]$ for $k=1$, $2$, $3$, $4$. Find the intersection of these.
Comment: I was again too quick. @JonasMeyer is right.
Comment: Is the set between $[0,2]$?
Comment: Yes, it's $[0,2]$.
Comment: Thanks. Sorry Im still a bit new to open/closed sets, so how would I proceed with then knowing that the set is between $[0,2]$?
Comment: The set is $[0,2]$, a closed interval. Closed intervals are closed.
Answer: Let $C = \cap_{k\in \mathbb{N}}[-\frac{1}{k},k+1]$, and suppose $x \notin C$. Then $\exists k$, such that $x \notin [-\frac{1}{k},k+1]$. Choose $\epsilon = \frac{1}{2} \min \{ |x+\frac{1}{k}|, |x-(k+1)|\}$. Then $B(x,\epsilon) \cap C = \emptyset$, since $C \subset [-\frac{1}{k},k+1]$.
Comment: Well, there is no standard way. In the above, either $x < -\frac{1}{k}$, or $x > k+1$. I just choose $\epsilon$ so it would be half the minimum distance from $x$ to the interval. Any other fraction would do, as indeed would many other schemes.
Comment: OK, so it is a little brute force :-).
Comment: Thanks @copper.hat The only question is, how did you choose $\epsilon = \frac{1}{2} \min \{ |x+\frac{1}{k}|, |x-(k+1)|\}$? Is that a standard way to choose epsilon?
Comment: Ok, thanks for your help!


How would I run gedit on a text file on a remote server?

Question: I've seen answers to this talking about how to run gedit on the remote server. But what I'm looking for is a way to run gedit locally, where the server only provides the data. Is there a way to do this? I'm running ubuntu 16.04
I already tried sftp, and that didn't work. I know I could use scp and then use gedit locally, but I'm trying to avoid the overhead of putting the right file back into the right spot.
Answer: You can use sshfs to mount a directory on the server on a local directory over SSH.

If you don't already have sshfs installed then install it:
 sudo apt-get install sshfs

This will also install any dependencies needed.
Mount a remote directory on a local directory:
 sshfs user@host:/path/to/remote/dir /path/to/local/dir

You must have write access to the local directory. If the remote path does not begin with a slash it is taken to be relative to the remote user's home directory.
You can now access the files in the remote directory as if they were in the local directory. The access to the files in the remote directory will be done with the remote user account with which you have connected. For example, you can run gedit to edit a file:
gedit /path/to/local/dir/file </dev/null &>/dev/null &

The actual file is of course on the remote server at /path/to/remote/dir/file.
When you are done unmount the remote folder:
fusermount -u /path/to/local/dir

You don't have to install anything on the remote computer; the access to files is made over the regular SSH protocol. After installing sshfs you can use man sshfs for detailed information.
Answer: Use Nautilus to connect to the remote server
Try using sftp from nautilus. Nautilus shows up as "Files" in the launchbar in Ubuntu. To use sftp:

Open nautilus in your local computer.
Click on Connect to Servers in the left panel
Type something like
sftp://your.url.goes.here./home/userid

or
sftp://your.IP_address.goes.here./home/userid

Click Connect button

If all goes well you will be prompted for password and you will see the files in the remote server's folder /home/userid.

Bookmark this server information for future easy use.
Use gedit by clicking on text the files on the remote server.
When you are done editing and browsing the files in the remote server, you can disconnect from the server by clicking on the eject icon next to the server connection in the left panel of Nautilus.

Thanks to ianorlin sftp works from many other file managers, such as pcmanfm, thunar, caja, and nemo. The location and exact method varies.
I hope this helps
Comment: This actually works with a lot more file managers than just natilus. both the gtk and Qt versions of pcmanfm, thunar, caja, and nemo all depend on that which s most of the gtk desktop environments and LXQt. Of course these have slighty different places in the ui to find each of theese.
Comment: I can't find "Connect to Servers". Does it exist on ubuntu?
Comment: Found it. Sorry, I hadn't updated my browser since you edited the comment when I responded.
Comment: @ianorlin thanks! I have added a note based on your comments.


Bar Graph Controlling - From the Graph Itself or from External Control

Question: I have a bar graph on my page I'm generating from D3.  The graph itself looks good.  Here's the question:
My graph has the following bars:
bar1 ****************
bar2 *******
...
barn ************

Now, each of these bars can be expanded into subcomponents:
bar1a *******
bar1b ***
...
bar1n ***
...
barn ************

Currently the way I'm expanding these bars is I have a little "x" on the left, so something like this:
x bar1 ****************

Finally, on the left, I'm going to use a tree control which will help display and filter the bar graph.  I'm using this:  https://code.google.com/p/checkboxtree/
My question:  Is it good UX design to use the checkboxtree control to control the graph itself?  Thus, if I have my tree menu w/ bar1 as a root, then I expand it, I will get (in the tree menu)
bar1
...bar1a
...bar1b
...bar1c

Then the bar graph will respond in that manner?
Thanks for your time
Comment: Make the display interactive. Do not create another control which controls the chart. With the touch interaction, people are getting accustomed to interacting with displays directly, plus the interaction would be more or less the same in the graph as in the external control. This is called "Direct Manipulation".
Comment: I wouldn't use "x" for expanding because if I'm the user, I would assume that's the delete button.
Comment: 1. How many steps does your tree have? If it's only two levels, there's no need to bother with the tree structure. 2. Inner data sets of each bar are repetitive (so that there is bar1a, 1b, 1c and bar2a, 2b, 2c) or variative for each bar?
Answer: The lower the friction you put between the user and their drilldown. The more usable the system.
I've seen drilldowns like you're suggesting used effectively in the past. However in each of those cases the core problem was the discoverability of the drill-down functionality.
You'll have to think very carefully about the icon you use to indicate that the bar graph is interactible in this way. I'd suggest using a couple of different icons and user-testing them.


StructureMap configure a profiled nested container

Question: I've come across an unexpected outcome when trying to resolve an instance. It's probably better to explain in code. Here is the Registry used for ObjectFactory.Initialize:
public MyRegistry : Registry {
    public MyRegistry() {
        this.For<IServiceA>.Use<ServiceA>();
        this.For<IServiceA>.Use<SpecialServiceA>().Named("Special");
        this.Profile("Special", p => p.For<IServiceA>().Use("Special"));

        this.For<IScreen>().Use<NullScreen>();
    }
}

In a factory class I build up a nested container and register the current screen with the container like so:
public void ProcessScreenRequest(IScreen screen) {
    using(IContainer nestedContainer = this._container.GetNestedContainer(screen.Profile)) {
        nestedContainer.Configure(x => x.For<IScreen>().Use(screen);
        //process chain of commands to display screen.
    }
}

In one of my commands it has a dependency for an IScreen, but instead of receiving the "screen" instance I configured for the nested container, it receives a NullScreen.
Is there something I'm doing wrong or will profiled nested containers not support this scenerio?
Comment: Well. I found if I put nestedContainer.EjectAllInstancesOf() before the nestedContainer.Configure() method. Is this by design? If I get a nested container without the profile, everything works as I would expect it.
Answer: I'm going with the solution of calling nestedContainer.EjectAllInstancesOf(). I still do not know why specifying the profile for a container would cause it to change the default instance of IScreen.


Session management using json web tokens in microservices

Question: I am trying to figure out how I will manage sessions using json web tokens in a microservice architecture.
Looking at the design in this article what I currently have in mind is that the client will send a request that first goes through a firewall. This request will contain an opaque/reference token which the firewall sends to an authorization server.  The authorization server responds with a value token containing all the session information for the user.  The firewall then passes the request along with the value token to the API, and the value token will then get propagated to all the different microservices required to fulfill the request.
I have 2 questions:

How should updates to the session information in the value token be handled? To elaborate, when the session info in a token gets updated, it needs to be updated in the authorization server.  Should each service that changes the token talk to the authorization server?
Should all the microservices use this single token to store their session info? Or would it be better for each service to have a personalized token? If it's the latter, please explain how to adjust the design.
Answer: A very(!) significant "fly in the ointment" of this kind of design ... which requires careful advance thought on your part ... is: "precisely what is meant by 'session' information." In this architecture, "everyone is racing with everyone else." If the session information is updated, you do not and basically cannot(!) know which of the agents knows about that change and which does not. To further complicate things, new requests are arriving asynchronously and will overlap other requests in unpredictable ways.
Therefore, the Authorization Server must be exactly that ... and, no more. It validates (authenticates ...) the opaque token, and supplies a trustworthy description of what the request is authorized to do. But, the information that it harbors basically cannot change. And specifically, it cannot hold "session state" data in the web server sense of that term.
Each microservice provider must maintain its own "tote board" *(my term ... "its own particular subset of what in a web-server would be 'the session pool'"), and it is desirable but not always feasible that its board would be independent of the others. Almost certainly, it must use a central database (with transactions) to coordinate with other service-providers similarly situated. And still, if the truth is that the content of any of these "totes" is causally related to any other, you now have an out-of-sync issue between them.
Although microservice architecture has a certain academic appeal, IMHO designs must be carefully studied to be certain that they are, in fact, compatible with this approach.
Comment: Your explanation really helps and does make sense.  I just want to clarify something.  In order to implement these "tote boards", I'm guessing I would make separate "tote board" services that essentially hold the sources of truth for the other services to query.  And from there I just have to deal with whether I want consistency or availability.  Does that sound right to you? Although with this design it seems like it doesn't get the benefit of passing around all the session state for a client in a token :/
Comment: No, I don't think that you could implement a tote-board service, because updates need to be atomic. Microservice architectures can frankly be very problematic when things *change,* because e.g. two requests could be started at about the same time, even on different servers, could run at different rates, and could "race" in quite-unpredictable ways.


Understanding complex forms and confusions

Question: I have few questions about forms that I am trying to grasp. So, first of all, let us consider the following things according to the order of difficulties.
First, we have space $L_{\mathbb{R}}(\mathbb{C},\mathbb{R})$ which is the space of all linear real forms. We have the following operators $dx : h \mapsto Re(h)$ and $dy : h \mapsto Im(h)$. Let us consider first $L_{\mathbb{R}}(\mathbb{C},\mathbb{R})$ as a real vector space. Suppose we have the operator $\phi \in L_{\mathbb{R}}(\mathbb{C},\mathbb{R})$.
Then $\phi(x) = \phi(x_1 + x_2i) = \phi(dx(x) + i dy(x)) = \phi(dx(x)) + \phi(dy(x)i) = \phi \circ dx + \phi \circ i *dy$. As $\{1,i\}$ forms a real basis for $\mathbb{C}$ we have $\{dx,dy\}$ forms a real basis for $L_{\mathbb{R}}(\mathbb{C},\mathbb{R})$. Is my reasoning correct?
A (1,k) form is a $C^k$ map from $\psi : U \rightarrow L_{\mathbb{R}}(\mathbb{C},\mathbb{R})$ where $U \subset \mathbb{C}$ is open. Any form (1,k) form $\omega$ can be written as:
w = P dx + Q dy, where $Q,P : U \rightarrow \mathbb{C}$.
I don't understand why is this case can someone explain this?
Finally a (2,k) form is defined as $C^k$ map $\phi : U \rightarrow \mathbb{B}(\mathbb{R}^2\times\mathbb{R}^2,\mathbb{C})$ the complex vector space of alternating bilinear mappings.
So I don't understand here what is the topology of $\mathbb{B}(\mathbb{R}^2\times\mathbb{R}^2,\mathbb{C})$ ? I mean I understand the first case the topology of $L_{\mathbb{R}}(\mathbb{C},\mathbb{R})$ is given by the supermum norm which exists as any linear map is continuous (hence bounded). I want a complete understanding of those things. Please be as detailed in your answer as much as possible.
Answer: I am a little bit confused about what are you trying to do. If you just want to define differential forms with complex coefficients then take a look at complexification. On Vladimir Arnold book Ordinary Differential Equations there is a good presentation on complexification.
The idea is to complexify the space of real differential forms. About the topology of the bilinear forms, since this is a vector space of finite dimension, any norm on it generate the same topology. So you can take any norm you want to generate the topology.


Kendo UI Grid saveRow method doesn`t sync data and doesn`t close the row

Question: Here is the updated Fiddle to test.
I am trying to setup grid with the in-line editing. Why saveRow method doesnt affect update function in transport definition and doesnt exit row from edit mode ?
Also please try to change var "can_edit" to false; Why this option doesn`t affect the field "day1"
Answer: If you debug your code for detecting the pressed key:
dataBound: function (o) {
    ...
    o.sender.element.delegate('tbody>tr', 'keypress', function (e, o) {
        if (!e.altKey && !e.ctrlKey && !e.shiftKey && e.key == "Enter") {
            if ($(".k-grid-edit-row").length > 0) {
                grid.saveRow();
            }
        }
    });
}

You will see that you never get to grid.saveRow(). Try using e.keyCode instead:
if (!e.altKey && !e.ctrlKey && !e.shiftKey && e.keyCode == 13) {
    ...
}

Comment: Your code did not change anything. Please check an update fiddle


Supervisor doesn't seem to be picking up directory parameter

Question: After an update from supervisor 3.0 to 3.2 (happened while upgrading 14.04 to 16.04), our configuration we use for supervisor doesn't seem to work properly any more.
The default supervisor configuration is completely unchanged and the only important parameter in there is:
[include]
files = /etc/supervisor/conf.d/*.conf

In the conf.d directory there are two files; one that is only used on this system and one that symlinks into the application directory, so we can use the same configuration across installations.
000-generic-environment.conf
[supervisord]
directory = /home/applicationuser/domains/<domain>/current

001-programs.conf (symlink to /home/applicationuser/domains//current/supervisord.conf)
[program:push-notifications]
rabbitmq:consumer device_notifications --env=prod --no-debug -m 100
autorestart = true
user = applicationuser
command = bin/console rabbitmq:consumer device_notifications --env=prod --no-debug -m 100

When I start supervisor, the only thing the log says is:
supervisord[11599]: 2018-06-21 08:00:16,549 INFO spawnerr: can't find command 'bin/console'

It tries a few times and then decides to go into FATAL state because of the retries. This setup has always worked for us, but now seems to be broken. Am I overlooking something here? I have been breaking my head on this issue for a while now and I could use some fresh eyes on the matter.
Comment: If I use the full path in 001-programs.conf instead of a relative path, supervisor works just fine; it's just that because of the way we deploy our application (001-programs.conf is a symlink ) we would rather not have the full path but have the relative path instead.
Answer: I eventually found the issue. I noticed in the documentation that the directory parameter is only used when daemonizing.
In supervisor 3.0, this was the default; apparently after upgrading ubuntu and supervisor, this default behaviour got changed and supervisor ran with the -n flag on the command line.
Removing this flag in systemd crashed the daemon for some reason, while running supervisord from the commandline worked perfectly. Chosing the easy way out because I wanted to continue with more important stuff, I downgraded supervisor to 3.0 and everything worked like a charm again.
Comment: When removing the `-n` flag, supervisor is started as a daemon. I suspect you also need to change the service definition to include `Type=forking`.


Cryptographically hash multiple keys

Question: How to hash using SHA1(or similar cryptogrphical functions) a class(or struct) which has multiple keys, e.g.,
struct Foo{
   string name;
   int age;
   int score;
}

A naive approach is hash(has(name) + hash(age) + hash(score)), but hash collision is possible.
Comment: And what's the question now?
Comment: Collision is always a possibility - you may be able to reduce the likelihood of that by using a more sophisticated combination function than addition.
Answer: Either hash the whole structure directly if it contains only POD (i.e. nothing allocated within and its sizeof is a constant): either you can use an union to get a proper byte array, or you use a cast to obtain a char* to provide to hash function.
If you have dynamic data inside your struct/class, you need to serialize all data and send them to the hash function - obviously, its size will vary during execution, because of dynamic data. But you must call hash only ONCE per data structure, and in NO WAY adding hashes together - that's a nonsense.
You can also use a framework feature that will serialize your struct/class to a text stream (often XML or JSON format), and hash this serialization instead of the binary structure.
How to do all this is obviously platform-dependent - which cryptography API do you use, if you prefer.
By applying these principles, the collision (totally unavoidable, mathematically proven) won't be more than for any other kind of hashed data.
Comment: using JSON is a pretty nice method. Thanks.
Comment: @Blade You're welcome. If it suits yourself, you can tag it as accepted. However, even if serializing to JSON/XML is a working and quite simple solution if you have these functions already available, don't forget that do it on binary data will be way more efficient and fast, because it involves the same class/struct parsing than serialization, but without the need to transform it to text before hashing.
Comment: can't agree more. JSON is easier to implement, but performance is definitely slower than processing raw bytes.

Cryptographically hash multiple keys


Matching string with preg_match

Question: I have the following string formats: "$ 3.20" or "$ 10.34". I want to verify with preg_match if the string is exactly this type of a format.
Any suggestions are appreciated?
Comment: I'd suggest [trying something](http://whathaveyoutried.com)
Answer: Try this pattern:
<code>if (preg_match('/\$\s[\d]+\.[\d]{2}/', $text)){
    //do something
}
</code>
Comment: Thx works great. I am not as good with those regexp stuff.

Matching string with preg_match


There's "0 but true", but is there "42 but false" in perl?

Question: As per the question. I know there's "0 but true" which is true in a boolean context but false otherwise, but can return something false in a boolean context but with a non-zero value (the obvious place for this is return statuses where 0 is success and anything else is an error).
Comment: Unless you count the empty list `()` or `undef`? Not AFAIK, although empty lists can be gotchas.
Answer: No. (Except for fun with dualvars and overloaded objects)
The truthiness of a Perl scalar depends primarily on the string value. If no string value is present, the numeric field will be used.
False values are: undef, "", 0, and to avoid issues by testing the stringification first: "0".
Not everything that is numerically zero evaluates to false: "0E0" is true, so is the more self-documenting "0 but true". The latter is special-cased to avoid non-numeric warnings.
However, enter dualvars. The numeric and stringy field of a scalar don't have to be in sync. A common dualvar is the $! variable that is the errno in numeric context, but a error string containing a reason as a string. So it would be possible to create a dualvar with numeric value 42 and string value "", which will evaluate to false.
use Scalar::Util qw/dualvar/;

my $x = dualvar 42, "";
say $x;   # empty string
say 0+$x; # force numeric: 42
say $x ? 1 : 0; # 0

And then overloaded objects. Instances of the following class will stringify nicely, but still evaluate to false in a boolean context:
package FalseString;
sub new {
  my ($class, $str) = @_;
  bless \$str => $class;
}
use overload
  '""'   => sub { ${shift()} },
  'bool' => sub { 0 };

Test:
my $s = FalseString->new("foo");
say $s;
say $s ? "true" : "false";

Prints
foo
false

Comment: "under strict"?  strict never gives warnings; warnings gives warnings.


Are we reading our propane tank wrong, or are we being overcharged?

Question: We have a buried 1000 gal (3785 l) propane tank used for heating.
When it was filled up recently the gauge went from about 49% to 88%. This would mean 490 gal to 880 gals, or an addition of 390 gals.
We were charged for 434 gals, which is an excess of 44 gals or about 11% extra. Both gauge readings were within about 24 hours, there's no way we consumed that much propane in that short of a time.
Are we interpreting this situation correctly? Could the gauge readings have as much as 11% error in them?
Note that this is the first time we have taken photos but we think this situation has happened before. So if the gauge is error prone would that error consistently under-represent the fill level? Usually measurement error goes both ways.
The supplier has said that they take readings from their truck, and that our gauge is really measuring pressure and not volume. I'm not sure if we should trust that or not. Our gauge is in gallons after all, not PSI or something pressure-related.

Here are before and after pictures of the gauge on the tank itself:
Before fill up:

After fill up:

FYI the tank is buried but there is a lid you open to view the gauge.
Comment: The propane company is charging you by the amount (i.e. volume) of propane metered through their dispenser.  That meter should be tested and sealed by your local (in the US, usually the county or state) weights and measures authority.  The gauge you are using is just an approximate measure and does NOT appear to be calibrated.
Comment: Given the sparsity of indication marks on the gauge dial and the thickness of the gauge pointer, it is reasonable to assume that the gauge is meant only as a rough guide and not for accurate readings. Besides the gauge error another source of error is that your tank may not be precisely 1000 gallons as you have assumed.
Comment: What is the temperature of the propane before the fillup?  What is the temperature of the propane after the fill-up? There is enough information on the gauge to google it, what is its stated precision?
Comment: @Harper-ReinstateMonica we are going to talk to the gauge company actually. I'm not sure how to know the propane temperature... the ground temp itself should be fairly constant this time of year though I don't think that's what you meant.
Comment: The ground temp may be consistent, but what about the temp of the propane that is on the truck?  It matters.  Also, is your tank *exactly* the diameter that the gauge is made for?  If the tank were a little larger, the gauge would fit but it would throw off the scale.
Comment: The truck's gauge is calibrated every year (same as filling stations etc in fact anyone who sells to the public) for most jurisdictions. They measured accurately the amount delivered. Has your gauge been calibrated? Have you fitted one of the new ones that does compensate for the changing volume while the sensor moves linearly? A mate has just fitted on of those new gauges and has found it to be very accurate as long as you program it correctly.
Comment: The reason your dial says "do not use for filling" is because it doesn't compensate for fill variables, most notably temperature. It should be considered approximation. If you got your tank filled in summer, you would likely see a change in the opposite direction.  On the subject of temperature compensation: https://bpnews.com/index.php/publications/magazine/current-issue/715-temperature-compensation-what-it-means-to-you
Comment: In short, you paid for a certain amount of heating units. Several variables affect the conversion of those heating units to volume. The dial on your tank does not compensate, unlike the sealed meter on the truck.
Answer: Your gauge is certainly not reading pressure.
The only thing pressure tells you is what temperature the propane is at (LPG is "liquified propane gas" and reflects the fact that propane is easily transported in bulk because it becomes a dense liquid rather than a gas a relatively low pressure. That pressure varies with temperature.)
So, there's probably a float in the tank reading the liquid level. Such things are not uncommonly in error - if you think about the shape of a typical buried LPG tank (a horizontal cylinder), there's a complex relationship between the distance the float travels and the percentage of the tank that is full, which is being "interpreted" by a mechanical linkage.
If you have a local authority in charge of weights and measures, they (probably) check on the metering of the supplier. You could inquire if they do and (if so) when the last test was, and what it showed.
Comment: in addition you don't need 11% error for this result,  if the 49 reading is 3% high and the 88 is 3% low you could get that same result.
Comment: For example, here is the [Texas government page](https://www.texasagriculture.gov/RegulatoryPrograms/WeightsandMeasures/Devices.aspx) saying that any LPG meters must be inspected/registered annually.  The gas company should be able to provide you with documentation about when their trucks were last inspected (assuming your area has similar requirements).


Python :sort list of dictionaries based on key

Question: I have a list of dictionaries
[{'abc':1},{'abcd':2},{'ab':1}]

Based on length of key list has to sorted
[{'abcd':2},{'abc':1},{'ab':1}]

Comment: Have you seen this: http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python?rq=1
Comment: Where is your code, and what exactly is the problem with it?
Comment: Will your dictionaries have only one key always?
Comment: @EdChum my keys are dynamic not the way they specified in the link
Comment: you can't sort regular dictionaries, except using ordereddict.
Comment: @thefourtheye dictionaries have only one key
Comment: @Marcin: this is sorting a *list* **containing** dictionaries.
Answer: If you want to sort by the longest key:
l = [{'abc':1},{'abcd':2},{'ab':1}]
l.sort(key=lambda x: len(next(iter(x))), reverse=True)
print(l)

Comment: `lambda x: len(x.keys()[0])` would work too as `.keys()` return list of keys.
Comment: @TanveerAlam: not in Python 3, where `dict.keys()` returns a *dictionary view*. `next(iter(x))` is better as it works in both versions.
Comment: @TanveerAlam, not in python 3, I changed to `iter` anyway
Answer: If u like to sort by 1st key it's gonna be this:
l.sort(lambda a, b: -cmp(len(a.keys()[0]), len(b.keys()[0])))

However if you want to sort by max key, here the answer:
def maxKeyLen(d): return max(len(k) for k in d.keys())
l.sort(lambda a, b: -cmp(maxKeyLen(a), maxKeyLen(b)))

Comment: when we haev list of dictionaries inside dictionaries  [{'abc':{'count':1}},{'abcd:{'count:2'}'}],  sorting this list based on 'count' , is it possible


mod_rewrite and pretty urls

Question: What I'm trying to achieve:
1) http://localhost/en/script.php?param1=random is mapped to http://localhost/script.php?param1=random&language=English

This has to work always.

2) http://localhost/en/random/text/here will be mapped to http://localhost/categories.php?term=random/text/here

This has to work if random/text/here is 404

What I have at the moment:
RewriteEngine on
RewriteCond substr(%{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^en/(.+)$ categories.php?lang=English&terms=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ee/(.+)$ categories.php?lang=Estonian&terms=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^fi/(.+)$ categories.php?lang=Finnish&terms=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ru/(.+)$ categories.php?lang=Russian&terms=$1 [L]

RewriteRule ^en/(.*) $1?lang=English [QSA]
RewriteRule ^ee/(.*) $1?lang=Estonian [QSA]
RewriteRule ^ru/(.*) $1?lang=Russian [QSA]
RewriteRule ^fi/(.*) $1?lang=Finnish [QSA]

What is the problem:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

It's supposed to redirect to categories.php?lang=English IF /en/this/here/does/not/match/a/script. If I load an URL like en/index.php it will also get mapped to categories.php?lang=English because en/index.php does not exist.
What I've thought:
substr(%{REQUEST_FILENAME},3) would fix my problem (as currently /ee/index.php is literally mapped to /ee/index.php instead of just /index.php)
Unfortunately I couldn't find a way to manipulate strings :/
Answer: I take it the language code is what makes the URL map to a non-existant file. Switch the two steps, moving the language code to the query string first. This also has the added advantage of simplifying the keyword step to a single RewriteRule, since they no longer need to do two things at once.
RewriteRule ^en/(.*) $1?lang=English [QSA,DPI]
RewriteRule ^ee/(.*) $1?lang=Estonian [QSA,DPI]
RewriteRule ^ru/(.*) $1?lang=Russian [QSA,DPI]
RewriteRule ^fi/(.*) $1?lang=Finnish [QSA,DPI]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ categories.php?terms=$1 [L,QSA]

Comment: That worked fine, but for some reason if the URL is http://localhost/en/sales/subcategory this is the arguments that get passed to catagories.php: array(2) { ["terms"]=> string(35) "sales/subcategory/sales/subcategory" ["lang"]=> string(7) "English" } Any thoughts?
Comment: Adding L to the language rules seems to have fixed that.
Comment: @Peeter: The [L] flag will skip the "categories" rule. For URLs that don't map to files, the trailing path component is stored as path info. Apache might be doubling the component in an attempt to preserve the path info. Try adding the discard path info flag ("DPI") to the language rules (see updated code).
Answer: For substr problem, you could try absolute paths:
RewriteRule ^en/(.*) /$1?lang=English&%{QUERY_STRING}

or
RewriteRule ^en/(.*) http:/localhost/$1?lang=English&%{QUERY_STRING}

Also, I might be nitpicking, but wouldn't it be easier if you did the language evaluation in the PHP base on language codes, 404'ed non-existent languages and used
RewriteRule ^(.*?)/(.*) $2?lang=$1&%{QUERY_STRING}

Edit: depending on how many scripts you have, can't you do something like:
RewriteRule ^(.*?)/(script.php|other.php) $2?lang=$1 [QSA]
= have pipe-list files, that are accesible?
Comment: The substitute problem begins at RewriteCond %{REQUEST_FILENAME} !-f/RewriteCond %{REQUEST_FILENAME} !-d

It's supposed to redirect to categories.php?lang=English IF /en/this/here/does/not/match/a/script. If I load an URL like en/index.php it will also get mapped to categories.php?lang=English because en/index.php does not exist.
Answer: the issue is that you are using the L flag. Which means that rule will be the last to be executed.
also
%{QUERY_STRING}

isnt necessary, add QSA and you will get all parameters added to the end of the url
try to do:
RewriteRule ^en/(.*) $1?lang=English [QSA]

Comment: `[L]` means a rule is the last to be executed in the same way that what you look for is always in the last place you look. The flag doesn't change evaluation order, if that's what you meant.
Comment: in the way that @Peeter done it the language rules wont never be reached, simple.

mod_rewrite and pretty urls


How to display .swf flash files in C# Windows Forms desktop application?

Question: My app is about categorizing and describing .swf files stored on my disc, so my main functionality should be to preview the files. How can I play flash files in my Windows Forms desktop app? I'm using visual studio 2010 premium.
Answer: I will see if I can find the full documentation and examples, but there are COM wrappers named axshockwaveflash
Here is a general link that might help guide you:  http://social.msdn.microsoft.com/Forums/en-US/winformsdesigner/thread/5815e676-50b0-47f4-964a-c1bcebfdb9a4/
Here is another: http://www.programmingforums.org/post164816.html
Comment: Thank you, but my main problem now is - what I need to import/include to my project before I will initalize these objects?
Comment: Try this: http://fci-h.blogspot.com/2007/06/how-to-play-flash-swf-inside-c.html?m=1


Transform $\sum_i c_i (B_i + \alpha)^{t_i}$ to $\sum_i \beta_i(1 + r)^{t_i}$ to compute Excess IRR

Question: Is it possible to transform something of the form
$$\sum_i c_i \bigl((1+b_i)^{1/t_i} + \alpha\bigr)^{t_i} = \sum_i c_i (B_i + \alpha)^{t_i}$$
into the form
$$\sum_i \beta_i(1 + r)^{t_i}$$
where $r$ is not dependent on $i$ and $b_i$ is independent of $\alpha$?

My motivation is that I'd like to know if it's possible to calculate an Excess IRR given that I have a function that solves a standard IRR.
Many languages have built-in functions like Excel's XIRR, but don't have something readily available for an excess IRR. Is it possible to somehow use the XIRR function to compute an excess IRR instead of having to resort to an iterative root finding approach?
Comment: It seems $\beta_1=1$ while all other $\beta_i=0$ and $r=(\sum_i c_i (B_i + \alpha)^{t_i} )^\frac{1}{t_1} - 1$ would do it. But I doubt this is what you are after? Furthermore solutions are hardly unique. Many other (more) resonable choices of $\beta_i$ would lead to different solutions for $r$. It seems you are really after a different problem: Find $\beta_i$ such that the root $r$ calculated according to XIRR logic from your DCF equation is equal to $α$.
Answer: I didn't figure out how to prove it rigurously but I have a strong suspicion it isn't possible. I tried to find the solution for the simplest case, only one period with an investiment at the beginning and a single payoff at the end. In this case the problem would be
Find $\alpha$ such that
$$ -I+ \frac{P}{1+b_{1}+\alpha} = 0 $$
where $I$=investment, $P$=payoff, $b_{1}$=index return, and $\alpha$=excess return.
There's a simple solution by setting $r = b_{1} + \alpha$, but this is not valid because $r$ is dependent on $b_{1}$. I can't see a way to transform it as you want.
You can simplify the problem by using continuous compounding because the problem is reduced to
Find $\alpha$ such that
$$ -I+ Pe^{-(b_{1}+\alpha)} = -I+ Pe^{-b_{1}}e^{-\alpha} = 0 $$
There you have it factorized as you wanted, the only problem is XIRR doesn't calculte IRR's with continuous compounding, but you can use the equivalent rate of return $(b_{i}^{'} = e^{b_{i}}-1 \enspace \forall i)$ using the cashflows $P_{i}e^{-b_{i}} \enspace \forall i$.
This won't give you the exact result as the original problem, because the original problem is the degenerate version of the problem
Find $\alpha$ such that
$$ -I+ P\left(\frac{1}{1+b_{1}}\right)\left(\frac{1}{1+\alpha}\right) = 0 $$
$$ -I+ P\left(\frac{1}{1+b_{1}+\alpha+\color{red}{b_{1}\alpha}}\right) = 0 $$
which is the equivalent problem of the continuous case. The good news is that if the numbers are small, the cross term will be even smaller and it would serve as a pretty good approximation. If you want to be safe better use an iterative root finding algorithm.
Comment: Thank you. It does appear to be impossible the way I wanted, but your answer led to me an approximation which may be good enough for my purposes.
Answer: The answer is simple.  You cannot use the EXCEL's built in XIRR to find the EXCESS IRR. The good news is I have created an EXCEL spreadsheet with a macro to find the EXCESS IRR.  It uses SECANT METHOD TO FIND THE alpha using the cashflow dates, cashflows and Index perfomance and finds the the alpha.  It is a standalone EXCEL sheet but you could make it as an add-inn if you want.  The image of this is shown in the image below.  If you could give the email address, I shall send it to you for your use and your company use. The validation is done using EXCEL's goal seek.
Comment: Yes, I already use the goal seek function to calculate Excess IRR in Excel, but I'm trying to figure out how to do this in Power BI.
Comment: The only advantage in using this macro is you don't need to copy formulas, you don't need to alter the sheet and and repeated try to use goal seek which is a three step process.  In this macro, I provides provision for 100 CFs, all you have to do is copy the CFs, CFDates and Copy the Indices and use can choose to use to any number of NAVs to find the excess IRR.  I am not sure about Power BI but the code should help you build one in Power BI.


Do Ice Pops do anything?

Question: Supposedly in Tales of Graces eating Ice Pops would grant (possibly temporary) stat boosts. There are Ice Pops in Tales of Xillia as well but they don't seem to serve any purpose.
Their description says they heal 10% of your health and give you a Win Stick or a Lose Stick. With a Win Stick you can get a free Ice Pop. I haven't seen any hint of them having any other purpose but after hearing about Tales of Graces I find it hard to believe that they do nothing.
So does anybody know if they do anything else?
Comment: That link sounds more like trolling than reliable.
Comment: I want to believe that they do something else since they are otherwise useless. They aren't even a cheap alternative to anything as far as I can tell lol.
Comment: I sincerely doubt the Ice Pops do anything but what they say they do.  You might get something if you get enough win sticks, but that's just speculation on my part.
Answer: They do not do anything but give you Win Sticks and Lose Sticks. A Win Stick will get you a free Ice Pop from the same vendor. But that is it.
Answer: They are part of an ingredient in custom made items and also food custom made items
Comment: Do you have a source for this?  I don't recall using these anywhere throughout my entire playthrough.

Do Ice Pops do anything?


Compare query result to array PHP

Question: I have an array $columns which contains the chosen values from the user. The user values is supposed to be saved in a database table so that the next time, the user wont be given points for the values that he or she chose the last time. Messy? A bit of code plz? ok:
$columns= isset($_POST['column']) ? $_POST['column'] : array();
print_r($columns);

So all columns that is chosen gets the value 1, and the other ones have value 0. This gives me:
Array ( [0] => 1 [1] => 1 [2] => 1 [4] => 1 [7] => 1 )

I have a database table with 8 different columns namned column1,column2,columnN....
I want to compare the database table to my array. To know which column to update. Now im thinking:
while($row = mysql_fetch_array( $result )) {
    if($row['column'.$checks]!=1){
        //update table with values
     }
    }

Should I compare my array to $row? or intersection? how can I get the values needed from my array?
Comment: **[Please, don't use mysql_* functions for new code.](http://bit.ly/phpmsql)** They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the **[red box](http://j.mp/Te9zIL)**? You can use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) instead - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://www.brightmeup.info/article.php?a_id=2).
Comment: Thank you! will look in to it.
Answer: Why not merge all those tables into one.
id  |  column_id  |  check

Which will make updating values a lot easier
foreach ($columns as $column_id => $value) {
   // UPDATE `table` SET check = {$value} WHERE column_id = {$column_id};
}

Comment: but wont the table look like (ID->1 column_id->1,2,3,6,7 check->1) or :)?
Comment: No! because you are looping over all column id's and updating one at a time!

Compare query result to array PHP


perspective projection transformation matrix

Question: In one text,  the  derivation for  perspective  projection  goes like  this:
If $x',y',z'$ represent any point along  the  projection line,and $x_{prp},y_{prp},z_{prp}$ are the projection reference point, then:
$$x'=x-(x-x_{prp})u$$
$$y'=y-(y-y_{prp})u$$
$$z'=z-(z-z_{prp})u$$
where $0\le u \le 1$
Now,   finding the value of u from the third equation above and  replacing in the first and  second  equations,   we get at  $z_vp$:
$$ x_p=x'= x.\frac{z_{vp}-z_{prp}}{z-z_prp}+x_{prp}.\frac{z-z_{vp}}{z-z_{prp}}$$
$$ y_p=y'= y.\frac{z_{vp}-z_{prp}}{z-z_prp}+y_{prp}.\frac{z-z_{vp}}{z-z_{prp}}$$
and there is no projection transformation matrix  given.
In the second text,  the  derivation is using  similar triangles:

comparing the  similar triangles  we  get:
$$x_p=\frac{-x_c}{\frac{z_c}{d}}$$
$$y_p=\frac{y_c}{\frac{z_c}{d}}$$
and  the projection transformation for  homogeneous coordinates x,y,z is  given by:
$$
\begin{bmatrix}
-1&&0&&0&&0\\
0&&1&&0&&0\\
0&&0&&1&&0\\
0&&0&&\frac{1}{d}&&0
\end{bmatrix}
$$
so,  my questions are:

How do I find the projection matrix of coordinates as found from
derivation 1?
Both are given in the perspective projection area of
these different texts,  are both transformations the  same? If not,
how  are  they different?
Comment: I think that my answer to your [other question](https://computergraphics.stackexchange.com/questions/8255/finding-the-projection-matrix-for-one-point-perspective/) applies here as well.
Answer: Given your equations (which i just assume are correct):
$$
\begin{align}
x_p &= x \frac{z_{vp}-z_{prp}}{z-z_{prp}}+x_{prp} \frac{z-z_{vp}}{z-z_{prp}}\\
y_p &= y \frac{z_{vp}-z_{prp}}{z-z_{prp}}+y_{prp} \frac{z-z_{vp}}{z-z_{prp}}
\end{align},
$$
if we take $(x_{prp}, y_{prp}, z_{prp}) = (0, 0, 0)$, then we have
$$
\begin{align}
x_p &= x\frac{z_{vp}}{z}\\
y_p &= y\frac{z_{vp}}{z}
\end{align}
$$
Assuming the projection plane is at distance $d$ from the origin, and, by your drawing, that the projection plane is on the negative side of the Z axis, we have $z_{vp} = -d$, which leads to
$$
\begin{align}
x_p &= - x\frac{d}{z}\\
y_p &= - y\frac{d}{z}
\end{align}
$$
Now we can follow the same reasoning (homogeneous coordinates) as in my answer to your other question (using column notation) to write
$$
\begin{align}
\begin{bmatrix}
x\\y\\z\\ \frac{-z}{d}
\end{bmatrix}
=
\begin{bmatrix}
1&0&0&0\\
0&1&0&0\\
0&0&1&0\\
0&0&\frac{-1}{d}&0
\end{bmatrix}
\begin{bmatrix}
x\\y\\z\\1
\end{bmatrix}
\end{align}
$$
which after the division by the last coordinate will give the projected point. Notice that because we are writing it in column notation, the perspective matrix is the transpose of the matrix in your other question. Also, the negative sign is because the camera reference frame is a right-handed one.
As for the second textbook that you are reading, I cannot understand why you would have a negative sign only in the x axis without knowing more about the camera reference frame. By the diagram you posted, there should not be a negative sign.
Comment: thank you for answering here as well, one user pointed out that the negative sign  was due to reflection on the yz plane to correct  the reference frame.... so the x coord was reflected was what he said.
Comment: if you have some time, could you please take a look at [this question of mine](https://computergraphics.stackexchange.com/questions/8262/preserving-z-values-during-projection) , I  can't  really seem to understand the given explanation.
Comment: Sorry for taking me so long to answer your comment. Another user has already answered your question, and it seems to be correct. If you just apply the perspective matrix as shown above, every z-value will map to d, losing the information about object ordering, which is needed for the Z-buffer algorithm to correctly render the scene. So, the original range of Z values is usually mapped to another range, such that after perspective projection, Z is mapped to normalized device coordinates, as expected by your graphics API of choice.