text:
Q: How to make Max Width and Height work with Jquery ImgViewer Plugin I am using the ImgViewer v.6 for zooming images (w/IE8 support).
It works fine when the image is wider than taller. However, when an image is taller, the entire height does not display in the container.
http://jsfiddle.net/TheFiddler/wmx05cty/
In this fiddle, you can see the top image has some of its height clipped off.
I need to fill up the viewport with as much of the image as possible without stretching the image. The image needs to remain proportional. The width should be 100%, and a tall image should have the height fit the viewport height as well. The tall image needs to be centered horizontally and its entire width and height visible initially.
So, I modified the plugin to detect the height, and if taller, set the height to the viewport's height.
  if (height > width) {
        var ratio = $view.height() / height;
        ih = $view.height();
        iw = width * ratio;
  }

This works except that the image is not centered. The math on the viewport and image are not quite right.
http://jsfiddle.net/TheFiddler/qontbr9e/
I need a way to center both images in their containers, display the entire width so that it fills the container, and if it is a taller image, resize it so that the height fits in the container on init.
This is a dynamic application, so I cannot apply styles to individual images. The same script needs to work on both images using the same css. I must use the v.6 version.

A: Edited: Cleaned up the answer.
So, this solution is a bit messy but it works:
Fiddle for centered only on x
Fiddle for centered on both x and y
In the widget constructor:
this.$oldview = $img.parent(); //store original container element

Then in the update method:
$(this.view).position({
                    my: "left top",
                    at: "left top",
                    of: this.$oldview
                });

This shifts the viewport back into position (for some reason the code you added makes the viewport go to absolute(0,0)).
At the end of update, I add an offset to zLeft.
var offsetx = //offset need to horizontally center image
    (this.$oldview.width() / 2) -
    (((this.zimg).width() / 2) / zoom);

$(this.zimg).css({ //center image
    left: zLeft + offsetx + "px"
});

And this at the start of update because it was misbehaving when zoomed out all the way:
if (zoom < 1) {
    this.options.zoom = 1;
    zoom = 1;
}

I also removed the text-align:center.I think that's all the changes I made.
If you want it centered vertically too, same thing: http://jsfiddle.net/qontbr9e/10/
Same thing but for both x and y:
var offsetx = //offset need to horizontally center image
    this.$oldview.width() / 2 -
    (this.zimg).width() / 2 / zoom;
var offsety = //offset need to vertically center image
    this.$oldview.height() / 2 -
    (this.zimg).height() / 2 / zoom;

$(this.zimg).css({ //center image
    left: zLeft + offsetx + "px",
    top: zTop + offsety + "px"
});

A: I think, you want to stretch your image to take entire div with. If, i am correct, then you can do this with css. Just set width and height to  100%.
Add this class to your css.
img {
    width:100%;
    height:100%;
}

JSFiddle: http://jsfiddle.net/wmx05cty/4/
/** EDITED CONTENT **/
If you only wants to stretch(resize) the image to fit to div, which is greater than div height or width, then use this css.
img {
    max-width:100% ;
    max-height:100%;
}

JSFiddle: http://jsfiddle.net/wmx05cty/6/
Hope, it helps.

A: You need the max width max height and a margin auto auto;
http://jsfiddle.net/wmx05cty/7/
css :
    img {
    max-width:100%;
    max-height:100%;
    margin:auto auto;

}


text:
Q: Angularfire facebook user_friends Using facebook authentication with angularFire, I don't see "user_friends" in the Auth object that is returned.
ng-click="auth.$authWithOAuthPopup('facebook',{scope:'user_friends'})"
This works fine for grabbing the uid, and I see the facebook object which contains the "accessToken", "cachedUserProfile" etc., but no "user_friends".
Someone is have a similar issue here with the "email" object:
Angularfire login with Facebook not recieving extended permissions
Am I missing something or is this a bug?
Thanks for any help/guidance.

A: So it turns out you can turn around and use that token to hit the facebook Graph API like so...
$http.get("https://graph.facebook.com/v2.0/me?fields=friends&access_token="+authData.facebook.accessToken)

redpajama_set_name: RedPajamaStackExchange


text:
Q: equality between the index between field with $p^{n}$ elements and $ \mathbb{F}_{p}$ and n? can someone explain this?
$ \left[\mathbb{F}_{p^{n}}:\mathbb{F}_{p}\right]=n $

A: $$|\Bbb F_p|=p\;,\;\;|\Bbb F_n^n|=p^n$$
amd since any element in the latter is a unique linear combination of some elements of it and scalars from the former, it must be that those some elements are exactly $\,n\,$ in number.


text:
Q: after changing scenes, hidden objects are no longer hidden I'm new to Unity and C# so bear with me please. I have several scenes where the player can move at will and in one there are imageobjects that I want hidden when mouseclicked. Right now I have added a script to one imageobject where I use renderer.enabled = false; to hide it. When the player moves back to that scene it is not hidden anymore. What would be the right way to do this?
//------EDITED PART-----------
Now it works :)
public static bool showIt = true;
    void Start () {
        renderer.enabled = showIt;
        print (showIt);
    }
    void OnMouseDown (){
        showIt = false;
        renderer.enabled = showIt;
    }

A: why not gameObject.SetActive(false) instead of renderer.enabled = false ?

A: You can try something like this using PlayerPrefs:
    public class RenderController : MonoBehaviour {

        // Check PlayerPrefs in Awake() to see if renderer should be enabled
        void Awake(){
            if (PlayerPrefs.GetInt ("rendererOn") == 0) {
                renderer.enabled = true;
            }
            else
                renderer.enabled = false;
        }

        void OnMouseDown(){

            // If the renderer is enabled when clicked then disable renderer
            if (renderer.enabled == true) {
                renderer.enabled = false;
                PlayerPrefs.SetInt("rendererOn",1);// Set state to 1(false)in PlayerPrefs
            }

            // If the renderer is disabled when clicked then enable it
            else if(renderer.enabled == false){
                renderer.enabled = true;
                PlayerPrefs.SetInt("rendererOn",0);// Set state to 0(true)in PlayerPrefs
            }
        }
    }

I tested it in Unity and it works. Basically just writing the enabled/disabled state of the renderer componenet to PlayerPrefs and every time the object loads it checks to see what the last state was. Remember to set rendererOn global variable equal to 0, as I did above, if you want it enabled when the game loads for the first time.

A: Why don't you use static variables to persist the objects's state? You could use PlayerPrefs, but it's not the optimal method. Set your boolean variable to record the state using static initialization, then use your Start() method to initialize your variable and set the value(s). Remember before your LoadLevel() you must persist the value to the the given variable (or PlayerPrefs.Set* if you go that route). Remember if you persist in Update() or OnGUI() or FixedUpdate() there is significant cost.


text:
Q: Indirect references to functions in javascript I was just reading the book, "You don't know JS" by kyle simpson and came across the following sinppet of code that somewhat confused me. basically I was reading a topic on the this keyword. below is the snippet:
function foo() {
    console.log( this.a );
}

var a = 2;
var o = { a: 3, foo: foo };
var p = { a: 4 };
o.foo(); // 3
(p.foo = o.foo)(); // 2

So far reading the book I do understand how this works, but for me its hard to understand whats really happening on the last line of the snippet.
if I analysis it bymyself the last line is an iffe executing in the global scope and if in the iffe the foo() fuction executes, the this.a in the foo() function will point to the a in the global scope, which is indeed 2.
But somehow I don't feel i totally understand whats happening on the last line, can somebody break it down for me?
Thank you.
Alexander.

A: The final line is passing along the reference to the foo function and then executing in the global scope, just as you see.  It is equivalent to this
var f = p.foo = o.foo;
f();

A: The return value of an assignment is always the value itself. At this example the return value is a reference to the function foo. Therefore two steps are executed on one line.

*

*p.foo = o.foo;

*foo();

A: This is whats happening:
when (p.foo = o.foo)(); is called, JS transforms it into
function foo() {
  console.log( this.a );
}

and since var a = 2 is set in the global scope, and nothing is passed to the function, your result is 2
So then the question is why does JS transform (p.foo = o.foo) into the foo() function?
well if you break it down, you have this:
p.foo = o.foo : this is assigning the variable from right to left. Just like var a = "something"; so this means that now, p.foo equals o.foo, and since o.foo equals foo, we are now saying p.foo = foo, in other words this:
(p.foo = o.foo)(); is the same as (foo)() which then runs the foo function.
To further explain:
 console.log(p.foo); //returns undefined because nothing was set to it
 console.log(o.foo); //returns foo, because it was assigned var o = {foo: foo};
 p.foo = o.foo; // this assignes foo to p.foo
 console.log(p.foo); //returns foo, it is no longer undefined, because of our assignment
 (p.foo)(); // will run the function

I had problems with getting undefined before, but that was because I was running tests on http://jsfiddle.net/ which prevented me from accessing my function correctly.


text:
Q: sending packets to a client given the remote_endpoint object and the socket? Is there a way to send a packet to a client knowing the remote_endpoint object where endpoint.address and endpoint.port are used?
EDIT: I added the async_write free function but I still don't know how to specify the ip-address or the port for the socket_ to send data_ to (the client). The changes are lines 44-49 to the boost async server example.
#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

class session
{
public:
  session(boost::asio::io_service& io_service)
    : socket_(io_service)
  {
  }

  tcp::socket& socket()
  {
    return socket_;
  }

  void start()
  {
      std::cout<<"start(): "<<std::endl;
          socket_.async_read_some(boost::asio::buffer(data_, max_length),
          boost::bind(&session::handle_read, this,
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
  }
void read_handler(const boost::system::error_code& ec, std::size_t bytes_transferred);

private:
  void handle_read(const boost::system::error_code& error,
      size_t bytes_transferred)
  {
      std::cout<<"handle read: bytes_transferred"<<bytes_transferred<<std::endl;
    if (!error)
    {
          data_ = {'0','1','2','3','4','5','6','7','8','9'};
          /*read_handler(error, bytes_transferred);
          boost::asio::async_write(socket_,boost::asio::buffer(data_, bytes_transferred),
                boost::bind(&session::handle_write, this,
                            boost::asio::placeholders::error));*/
          boost::system::error_code ec;
          boost::asio::ip::tcp::endpoint endpoint = socket_.remote_endpoint(ec);
          std::cout<<"ip address: "<<endpoint.address()<<std::endl;
          std::cout<<"port: "<<endpoint.port()<<std::endl;
          //how to get the socket to send data to specific port, ip-address e.g. changing the ip-address and port by editing it?
          async_write(socket_, boost::asio::buffer(data_, max_length), boost::bind(&session::writeHandler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
    }
    else
    {
      delete this;
    }
  }
  void writeHandler(const boost::system::error_code& errorCode, size_t bytesTransferred)
  {
        std::cout << "DEBUG> Transfered " << bytesTransferred << " bytes to " << socket_.remote_endpoint().address().to_string() << std::endl;
  }
  void handle_write(const boost::system::error_code& error)
  {
      std::cout<<"handle write: "<<std::endl;

    if (!error)
    {
            std::cout<<"before: "<<data_<<std::endl;

            socket_.async_read_some(boost::asio::buffer(data_, max_length),
            boost::bind(&session::handle_read, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));

            std::cout<<"after: "<<data_<<std::endl;
    }
    else
    {
      delete this;
    }
  }

  tcp::socket socket_;
  enum { max_length = 1024 };
  char data_[max_length];
};
void session::read_handler(const boost::system::error_code& ec, std::size_t bytes_transferred)
{
      std::cout<<bytes_transferred<<std::endl;
}

class server
{
public:
  server(boost::asio::io_service& io_service, short port)
    : io_service_(io_service),
      acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
  {
    start_accept();
  }

private:
  void start_accept()
  {
    session* new_session = new session(io_service_);
    acceptor_.async_accept(new_session->socket(),
        boost::bind(&server::handle_accept, this, new_session,
          boost::asio::placeholders::error));
  }

  void handle_accept(session* new_session,
      const boost::system::error_code& error)
  {
    if (!error)
    {
      new_session->start();
    }
    else
    {
      delete new_session;
    }

    start_accept();
  }

  boost::asio::io_service& io_service_;
  tcp::acceptor acceptor_;
};

int main()
{
  try
  {
    boost::asio::io_service io_service;
    server s(io_service, 4000);

    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

A: Assuming TCP sockets since that is what you linked to in the documentation, no that is not possible. You need a socket object to send data, not just an endpoint. Use the async_write() free function, one of its many overloads, or any of the socket class methods to send data.


text:
Q: Physics of Sound and the middle ear? Once sound waves reach the eardrum, the eardrum moves back and forth and transmits those waves/pulses to three bones that serve to transmit and amplify the pulses to another "drum" in the inner ear.
The diagram I linked below shows how that amplification occurs, due to the relationship between Pressure  = Force x Surface Area.
I don't understand how F1 and F2 are related? I think it has to do with the two pivot points but I am confused as to how to work out the relationship.

I also have trouble understanding how if these bones become more rigid, then why that would only affect the amplification but not the frequency of the sound?
Doesn't frequency get translated by the bones as well? so if the three become more immobilized/stiffer, the frequency of pitches would go up? (more stiff higher frequency). On this point I am just trying to make an educated guess

A: You are right to some extent, the properties of bones has some small effect on the frequency. Not only that but some sound waves even get transmitted via out skull bones.
The point is decoding what comes through and understanding the sounds happens in the brain, which has already anticipated and adjusted to the interference of our bones and acoustics of our ears. Plainly said It is the brain that understand what you hearing for example is the sound of passing bus in the street while still allowing you to hear what your friend walking next to is saying
By looking at the diagrams you have one realizes there has to be a great leap of faith to arrive at the quantities and proportions the book states. The bones are leaning and pushing against each other in very complex surfaces and in off-center axis.
To illustrate how important the role of brain is in hearing, I have to wear hearing aids and as opposed to intuition when I don't wear them I hear some low frequencies even louder, to the point of being painful. My guess is my brain in trying to compensate for lack of understanding amplifies the band of spectrum of total sound it hears, beyond comfortable level!


text:
Q: Bruhat-Tits building for $PGL_2(F)$ and repressentation theory I am trying to understand representation theory of $GL_2(F)$ where $F$ is a finite extension of $\mathbb{Q}_p$. I am using the following paper of Colmez to understand it:
https://webusers.imj-prg.fr/~pierre.colmez/kirilov.pdf
There in page 73, the author discussed briefly the Bruhat-Tits tree for $PGL_2(F)$ and define the notion of an "arete" to be "une extremite". However I am unable to visualize it and for which I am failing to understand simple proofs like the proof of Lemma III.1.13 (page 78). For example, in the proof of Lamma III.1.13, the author says:
"Soit $[r_0,r_1]$ une extremite de $\mathcal{A}$, telle que $r_o$ is not in $I_{\mathcal{A}_1 \cap \mathcal{A}_2}(W,\Pi)$; il exists .... $r_0 \in \mathcal{A}_i$"
I do not understand why such $r_0 $ should exists. I think that I am lacking a proper visualization of the Bruhat-Tits tree.
Merci to explain the visualization of the notion of concept of "extremite" in Bruhat- tits tree.
My background: I do not have a prior background of Bruhat -Tits tree or buildings, appartments in general.


text:
Q: How to stop touchesMoved I want win my frame moved 40/3px then stop moved!
How to stop moved and change frame x to 40+320! thank you
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(self.frame.origin.x > 40/3) {
            CGRect myFrame = self.frame;
            myFrame.origin.x = 40 + self.frame.size.width;
            self.frame = myFrame;
    }
}

A: Change your code like this :
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(self.frame.origin.x > 40/3) {
            CGRect myFrame = self.frame;
            myFrame.origin.x = 40 + self.frame.size.width;
            self.frame = myFrame;
            [self touchesEnded:touches withEvent:event];
    }
}

Hope it helps


text:
Q: Can any SSL certificate can be used for client certificate authentication purpose? I am trying to connect to a third party API which have a mutual TLS authentication setup enabled. So I am supposed to install my client certificates inside my key store and send it on TLS handshake process.
For this process I am right now using commodo positive SSL as client side certificate. When I make TLS calls, Evnthough server is requesting a certificate, Client is not sending one. And when I checked SChannel Log, I can see a warning like this

The remote server has requested TLS client authentication, but no suitable client certificate could be found. An anonymous connection will be attempted. This TLS connection request may succeed or fail, depending on the server's policy settings.

SO my doubt is like this, Am I using the correct type of X509 certificate for the purpose of client side authentication? Do I need to use any other specific type? As my current certificate is not getting send.

A: It depends. X.509v3 certificates usually come with an "Extended Key Usage" extension field, which contains a list of permitted usages (EKUs).

*

*Regular web server certificates contain the "TLS Server Authentication" usage (sometimes shown as "TLS Web Server", but it really is not Web-specific at all).

*To act as a client, you need a certificate with "TLS Client Authentication" (again often shown as "TLS Web Client", despite having nothing Web-specific in it).
It is quite common for regular "web server" SSL certificates to contain both usages – for example, I'm looking at certificates issued by Let's Encrypt and DigiCert, and all of them contain both usages, therefore can be used for client/mutual authentication.
However, it's possible that in some other CAs, especially private organization CAs, most certificates have one usage or the other, but rarely both.
For example, OpenVPN used to strictly require "only TLS Client" (rather than "at least TLS Client" as other programs do), therefore its easy-rsa script issues server-only and client-only certificates but not the mixed kind.

So you should examine your certificates and make sure they contain the required EKU. Practically any certificate tool will do the job – for example, the Certificate properties dialog in Windows will show this under "V3 Extensions", as will web browsers, openssl x509, certtool, certutil, etc.
Also worth remembering if you run your own internal CA: If you use an intermediate CA certificate, pay attention to it as well. Intermediates aren't required to have an EKU extension, but if they do have it, then all certificates issued by that intermediate are constrained by it. (If you obtain the certs commercially, shouldn't need to worry about it.)

Additionally, the certificate will have a basic "Key Usage" field which contains some very general restrictions: e.g. "Digital Signature" means the certificate is allowed to sign data (and therefore allows EDH/EECDH handshake in TLS); "Key Agreement" appears to be for static-DH/ECDH; "Key Encipherment" allows static-RSA handshakes.
The official X.509v3 documentation is very confusing in what usages are needed when... Commercial CAs will usually get this field right. But for private CAs it's worth double-checking.


text:
Q: Unsafe threading with dictionary - Let's break some stuff So at the bottom of http://msdn.microsoft.com/en-us/library/xfhwa508.aspx we see

A Dictionary(Of TKey, TValue) can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

In my asp.net application, I occasionally see NullReferenceExceptions generated from inside System.Collections.Generic.Dictionary`2.Insert.
How could I recreate this in a sandbox?
The following code doesn't cause the exception, in spite of a local dictionary being accessed by separate threads.
class Program {
    static void Main(string[] args) {
        int maxThreads = 20;
        Dictionary<Guid, Guid> dict = new Dictionary<Guid, Guid>();
        var tws = new threadWithState();
        while (true) {
            for (int i = 0; i < maxThreads * 2; i++) {
                var thread = new Thread(tws.Work);
                thread.IsBackground = true;
                thread.Start(dict);
            }
            dict[Guid.NewGuid()] = Guid.NewGuid();
        }
    }
}

class threadWithState {
    public void Work(object dict) {
        Console.WriteLine((dict as Dictionary<Guid, Guid>).Count);
        for (int i = 0; i < 1000; i++) {
            (dict as Dictionary<Guid, Guid>)[Guid.NewGuid()] = Guid.NewGuid();
        }
    }
}

A: That's part of the problem with threading - bugs are not necessarily reproducible reliably.  The issue is that the insert has to hit a specific race condition, which obviously isn't happening in your test.  Of course, enough runs may cause this to trigger, but that's going to be difficult to reliably test.
That being said, this is obviously a problem.  Instead of focusing on reproducing it, you should consider how to just correct it.  The obvious answer here, of course, is to switch to a different technique, such as using a ConcurrentDictionary<T,U> instead, which is thread safe.

A: This code suffers from accidental synchronization due to the garbage collected heap lock.  You'll get it to crash much quicker by injecting random delays, much like what happens on the actual server.  This code made it crash in a fraction of a second on my machine, ymmv:
        public void Work(object dict) {
            var rnd = new Random();
            Console.WriteLine((dict as Dictionary<Guid, Guid>).Count);
            for (int i = 0; i < 1000000; i++) {
                (dict as Dictionary<Guid, Guid>)[Guid.NewGuid()] = Guid.NewGuid();
                for (int ix = 0; ix < rnd.Next(1000); ++ix) ;   // NOTE: random delay
            }
        }


text:
Q: How to use Applescript to Change Preference Pane Slider value? I'm trying to create an AppleScript for setting the value of Input Volume of the Input category under the Sound menu in System Preferences.
How does one change the value of a Slider?
tell application "System Preferences"
    activate
    set current pane to pane "com.apple.preference.sound"
end tell
tell application "System Events"
if UI elements enabled then
    try
        tell application process "System Preferences"
            tell tab group 1 of window "Sound"
                click radio button "Input"
                select row 1 of table 1 of scroll area 1
                set selected of row 1 of table 1 of scroll area 1 to true
                set deviceselected to "Microphone"
                set slider "Input Volume" of group "Input Volume" of tab group "Input" to 0
                select row 2 of table 1 of scroll area 1
                set selected of row 2 of table 1 of scroll area 1 to true
                set deviceselected to "Microphone"
                set slider "Input Volume" of group "Input Volume" of tab group "Input" to 0

            end tell
        end tell
    end try
end if
end tell

This doesn't seem to work.
I also tried using Accessibility Inspector to find out how to hierarchically access the elements in the following manner,
 value of slider of group "Input volume" of tab group "Input" of window "Sound"

That doesn't seem to be a correct way either.
What's wrong here?
EDIT
set content of slider "Input volume" of tab group "Input" of window "Sound" of tab group     1 of window "Sound" of application process "System Preferences" to 0
        --> error number -1700 from content of slider "Input volume" of tab group "Input" of window "Sound" of tab group 1 of window "Sound" of application  **

So it returns an error. I couldn't find any description for error code -1700, what does it mean?

A: You can access the volume settings directly without using gui scripting. These commands are in the standard additions osax of applescript. To see the volume settings you can change use this. Notice it requires the word "get" in the command.
get volume settings

Looking at those results you can see that the input volume is one of the volume settings you can access. It's a value from 0 to 100. Here's how you can set it...
set volume input volume 64

The above command is a little strange because there is no "to" word in that command. You're not setting the volume "to" something so it's strange. Anyway Good luck!
EDIT: Here's how to access it using gui scripting. Also if you want to know the error codes, I posted a script for that here. See post #9 for the latest version.
tell application "System Preferences"
    activate
    set current pane to pane "com.apple.preference.sound"
end tell

tell application "System Events"
    tell application process "System Preferences"
        tell tab group 1 of window "Sound"
            click radio button "Input"
            get value of slider 1 of group 2
        end tell
    end tell
end tell

A: Sliders can be manipulated with the increment and decrement actions. So, you can just repeat until it reaches the level you desire. This example sets the Sound Effects Alert volume to 0.5
tell application "System Preferences"

    tell anchor "effects" of pane "com.apple.preference.sound" to reveal

    tell application "System Events" to tell process "System Preferences"
        set s to slider "Alert volume:" of tab group 1 of window 1
        repeat while value of s is less than 0.5
            increment s
        end repeat
        repeat while value of s is greater than 0.5
            decrement s
        end repeat

    end tell

end tell

A: set content of slider "Input volume" to x


text:
Q: Generalization of the Riemann integral to functions on the sphere I want to do something a bit strange: define the Riemann/Darboux integral for bounded real functions defined on the n-dimensional sphere.
The catch: I cannot use Lebesgue integration theory to do this. This is because I want to do something similar to averaging the values of the function over an equidistributed sequence of points, and then claiming the averages tend to the integral as I take more and more points. This idea is true for Riemann-integrable functions (see Theorem 1.1 and Corollary 1.1 in the book Uniform Distribution of Sequences by Kuipers and Niederreiter) but it fails for Lebesgue-integrable functions.
In particular, a Dirichlet-type function (nonzero on a countable dense set and zero elsewhere) cannot be Riemann-integrable for my needs.
So, to avoid reinventing the wheel, I'm looking for a reference where someone went through defining the Riemann or Darboux integral for either a sphere or a more general space. The definition must allow the following theorems:

*

*Continuous functions are Riemann-integrable.

*Riemann-integrable functions are Lebesgue-integrable and the two integrals are the same.

A: You can find it in most of books an analysis of functions of several variables. Let me mention Apostol, Bartle, Marsden & Hofman and Spivak.


text:
Q: Alamofire URL Request - unexpectedly found nil when unwrapping an Optional Value So I have a PageViewController to manage various VCs that contain an array of stock symbols, prices etc.
I use Alamofire to manage the API call in my model. Here is the shorten summary of the model and its problem:
struct Stock {
    var last: String?
    var companyName: String?
    var symbol: String?

    var dataFields: [[String : String]]
}

class SwiftStock {
  class func fetchStockForListOfSymbols(#symbols: Array<String>, completion:(stock: Stock) -> ()) {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

      var stockURL = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22\(symbols)%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json"

      request(.GET, stockURL)
        .responseJSON { (_, response, resultsJSON, _) in

          if response?.statusCode == 200 {

            if let stockData = (((resultsJSON as! [String : AnyObject])["query"] as! [String : AnyObject])["results"] as! [String : AnyObject])["quote"] as? [String : AnyObject] {

              // lengthy creation, yeah
              var dataFields = [[String : String]]()

              dataFields.append(["Last" : stockData["LastTradePriceOnly"] as? String ?? "N/A"])
              dataFields.append(["Company" : stockData["Name"] as? String ?? "N/A"])
              dataFields.append(["Symbol" : stockData["Symbol"] as? String ?? "N/A"])

              let stock = Stock(
                last: dataFields[0].values.array[0],
                companyName: dataFields[1].values.array[0],
                symbol: dataFields[2].values.array[0],
                dataFields: dataFields
              )
              dispatch_async(dispatch_get_main_queue()) {
                completion(stock: stock)
              }
            }
          }
      }
    }
  }

There was an unexpectedly nil found while unwrapping an Optional value during the Alamofire's URLRequest. Not sure where I screw up. Any advice?
The codes on the PageViewController are as follows:
class PageViewController: UIPageViewController, UIPageViewControllerDataSource
{
  var symbols: Array<String> = ["CMG", "TSLA", "FB", "SHAK"]
  var prices = [""]

  var stock: Stock?

  override func viewDidLoad() {
    super.viewDidLoad()

    // Set the data source to itself
    dataSource = self

    // Create the first screen
    if let startingViewController = self.viewControllerAtIndex(0) {
      setViewControllers([startingViewController], direction: .Forward, animated: true, completion: nil)
    }
  }

  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    updateUI()
  }

  func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {

    var index = (viewController as! MainViewController).index
    index++
    return self.viewControllerAtIndex(index)
  }

  func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {

    var index = (viewController as! MainViewController).index
    index--
    return self.viewControllerAtIndex(index)
  }

  func viewControllerAtIndex(index: Int) -> MainViewController? {
    if index == NSNotFound || index < 0 || index >= self.symbols.count {
      return nil
    }

    // Create a new view controller and pass suitable data.
    if let pageContentViewController = storyboard?.instantiateViewControllerWithIdentifier("PageContentViewController") as? MainViewController {
      pageContentViewController.symbol = symbols[index]
      pageContentViewController.price = prices[index]
      pageContentViewController.index = index
      pageContentViewController.pageCount = symbols.count

      return pageContentViewController
    }
    return nil
  }

  func updateUI() {

    SwiftStock.fetchStockForListOfSymbols(symbols: symbols) { (stock) -> () in

      self.prices = ["\(stock.last!)"]
    }
  }

}

A: Your url is wrong, if you copy and paste the url into the browser its supposed to return json, but instead it returns this
{
  error: {
  lang: "en-US",
description: "Query syntax error(s) [line 1:54 mismatched character  '(' expecting set null,line 1:65 mismatched character ' ' expecting '"']"
}
}

Here is the complete code without using a library to retrieve the stock symbols :
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = NSURL(string: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22CMG%22%2C%20%22TSLA%22%2C%20%22FB%22%2C%20%22SHAK%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json")
        let session = NSURLSession.sharedSession()

        let dataTask = session.dataTaskWithURL(url!) { (data, response, error) -> Void in
            if(error != nil){
                print("Something wrong")
            }

            do{
                let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                if let quote = jsonData["query"]?["results"] as? NSDictionary {
                    if let quoteArray = quote["quote"] as? NSArray {
                        for quoteItem in quoteArray {
                            print(quoteItem["symbol"] as! NSString)
                        }
                    }
                }

            } catch{

            }

        }

        dataTask?.resume()
    }

}


text:
Q: SQL ranking repeating groups I have the following data which is sorted by start date. What i want to do is rank the product name as is appears for example product number 27675 is on row 1 and the first time this product is found therefore rank 1... again this product is on row 5 so rank 2.
I want to then select this data without the date and group by section, row, product and rank.
SECTION_NAME    ROW_NAME    PRODUCT NAME    start_date         DESIRED RANK
SEW             LS-1-A_1    27675           02/03/2016 14:39    1
SEW             LS-1-A_1    26298           06/04/2016 16:56    1
SEW             LS-1-A_1    26298           16/05/2016 16:56    1
SEW             LS-1-A_1    26298           04/06/2016 09:26    1
SEW             LS-1-A_1    27675           16/06/2016 16:22    2
SEW             LS-1-A_1    18969           17/07/2016 12:54    1
SEW             LS-1-A_1    26298           01/08/2016 10:52    2
SEW             LS-1-A_1    27675           29/08/2016 08:38    3
SEW             LS-1-A_1    LEVI F17 SMS    12/09/2016 13:39    1

the rank i am producing is:
SECTION_NAME    ROW_NAME    PRODUCT NAME    start_date             RANK
SEW             LS-1-A_1    27675           02/03/2016 14:39    1
SEW             LS-1-A_1    26298           06/04/2016 16:56    1
SEW             LS-1-A_1    26298           16/05/2016 16:56    2
SEW             LS-1-A_1    26298           04/06/2016 09:26    3
SEW             LS-1-A_1    27675           16/06/2016 16:22    2
SEW             LS-1-A_1    18969           17/07/2016 12:54    1
SEW             LS-1-A_1    26298           01/08/2016 10:52    4
SEW             LS-1-A_1    27675           29/08/2016 08:38    3
SEW             LS-1-A_1    LEVI F17 SMS    12/09/2016 13:39    1

SELECT
   SECTION_NAME,
   ROW_NAME,
   PRODUCT_NAME,
   start_date,
   dense_rank() OVER (PARTITION BY product_name ORDER BY START_DATE)RANK
FROM
   TABLES

Order by
    SECTION_NAME,ROW_NAME,START_DATE

UPDATE----
using the following:
SELECT
  SECTION_NAME ,
  ROW_NAME,
  PRODUCT_NAME [Style],
  (START_DATE) as [Start dt],
  SUM(isChange) OVER (PARTITION BY SECTION_NAME , ROW_NAME,product_name     ORDER BY START_DATE) as rank_

FROM (SELECT SECTION_NAME,
        ROW_NAME,
        PRODUCT_NAME,
        sd.START_DATE,
         (CASE WHEN lag(PR.ROW_NAME ) over (order by SD.START_DATE) = PR.ROW_NAME
               THEN 0
               ELSE 1
          END) as IsChange
  FROM
    TABLES_t
 ) t
Order by SECTION_NAME, ROW_NAME, START_DATE;

Produces this: ( In situations where the product is the same on each row (10,11,12) i would expect these to have the same rank.

A: This is actually similar to your other question.  The difference is that the counting needs to start over again for each product_name.  So, here is one method:
SELECT PS.SECTION_NAME [Planning Group], PR.ROW_NAME as [Planning Row],
       P.PRODUCT_NAME [Style], (SD.START_DATE) as [Start dt],
       SUM(isChange) OVER (PARTITION BY product_name ORDER BY start_dt) as rank_
FROM (SELECT t.*,
             (CASE WHEN lag(row) over (order by start_dt) = row
                   THEN 0
                   ELSE 1
              END) as IsChange
      FROM tables_ t
     ) t
Order by PS.SECTION_NAME, PR.ROW_NAME, SD.START_DATE;

Note:  in this question as in the previous one, I don't understand the role of SECTION_NAME and ROW_NAME.  This version ignores these columns.  If you want the query to restart the numbering in each group, then include them in the partition by statement.

A: Needed to correct the ordering in the partition by.
SELECT
SECTION_NAME ,
ROW_NAME,
PRODUCT_NAME [Style],
(START_DATE) ,
SUM(isChange) OVER (PARTITION BY ROW_NAME,product_name ORDER BY START_DATE) as rank_
,IsChange
FROM (SELECT SECTION_NAME,
        ROW_NAME,
        PRODUCT_NAME,
        sd.START_DATE,
         (CASE WHEN lag(product_name ) over (order by SECTION_NAME, ROW_NAME, sd.START_DATE) = product_name
               THEN 0
               ELSE 1
          END) as IsChange

  FROM
    Table_ t
 ) t

Order by SECTION_NAME, ROW_NAME, START_DATE;


text:
Q: what does "Encountered:  after : "" " mean using pig I am a beginner on Hadoop and Pig. I examined the example proved in cloudera virtual image, and modefied it to count Top 5 frequent words:
Lines = LOAD '/user/hue/pig/examples/data/midsummer.txt' as (line:CHARARRAY);
Words = FOREACH Lines GENERATE FLATTEN(TOKENIZE(line)) AS word;
Groups = GROUP Words BY word;
Counts = FOREACH Groups GENERATE group, COUNT(Words);
Results = ORDER Words BY Counts DESC;
Top5 = LIMIT Results 5;
STORE Top5 INTO /user/hue/pig/examples/data/summertop5Hi

However, when I run this script, I got this message error:
ERROR org.apache.pig.tools.grunt.Grunt  - ERROR 1000: Error during parsing. Lexical error at line 8, column 0.  Encountered: <EOF> after : ""

What does it mean?

A: You need to fix three issues in your code to make it work.
 1.STORE stmt is not properly ended with semicolon.
    2.STORE stmt output file is not properly enclosed with single quotes.
    3. Need slight modification in Counts and Results stmt logic.
Modified Script:
Lines = LOAD '/user/hue/pig/examples/data/midsummer.txt' as (line:CHARARRAY);
Words = FOREACH Lines GENERATE FLATTEN(TOKENIZE(line)) AS word;
Groups = GROUP Words BY word;
Counts = FOREACH Groups GENERATE group, COUNT(Words) AS cnt;
Results = ORDER  Counts BY cnt DESC;
Top5 = LIMIT Results 5;
STORE Top5 INTO '/user/hue/pig/examples/data/summertop5';

If you face any issues in the script, let me know.


text:
Q: Como ordenar um array por dois indices diferentes? Olá a todos recentemente escrevi esse código, onde ele vai mostrar a lista de alunos na array por order decrescente de score e no fim mostra o top 3. Este é o código:
<?php

$Turma = array(

array("nome" => "Diogo", "score" => "100", "time" => "6" ),
array("nome" => "Joao","score" => "500", "time" => "3" ),
array("nome" => "Miguel", "score" => "125", "score" => "8" ),
array("nome" => "Daniela", "score" => "105", "time" => "7" ),
array("nome" => "Joana", "score" => "100", "time" => "6" ),
array("nome" => "Diogo", "score" => "275", "time" => "4" ),
array("nome" => "Francisco", "score" => "300", "time" => "9" ),
array("nome" => "Ines", "score" => "650", "time" => "2" ),
array("nome" => "Dionisio", "score" => "101", "score" => "10" ),
array("nome" => "Ricardo", "score" => "200", "score" => "8" ),
array("nome" => "Fabio", "score" => "201", "score" => "11" ),
array("nome" => "Tiago","score" => "50", "score" => "13" ),
array("nome" => "Carolina", "score" => "150", "time" => "5" ),
array("nome" => "Rui", "score" => "130", "time" => "3" ),
array("nome" => "Luisa", "score" => "1000", "time" => "1" ),

);

 usort($Turma, function($a,$b){
    return $b["score"] - $a["score"];

});

 foreach($Turma as $key => $value) {

    $position = $key + 1;

    echo "{$position}: {$value['nome']} : {$value['score']}
";

}

echo "
";
echo "WINNERS!!
 ";

foreach($Turma as $key => $value) {

    $position = $key + 1;

    if ($position < 4) {
        echo "{$position}: {$value['nome']} : {$value['score']}
";
    }

}

Agora é me pedido para ordernar os alunos caso haja empate de score o mais rápido ganha, gajo haja empate em tempo e score temos de ordenar alfabeticamente.

A: Primeiro detalhe é que seu arrayestá com alguns erros. Você duplicou a chave score aqui:
array("nome" => "Ricardo", "score" => "200", "score" => "8" ),

Segundo detalhe é que, pra fazer essa comparação, como foi dito, pode usar a função strcmp ou strcasecmp, porém eu preferi utilizar uma abordagem nova, introduzida nas versões mais novas do php: O spaceship operator.
usort($Turma, function ($a, $b) {

    $resultado = $b['score'] <=> $a['score'];

    return $resultado === 0 ? $b['time'] <=> $b['time'] : $resultado;
});

O operador <=> vai comparar os valores, podendo retornar -1, 0 ou 1. Quando retorna 0, é porque os valores são iguais. Então, utilizei uma condição ternária para que, quando for igual a 0, a comparação se der pela coluna time.
Versão corrigida do seu array
$Turma = array(

array("nome" => "Diogo", "score" => "100", "time" => "6" ),
array("nome" => "Joao","score" => "500", "time" => "3" ),
array("nome" => "Miguel", "score" => "125", "time" => "8" ),
array("nome" => "Daniela", "score" => "105", "time" => "7" ),
array("nome" => "Joana", "score" => "100", "time" => "6" ),
array("nome" => "Diogo", "score" => "275", "time" => "4" ),
array("nome" => "Francisco", "score" => "300", "time" => "9" ),
array("nome" => "Ines", "score" => "650", "time" => "2" ),
array("nome" => "Dionisio", "score" => "101", "time" => "10" ),
array("nome" => "Ricardo", "score" => "200", "time" => "8" ),
array("nome" => "Fabio", "score" => "201", "time" => "11" ),
array("nome" => "Tiago","score" => "50", "time" => "13" ),
array("nome" => "Carolina", "score" => "150", "time" => "5" ),
array("nome" => "Rui", "score" => "130", "time" => "3" ),
array("nome" => "Luisa", "score" => "1000", "time" => "1" ),

);

Teste no ideone

*

*https://ideone.com/O0lFYc


text:
Q: how can I prevent javascript from evaluating function parameters I'm a javascript noob taking a crack at making minesweeper. I am passing HTML element ID strings to a function. The strings have the format row hyphen column. So the top left cell would be 1-1. My function is evaluating these strings as if they were expressions. So...
function notMine(id){
alert(id) //If the incoming id=4-4, this pops up 0. I want it to pop up 4-4

How can I fix this?

A: The expressions are evaluated before the function is called, as they are not strings. Use apostrophes or quotation marks to make it a string:
notMine("4-4");

or
notMine('4-4');

A: When you pass the parameter in, use quotes:
Cheers.
<script type="text/javascript">
    feedMe( 4 + 4 );
    feedMe( "4 + 4" );

    function feedMe( id )
    {
        alert(id);
    }
</script>


text:
Q: How to assign local machines into Mikrotik Router? I have a Dedicated Server and installed a VMWare-Esxi as main OS on it.
Then, I added 4 VMs on VMWare-Esxi :
VM1 - Windows Server 2008 - Local IP  192.168.100.10
VM2 - Windows Server 2008 - Local IP  192.168.100.11
VM3 - Windows Server 2008 - Local IP  192.168.100.12
VM4 - Mikrotik Router 6.6 - Public IP 149.252.96.29   // definitely it's not my real IP :)

What I want to do?
I want to implement port forwarding on Mikrotik Router to Local VMs like so :

149.252.96.29:1573  == forward to => 192.168.100.10:3389
149.252.96.29:1574  == forward to => 192.168.100.11:3389
149.252.96.29:1575  == forward to => 192.168.100.12:3389

The main question :
The main question is that I don't know how to add the VMs with local IP to the Mikrotik Router?
Any helps would be great appreciated.

A: You have to use Dnat action on nat tab of firewall like this:
/ip firewall nat add chain=dstnat  dst-address=149.252.96.29 protocol=tcp dst-port=1573 action=dst-nat to-addresses=192.168.100.10 to-ports=3389
/ip firewall nat add chain=dstnat  dst-address=149.252.96.29 protocol=tcp dst-port=1574 action=dst-nat to-addresses=192.168.100.11 to-ports=3389
/ip firewall nat add chain=dstnat  dst-address=149.252.96.29 protocol=tcp dst-port=1575 action=dst-nat to-addresses=192.168.100.12 to-ports=3389

Ofcourse you should have an IP address in range of 192.168.100.x on the mikrotik to be able to contact with servers.

-

And possibly if you have some Deny rules on mikrotik Firewall here is
  the code to allow these connection to pass through:

/ip firewall filter add place-before=0 chain=forward protocol=tcp dst-port=3389 action=accept


text:
Q: Finder hiding items under a grey box in list view In Mojave, when I open a finder window, I don't see all the requested columns displayed.
For example, the finder should open for the desktop and look like this:

However, I see this:

Which looks like a window within the finder window is not wide enough to display my columns.
So, I resize the window and columns.
I delete all the .DS_Store files on my Mac.
I save the new finder window setting as the default.
Then when I open a new finder window, I have the same problem.
How do I remove this overlay ?

A: Go in Finder to View and select "Hide Preview"

A: Turns out it was just the preview pane which I had forgotten about.
I wasn't expecting this to be available in list mode; so I wasn't expecting it to cover anything there.


text:
Q: Using hardlink to .git instead of git worktree There is a known bug in Eclipse which prevents it from working with git worktree.
The only practical work-around I can think of is creating .git hardlink from secondary (branch) working copy to the primary one containing the real .git folder.
What might be the negative consequences of such a work-around (on Windows platform)?

A: You probably don't want to do this.  A worktree includes its own version of HEAD, the HEAD reflog, and the index.  This is required because you have two separate branches checked out and you can stage files in each worktree independent of the other one.
If you hardlinked .git into another directory, you'll actually have the same HEAD, so you'll be on the same branch.  Also, you'll have the same index, so as soon as you run git status in one directory, running it in the other directory will cause every file to be re-read.  That's in addition to the fact that if you run git add in one directory, it will be reflected in the other as well.
As a result, this is likely to lead to a bunch of unhappiness and possibly some repository corruption.  If you want to continue to use Eclipse, use separate clones, or you can use a different editor if you want to use worktrees.


text:
Q: Connection Failure to remote server I have a sample app and when I deploy it on the Localhost MobileFirst Server, it successfully connects to the wlapp. When I try to connect the wlapp on my remote server, it fails. After checking the logs, I found out that the URL "https://MyServerIp:Port/MyContextRoot/authorization/vl/clients/instance" is incorrect according to the URL I usually hit. I have been trying to search that where this URL generates so that I could modify it according to my need. I have highlighted the part of the URL which is incorrect.

A: In https://MyServerIp:Port/MyContextRoot/authorization/vl/clients/instance, the "authorization/vl/clients/instance" part is a constant and you need not change it. However the first part of the "myServerIp" and "Port" is something you need to once moving to a remote server.
To change it, you need to build the application with the correct values. See the instructions in the following user documentation topic on Build Settings and Deploy Target: http://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.1.0/com.ibm.worklight.dev.doc/dev/c_building_and_deploying_build_settings_deploy_target.html?lang=en


text:
Q: Calculated field based on values in other columns I have a new SP 2013 List that I would like to add a new field with a calculated 'score' based on the values of a few other columns.
For example,
The Choices for Col1, Col2, Col3 and Col4 are all High, Med or Low.
If High = 3, Med = 2 and Low =1, I would like to have a score field which is a sum of each Col1-4.
I am new to calculated formulas in SP, so would appreciate any help or reference.
Thanks,
Bob

A: You can simply use below formula in calculated field.
=SUM(
       if([Col1]="High",3, if([Col1]="Med",2, if([Col1]="Low",1,0)))
     , if([Col2]="High",3, if([Col2]="Med",2, if([Col2]="Low",1,0)))
     , if([Col3]="High",3, if([Col3]="Med",2, if([Col3]="Low",1,0)))
     , if([Col4]="High",3, if([Col4]="Med",2, if([Col4]="Low",1,0)))
    )

Please let me know it works or not.


text:
Q: How to calculate duty cycle of a servo motor? I have this servo motor and in its specifications only speed and torque is given:
Torque At 4.8V  3.5 kg-cm / 49 oz-in
Torque At 6.0V  4.4 kg-cm / 61 oz-in
Speed At 4.8V   0.25 sec / 60°
Speed At 6.0V   0.22 sec / 60°

How to determine frequency and duty cycle of this motor? I am connecting this motor to 5V pin of a microcontroller.

A: Speed At 4.8V   0.25 sec / 60°
Speed At 6.0V   0.22 sec / 60°

At 4.8V if it takes 0.25sec for a 60 degrees shift then for a full shift (360 degrees) we will need 6*0.25 = 1.5s which is the period of the shift.
f = 1/T = 1/1.25 = 0.8Hz
The same way for 6.0V
We don't have enough info for the duty cycle of the motor.


text:
Q: How to color certain token from custom language? I create custom langauge abc, from tutorial https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide, hence my files contains:
package.json:
{
    "contributes": {
        "languages": [
            {
                "id": "abc",
                "extensions": [".abc"]
            }
        ],
        "grammars": [
            {
                "language": "abc",
                "scopeName": "source.abc",
                "path": "./syntaxes/abc.tmGrammar.json"
            }
        ]
    }
}

abc.tmGrammar.json:
{
    "scopeName": "source.abc",
    "patterns": [{ "include": "#expression" }],
    "repository": {
        "expression": {
            "patterns": [{ "include": "#letter" }, { "include": "#paren-expression" }]
        },
        "letter": {
            "match": "a|b|c",
            "name": "keyword.letter"
        },
        "paren-expression": {
            "begin": "\\(",
            "end": "\\)",
            "beginCaptures": {
                "0": { "name": "punctuation.paren.open" }
            },
            "endCaptures": {
                "0": { "name": "punctuation.paren.close" }
            },
            "name": "expression.group",
            "patterns": [{ "include": "#expression" }]
        }
    }
}

And this works, because when I open VSC I can see and can pick abc language. Now how to color expression.group token to #ff0000? Where define color for it? In package.json in colors contribution point?

A: You can only set your own theme styling, or set color in user setting.
https://github.com/microsoft/vscode/issues/66729
you can see the scope in command developer inspect editor tokens and scopes

"editor.tokenColorCustomizations": {
    "textMateRules": [
        // JavaScript
        {
            "scope": "source.js keyword",
            "settings": {
                "foreground": "#FF0000"
            }
        },
        // TypeScript
        {
            "scope": "source.ts keyword",
            "settings": {
                "foreground": "#0000ff"
            }
        },
    ]
}


text:
Q: How to get response from div which is having link in another div I am really tired for searching this can someone help me... help will be really appreciate.
My question is Suppose I have one div element eg.

and I have some links in that div so my code will something like:

 Example1

  Example2

and I have another div element which is

and I Now what i want, when i will click the link in first div eg. Example1.. I want the response of that link into div no 2 . IE on the another div which is

A: This is provided in html, for instance

  Example1

  Example2

Then in your reference div ensure you have given it the referring id, for instance

When you click on first link it should bring up the div with the id requested. Of course styling effects such as z-index can be added.

A: To be frank, you question is not understandable, However I am relating "Response" to "HTML" and "Link" to "Element".
So, Onclick of demo the content of demo will be moved to demo2.
Use JQUERY,

$(".demo").on("click", function(e){
    $(".demo2").html($(this).html());
});


text:
Q: A little bit stuck with MVC pattern on Swift So I am really trying to understand MVC. I have migrated my app into an MVC(ish) architecture but i still know I have made some mistakes. The most confusing part for me is the communication between view and the controller part. I have defined all my Outlets,Actions(Text Fields, Image Views, button actions) in my controller(UIViewController) class and all the initial stuff like property widths, heights are in my view. Today I saw a post with MVC and M-VC(Massive View Controller). Now I am more confused.
What I want is one single example for my code. Where should I move the outlets and other stuff, and how do I establish a communication between my view and the controller.
Here is my view for a screen:
class incidentMgmView: UIView, UIPickerViewDataSource {
    var textHeightConstraint: NSLayoutConstraint!
    var datePicker: UIDatePicker?
    let namePickr = UIPickerView()
    var pickerData = namePicker()

    // Auto Resizing Text Field Functions
    func autoResizeTextView(textView: UITextView){
        textView.clipsToBounds = true
        textView.layer.cornerRadius = 5
        textHeightConstraint = textView.heightAnchor.constraint(equalToConstant: 40)
        textHeightConstraint.isActive = true
        adjustTextViewHeight(txtView: textView)
    }

    func adjustTextViewHeight(txtView: UITextView) {
        let fixedWidth = txtView.frame.size.width
        let newSize = txtView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
        textHeightConstraint.constant = newSize.height
    }

    // Exit editing if a touch is registered.
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        endEditing(true)
    }

    // Date Picker View
    func datePick(dateTextField: UITextField){
        datePicker = UIDatePicker()
        datePicker?.datePickerMode = .date
        datePicker?.addTarget(incidentMgm(), action: #selector(incidentMgm.dateChanged(datePicker:)), for: .valueChanged)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewTapped(gestureRecognizer:)))
        addGestureRecognizer(tapGesture)
        dateTextField.inputView = datePicker
        let pickerToolBar = toolBarPicker().ToolbarPicker(mySelect: #selector(incidentMgm.dismissDatePicker))
        dateTextField.inputAccessoryView = pickerToolBar
    }

    // Exit editing if a touch is registered.
    @objc func viewTapped(gestureRecognizer: UITapGestureRecognizer){
        endEditing(true)
    }

    // Picker View
    func namePick(pickerTextField: UITextField){
        pickerTextField.inputView = namePickr
        namePickr.dataSource = self
        let toolBar = toolBarPicker().ToolbarPicker(mySelect: #selector(incidentMgm.dismissPersonPicker))
        pickerTextField.inputAccessoryView = toolBar
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView( _ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.contentSize
    }

And here is the controller of this view:
class incidentMgm: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UITextFieldDelegate, UIPickerViewDelegate,UITextViewDelegate {

    // Outlets
    @IBOutlet weak var neredeTextField: UITextField!
    @IBOutlet weak var aTextField: UITextField!
    @IBOutlet weak var hangiTextField: UITextField!
    @IBOutlet weak var neTextField: UITextField!
    @IBOutlet weak var myTextView: UITextView!
    @IBOutlet weak var dateTxtField: UITextField!
    @IBOutlet weak var imageView3: UIImageView!
    @IBOutlet weak var imageView2: UIImageView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var nameTextField: UITextField!
    //
    var views = incidentMgmView() // View Class
    let imagePicker = UIImagePickerController()
    var imagepos = 0
    var camimg = UIImage.init(named: "camicon")
    var imgArray = [UIImageView]()
    override func viewDidLoad() {
        super.viewDidLoad()
        initialize()
        views.namePick(pickerTextField: nameTextField)
        views.datePick(dateTextField: dateTxtField)
        views.autoResizeTextView(textView: myTextView)
        imgTap()
    }
    //  Assinging tags and delegates
    func initialize(){
        neTextField.delegate = self
        dateTxtField.delegate = self
        neredeTextField.delegate = self
        hangiTextField.delegate = self
        aTextField.delegate = self
        imagePicker.delegate = self
        myTextView.delegate = self
        views.namePickr.delegate = self
        //  Image stuff
        imgArray.append(imageView)
        imgArray.append(imageView2)
        imgArray.append(imageView3)
        for i in 0...2{
            imgArray[i].image = camimg
            imgArray[i].tag = i
        }
    }
    //  Image Picker Controller Functions
    func imgTap(){
        var tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
        for imgView in imgArray{
            imgView.isUserInteractionEnabled = true
            imgView.addGestureRecognizer(tapGestureRecognizer)
            tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
        }
    }

    @objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
    {
        _ = tapGestureRecognizer.view as! UIImageView
        imagePicker.sourceType = .camera
        imagePicker.allowsEditing = false
        present(imagePicker, animated: true, completion: nil)
        imagepos = tapGestureRecognizer.view!.tag
    }

    @objc func imagePickerController(_ picker:UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
            for imgView in imgArray {
                if(imagepos == imgView.tag){
                    imgView.image = image
                    imagePicker.dismiss(animated: true, completion: nil)
                }
            }
        }
    }

    // Skip to the next text field with return button
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        switch textField{
        case neTextField:
            dateTxtField.becomeFirstResponder()
            break
        case dateTxtField:
            neredeTextField.becomeFirstResponder()
            break
        case neredeTextField:
            nameTextField.becomeFirstResponder()
            break
        case hangiTextField:
            myTextView.becomeFirstResponder()
            break
        case myTextView:
            aTextField.becomeFirstResponder()
            break
        default:
            textField.resignFirstResponder()
            break
        }
        return true
    }

    @objc func dismissPersonPicker(textField: UITextField){
        hangiTextField.becomeFirstResponder()
    }

    @objc func dismissDatePicker(textField: UITextField) {
        neredeTextField.becomeFirstResponder()
    }

    @objc func dateChanged(datePicker: UIDatePicker){
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd/MM/yyyy"
        dateTxtField.text = dateFormatter.string(from: datePicker.date)
    }

    internal func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        nameTextField.text = views.pickerData.pickerContent[row]
    }

    func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return views.pickerData.pickerContent[row]
    }

    func textViewDidChange(_ textView: UITextView) {
        views.adjustTextViewHeight(txtView: myTextView)
    }
}

What this view does is it submits a form with text and images in it to my service.
I would be really happy if i had one example to define the MVC pattern for me.
I tried reading lots of forum posts and Apple's MVC documentation, but that didn't help me at all.
Thanks...

A: I highly recommended you to use MVVM for you application design pattern. There is a great amount of information about it online. Sample Below. On the other hand, I can not recommend you to use Viper, because about this design pattern there is not so much detailed info online. In addition to this, Viper is a good architecture for enourmous projects.


text:
Q: Nginx redirect if 404 and request contain certin words I need to redirect if the page doesn't exist ( 404)
redirect must be smart
if URL contains word "test" redirect 301 to a new_page, else throw 404
# define error page
error_page 404 = @notfound;

# error page location redirect 302
location @notfound {

   if ($request_uri = "test"){
        return 301 /new_page ;
    }

}

A: Try this:
map $request_uri $error404 {
    ~test    error404_redirect;
    default  error404_notfound;
}

server {
    ...
    error_page 404 = @$error404;
    location @error404_notfound {
        return 404;
    }
    location @error404_redirect {
        return 301 /new_page;
    }
}


text:
Q: How to flatten a multilevel xml into List in java? the objective is to flatten a multilevel repeated xml into xpaths at a leaf level ; so that we can store it in a Key-Value store and retrieve it . The assumption is that every repeating node will have a UID.

*

*generate a list of  pairs where the Key is a "XPATH" and Values are the actual value of that leaf

*Should be able to assemble it back into an xml

*the xml is backed by an xsd ( is there a JAXB solution )

Edited and replaced the previous xml with a simpler one.
a sample xml looks like below
<?xml version="1.0" encoding="UTF-8"?>
<cars>
    <car uid="WxiMr123">
        <carDoor uid="WRP2">
            <location uid="loc-1">
                <width uom="ft">2</width>
                <height uom="ft">3</height>
            </location>
            <location uid="loc-2">
                <width uom="m">5</width>
                <height uom="m">7</height>
            </location>
        </carDoor>
        <commonData>
            <timeCreated>2001-04-30T08:15:00.000Z</timeCreated>
        </commonData>
    </car>
</cars>

The xpath K,V pairs I'm looking at should look like
/cars/car[@uid="WxiMr123"]@uid , "WxiMr123"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]@uid, "WRP2"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-1"]@uid, "loc-1"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-1"]/width[@uom="ft"]@uom, "ft"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-1"]/width[@uom="ft"]/text(), "2"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-1"]/height[@uom="ft"]@uom, "ft"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-1"]/height[@uom="ft"]/text(), "3"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-2"]@uid, "loc-2"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-2"]/width[@uom="m"]@uom, "m"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-2"]/width[@uom="m"]/text(), "5"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-2"]/height[@uom="m"]@uom, "m"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-2"]/height[@uom="m"]/text(), "7"
/cars/car[@uid="WxiMr123"]/commonData/timeCreated/text(), "2001-04-30T08:15:00.000Z"

Any help is highly appreciated.

A: Producing the required document is not that difficult. For example, the following stylesheet:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/">
    <xsl:for-each select="//text() | //@*[string()]">
        <xsl:for-each select="ancestor::*">
            <xsl:value-of select="concat('/', name())" />
                <xsl:for-each select="@*">
                    <xsl:value-of select="concat('[@', name(), '="', ., '"]')" />
                </xsl:for-each>
        </xsl:for-each>
        <xsl:choose>
            <xsl:when test="name()">
                <xsl:value-of select="concat('/@', name())" />
            </xsl:when>
            <xsl:otherwise>/text()</xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select="concat(', "', ., '"
')" />
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

when applied to your example input, will produce the following result:
/cars/car[@uid="WxiMr123"]/@uid, "WxiMr123"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/@uid, "WRP2"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-1"]/@uid, "loc-1"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-1"]/width[@uom="ft"]/@uom, "ft"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-1"]/width[@uom="ft"]/text(), "2"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-1"]/height[@uom="ft"]/@uom, "ft"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-1"]/height[@uom="ft"]/text(), "3"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-2"]/@uid, "loc-2"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-2"]/width[@uom="m"]/@uom, "m"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-2"]/width[@uom="m"]/text(), "5"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-2"]/height[@uom="m"]/@uom, "m"
/cars/car[@uid="WxiMr123"]/carDoor[@uid="WRP2"]/location[@uid="loc-2"]/height[@uom="m"]/text(), "7"
/cars/car[@uid="WxiMr123"]/commonData/timeCreated/text(), "2001-04-30T08:15:00.000Z"

Note:

*

*This may not be the most efficient method; with large XMl documents it might be better to apply template/s to traverse the entire tree recursively;

*Elements may have multiple attributes; your example does not show how to handle these when building the paths;

*Elements may be in namespaces; your example does not show how to handle these;

*Empty nodes are excluded; if you try to reconstruct the original XML document from the result of this transformation (not that I have any idea how one would go about that), these nodes will be missing.


text:
Q: Search Macro gives error stating, "You can't use Find or Replace" when search is used and focus is lost before search is complete Using macro button in form to search database. My database is quite large, so that can take 10-20 seconds depending on how good my VPN connection is. I frequently use a few programs together and switch between windows. If I initiate a search, then change focus to another program, Access will give me an error when it regains focus. Is there any way to suppress this? It's quite annoying and not at all helpful. I inherited this database and I don't have a lot of experience using macros. Googling has not been helpful.
Here is the code for the macro:
OnError
       Go to   Next
    Macro Name

GoToControl
    Control Name =[Screen].[PreviousControl].[Name]

Clear MacroError

RunMenuCommand
      Command   Find

If   [MacroError]<>0   Then
      MessageBox
            Message =[MacroError].[Description]
               Beep   Yes
               Type   None
               Title
End If

EDIT: In place of the screenshot here is the error dialogue:

You can't use Find or Replace now.
The fields are not searchable due to one of the following:
*The fields are controls (such as buttons or OLE objects).
*The fields have no data.
*There are no fields to search.

TYIA


text:
Q: Weibull distriution. Problem with paramets and qqPlot I have 10 years worth of mean wind speed meteorological data (timely 10-minutes data). I want to compare the observed wind speed data against a Weibull distribution on a graph of the probability density distribution. I used function in R:fitdistr(). But the Weibull paramets, which gave me this function is probably wrong? Because when I made qqPlot with this paramets, I had something like this:

Help me please and tell me, what I have been wrong? What should I do?

A:
I want to find the percentiles [0,9; 0,95; 0,999]

You don't need to fit this using a Weibull-distribution. Given $N$ observation, sort the vector of observations and take the 1st, the  $N0.9$th,$N0.95$th, etc
Also as @glen_b noted, you need to add more bins to the histogram before even considering if your visual inspection has any merit


text:
Q: Ethernet NIC architecture: Function of loopback circuit
(source: flylib.com)
I want to make sure my understanding of the function/the needs of loopback to detect collision is correct.

*

*There is frame to transmit from Ethernet controller.

*TX transmits to wire, loopback and collision detector.

*RX receives from wire and loopback.

*RX transmits to collision detector and Ethernet controller.

*Collision detector compares whether the voltage it receives from TX and RX is same or not.

Is this correct?

A: *

*The SW 127.0.0.1 loopback tests the network stack but not the NIC.

*The NIC loopback tests the network stack and the NIC card.

*Cable loopback tests the network stack, the NIC and the connectors.

For the NIC card the loop back is a "mode" of operation, A properly designed NIC would deal with the collision detection appropriately, in full duplex, half duplex etc. situations.
I Think that your second item, "TX transmits to ..." is not right.  I'd say that in loop back the TX transmits only to the RX channel and NOT to the connector/wire as that would defeat the intent of loopback testing.  Likewise for your third item, the RX in loopback would only receive from the TX and not the wire also.


text:
Q: Laravel Login User Conditional Not Working I am currently starting a new project and using a SSO with my laravel site and Flarum (forums made with laravel). The developer of the extension provided a sample script to use but I am not sure why this conditional is not working. This will run after the username and password or submitted for the login.
$users = [
    'user' => [
        'password' => 'password',
        'email' => 'user@example.com',
    ],
    'admin' => [
        'password' => 'password',
        'email' => 'user1@example.com',
    ],
];

// Get username and password
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';

if (!empty(Arr::get($users, $username)) && Arr::get($users, "$username.password") === $password) {

// login script goes here ..

} elseif (!empty($username) || !empty($password)) {
    $success = false;
}

This always fails and the arrays when dumped are NULL. Any suggestions or ideas on a better way of putting this?


text:
Q: Adding a right click / context menu to listbox items in C# I have a ListBox, and its populated with items, id like to know how to:

*

*when you rightclick in the listbox, that the rightclicked item will be selected,

*a rightclick menu will be displayed with several items..

*when you click on any of the items, a corresponding void will be triggered..

thanks in advance for any help, and code examples please!

A: This feels to me like a "homework" question, so I am going to answer by (I hope) giving you just a few pointers to solving this for yourself.
Phase One

*

*create a sample project with a ListBox

*define event handlers for MouseClick, MouseDown, and Click events.

*put a Console.WriteLine("some appropriate text"); statement in each of those handlers so you can look in the Output Window in Visual Studio and see which event handler was called.

...
Phase Two

*run the test program and observe the difference between what events are reported for a left mouse down and a right-mouse down (assuming your environment has the context click set to the right mouse down ... which may not be true for everyone).

*focus on the one event you can intercept with a context-click.

*add a context menu to the test project and set that context menu to be the context menu of the ListBox.

*verify that you can now right click on an item in the ListBox and that the context menu will appear, BUT THE EVENT IS STILL HANDLED BY THE HANDLER YOU "DISCOVERED" IN STEP 2.

*now go through all the Event handlers for ListBox, and figure out which one could be used to detect, given a certain location in the ListBox, which List Item was "hit."

*once you can determine which List Item was right-clicked on, and you know your context menu is working, you have only the problem of making sure that the right-clicked List Item is selected : and that's pretty easy.
Figuring this out yourself will teach you several very useful things you'll be able to use later in programming to other controls.
best of luck, Bill

A: First, you need to subscribe to ListBox.MouseClick event. You will be able do determine what button was pressed and cursor coordinates. Then, use ListBox.IndexFromPoint method to find clicked item. You can select it using ListBox.SelectedIndex property. To display context menu use ContextMenu or ContextMenuStrip classes. Additional documentation on context menu is available in MSDN

A: 1.when you right click in the listbox, that the right clicked item will be selected
2.a right click menu will be displayed with several items..
private void listBoxNode_MouseUp(object sender, MouseEventArgs e)
    {
        int location = listBoxNode.IndexFromPoint(e.Location);
        if (e.Button == MouseButtons.Right)
        {
            listBoxNode.SelectedIndex = location;                //Index selected
            contextMenuStrip1.Show(PointToScreen(e.Location));   //Show Menu
        }
    }

3.when you click on any of the items, a corresponding void will be triggered..
private void showDetailsToolStripMenuItem_Click(object sender, EventArgs e)
        {
              //put your code here after clicking
              //on items in context menu
        }


text:
Q: Параллакс эффект для шапки сайта Как мне по мере прокрутки страницы сделать так, чтобы полукруг, в котором находится изображение, выпрямлялся?

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.intro {
  position: relative;
  height: auto;
}

.intro img {
  display: block;
  position: relative;
  width: 100%;
  height: auto;
  z-index: 1;
}

.intro .caption {
  position: absolute;
  bottom: 25%;
  left: 0;
  width: 100%;
  z-index: 3;
  text-align: center;
  color: black;
}

.intro .caption h1 {
  display: inline-block;
  width: 70%;
  font-size: 5vw;
  font-weight: 100;
}

.intro .overlay {
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
}

.intro .overlay svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.text {
  width: 100%;
  height: 200vh;
}

Заголовок

<svg version="1.1" id="circle" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  viewBox="0 0 500 250" enable-background="new 0 0 500 250" xml:space="preserve" PreserveAspectRatio="none">
<path fill="#FFFFFF" d="M250,246.5c-97.85,0-186.344-40.044-250-104.633V250h500V141.867C436.344,206.456,347.85,246.5,250,246.5z"
 />
</svg>

A:

function inViewport($el) {
  var H = $(window).height(),
    r = $el[0].getBoundingClientRect(),
    t = r.top,
    b = r.bottom;
  return Math.max(0, t > 0 ? H - t : (b < H ? b : H));
}
$(window).on("scroll resize", function() {
  var window_offset = inViewport($('.intro'));
  $(".overlay").height(window_offset);
  $(".caption").css("bottom", (window_offset / 4));
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.intro {
  position: relative;
  height: auto;
  transform: translateZ(0);
}

.intro img {
  display: block;
  position: relative;
  width: 100%;
  height: auto;
  z-index: 1;
  mix-blend-mode: multiply;
}

.intro .caption {
  position: absolute;
  bottom: 25%;
  left: 0;
  width: 100%;
  z-index: 3;
  text-align: center;
  color: black;
}

.intro .caption h1 {
  display: inline-block;
  width: 70%;
  font-size: 5vw;
  font-weight: 100;
}

.intro .overlay {
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  pointer-events: none;
}

.intro .overlay svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.text {
  width: 100%;
  height: 200vh;
}

Заголовок

<svg version="1.1" id="circle" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  viewBox="0 0 500 250" enable-background="new 0 0 500 250" xml:space="preserve" PreserveAspectRatio="none">
<path fill="#FFFFFF" d="M250,246.5c-97.85,0-186.344-40.044-250-104.633V250h500V141.867C436.344,206.456,347.85,246.5,250,246.5z"
 />
</svg>


text:
Q: ruby on rails model creation error
i am new to ruby.
When i am creating the model it gives the following error. Please resolve this issue.
noexec.rb:75:in `block in setup': undefined method `name' for ["hike-1.2.3", #<Gem::Specification name=hike version=1.2.3>]:Array (NoMethodError)

from /home/rajesh/.rvm/gems/ruby-1.9.3-p484@global/gems/rubygems-bundler-1.4.2/lib/rubygems-bundler/noexec.rb:75:in `each'

from /home/rajesh/.rvm/gems/ruby-1.9.3-p484@global/gems/rubygems-bundler-1.4.2/lib/rubygems-bundler/noexec.rb:75:in `map'

from /home/rajesh/.rvm/gems/ruby-1.9.3-p484@global/gems/rubygems-bundler-1.4.2/lib/rubygems-bundler/noexec.rb:75:in `setup'

from /home/rajesh/.rvm/gems/ruby-1.9.3-p484@global/gems/rubygems-bundler-1.4.2/lib/rubygems-bundler/noexec.rb:114:in `check'

from /home/rajesh/.rvm/gems/ruby-1.9.3-p484@global/gems/rubygems-bundler-1.4.2/lib/rubygems-bundler/noexec.rb:121:in `<top (required)>'

from /home/rajesh/.rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:33:in `require'

from /home/rajesh/.rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:33:in `rescue in require'

from /home/rajesh/.rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:29:in `require'

from /home/rajesh/.rvm/gems/ruby-1.9.3-p484@global/gems/rubygems-bundler-1.4.2/lib/rubygems_executable_plugin.rb:4:in `block in <top (required)>'

from /home/rajesh/.rvm/gems/ruby-1.9.3-p484@global/gems/executable-hooks-1.3.1/lib/executable-hooks/hooks.rb:50:in `call'

from /home/rajesh/.rvm/gems/ruby-1.9.3-p484@global/gems/executable-hooks-1.3.1/lib/executable-hooks/hooks.rb:50:in `block in run'

from /home/rajesh/.rvm/gems/ruby-1.9.3-p484@global/gems/executable-hooks-1.3.1/lib/executable-hooks/hooks.rb:49:in `each'

from /home/rajesh/.rvm/gems/ruby-1.9.3-p484@global/gems/executable-hooks-1.3.1/lib/executable-hooks/hooks.rb:49:in `run'

from /home/rajesh/.rvm/gems/ruby-1.9.3-p484@global/bin/ruby_executable_hooks:10:in `<main>'

A: I'll assume you're using this https://github.com/sstephenson/hike
Remove it from your project and start again - if the model gets created then problem is in the hike gem,
then try different versions of the gem, see on https://github.com/sstephenson/hike if there's a similar reported issue


text:
Q: How to remove moving objects to obtain background only? I'm practically new to python and don't have much knowledge about it. I need help converting this pseudocode into Python which is written to obtain the background by removing moving objects in the images. In regards to the Pseudocode, I don't understand the Lines 3, 4 and 5 so maybe once its converted into Python, I can understand it better. In line 3 and 4, I don't understand what the & does and in the last line, I don't understand how is it even computing an image.
Any help will be appreciated.
The code is provided below:
Mat sequence[3];// the sequence of images to loop through
Mat output, x = 0, y = 0; // looping through the sequence
    matchTemplate(sequence[i], sequence[i+1], output, CV_TM_CCOEFF_NORMED)
    mask = 1 & (output>0.9) // get correlated part amongst the images
    x += sequence[i] & mask + sequence[i+1] & mask; // accumulate background infer
    y += 2*mask; // keep count
end of loop;
Mat bg = x.mul(1.0/y); // average background

Sample images to try are also provided below:
image1
image2
image3

A: I'm not very familiar with OpenCV, so I hope you'll excuse me if I don't provide a code snippet you can just copy and paste. But if I understand the pseudocode correctly, it is doing this:
sequence = list of images
x will hold sum of backgrounds
y will hold the number of frames use to build x

for each index i in sequence:
    c = matrix of correlation coefficients between (sequence[i], sequence[i+1]) from matchTemplate
    mask = pixels that are highly correlated (90%+)
    x += actual pixels from sequence[i] & mask and sequence[i+1] & mask that are considered background
    y += 2 for every pixel in mask

bg = average of background images x / number of frames y

So what's happening is, for every pair of images, it marks the pixels that are the same in both images. The assumption is that background doesn't change between adjacent frames and foreground does. Whether pixels are "the same" is judged on the basis of correlation being >90%. Then it takes all the marked pixels, and averages them.

A: As one of the commentors mentioned, the mean of the images does remove the foreground but the entire image becomes a little faded. Here is the code that does that:
import skimage.io as io
import numpy as np
import matplotlib.pyplot as plt

cim1 = io.imread('https://i.stack.imgur.com/P44wT.jpg')
cim2 = io.imread('https://i.stack.imgur.com/wU4Yt.jpg')
cim3 = io.imread('https://i.stack.imgur.com/yUbB6.jpg')

x,y,z = cim1.shape
newimage = np.copy(cim1)
for row in range(x-1):
    for col in range(y-1):
        r = np.mean([cim1[row][col][0],cim2[row][col][0],cim3[row][col][0]]).astype(int)
        g = np.mean([cim1[row][col][1],cim2[row][col][1],cim3[row][col][1]]).astype(int)
        b = np.mean([cim1[row][col][2],cim2[row][col][2],cim3[row][col][2]]).astype(int)
        newimage[row][col] = [r,g,b]

fix, ax = plt.subplots(figsize=(10,10))
ax.axis('off')
ax.imshow(newimage)

The output image I get from this:

A better approach to this problem is to find the median of the three images. The more images you have in the algorithm the better is the background. Here is a snippet I tried (just replacing mean with median). If you have more images you can get a much more accurate one.
x,y,z = cim1.shape
newimage = np.copy(cim1)
for row in range(x-1):
    for col in range(y-1):
        r = np.median([cim1[row][col][0],cim2[row][col][0],cim3[row][col][0]]).astype(int)
        g = np.median([cim1[row][col][1],cim2[row][col][1],cim3[row][col][1]]).astype(int)
        b = np.median([cim1[row][col][2],cim2[row][col][2],cim3[row][col][2]]).astype(int)
        newimage[row][col] = [r,g,b]

fix, ax = plt.subplots(figsize=(10,10))
ax.axis('off')
ax.imshow(newimage)

The final output:

If you had more images, you can completely remove the foreground. Hope you got the idea on which you can build upon.
My code assumes all your images are of the same dimensions. The solution will be a bit more complicated if you captured the images in different views. In that case you may have to use template matching algorithm (your pseudo code seems to be doing something similar) to extract the common canvas from your images.


text: Q: All-KNN (All-K-Nearest-Neighbors) in Cover Trees I think I know how to do K-Nearest-Neighbors using Cover Trees. (Incidentally: can anybody point me to a run-time complexity analysis of this?), BUT I am looking for all-kNN (that is: find the kNN of all points in the tree).


text:
Q: Why am I getting an 'Illegal parameter number' error, here? I have following text MWE:
\documentclass[12pt,a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage[color=red,opacity=0.1,contents={}]{background}
\usepackage{hyperref}
\usepackage{indentfirst}
\usepackage{caption}
\usepackage{listings}
\usepackage{tcolorbox}
\usepackage[slovene]{babel}
\usepackage{titlesec}

\setcounter{secnumdepth}{4}

\titleformat{\paragraph}
{\normalfont\normalsize\bfseries}{\theparagraph}{1em}{}
\titlespacing*{\paragraph}{0pt}{3.25ex plus 1ex minus .2ex}{1.5ex plus .2ex}

\author{Marko Frelih \\ Company name \\ \texttt{email}}
\title{Some manual}
\date{Ljubljana, Marec 2015}

\begin{document}
\maketitle
\thispagestyle{empty}
\pagebreak
\clearpage
\pagenumbering{arabic}

\AddEverypageHook{
  \ifnum\value{page}<1\relax
  \else
  \backgroundsetup{contents={ZAUPNO}}
  \fi
\BgMaterial
}

\subsection{Section with error}
Kot smo \v{z}e namignili v prej\v{s}njem poglavju, bo prva particija imela
datote\v{c}ni sistem \textit{FAT32}, druga \textit{ext4} ter tretja zopet \textit{FAT32}.
\textbf{OPOZORILO: \v{C}e je katerakoli particija priklopljena, jo moramo obvezno
odklopiti za ukazom:
\begin{lstlisting}[language=bash]
# sudo umount /dev/sdbx
\end{lstlisting}
, kjer je x \v{s}tevilka particije.}

\end{document}

If I try to compile this latex document, I get following errors:
! Illegal parameter number in definition of \reserved@a.
! Illegal parameter number in definition of \lst@insertargs.
! Illegal parameter number in definition of \lst@arg.
! Illegal parameter number in definition of \lst@arg.
! Illegal parameter number in definition of \lst@arg.
! Illegal parameter number in definition of \reserved@a.
! Illegal parameter number in definition of \lst@arg.
! Illegal parameter number in definition of \lst@arg.
! Illegal parameter number in definition of \lst@arg.

In document, all of this errors are detected in line 210, which is in our MWR line with text , kjer je x \v{s}tevilka particije.}. I've used \begin{lstlisting}[language=bash] and \end{lstlisting} before in document and there were no errors. What am I missing?!

A: You cannot have a lstlisting in the argument of \textbf.
In these cases use the \bfseries switch.
\documentclass[12pt,a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage[slovene]{babel}
\usepackage[color=red,opacity=0.1,contents={}]{background}
\usepackage{indentfirst}
\usepackage{caption}
\usepackage{listings}
\usepackage{tcolorbox}
\usepackage{titlesec}
\usepackage{hyperref}

\setcounter{secnumdepth}{4}

\titleformat{\paragraph}
{\normalfont\normalsize\bfseries}{\theparagraph}{1em}{}
\titlespacing*{\paragraph}{0pt}{3.25ex plus 1ex minus .2ex}{1.5ex plus .2ex}

\author{Marko Frelih \\ Company name \\ \texttt{email}}
\title{Some manual}
\date{Ljubljana, Marec 2015}

\begin{document}
\maketitle
\thispagestyle{empty}
\pagebreak
\clearpage
\pagenumbering{arabic}

\AddEverypageHook{
  \ifnum\value{page}<1\relax
  \else
  \backgroundsetup{contents={ZAUPNO}}
  \fi
\BgMaterial
}

\subsection{Section with error}
Kot smo \v{z}e namignili v prej\v{s}njem poglavju, bo prva particija imela
datote\v{c}ni sistem \textit{FAT32}, druga \textit{ext4} ter tretja zopet \textit{FAT32}.
{\bfseries OPOZORILO: \v{C}e je katerakoli particija priklopljena, jo moramo obvezno
odklopiti za ukazom:
\begin{lstlisting}[language=bash]
# sudo umount /dev/sdbx
\end{lstlisting}
, kjer je x \v{s}tevilka particije.}

\end{document}

As a side note, note the package loading order.
For further reading:

*

*Which packages should be loaded after hyperref instead of before?

*LaTeX package conflicts


text:
Q: How to recognize an Ajax update in a 3rd party iframe When the page loads it includes an 3rd party iframe (read: file uploader). I select a file, click the "start upload" button and once the upload is complete I get a "thank you - upload complete" message.

*

*There is no Ajax response (that I know of).

*The 3rd party does allow me to specify the message. I can also add ... to that message.
Once the upload is complete I need to update a hidden input with the upload_file_id which I know from the start. What I wanting to catch / use if the "upload complete" message / moment / event. But the dynamic-ness of the page is somewhat new to me and I could use some support.
Thanks in advance.

A: Unfortunately, you wont be able to access any useful properties of the iframe unless it is within the same host/domain as your code. This is a security feature implemented by all current/worthy browsers - called the same-origin or cross-domain policy.
The only options you have of detecting the changes in a third-party iframe are if the third-party code supports sending a message out to the surrounding frame. There are a few ways of doing this, but they need to support it. If they don't, there isn't much you can do. If it were me I would check the following:

*

*Read the third-party documentation, see if they support triggering any js messages or events

*See if the third-party system offers another way, beside iframe, to implement the same ability.

script tags?

With regard to the message you can add, have you tested to see if you can add any HTML tags to that message? It's unlikely, but if so, you could add your own script tag to communicate back to your frame, to trigger your own function (i.e. `window.iframeSuccess`) and tell you the event has occured...

The following code will only work - again - if both sides are of the same domain (the outer frame and the iframe). Otherwise it'll be blocked by the same-origin policy.
<script>
if( window && window.parent && window.parent.iframeSuccess ){
  window.parent.iframeSuccess();
}
</script>

Instead you could implement the following which has been designed precisely for the communication between frames. It's a more modern solution so wont work on older browsers - to see what supports it you could read here:
What browsers support the window.postMessage call now?
An example of how to use window.postMessage - first the code in the outer frame:
function messageListener(event){
  /// make sure we only get messages from where we expect
  if ( event.origin != "http://the-domain-we-expect-from.com" ){ return; }
  /// here you can do what you want depending on the message you get
  alert(event.data);
}

/// define for nearly every modern browser
if (window.addEventListener){
  addEventListener("message", messageListener, false);
} else {
  /// fallback for internet explorer
  attachEvent("onmessage", messageListener);
}

Then the code placed in the iframe:
if( window && window.parent && window.parent.postMessage ){
  window.parent.postMessage('success',
     'http://the-domain-we-are-sending-to.com');
}

for more information you can read here:
https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
image tag?
If they block script tags it's possible they may allow image tags. If this is the case you have a slightly trickier option available which is to embed an image that reports back to a server-side script, which can then flag the event in a database...
<img src="http://mysite.com/image-that-is-actually-a-script.php?id=user-id" />

however to get your javascript to notice this event you will need some sort of polling system that is constantly checking your server-side database from your js (via ajax or websockets) - and you will need to be able to uniquely identify the user on both sides (yours and the third-party) with an id of some sort. So this method is really only possible if the third-party system allows you to insert the user id (or some other unique user information) into the message shown to the user. This is pretty much a last fallback if you have no other option.