Can GET Requests Contain Hidden Data or Paramters?

Question: For my school, we have to do these "Advisory Lessons" that tell you about College, etc. After completing the lesson, I am wondering if I would be able to replicate the same process using a set of requests from a PHP script with cURL.
I went through the lesson again, this time with Firebug on and an HTTP Analyzer.
Much to my surprise, the only GET requests were sent out during the entire lesson.
In case your curious, here is what the "Lesson" window looks like. It's sort of powerpoint-type thing where you read the slide and then some slides have questions on them. At the end, there is a quiz and if you don't pass it, the lesson doesn't count.
My question is this: If I were to setup a PHP/cURL script that logged into my account, and then made every single one of those requests, would the lesson be counted as complete?
Now obviously it's impossible for you guys to know how their server works and such...
I guess what I am saying is, is there any hidden content or fields that you can pass through a GET request? It just doesn't seem like the lesson window is passing enough info to the server for it to know if the lesson was complete or not.
Thanks so much for any advice and tips on my project!
EDIT: Here is my official test run (please don't do it too many times):
As many of you hinted, it did not work....but I am still not completely sure why.
Comment: Why don't you just try it? Chances are it won't work because of cookies, but maybe it is as simple as that.
Comment: But I am storing cookies with cURL...
Answer: Like you say, we can't speak to the details of their server, but it is possible to do these kinds of things with GET requests only because servers can use cookies and store state (associated with these cookies) on the server.
This gives the appearance, probably, of passing extra hidden information to the server.
You can research cookies, and even that jsessionid thing that is appearing in their URLs.  That BTW tips you off that they are using at least some Java. :)
Comment: I can grab the jsessionid though and get that right, because it's in the source code on the homepage (after the login). Is having a cookiejar in cURL enough? And what do you mean, passing "hidden information to the server". Is there anyway to pick up on this info?
Answer: The lesson application may very well be storing data in a session or some other persistant data store server-side and using a token from your browser (usually a cookie or a GET parameter) to look up that data when needed.
Answer: Its a kinda complicated task. With only cURL you can't emulate execution of javascript code, AJAX requests etc
Comment: I know that, but does that matter? Javascript is only client side, except for the AJAX requests, but those AJAX requests are the things that the analyzer picks up. Those GET requests are from the AJAx.
Comment: you have to know what to send. curl just grab html as plain text and all you can do is parse it and send requests. curl can't do it
Comment: I still don't understand what you mean? If I have an HTTP analyzer on, then ANY contact between my lesson window and the server should be picked up, right?
Comment: picked up how? you said `I am wondering if I would be able to replicate the same process using a set of requests from a PHP script with cURL` and the answer is no. but maybe i do not understand something
Comment: What I am asking is this: Is it possible to communicate with a server without web-requests? Because the HTTP Analyzer should log every single request made from my computer to the server. The point isn't so much as to replicate the process as it is to trick the server into thinking that I have completed the lesson. If the only communication that my computer and the server has is those GET requests, can't I just replicate all of them with cURL?
Comment: with curl you can send only one GET/POST request and in response you'll get plain text with web-server's headers. then you should parse this text, find out places from where GET request being sent and send these requests one by one. if source code has embed js files like `` you need to download them using curl and parse it too to find out possible places from where AJAX requests can be sent.
Comment: Thanks for your help Alexander. Yes there .js files and I have bookmarked all the lines with functions that contain AJAX. I have even used Firebug on firefox to inject javascript and have it alert the URL whenever it makes a request. The picture in my original question is a list of all the ajax requests that are made.
Comment: I am thinking that, perhaps the server is checking for AJAX and therefore ignoring my PHP requests. http://davidwalsh.name/detect-ajax your thoughts?
Answer: I am not sure what you are trying to do. For one HTTP is stateless protocol meaning the server gets request and gives a response to that particular request (that might be GET, POST or whatever and might have some request parameters). Statefullness in system usage is usually achieved by server creating a session and setting up a cookie on client side to pass session id in later requests. Session id is used to recognize the client and track his session. Everything you send during request is plain text. What response you get most likely will depend on session state and will also be a plain text. There is nothing hidden on a client side about client side. You just don't get to know what information server keeps in session and how requests are processed based on that and information you give during requests.
Comment: so if I replicate the reqests exactly, with the same cookies, shouldn't the server handle the cURL the same way it handled me actually taking the lesson?
Comment: It does not matter what the client is, just the information sent (requests) to the server ...and probably the sequence of those requests.


Objective C: Properties Not Found In Forward Declaration Vs Parse Issue: Expected A Type

Question: I have a singleton class called DataManager.  This class is used by several other classes to deal with loading and saving plist files.
I am adding the ability for DataManager to save screenshots as well as plist files. This requires me to load the view I wish to take a screenshot of.  The view I'm loading comes from a controller that imports DataManager.
Obviously this is circular dependency, so I used:
@class GardenView;

However, this resulted in the following errors:

Receiver 'GardenView' for class message is a forward declaration
Receiver type 'GardenView' for instance message is a forward
declaration  Property 'bounds' cannot be found in forward class
object 'GardenView'  Property 'layer' cannot be found in forward
class object 'GardenView'

This seems like it can't find properties inherited from the UIView superclass.  Is this true of forward class declarations?
If I use the standard #import instead of @class, I get:

Parse Issue: Expected A Type

for the methods in GardenView referencing Plant (which I am importing just fine):
- (void) addPlantToView: (Plant*) plant;
- (void) addPlantToGarden: (Plant*) plant;
- (void) addPlantToViewAndGarden: (Plant*) plant;

The Plant class DOES import the DataManager, but if I change it to @class, I get:

No known class method for selector 'sharedDataManager'

What is the solution for this problem?  The class method is there in the header file (+sharedDataManager). Am I doing something completely wrong?
Answer: You haven't made it clear where exactly you're doing the imports vs @class. And I think that's causing confusion. Here's what you want to do:

In GardenView.h, use @class Plant
In Plant.h, use @class GardenView
In GardenView.m, use #import "Plant.h"
In Plant.m, use #import "GardenView.m"

This breaks the circular dependency in the headers, but still allows the implementations to see the full information of the dependent class.
Now the reason why @class alone isn't sufficient is because all @class Foo does is it tells the compiler "There exists a class named Foo", without telling it anything at all about the class. The compiler doesn't know its methods. It doesn't know its superclass. All it knows is if it sees the token Foo, then that represents a class type. You can use this in header files so you can refer to the class in arguments and return types, but in order to actually do anything with values of that type you still need the full #import. But you can put that #import in the .m file without any problem.
The only time you need #import instead of @class in your header is if you want to inherit from the class in question. You cannot inherit from forward-declared classes, so you need the full #import. Of course, you may also need the #import if you need access to other types defined in the same header (e.g. structs, enums, etc.), but that's less common in obj-c.
Comment: That did the trick! Thank you! I thought all import/@class declarations had to be in the header file, and that the only import that could be in the .m file was the reference to its own header. Thank you!
Comment: @Jenny: Nope. All an `#import` does is literally copy&paste the contents of the referenced file in place of the `#import` line (well, it also checks to see if the header has been imported before, and does nothing if it has. That's how it differs from `#include`). You can even put code in your .h if it's ok for the code to be included in multiple translation units (read: source files), although that's pretty rare.
Comment: "The only time you need #import instead of @class in your header is if you want to inherit from the class in question." Thanks, was not aware of this.
Comment: This indeed a great post.!!


Prove Composite Infinitely Often

Question: Suppose we let $f(x) = ax^2 + bx + c$ be a non-constant polynomial, and assume that $a$, $b$, and $c$ are integers.
Prove: There are infinitely many integers $n$ such that $f(n)$ is composite.
Answer: For sufficiently large $N$, $|f(N)| > 1$.  Let $p$ be any prime dividing $f(N)$.
For any integer $k$, $f(N+kp)-f(N)$ is divisible by $p$, so  $f(N+kp)$ is also divisible by $p$, and only finitely many of these can be $p$, $0$ or $-p$.
(I'm assuming you're not restricting "composite" to positive integers: otherwise $f(x) = -x^2$ would be a counterexample)
Comment: So basically now, Q.E.D
Comment: No, no restrictions.

Prove Composite Infinitely Often


Can a vector hold two allocators or use different allocators to allocate and construct/destroy?

Question: I'm trying to implement my custom vector. In some case, I decide to place capacity in front of the real data, and access capacity by shifting the pointer.
Assuming that sizeof(capacity) == 4 while sizeof(value_type) == 512, using allocator<T> will cause memory fragment undoubtedly, which might be unacceptable.
Therefore, I can't use allocator<T>::allocate to allocate the whole chunk memory.
However, I can hold two allocators(allocator<T> and rebind_alloc<byte>) at the same time, then allocate memory by rebind_alloc<byte> and constrcut value by allocator<T>. I wonder whether it satisfy standard requirements. Or, is there any other good idea?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Holding two allocators for one container might be hard to maintain, so according to my problem, what I need is a stateful allocator.
There is already a ready-made paradigm in the standard library, which is called std::scoped_allocator_adapater.

The std::scoped_allocator_adaptor class template is an allocator which can be used with multilevel containers (vector of sets of lists of tuples of maps, etc). It is instantiated with one outer allocator type OuterAlloc and zero or more inner allocator types InnerAlloc.... A container constructed directly with a scoped_allocator_adaptor uses OuterAlloc to allocate its elements, but if an element is itself a container, it uses the first inner allocator. The elements of that container, if they are themselves containers, use the second inner allocator, etc. If there are more levels to the container than there are inner allocators, the last inner allocator is reused for all further nested containers.

That std::scoped_allocator_adapter is what I need here. So, I implement my allocator like this:
template <class AllocByte, class AllocTy>
class MyAlloc : AllocTy, AllocByte {
    using alty_traits   = std::allocator_traits<AllocTy>;
    using albyte_traits = std::allocator_traits<AllocByte>;

public:
    using alty_type   = AllocTy;
    using albyte_type = AllocByte;

    // other functions and type alias

    albyte_type& byte_allocator() noexcept { return static_cast<AllocByte&>(*this); }

    const albyte_type& byte_allocator() const noexcept { return static_cast<const AllocByte&>(*this); }

    alty_type& value_allocator() noexcept { return static_cast<AllocTy&>(*this); }

    const alty_type& value_allocator() const noexcept { return static_cast<const AllocTy&>(*this); }

    pointer allocate(size_type n) { return albyte_traits::allocate(byte_allocator(), n); }

    void deallocate(pointer ptr, size_type n) { return albyte_traits::deallocate(byte_allocator(), ptr, n); }

    size_type max_size() const { return albyte_traits::max_size(byte_allocator()); }

    template <class _Ty, class... _Args>
    void construct(_Ty* ptr, _Args&&... args) {
        alty_traits::construct(value_allocator(), ptr, std::forward<_Args>(args)...);
    }

    template <class _Ty>
    void destroy(_Ty* ptr) {
        alty_traits::destroy(value_allocator(), ptr);
    }
};


For what p $\int_{1}^{\infty} x^p \cdot \sin(\frac{1}{x^2}) dx$ converges?

Question:
For what values of $p$ does $\displaystyle\int_{1}^{\infty} x^p \cdot \sin\bigl(\frac{1~}{x^2} \bigr)\, \mathrm{d}x$ converge?

I was able to see that for $p \geq 2$ it diverges because the limit exists and its different than 0.
Then I used $\sin\bigl( \frac{1~}{x^2} \bigr) < \frac1{x^2}$, and saw that the integral converges for $p<1$.
However, I am completely stuck for $1<p<2$, can anyone give some guidance?
The limit does seem to be $0$.
Thanks a lot.
EDIT: The only thing we were taught in class is $\sin t < t$ and nothing beyond that. Answers without using other trigonometric inequalities will be preferred.
Answer: Hint: if $x$ is sufficiently small, $\frac{x}{2}\le \sin x$
Answer: Recall $\frac{2}{\pi}\theta\leq\sin\theta\leq\theta$ for all $\theta\in[0,\pi/2]$.  We will use the $\frac{2}{\pi}\theta\leq\sin\theta$ estimate here, giving
$$
x^p\sin(x^{-2})\geq\frac2\pi x^{p-2}
$$
for all $x\geq 1$.  Since $p-2\geq -1$ if $p\geq 1$, we have $\int_1^\infty x^{p-2}\,\mathrm{d}x=\infty$ and thus $\int_1^\infty x^p\sin(x^{-2})\,\mathrm{d}x$ diverges too.


streamread can't read any data from NetworkStream in c# ,

Question: I have a sensor that has an ip and port 192.168.2.44:3000.
I used the herculas to connect to the device ,as you can see in the picture :
enter image description here

I need to implement this software in c# ,so i write this code :
private static void Main(string[] args)
        {
            try
            {
                byte[] buffer = new byte[2048]; // read in chunks of 2KB
                int bytesRead;
                var listener = new TcpListener(IPAddress.Any, 3000);
                listener.Start();
                NetworkStream network_stream;
                StreamReader read_stream;
                StreamWriter write_stream;
                var client = listener.AcceptTcpClient();
                network_stream = client.GetStream();

                read_stream = new StreamReader(network_stream);
                write_stream = new StreamWriter(network_stream);

                write_stream.WriteLine("00010002000B0300010004C380");
                write_stream.Flush();  //veriyi gönderiyor

                string gelen;
                gelen = read_stream.ReadLine();
                Console.WriteLine(gelen);
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }

When i put a breakpoint the  gelen = read_stream.ReadLine(); returns null

http://www.hw-group.com/products/hercules/index_en.html
Comment: possible duplicate of [the c# can't receive any data from the networkstream](http://stackoverflow.com/questions/31005914/the-c-sharp-cant-receive-any-data-from-the-networkstream)
Answer: the final code :
class Program
    {
        static void Main(string[] args)
        {
            TcpListener server = null;
            try
            {
                Int32 port = 3000;
               // IPAddress localAddr = IPAddress.Parse(IPAddress.Any);

                server = new TcpListener(IPAddress.Any, port);

                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[256];
                String data = null;

                while (true)
                {
                    Console.Write("Waiting for a connection... ");
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");

                    data = null;

                    NetworkStream stream = client.GetStream();

                    byte[] aaa = { 0, 1, 0, 2, 0, 11, 3, 0, 1, 0, 4, 195, 128 };
                    stream.Write(aaa, 0, aaa.Length);
                    int i;

                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        Console.WriteLine("Received: {0}", data);

                        data = data.ToUpper();
                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
                        stream.Write(msg, 0, msg.Length);
                        Console.WriteLine("Sent: {0}", data);
                    }

                    client.Close();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                server.Stop();
            }

            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }
    }


Como customizar materialize css?

Question: Sou iniciante em materialize. tenho uma nav bar, em qual a cor do link é Cinza. Quero editar o hover para que ao passar o mouse em cima mude sómente a cor do link para azul, podem me ajudar pfv???
Esta é minha nav bar

      MATTAR

        menu

HOME

SERVICES

ABOUT

CONTACT

Comment: criei um codiggo pra customizar o hover, mas esta vazio. tentei: um a a:hover{ color:red;} mas não funcionou
Answer: Mateus o que acontece é que vc está usando duas classes de cor do Materialize na sua tag  e essas classes de cor grey-text e text-darken-1 do Materialize têm por padrão !important na propriedade color, com isso mesmo colocando a:hover{ color:red;} a cor não vai ser aplicada. Sugiro que vc leia aqui: Qual seletor css tem prioridade?
Veja essa imagem para entender melhor.

Sugestão para aplicar a cor
Uma das opções é colocar !important também no estilo que vc vai fazer para aplicar a cor nova. Por exemplo como eu fiz no código abaixo.
.texto-red:hover{ color:red !important }

Execute em "Página toda" para ver o menu completo e os links

<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Page Title</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

      MATTAR

        menu

HOME

SERVICES

ABOUT

CONTACT

Comment: Ajudou Muito!!!!!! muito obrigado Hugo, sou novo na area e no forum, como posso fz para agradecer?
Comment: @MateusAraújo tranquilo meu caro, fico feliz em ter ajudado. Na verdade não eh preciso "agradecer", o site aqui eh um site de perguntas e respostas, não eh bem um fórum Pq não eh para conversas e bate papo, eh mais pergunta e resposta mesmo. Vi que vc aceitou a resposta, isso eh o principal a fazer, já que sua duvida foi resolvida. Assim a pergunta não fica em aberto sem resposta aceita mesmo já tendo sido resolvida. No mais sucesso e bons estudos ;)

Como customizar materialize css?


Serverless Framework with lambda-proxy integation and API Model Validation

Question: I have an issue validating a request with a model when the user changes the content-type of the request in a serverless framework lambda-proxy integration
As per AWS docs, we can not change too much when using lambda-proxy integration
For example, the passthrough behavior that explains what happens when a validation model does not match the request type, can not be used on lambda-proxy integration.
My problem: I want to reject all requests that are not JSON so they must be forced to use the model validation. But at the same time, I do not want to change the integration type from lambda-proxy to lambda.
What can I do to solve this issue?
BR
Answer: One thing you can do is inspect the headers in the event object to confirm that it is the type you expect and if not return an error:
https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html
Answer: We can enforce the Content-Type header straight into the API Gateway like below.

References can be found here: https://docs.aws.amazon.com/apigateway/latest/developerguide/request-response-data-mappings.html


What's the best way to migrate from manual upgrades to composer updates?

Question: I have an 8.9.19 installation that I would like to move over to use composer.
What's the best way to migrate the installation to use composer upgrades?  Manual installations are becoming a real pain.
Comment: You need to use the Composerizer project. https://github.com/grasmash/composerize-drupal
Comment: That does it. Please post that as an answer when you can so I may mark it solved by you.
Answer: The most common way to 'flip' a project from not having Composer managed dependencies to being managed by Composer is to use the Composerize project: https://github.com/grasmash/composerize-drupal
Answer: I wouldn't say there is a most common way. Drupal is by default now composer ready since it introduced two project templates of its own. The answer depends on the specific requirements. If you want to switch between different composer templates it's also no problem to start a new composer project, require the packages of the installed modules and then move database and files directory from the old to the new installation.
See https://www.drupal.org/docs/develop/using-composer/starting-a-site-using-drupal-composer-project-templates


iOS 11: How to get the location (File Provider) name of cloud-based file?

Question: My iOS 11 app works with cloud-based files using UIDocumentPickerViewController (in .open mode). Once I have the URL, how can I get the name of the location (file provider) that stores the file? (such as "iCloud", "Dropbox", etc)
My best guess was URLResourceValues.ubiquitousItemContainerDisplayName, but it seems to work only for iCloud.
Here's a test code:
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    guard let url = urls.first else { return }
    let isAccessible = url.startAccessingSecurityScopedResource()
    let res = try! url.promisedItemResourceValues(forKeys:     [.ubiquitousItemContainerDisplayNameKey])
    print("Container name: \(res.ubiquitousItemContainerDisplayName)")
    if isAccessible {
        url.stopAccessingSecurityScopedResource()
    }
}

For files picked from iCloud, it prints "iCloud Drive". But for Dropbox-based files the container name is nil.
Am I missing something? Is there another way?
Answer: This is not possible. Apple does not let you get this information to protect the user's privacy.
Answer: This works with iOS 15 and probably much earlier:
func documentPicker(_ controller: UIViewControllerType, didPickDocumentsAt urls: [URL]) {
    guard let url = urls.first else { return }
    guard url.startAccessingSecurityScopedResource() else {
        print("unable to access security scoped resource: \(url.absoluteString)")
        return
    }
    defer { url.stopAccessingSecurityScopedResource() }

    let fileCoord = NSFileCoordinator.init()
    fileCoord.coordinate(readingItemAt: url, options: .immediatelyAvailableMetadataOnly, error: nil) { (url) in
        if let res = try? url.resourceValues(forKeys: [.ubiquitousItemContainerDisplayNameKey]),
           let name = res.ubiquitousItemContainerDisplayName {
               print("\(name)")
           } else {
               print("no name found")
           }
    }
}

You only get a result if the URL represents a location in iCloud Drive.
Comment: Thank you. I had solved the original question by [parsing bookmark data](https://github.com/keepassium/KeePassium/blob/20864cd1bef61cf5e289c00511a145d5426e40ba/KeePassiumLib/KeePassiumLib/files/URLReference.swift#L512) directly — it happens to contain file provider ID in plain text. However, all the credit goes to Michael Lynn (aka pudquick) who wrote [Apple's BookmarkData - exposed!](http://michaellynn.github.io/2015/10/24/apples-bookmarkdata-exposed/)
Comment: Sorry - I realise I didn't actually answer your question. Thank you for the links. Your solution is a hard road to travel!


vector push_back memory access denied in Visual Studio

Question:
#include <stdio.h>
#include <vector>

using namespace std;

int main()
{
    vector<int> numbers;

    numbers.resize(10001);
    for (int i = 0; i < 10000; i++)
    {
        numbers.push_back(1);
    }

    return 0;
}

If I put more than 5000 1s in the vector, I get the following error, I don't understand.
There is no doubt about it other than the memory overflow. But int type = 4 bytes, so 4byte * 10000 = 40000byte 0.04mb
Why am I getting an error?
Comment: Use `reserve` instead of `resize` if you're using `push_back`. You can also just use `std::vector numbers(10001,1);` Then there will be no need to use `push_back`.
Comment: Resize sets the size, it will make the vector have `10001` default initialized elements. Then you use `push_back`to add *more* elements.
Comment: Nothing in the posted code that should cause a memory problem.
Comment: Also, why do you set the size to `10001` and then only (attempt to) use `10000` elements?
Comment: Side note: better to avoid `using namespace std` - see here https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice.
Comment: Is this a [mre]?
Comment: Thanks for your reply. understand. In fact, what I did not understand was that a memory error occurred when data was input to only 10000.
before running
I was able to solve it as Kim by shutting down the computer.
Answer: The error seems unrelated to the code that you've shown.
Now, looking at your code there is no need to use resize and then using push_back as you can directly create a vector of size 10001 with elements initialized to 1 as shown below:
std::vector<int> numbers(10001,1);// create vector of size 10001 with elements initialized to 1

Or you can used std::vector::reserve instead of std::vector::resize, though this is totally unnecessary as you can use the first method shown above.
vector<int> numbers;

numbers.reserve(10001); //use reserve instead of resize
for (int i = 0; i < 10000; i++)
{
    numbers.push_back(1);
}

Comment: The first method works fine. However, the second method produces the same error.
Comment: @김태후 Can you try reserving some small number like 20 or 30 say by writing `numbers.reserve(20); for (int i = 0; i < 20; i++){numbers.push_back(1);}` and see if it produces the same error. Also, you can/should just use the first method.


Extension of lower end of the vocal range

Question: I'm a 17 year old male with a comfortable range of D2- E2-E4-F#4
I've been working on my lower as well as the higher end of my vocal range and while I've gotten better at the highest end, just recently getting past E4 without straining, my lows seem unaffected and I can't seem to get any lower than that D2 (except, of course, in the mornings, when I can get down to an A#1 on good days and B1 on a daily basis, but they don't count).
So I don't really know if I'm gonna be stuck at this D2 forever or if there are hopes for me to get to a good C2 or even, hopefully, a B1 as I get older.
Comment: Does this answer your question? [Extend Lower Vocal Range](https://music.stackexchange.com/questions/80662/extend-lower-vocal-range)
Comment: What's the difference between A#1 and Bb1, especially since you say that "I can get down to an A#1 on good days and Bb1 on a daily basis" in the morning? Is A#1 very slightly lower than Bb1 or what?
Comment: Oh wow. Yeah no I just got my notes mixed up, sorry about that. I meant a B1 not Bb1.
Answer: this is fun to say, but here's what happened to me.
I practiced my low range for about a year and nothing changed.
Then, this year during winter break, aàI cought a bad cold and couldn't speak for a few days.
Since then I can get almost a tone under. (I couldn't go any lower than F, and now I'm almost at Eb).
So I think if you practice, it pobably won't change until you get something stopping you from speaking form a few days.
So good luck.
Btw, if you can already go down to D2, should be enough for almost all, no?
Comment: However, while I'm not exactly saying a D2 isn't enough, there are a few songs that I really want to sing that go down to a C2 or C#2 at some parts and it's really off putting when I can't hit it without frying or not hitting it at all. I know I can sing different songs but I'm kinda stubborn about it.


Deployment of Access SQL database to SQL Server

Question: I know I'm asking quite a large question in scale here, but I'm looking more for some general guidelines.
At my work, I have the skeleton of an MS Access database that is ~50% completed. The scope of the project, however, is growing larger and larger as we plan for it more.
I am comfortable in HTML/CSS and Javascript, but have never done any SQL Server back end type stuff - but my question is: what is the process of deploying this access database to an online database? What are some guidelines, links, or guidebooks I can look into for this?
Comment: Did you find either of the answers useful? It'd be great if you could put closure to your question by accepting an answer
Answer: You should definitely check out the upsizing wizard information on https://support.office.com/en-us/article/Move-Access-data-to-a-SQL-Server-database-by-using-the-Upsizing-Wizard-5d74c0df-c8cd-4867-8d07-e6e759d72924.
Use the upsizing wizard with a test SQL Server instance and see how it works. If you need a different tool, SQL Server's import/export tool will work great to migrate your databases over to SQL Server. Use this documentation for that: https://msdn.microsoft.com/en-us/library/ms141209.aspx
There are many YouTube videos that you can watch prior to migrating to SQL Server also: https://www.youtube.com/results?search_query=migrate+access+to+sql+server&page=&utm_source=opensearch
Answer: Sql Server has an import functionality that allows you to import from other ODBC drivers, text files (csv), and Access.  If you have access to the SQL Server management studio then you'll be able to do this.  If not, then you can always download the express version locally,  import your access file, then export (dump) your sql server database, and then upload/import it to your server.
My recommendation, if you see yourself expanding away from Access then do it now rather than later.  You will most likely run into minor details to fix which are better off sorting early than later in the project when it's close to release.   The express version should help with local development.


Cannot see the subscriptions with global administrator access in Azure AD

Question: I have the global admin account in my organization's Windows Azure AD and need to manage the subscriptions of my organization in Azure. I see No subscriptions error message when logging on management portal manage.windowsazure.com. I guess I need to be a co-administrator of the organization subscription. I think that global administrator rights should be enough to give the co-administrator rights to my own account. The question is How can I get the co-administrator rights to the azure subscription if I have global administrator rights in Azure AD?
Comment: Do you have an enterprise subscription (portal access) with Microsoft?  If so, use the Enterprise Portal.
Comment: This is not an enterprise subscription. At least my organizational account is not valid on the enterprise portal. Are there any other possibilities?
Comment: If you are an admin of the Azure subscription, you should be able to see the subscriptions you are admin of (I admin multiple enterprise, MSDN and personal Azure accounts in a single log in).  If you have a enterprise/org account the account is going to be under your org's domain account.  Previous Azure subs required a "Live" account.  I had to make myself co-admin of the other account to have everything under one umbrella.  Are you sure you are logging in with the correct account?  Azure support for billing and security is FREE (not technical), so contact them and they are pretty responsive.
Answer: No, all what you need is to set the "Access management for Azure resources" option on your AzureAD Tenant. This way you will get access to all subscriptions. Please keep in mind this option is like a "Break Glass" or Emergency option. I would not recommend having it enableded all the time. You can however enable it, get access to what you need (e.g. set yourself as owner on 1 or more subscriptions) and then disable it back.
https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/role-based-access-control/elevate-access-global-admin.md#azure-portal


Should I play the piano with or without pedals?

Question: I have been playing the piano for a while now, but I'm going to ask a question which still bugs me.
When Beethoven composed his piano sonatas, did he imagine that they would sound like they do now in recent recordings? The pianofortes in his day were not as technologically advanced as the pianos in our time.
So, the question is... should his (or rather, any composer of the classical — early romantic period) pedal markings be followed to the letter, or should one exercise some discretion?
I personally use a little discretion, especially when playing the slow tempo part of the pieces. As most pianists know, the resonance of early day pianofortes is nothing compared to the resonance modern pianos are able to produce.
Comment: Apart from the issue of changes in the instrument, you may also want to keep an eye on whether the markings are Beethoven's or by a later editor (which need not make them worse).
Answer: It depends why are you playing it.  If you're playing it for an exam, then you probably need to demonstrate your ability to follow the music 'to the letter'.
If you're playing for your own enjoyment.  I would be tempted to encourage you to be yourself and play it however you think sounds best.  Not all pianos sound alike anyway, not even modern ones.
If you're playing it for a performance at a concert / theatre etc, then maybe ask the conductor / director / producer what they think.
You could also try making recordings of yourself so you can hear the difference.  Sometimes you don't hear certain peculiarities whilst playing, minor bad habits are often subconsciously dismissed.  (For example, "well of course I was late playing that note, I had to move my fingers quite some distance to reach it")
As for did Beethoven imagine that his works would sound like they do in the future?  The obvious answer is "No, how could he?".  However, when a composer (or any artist) translates a concept/idea from the mind into a tangible form, the result is often a compromise.  The concept/idea as it was perceived in one's imagination is often a grander, richer, fuller, perfect.  So whilst Beethoven may be impressed/pleased with how his compositions have translated to modern instruments, he would probably have imagined the composition sounding even better still.
Answer: Yes, Beethoven's piano had less resonance.  He sometimes wrote close-position chords in the bass register which, to be blunt, just sound muddy on a modern piano.   And he could notate pedaling that, taken literally, sounds blurred now.
I suggest you look at WHY a passage is marked with pedal and do your best to achieve it on the instrument you're playing.   Interpret  'ped' as 'con ped' - use the pedal but in a more subtle way than just plonking it down!   (Actually, that's a pretty good approach to pedal markings from any period!)
I wouldn't be tempted to cite Beethoven's deafness as a factor here. He was better than that!
Answer: To expand on Lee's excellent answer, I imagine Herr v.B. would be delighted to hear any musically sensitive, imaginative, and sympathetic rendition of his music, by whatever means the interpreter deems necessary. It's about the story, not the handwriting. I have heard people play my own compositions beautifully, and it disturbs me not one bit that the version I have in my head during composition is very different to the one I hear during performance. And I know no composers personally who haven't said the same at some time or other.
Answer: You are correct-- pianos in Beethoven's time are definitely different than pianos now. Thus, Beethoven's pedaling (and others in the Romantic era) should be treated more like a guide rather than a definitive roadmap. Not sure you have access to a music library, but there are many, many score editions for Beethoven like Schnabel, Schenker, Ward/Cooper that can be illuminating to look at for ideas to do with the pedaling.
I do think actually, for any composer, you are allowed discretion. There are varying degrees-- modern composers who like to micro-manage and composed for the modern piano in mind must be followed more to the letter. However, even these modern composers can't compose for every piano in the world, located in different places with varying weather and acoustics. You'll need to adjust regardless. There can be some stark differences-- some concert halls are so "wet" that sound sticks even if you're not using the sustain pedal, etc.
I also disagree with Mr. Kowalkowski that if you're playing for an exam, you must follow the score to the letter. Bach never wrote any pedaling in his original scores (because they were for harpsichord; this can be seen as a parallel to the early piano), but it's standard practice to use pedal when playing his pieces. If you are playing for an exam, what I would do is learn the standard interpretation in conjunction with studying from the score itself and make your own judgment from there on.
Comment: :-) I am self-taught, I have never taken a music exam for any instrument (I've played a few instruments in orchestras though). I also don't sight-read (because I'm a lousy page turner ha ha). In my answer I was supposing if you're being observed by an examiner, and your ability to interpret sheet music is an examination criteria (I assumed it must be at some level, but I don't know), then it would not be a good idea to wilfully deviate from the score. I have no idea how harsh/pedantic music examiners are. Of course if there are no pedalling marks on the score then that is a different matter.
Comment: By the way... welcome to "Musical Practice & Performance"!  If any of the sheet music I've ever used contained pedal markings, well I've ignored them completely so far, I personally do whatever I like! :-O  Keep up the excellent contributions!!
Comment: As I understand it from a commentary on the _Well-tempered Clavier_ (Tovey?), Bach did not write specifically for harpsichord so much as often generally for the various keyboard instruments of his time, and sometimes, perhaps, thinking particularly of the clavichord, for which he seems to have had a special affection, with its greater sensitivity to touch – but no pedal either.


apache forward ip/port to local domain

Question: First i want to apologize if i am not using all the correct terminology, all this network and linux stuff is brand new to me so using tutorials to learn as i go. I work with vb.net and c# so i've been able to pick this stuff up pretty quickly, i just don't fully understand the linux file structure or commands yet.
I have some web services running on an old computer running ubuntu server, and they resolve to an ip address and a port number, like 192.168.1.166:6789 brings me to that services web UI.
I also have apache running on this box which is hosting another service so when i visit 192.168.1.166 WITHOUT the port number at the end, it brings me directly to that web UI for that service (for whatever reason this service needed apache to run, the others just work on their own when i run the service on the server and visit ip/port tied to them).
So basically i want to setup apache (or anything else through ubuntu that can do this) that will forward 192.168.1.166:6789 to say "http://myService" or "http://myService.com" so its easier for non-technical people in the house to pull these web UI's up (not sure what format is valid for local urls, again i am a big time newbie with all this). I have 2-3 services on different port numbers i want to do this for.
Is this possible? I did something earlier inside the /etc/apache2/sites-available config file that let me create a link like "192.168.1.166/myService" but i want to eliminate the ip all together and just have a short alpha name for the URL.
Comment: This is just a local machine on my local network, i do not need to reach a real domain outside my LAN. I just want to be able to type in "http://radarr" and have it bring me to 192.168.1.166:7878 when done on the LAN.
Answer: You can use URL redirection to make it possible, here you can check with this  link
Answer: You need to access to that service from inside your network or outside it?
If the problem of solve the service name to the correct ip is solved
and I undestood correctly your question you need to configure a virtual host.
https://httpd.apache.org/docs/2.4/vhosts/examples.html
You can answer to "service_nX" using apache (and a configured virtual host) and it can redirect to the correct port.
You will and on ip/port but user only need to know service_nx.
If you want to use this from outside your localnetwork well' it' triky, but let us know.
I hope this answer is useful.
Comment: I just need to access these locally, i tried to edit my .conf file but this did not work: `
``
`    `
`        Options FollowSymLinks`
`        AllowOverride All`
`        Order allow,deny`
`        allow from all`
`    `
``
`    DocumentRoot /var/www/newznab/htdocs/www`
`    ErrorLog /var/www/newznab/logs/error.log`
`    CustomLog /var/www/newznab/logs/access.log combined`
``
``
``
`ServerName 192.168.1.164:7878`
`Redirect / http://radarr`
``

apache forward ip/port to local domain


Unable to submit form to database in custom module

Question: I am building a custom module and I'm unable to get the form to talk to the database. The section for uploading to the file system works fine.
This is MyModuleBlock.php
<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

use Drupal\my_module;

/**
 *  @Block(
 *    id = "my_module",
 *    admin_label = @Translation("Add Image"),
 *  )
 */

class ImageBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
      // stuff here;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {

    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();

    $form['image'] = array(
      '#title' => t('My Module'),
      '#type' => 'managed_file',
      '#upload_location'=> 'public://images/',
      '#required' => FALSE,
    );

    $form['submit'] = array(
      "#type" => 'submit',
      '#value' => 'Upload',
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */

  public function submitForm($form, FormStateInterface $form_state) {
      MyModuleDB::add();
  }
}

The MyModuleDB.php (I am trying out plain text to see if any errors or anything pops up):
<?php

namespace Drupal\my_module;

class MyModuleDB {
    static function add(){
        db_insert('my_table')
            ->fields(array('image' => 'img1'
            ))->execute();
    }
}

I'm at a total loss here. The tutorials I've found claim that this should work out fine, but it isn't working for me at all. I even tried inserting into the database directly from submitForm() in the main block class. I also tried to add redirects to the submitForm(). I'm thinking the issue is in that function, but I don't see what the issue could be.
Comment: There's a lot here that doesn't make sense. If you have a block then you are not supposed to save anything yourself somewhere in the database. Anything that is part of the block configuration just needs to be added to $this->configuration in blockSubmit() as mentioned by Daniel Wehner.
Comment: Thanks. I'm pretty new to Drupal, so yeah, I'm sure quite a bit won't make sense.
Answer: If you write a block, use \Drupal\Core\Block\BlockPluginInterface::blockSubmit for submission
Answer: What your submitForm() should do is shown from AggregatorFeedBlock::blockSubmit(), for example.
public function blockSubmit($form, FormStateInterface $form_state) {
  $this->configuration ['block_count'] = $form_state->getValue('block_count');
  $this->configuration ['feed'] = $form_state->getValue('feed');
}

See the code of AggregatorFeedBlock::blockForm() too.
public function blockForm($form, FormStateInterface $form_state) {
  $feeds = $this->feedStorage->loadMultiple();
  $options = array();
  foreach ($feeds as $feed) {
    $options [$feed->id()] = $feed->label();
  }
  $form ['feed'] = array(
    '#type' => 'select',
    '#title' => $this->t('Select the feed that should be displayed'),
    '#default_value' => $this->configuration ['feed'],
    '#options' => $options,
  );
  $range = range(2, 20);
  $form ['block_count'] = array(
    '#type' => 'select',
    '#title' => $this->t('Number of news items in block'),
    '#default_value' => $this->configuration ['block_count'],
    '#options' => array_combine($range, $range),
  );
  return $form;
}


How to extract a set of *.tar.gz.(letters) files?

Question: I have downloaded a medical data set to use in machine learning and the files are like this:
dicom_v1.tar.gz.aa
dicom_v1.tar.gz.ab
dicom_v1.tar.gz.ac
dicom_v1.tar.gz.ad

I don't know how to extract these files. When I use WinRAR or 7-Zip, it doesn't work.
It is written in the attached ReadMe file:

To decompress this data set execute in a Unix command line:
cat dicom_archive.tar.* | tar -xzvf

How can I do this in Windows 10 as I am a beginner?
Answer: These files have been split into chunks for distribution, so you need to put them back together before you can see whether Winrar or 7-zip will be able to extract them.
Since you're using Windows, you probably want to the Powershell get-content command (which helpfully aliased to cat btw) - and since the files are chunks of a compressed archive you probably want to use the -raw argument too.
https://shellgeek.com/use-cat-equivalent-type-command-in-windows/ is a good page to read.
I would try something like this as a starting point:
PS C:\> get-content -raw dicom_v1.tar.gz.* > dicom_v1.tar.gz

According to https://pureinfotech.com/extract-tar-gz-files-windows-10/ you should be able to run tar with the z flag natively in Powershell to extract all the files from the dicom archive.
Comment: Thank you For Your Response ,when i run the Command it gave me this text in red:get-content : Insufficient memory to continue the execution of the program.
At line:1 char:1
+ get-content -raw dicom_archive_v2.tar.gz.* > dicom_archive_v2.tar.gz
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-Content], OutOfMemoryException
    + FullyQualifiedErrorId : ProviderContentReadError,Microsoft.PowerShell.Commands.GetContentCommand
Comment: Each File is a 3GB , and There are about 15 Files , so the Whole Thing is about 45 GB
Comment: The Above Message is displayed for 15 Times (The Number of Files) in the Power Shell Window
Comment: Ouch. Does the distributor of the data provide a complete archive file you could download instead?
Comment: Sadly , No , Is there still a Solution ? .As this is very important to me !
Comment: You're going to need a virtual machine of some sort - either WSL2 on your system, or a linux container in Docker or an EC2. Then use the cat pipeline the data authors suggested before moving the output back to your system.
Comment: Actually , Most of the things you are describing  , i don't understand  . Do you think if i enable the Linux Subsystem on the Windows and run the Command , Will it Work ?
Comment: WSL2 should work. The other options I suggested are different ways of approaching the idea of getting access to a linux environment.
Comment: The Solution Was Actually Available in windows using this Command: type *.tar.gz.* | tar xvfz -
Comment: There was no Need For Linux  . Thank you very much


With sudoers, how can I allow a user to change the group of files/folders within their home directory?

Question: I have a webserver where apache runs as www-data. Users are set up using chef, and some of their file/folder permissions are set to group: www-data, e.g. uploads folders.
Deployments are done with Capistrano, using the user account. It would be useful if during deployment, Capistrano could also change the group of files/folders to www-data.
How could I configure this, whilst maintaining security? I'm thinking an entry in the sudoers file that allows <user> to execute chgrp www-data /home/<user>/* whilst ensuring that the command does not contain ...
Comment: I would check out this answer: http://unix.stackexchange.com/a/44623
Answer: You might be best off writing a script and enabling that in sudoers. If your users will only ever need to run it on * within their homedir then something as simple as the following. It makes use of the SUDO_USER environment variable which you can find out more about here: http://www.sudo.ws/sudo/sudo.man.html#environment
chgrp www-data /home/`echo $SUDO_USER`/*

I haven't tested this but it should work in principal.
Comment: Thanks. I think I'll have to write a wrapper script as you say. the `*` was meaning *anything*, rather than specifically `*` in the command, so it's not possible to protect against `..` in the path, and symlinks pointing elsewhere on the system.
Comment: In the spirit of being over paranoid, would welcome any feedback on this - which is first draft to solve the problem - https://gist.github.com/colinbm/6507094


References module doesn't specify/read a pager limit when field is using a view to generate potential references

Question: Discovered an oddity that seems inherent in the node_reference.module 7.x-2.1. It is a rather specific use-case, so I can see why it might not have come up frequently before. Just wondering if anyone has any work around ideas, either that or I'll document my findings if I reach a solution.
How to reproduce the issue:

Create a reference list view, and use it to power an autocomplete field.
Create another view and attempt to use the created field as a filter.
Everything will work fine, unless that field has a large number of values. The field I'm using has upwards of 90,000 items.
This is because the views filter UI attempts to render all possible values as a checkbox list.

The reason it trips up is because:
function _node_reference_options($field, $flat = TRUE) {

Goes on to call:
$references = node_reference_potential_references($field);

Without any options. Which leads to:
references_potential_references_view(
  $entity_type, $view_name, $display_name, $args, $options);

Being called without any options, and it seems this code does not read the pager settings to get its limit value. Instead it relies on $options['limit'].
$limit = !empty($options['limit']) ? $options['limit'] : 0;
$view->display_handler->set_option('pager', array(
  'type' => 'some', 'options' => array('items_per_page' => $limit)));

I'm not sure which bit of the code is at fault — i.e. who should definite a limit, or read the pager settings — but there definitely needs to be a defined limit and not 0. Especially when dealing with so many possible values. Setting a limit specifically for the pager in Views UI does not work as it is circumvented.
Currently I can't even get to edit my view with the filter specified, unless I hack the references module to pass:
$references = node_reference_potential_references($field, array('limit' => 10));

I'm only adding this as a filter so I can state that the field isn't empty. I could just leave the hack in until I've set the filter to a state that doesn't read the values. However this feels rather unsafe — especially if someone else was to take over the code at a future point.
Answer: I haven't found a neat general solution to this issue, but in terms of a specific solution you can use hook_query_alter. Basically in one of my bespoke modules I added the following:
/**
 * Implements hook_query_alter().
 */
function bespoke_module_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('views_autocomplete_for_ref_files')) {
    $view = $query->getMetaData('view');
    if ( !empty($view) && $view->current_display == 'references_lead_image_by_default' ) {
      $query->range(0, 10);
    }
  }
}

NOTE: Awkwardly there doesn't seem to be an ability of SelectQuery to get back the current range settings. The code could be more general if it could detect that no limit was set.

Out of the above views_autocomplete_for_ref_files is the machine name of the reference list view, and references_lead_image_by_default is the name of the display. I can focus on the default display because I have code elsewhere that switches the view in use depending on certain contexts. The default display is never actually used by the site, except when it is requested by the Views UI (because the widget hook below is not used for the Views UI display).
/**
 * Implements hook_field_widget_form_alter()
 *
 * Modifies the autocomplete path for autocomplete widgets
 */
function bespoke_module_field_widget_node_reference_autocomplete_form_alter (&$element,
    &$form_state, $context) {
  $instance = &$context['instance'];
  $field = &$context['field'];
  /// only step in if the field uses a view to populate
  if ( $field['settings']['view']['view_name'] == 'autocomplete_for_ref_files' ) {
    /// switch the view display depending on content type
    if ( (arg(0) == 'node') && ($node=node_load(arg(1))) && ($node->type) ) {
      $field['settings']['view']['display_name'] =
        'references_lead_image_for_' . $node->type;
    }
    /// hijack the current autocomplete path to point to our own callback
    $element['nid']['#autocomplete_path'] =
      $instance['widget']['settings']['autocomplete_path'] . '/' .
      $instance['entity_type'] . '/' . $instance['bundle'] . '/' . $field['field_name'];
    /// hijack the autocomplete validate function, to validate with our own criteria
    $element['nid']['#element_validate'] =
      array('bespoke_module_node_reference_autocomplete_validate');
  }
}

I'll keep looking to see if I can find a more general solution.


Site showing white background behind status bar on iOS

Question: Im having trouble with the status bar color on my website for iOS device. The background color seems to be ignored and there is a white bar behind the status bar on my ios device. I've tried setting up theme-color and apple-mobile-web-app-status-bar-style meta tags with HSL color tags but they don't seem to do anything. When I minimize the page and open another tab and come back to it, sometimes the background behind the status bar becomes the correct color and works like I would like it to.
Does anyone have any ideas for how I can fix this?
bad example
good example
Code on website.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Solved by adding the background-color property to the html element.
when the style was only applied to the body the area behind the status bar and under the navigation bar would be white and draggable


Align text vertically in flutter

Question: Is there any way to do this in flutter.

I am trying to align the text inside container vertically.Just increased the height of container but it was not working. it camed like this :

Code :
Comment: your code is missing
Comment: Please provide minimum producible code.
Comment: Rotate it around Z axis
Answer: use RotatedBox Widget
RotatedBox(
      quarterTurns: 3,
      child: Container(
        color: Colors.blue,
        child: Padding(
          padding: EdgeInsets.all(10),
          child: Text("Rotated Text"),
        ),
      ),
    )

Answer: You can achieve it using below code snippet:
import dart.math;
Transform.rotate(
angle: math.pi *15 /90

// Set degree as per requirement
child :CustomWidget()
)

Align text vertically in flutter


Where should assets go in a CodeIgniter project?

Question: I'm just starting with CodeIgniter, and I am not sure where things such as css, js, and images should go. Outside the whole system folder seems ok, but that means everything is seperate. Inside means the filepaths are longer, and I'm worried that it might mess things up. What's the best practice on this issue?
Answer: I usually put separate folders at the root level, so I end up with a directory structure like this:
/system
/css
/js
/img

Seems to work for me - when you use site_url(url), the URL it generates is from the root, so you can use site_url('css/file.css') to generate URLs to your stylesheets etc.
Comment: @Blowski Yes. I know it's not best practice but I don't think it's necessarily an issue, especially if you use .htaccess to close off access to it.
Comment: Ah, that makes sense. I wanted to be able to use site_url, so this makes sense.

Thanks!
Comment: Does that mean you keep your system folder inside a public directory?
Answer: Personally, I rip the application directory out of the system directory and make it a sibling to system. I then create a project directory in public_html (www) where I move index.php and store my public assets.
Let's assume the project you're working on is called projekt. In the parent directory to public_html (www) create a directory called CISYSTEM, and inside that directory create a directory from the version you're using, 202, 210 etc.
/CISYSTEM
    /202
    /210
    /another_CI_version
/projekt_application
    /models
    /views
    /controllers
    /private_assets
/public_html
    /projekt
        index.php
        .htaccess
        css
        img
        js
        lib

The beauty of this directory structure is it adds another layer of security and makes it dead-easy to upgrade/swap out your CI core. Plus, you're not supposed to make changes to the core - having a single directory where your core is stored and having all projects reference it keeps things DRY.
All this directory shuffling requires you to reroute a few things though. Luckily, CodeIgniter makes it easy -- all changes can be made in the index.php file.
Open index.php and reroute a couple things:
Change: $system_path = 'system';
To: $system_path = '../../CISYSTEM/210';
Change: $application_folder = 'application';
To: $application_folder = '../../projekt_application';

Also, I see a lot of people talking about using site_url() in the other answers. I recommend a less verbose way of using site_url()... you don't have to call it every time if you make use of HTML's <base> element:
<base href="<?= site_url();?>">
Just include that in your application's  and you can call your controllers directly... as in:
Some Action
Cheers
Answer: I find it best to keep the assets on the root level.  You can use <?=base_url()?> to echo the full root of the site.  In the config file, you set up the root of the website.  This statement just echoes that out.
Because of this, you can use includes like this:
<link href="<?=base_url()?>/css/style.css" rel="stylesheet" type="text/css" />

anywhere in your code, and it will still get http://example.com/css/style.css.
Answer: I hate having so many directories at the root level, so I use /public and use htaccess to rewrite /scripts to /public/scripts and so on.
Comment: Could you post your mod_rewrite?
Answer: base_url()/css/name.css
Comment: base_url() actually includes the trailing slash so you'd want: base_url() . 'css/name.css';
Answer: In order to use the site_url(url) helper in this way you MUST first configure Apache mod_rewrite (or equivalent) to remove the index.php segment from the URI.
Otherwise the site_url method adds index.php to the URL which will likely screw up the paths to your assets if you've got them in the base directory like above.
Here's the CodeIgniter documentation on removing index.php from the URI:
http://codeigniter.com/wiki/mod_rewrite/


Simplifying a recursive fraction involving Lambert function

Question: Is there a simplification for the following recursive fraction :
$$\frac{\frac{\frac{n}{W(n)}}{W\left(\frac{n}{W(n)}\right)}}{W\left(\frac{\frac{n}{W(n)}}{W\left(\frac{n}{W(n)}\right)}\right)}$$
The above formula uses a recursion 3 times. I'm looking for a simplification when we have such a finite recursion, for instance when this one appears $i$ times. I would like to remove the recursion, i.e. obtain a single fraction.
Thank you.
Comment: The question is unclear.  What is it that you mean by "simplifying"?
Comment: @SimplyBeautifulArt Thank for your comment. I mean "reducing to a single fraction", without any recursion, using simple terms (except the Lambert function). Post edited ! :-)
Comment: Since $W(n)\approx\log(n)-\log\log(n)$ for large $n$s, I doubt there is any substantial simplification. What is the source of this problem?
Comment: @JackD'Aurizio This a problem of mine but, in fact, I'm wondering if there exists a result on that.
Answer: Since $u=W(u)e^{W(u)}$, it follows that $\frac u{W(u)}=e^{W(u)}$ and we get
$$\frac{\frac{\frac{n}{W(n)}}{W\left(\frac{n}{W(n)}\right)}}{W\left(\frac{\frac{n}{W(n)}}{W\left(\frac{n}{W(n)}\right)}\right)}=e^{W\left(e^{W(e^{W(n)})}\right)}$$
Which is the best simplification I can see.
Comment: @Dingo13: as said in the comments, it is $\approx\frac{n}{\log(n)^3}$.
Comment: @JackD'Aurizio that might look nice due to the exponentials.  Or you've already calculated that...
Comment: Thank you again. Why do you use $\approx$ for asymptotic?
Comment: @Dingo13 he uses it as an approximation.  But I suppose it's also an asymptote.
Comment: @SimplyBeautifulArt Can we use asymptotic equivalence?
Comment: @Dingo13 yes, Jack's result fits nicely if that's what you aimed for.
Comment: @SimplyBeautifulArt Ok, thank you again !
Comment: No problem! :-)


Why do polymorphic calls (such as listener in kauth) have anonymous arguments rather than an opaque pointer and access functions?

Question: I'm looking at the kauth tech note, but this isn't about that specifically. It's more a general API design question.
The scope for a listener is:
static int MyListener(
    kauth_cred_t   credential,
    void *         idata,
    kauth_action_t action,
    uintptr_t      arg0,
    uintptr_t      arg1,
    uintptr_t      arg2,
    uintptr_t      arg3
);

The arg0 ... arg3 depend on scope (i.e. context). To quote the documentation:

The meaning of the remaining parameters is scope dependent. in later sections ... For example, for the VFS scope (KAUTH_SCOPE_VNODE), arg1 is a reference to the vnode (of type vnode_t) that's being operated on

I'm assuming that there's a good reason for this design, but I can't see it. What if I want to add arguments later? What if I want to pass in differently sized types (in this case uintptr_t is typedefed to unsigned long but what if I wanted to pass in a larger struct?).
An example of this kind of issue can be seen in the same document:

IMPORTANT: When inspecting the credentials associated with a request, always use the accessor functions defined in sys/kauth.h. Be especially careful when testing for group membership. In Tiger a user can be in lots of groups (many more than the traditional limit of 16) and groups can be nested. If you want to test whether a user is a member of a group, use kauth_cred_ismember_gid.

If I were implementing an API function that can be called with different arguments in different contexts, I would pass in an opaque type (i.e. a void *) and provide a set of functions to extract data from it. The functions change with the API, futureproof.
So, can anyone provide insight as to why the authors might have chosen this design for the remaining arguments? Is it purely speed (kauth code paths are incredibly hot after all)?
Answer: The type uintptr_t is an unsigned integer that is guaranteed large enough to hold a pointer as well.
This means that integers can be passed through the interface without any hassle, but if you have a larger type, then that can be passed by pointer as well.
So, if integers are the common case, then you get the best of both worlds:

No hassle for the common case and no doubts/inconsistencies about passing integers (masquerade them as a pointer, or pass a pointer to the integer)
It is still possible to pass pointers if you need (a reference to) a larger structure.
Answer: The portable and extensible way to implement a function that take a variable number of arguments is to declare it variadic:
#include <stdarg.h>

static int MyListener (kauth_cred_t   credential, void* idata,
                       kauth_action_t action, ...
{
    va_list ap;
    int count = some_context_dependend_count;
    int j;

    va_start(ap, count);
    for (j = 0; j < count; j++)
        do_something_with_each_optional_arg (va_arg(ap, uintptr_t);
    va_end(ap);
    return some_result;
}


htaccess order Deny,Allow rule

Question: I'd like to dynamically add IPs to a block list via htaccess. I was hoping someone could tell me if the following will work in my case (I'm unsure how to test via localhost).
My .htaccess file will have the following by default:
order allow,deny
allow from all

IPs will be dynamically appended:
Order Deny,Allow
Allow from all
Deny from 192.168.30.1

The way I understand this is that it is by default allow all with the optional list of deny rules. If I'm not mistaken Order Deny,Allow will look at the Deny list first, is this correct?
And does the Allow from all rule need to be at the end?
EDIT 1
If I'm not mistaken I need to do this based on jeffatrackaid's answer:
Order Allow,Deny
Allow from all
Deny from 192.168.30.1

EDIT 2
For the sake of completeness, this is probably more appropriate for my requirements:
Order Deny,Allow
Deny from 192.168.30.1

Answer: This rule allows everyone into your site.
Order Deny,Allow
Allow from all
Deny from 192.168.30.1

The Order directive determines the order in which your rules are processed. With Order deny,allow the deny list will be processed first then the allow list.
With Apache, all rules are processed with the last one matching being the effective rule.
So in this case, your last rule would be allow from all.
This means that 192.168.30.1 would initially be denied but then allowed since the allow rules are processed last.
This would produce the same result
Order Deny,Allow
Allow from all
Deny from 192.168.30.1
Allow from 192.168.30.1

Think of it this way.

The allow/deny rules are simply separate lists of IPs to be allowed/denied.
The order directive determines the order in which these lists are
processed.
Apache evaluates all rules and acts on the result of the
last matching rule.

The major confusion is that this is very different from how firewalls work where rule order and first match is often what determines access.
See: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order
Comment: Thnaks for the detailed explanation.  I was under the impression that 'deny, allow' will always apply the deny rule, even on subsequent attempts. Any recommendations on how I can achieve this?
Comment: Your updated code `allow,deny` should work. The allow list is processed first followed by the deny list.  So if an IP is listed in the deny list it will be blocked since it will be last matched.  Just one note, if you have too many deny rules you may see performance issues.  All rules are processed on every request.  "Too many" depends on your hardware and server loads but something to keep in mind with any tool that auto-adds rules to .htaccess.
Answer: In the configuration file, e.g., .conf, if you have:
Order Deny,Allow
Allow from all
Deny from 192.168.30.1

The user wanted to block the access to only one IP, 192.168.30.1, but allowing access to the rest.
Reality: Apache grants access to all IP address, exposing a severe security threat and is entirely opposite of the user's intent.

Root Cause: the entry Order plays the key role: it decides the order in which the functions deny and allow are executed. If the value of Order is set to deny,allow, any IP address matching the value specified in the entry Deny from gets a temporary return value deny. After that it is checking the entry Allow from, and if it matches, it receives the return value allow, that overwrites the previous value.

Looking at the source code snippet in Apache (see below), you can find that
why 192.168.30.1 is not blocked by Apache.
int ret = OK; // default

if (a->order[method]==ALLOW_THEN_DENY) {
    ret = HTTP_FORBIDDEN;

    if (find_allowdeny(r,a-> allows,method))
        ret = OK;

    if (find_allowdeny(r,a-> denys,method))
        ret = HTTP_FORBIDDEN;}

else if (a->order[method]== DENY_THEN_ALLOW) {
    if (find_allowdeny(r,a-> denys,method))
        ret = HTTP_FORBIDDEN;

    if (find_allowdeny(r,a-> allows,method))
        ret = OK;}
else

   { if (find_allowdeny(r,a-> allows,method) && !find_allowdeny(r,a-> denys,method))
    ret = OK;
else

    ret = HTTP_FORBIDDEN;}

The correct version of this configuration would be:
Order Deny,Allow
Deny from 192.168.30.1

or just a single line of
Deny from 192.168.30.1

htaccess order Deny,Allow rule


Android: UI Collaboration (Jenkins+Spoon+?)

Question: I really like the idea of automated testing for Android.
I've tried Spoon, which gives great results for previewing current state of UI on different devices.
The problem is how to effectively share it with the team (developers/UI/UX).
What I want to have is: build server(Jenkins) triggers Robotium+Spoon test, which takes screenshots of each screen, then the build server publishes results of Spoon to some web-app(?), where we can see all the Spoon reports grouped by date and where we can leave comments on each of the screenshot.
What web-app will fit my needs?
Comment: Interested in commercial solutions?
Comment: Sure. I'm open to any solutions.
Comment: I can recommend Testdroid, however it doesn't support Spoon. Anyway you can integrate it with Jenkins and run Robotium, UIAutomator, Calabash etc. Unfortunately Spoon is not at the list of supported frameworks yet.
Comment: Nice. It's third-party service, right? I would like to install the web-app behind our corp firewall, like internal resource. Should I write small java-based web-app + DB, so I'll be able to add comments (it's basically all I need)? Is there any template for this kind of web-app?
Answer: I currently just use Jenkins. I have a script execute spoon and then I pointed Jenkins to where spoon outputs the results and presto! We now have automated test results attached to every build. Coupled with the screenshots this has impressed my managers and made debugging a much easier process. The last bonus is that it's all FREE!
Comment: It's perfect! Quick and easy to implement. Is there a way to add comments to each screenshot?
Comment: I can't think of an easy or pre-constructed solution to that one... Sounds like a fun weekend project though... :D
Comment: @psionicNinja Can you share that script?
Answer: Note the selected answer of the HTML Publisher extension no longer works due to security changes in jenkins.  Starting in jenkins versions 1.625.3 and 1.641 restrictions were added to block javascript which makes it more limited in display and almost useless


how do I reverse a stack using another stack in java

Question: Hi I am trying to reverse a stack(one I coded myself) using another empty stack. For some reason it is not working properly. Can anyone help me with this ?
<code>public static void main(String[] args) {

    Stack stack1 = new Stack();

        //filling the stack with numbers from 0 to 4
        for(int i = 0; i < Constants.MAX_ELMNTS; i++){

            stack1.push(new Integer(i));
            System.out.println(i);
    }

    Stack reverse = new Stack();

    while(stack1.getNbElements() > 0){

        reverse.push(stack1.pop());
    }
</code>
Comment: please define "not working properly". Also you populate variable `stack` in first loop and use variable `stack1` in the second loop.
Comment: You're showing us code you use to test your class. What you should really be showing us is the code for push and pop (and perhaps getNbElements() too)
Comment: Since this is a custom stack, the actual implementation is required before suggesting the optimal strategy for reverse().
Comment: Update i'm 99% sure it's working but I don't know how to output reverse. It outputs:"stack@1540e19d". What is this ?
Comment: @DoctorLongLegs I have updated the answer to include output of the values.
Comment: Yes it's working thanks a lot !
Answer: <code> while(!stack1.isEmpty()){
        Integer value = (Integer)stack1.pop();
        System.out.println(value);
        reverse.push(value);
 }
</code>


JS function to get scroll amount to nth character of an element

Question: Say I have a html element like the following:

There is a long sentence here.
The sentence is so long that it overflows from the element.

With css like:
#targetElement{
   width:50px;
   height:50px;
   overflow-y:auto;
}

Now, the sentence inside the #targetElement tag is not going to fit(hopefully, it's long enough, but even if it's not, I hope you get the idea), so there is going to be a scroll bar on #targetElement.
With that all been said, here is what I want. I want a javascript function that gives me the scroll amount (scrollTop() amount in jQuery) when I input the nth character I want to scroll to.
It would be something like this:
function scrollToChar(charIndex){
    //some how get scrollTop() to nth character like this
    var scroll=$("#targetElement").nth-char(charIndex).scrollTop();
    return scroll;
}

Comment: http://www.w3schools.com/jsref/prop_element_scrolltop.asp shows you how to get x-/y-values with plain JS (also for `overflow-y:scroll;`).
Comment: Sorry, maybe it wasn't clear, but I want the scroll amount within the #targetElement to nth character, not scroll amount to #targetElement.
Comment: Keep each element in a span and scroll to needed character's span?
Answer: Assuming that you're looking for the pixel offset of the nth character (which could then be used to scoll the element to that position), here is a solution: fiddle.
It works by temporarily inserting a  around the nth character, and using jQuery to find the 's position, relative to its parent. Note that #targetElement needs to be positioned for this to work properly.
This solution is based off of the answer here: https://stackoverflow.com/a/7913678/5306129


Java NIO library, api ...?

Question: Can anyone suggest some good java library that can help me easily create non-blocking server and client. I was searching on the internet i found 2 solution that so far didn't get me anywhere:
1 . XSockets http://xsocket.org/
Great library but you cannot set the tcp client socket to reuse the socket if u are trying to reconnect (I must wait some time until the port is free to reconnect, this happens if u must use predefined port for ex 6789). Also u cannot download the source code to modify it.
2 .  Kyronet https://github.com/EsotericSoftware/kryonet
Great library, you can download the source code and modify it. The support is great, i get answers on the forum max after 1 hour. When u communicate with java server and client that use kyronet there are no problems, but when u try to connect to a VB6 or C TCP server it gets complicated and throws some funny errors like "Unable to read object larger than read buffer: 1466262560" witch appears when u try to connect with a server (the both server are just accepting my connection and not sending anything).
I would like to try more solution like this two, and if i find i will post my impressions and test result here. Hope you can share some knowledge about this problem.
Answer: As far as I know netty is the most popular tool in this field.

Java NIO library, api ...?


Tower Property With Product of 2 Distributions

Question: Problem: $Z\sim \operatorname{Ber}(.55)$ and $X\sim \exp(\frac{1}{8}) $ or exp with mean 8 and variance 64.
Calculate $\operatorname{Var}[XZ]$
The solution offers the guidance of using the property $Y=XZ$ for:
$\operatorname{Var}[Y]=E[\operatorname{Var}[Y\mid Z]]+\operatorname{Var}[E[Y\mid Z]]$.
When $Z=0$, $E_Y[Y\mid Z]=\operatorname{Var}_Y[Y\mid Z]=0$ and when $Z=1$, $Y=X  \implies E_Y[Y\mid Z=1]=E_X[X]=8$ and  $\operatorname{Var}_Y[Y\mid Z=1]=\operatorname{Var}_X[X]=64$. This part makes perfect sense to me. Here is the part that doesn't make sense to me. The solution goes on to say that $E_Y[Y\mid Z]=E_X[X]=8Z$ and $\operatorname{Var}_Y[Y\mid Z]=\operatorname{Var}_X[X]=64Z$, so my main question is, why is there a coefficient  $Z$ now  when previously we just had a number??
Answer:
The solution goes on to say that $E_Y[Y\mid Z]=E_X[X]=8Z$

That is not quite correct (the middle expression is erroneous).
  Assuming that $Z$ is independent from $X$, then so too will $X$ be conditionally independent from $Z$ when given $Z$, and therefore:-
$$\begin{align}\mathsf E(Y\mid Z)&=\mathsf E(XZ\mid Z)\\&=\mathsf E(X\mid Z)\cdot\mathsf E(Z\mid Z)\\&=\mathsf E(X)\cdot Z\\&=8\,Z\end{align}$$
Likewise for the variance:
$$\begin{align}\mathsf{Var}(Y\mid Z)&=\mathsf {Var}(XZ\mid Z)\\&=\mathsf E(X^2Z^2\mid Z)-\mathsf E(XZ\mid Z)^2\\&=\mathsf E(X^2\mid Z)\cdot\mathsf E(Z^2\mid Z)-\mathsf E(X\mid Z)^2\cdot\mathsf E(Z\mid Z)^2\\&=\mathsf E(X^2)\cdot Z^2-\mathsf E(X)^2\cdot Z^2\\&=\mathsf{Var}(X)\cdot Z^2\\&=64\,Z^2\end{align}$$

why is there a coefficient $Z$ now when previously we just had a number?

Previously you were conditioning on the event of $Z$ being a specified value.  Here you are conditioning over the random variable $Z$ being an unspecified value (it may be whatever it may be). These are related concepts.
So $\mathsf {Var}(Y\mid Z{=}0)~{=\left.64\, Z^2\right\rvert_{\small Z=0}\\=0}\\\mathsf {Var}(Y\mid Z{=}1)~{=\left.64\,Z^2\right\rvert_{\small Z=1}\\=64}$

Thus $\mathsf E(\mathsf{Var}(Y\mid Z))~{=64\,\mathsf E(Z^2)\\=64\cdot(0^2\cdot 0.45+1^2\cdot 0.55)\\=35.2}$
And $\mathsf{Var}(\mathsf{E}(Y\mid Z))~{=\mathsf{Var}(8\,Z)\\=64\cdot(0.55(1-0.55))\\=15.84}$
Answer: It might be more clear to write it out as: $E_Y[Y\mid Z = 0]=\operatorname{Var}_Y[Y\mid Z = 0]=0$ and $E_Y[Y\mid Z = 1]= E_X[X] = 8 $ and finally:
$$\operatorname{Var}_Y[Y\mid Z = 1]=\operatorname{Var}_X[X] = 64$$
What we really want is $\operatorname{Var}[Y] = \operatorname{Var}[Y]=E[\operatorname{Var}[Y\mid Z]]+\operatorname{Var}[E[Y\mid Z]]$. This is just $\mathbb{E}[64Z] + \operatorname{Var}[8Z]$ which can be evaluated with what you have above.
$Z$ appears in the conditional expectation since when you condition on $Z$, you treat it as a constant.
Comment: The Law of Total Variance is: $\mathsf{Var}(Y)=\mathsf E(\mathsf{Var}(Y\mid Z))+\mathsf{Var}(\mathsf E(Y\mid Z))$.


Simple test always failing for custom module

Question: I am trying to implement simple test for my custom module. But the test case always failing for user login. In the test script what I am trying to test is whether admin page is loading properly without any errors.
I am following similar code from core modules and other contributed modules. But couldn't figureout what I am missig in mine. My test script is given below:
<?php

/**
 * @file
 * Test file for custom_module module.
 */

/**
 * Default test case for the custom_module module.
 *
 * @ingroup custom_module
 */
class MyCustomModule extends DrupalWebTestCase {

  /**
   * {@inheritdoc}
   */
  public static function getInfo() {
    return array(
      'name' => 'My Custom Module Test Case',
      'description' => 'Functional test for My Custom Module Module',
      'group' => 'My Custom Module',
    );
  }

  /**
   * {@inheritdoc}
   */
  function setUp() {
    parent::setUp('custom_module');

    $permissions = array(
      'access administration pages',
      'administer custom module',
    );
    $this->admin_user = $this->drupalCreateUser($permissions);
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Test site working properly after installs the module.
   */
  function testCustomModulePageLoads() {
    $paths = array(
      '/admin/config/custom_module/manage',
    );
    foreach($paths as $path) {
      $this->drupalGet($path);
      $this->assertResponse(200, '200 response for the path ' . $path);
    }
  }

}

Result:
Comment: The user probably needs the 'access administration pages' permission as well
Comment: Thanks @Clive, I updated my code. But no difference, getting same result.
Comment: Sorry, my answer was for D8.
Comment: Could you provide the first Verbose message in that list? And also, are the code lines reported in the screenshot in sync with the code you provided? How much memory do you have assigned to your Drupal? And what does the error log shows for the "Parsed page successfully" failure?
Comment: Are you using an install profile on the site in which you are running the tests?
Answer: Try calling $this->setUp(); from the testCustomPageLoads() function.
Comment: I tried.. still not working.
Answer: With the info given here, it's essentially impossible to say what's wrong.
The code you have provided and test results doesn't match. It says user creation happens on line 36 and user login happens on line 43/44 but this not what the code says.
Also it's worth noting that you are getting 500 response (internal server error) and invalid HTML meaning something fundamentally is failing in your tests. It's not possible to say what it causing this, could be any kind of coding error on your part.
If the module works in non test scenario, most likely you have unmet dependencies, like some module/theme not being enabled which is causing errors and trouble.
Looking at the debug messages and DrupalWebTestCase::parse would be a good place to start debugging.


How to find $\angle{EAD}$ in the given figure?

Question:
(It is not a homework problem! It was asked in one of my friends' placement related entrance examination this year.)
My work: Assuming $\angle{EAD}=\angle{\mathbf{1}}=x,$ it is clear that $\angle{ODB}=x$ since $\angle{AEB}=90^\circ,$ being a semi-circular angle.
(Now if I consider $BC$ to be a tangent to the circle at $B,$ then using all the known facts we can find $\angle{ACB}$ as well as $\angle{DAO}.$ But still I am not able to find $x.$)
Although it is not mentioned that $BC$ is a tangent so considering $BC$ to be a secant, I am not able to make use of the fact that $OB=BC.$ (I think I should not consider $BC$ as a tangent.) Either way I am stuck basically.
Please give some hints to make use of the fact: $OB=BC$ for finding $x.$ Thanks in advance.
Comment: Hints: Drop the perpendicular BH of B onto line AC, with $H$ belonging to the circle: we get BH = 2 DO. Besides, use Pythagoras theorem in triangle ABC to express $AC$ as a function of $R$ (the radius of the circle).
Comment: If you don't know BC is tangent, then BC = OB gives no information to find $x$
Comment: Thank you both Jean Marie and Ivan Kaznacheyeu sir for your comments. These helped a lot for me to find $x$.
Comment: @Jean Marie Sir how did you realize that if $BF\bot AC$ is drawn then our job will be done? I mean while solving geometry problems I get confused what and where should I make a construction so that the goal is achieved. While solving this problem on my own I was thinking of a construction but wasn't really sure where to construct actually. Any tip regarding how to overcome such confusions quickly and effectively?
Comment: @Usual_Learner Please don't be discouraged by my down vote, it is not for you but for the problem. Because of its inaccurate wording, it wasted much of my time (and yours and other people's here). Please see details in my answer.
Answer:
I am assuming $BC$ is tangent to the circle as you mentioned in your work.
We have $\triangle ADO \sim \triangle ABC$
Also, $\triangle ADO \sim \triangle AFB$
Using similarity, what is the relation between $BF$ and $FD$?
Finally note that $x = \angle FBD$
Comment: @DhrubajyotiBhattacharjee $AB$ is a diameter of the circle and hence $AB$ will subtend an angle of $90^\circ$ at all points on the perimeter.
Comment: Ohh yes yes correct.. Dumb/blind me!
Comment: @Math Lover Thank you sir. Following your approach I could deduce that $BF=FD$ and hence $x=45^\circ.$
Comment: Great answer but I have one doubt which is how do we know that the foot of the perpendicular from $B$ will lie on the circle, namely at $F$?
Comment: @Usual_Learner yes that is absolutely correct.
Answer: Assuming $CB$ tangent at $B$ (see @Ivan Kaznacheyeu comment), then join $CO$.
Since $BCDO$ is a cyclic quadrilateral, and right triangle $COB$ is isosceles, then$$\angle COB=45^o$$But $$\angle CDB=\angle COB$$since they stand on common arc $CB$.
Hence$$\angle EDA=\angle CDB=45^o$$Therefore right triangle $ADE$ is also isosceles and$$\angle EAD=45^o$$
Comment: Sir one question: Which soft ware did you use to draw the figure you have given here? Although in this approach, we do not have to draw $BF\bot AC.$
Comment: I used GeoGebra for the figure, which I have edited in light of your observation that $BF$ is not used in the argument and so is unnecessary.
Comment: Wow! All of you make these problems look so easy by providing simply elegant solutions. I can't choose which answer to "accept" basically and so I won't.
Answer: I respectfully disagree with Math Lover, Edward, and OP's assumption of tangency of $BC$ to the large circle. Below, I first explain the construction, then I show with an example that the problem indeed lacks sufficient information, then I give a general guideline for solving the problem. I will conclude with remarks about the problem.
1.Construction
Reproducing the construction helps us better understand the problem. We can start from the large circle with center $O$ and radius $OA$. Let's call it the main circle.

Within the main circle, draw $Circle1$ with diameter $OA$.
From $B$ draw a line such that it intersects (or touches) $Circle1$. Let this line first meet $Circle1$ at $D$ and then meet the main circle at $E$. Already we have constructed the angles $\widehat{AEB}=\widehat{ODA}=90^o$ (why?) and the unknown angle $\widehat{EAD}$, the measure of which we wish to find.
Draw $Circle2$ with center $B$ and radius $OB$.
Extend $AD$ to meet (or touch) $Circle2$. Name the furthest meeting point of this extension as $C$.

2.Information
The above figure shows two examples of the construction. In the lower example, $BC$ is tangent to the main circle. Note that

$\widehat{EAD}$ measures differently in the two examples. This means that the problem in its current wording does not have a unique answer. Comparing the measures with the multiple choices of the problem shows that the designers of the problem had assumed that $BC$ is tangent to the main circle, but they did not mention this assumption in the problem. Therefore, the problem lacks information necessary for the intended solution.
The construction of the angle $\widehat{EAD}$ was completed without any regard to point $C$. In the problem as it is worded, especially without mentioning the constraint of tangency of $BC$ to the main circle, the information given about $BC$ and $C$ is useless.

3.General guideline
The interested reader can solve the problem using analytic geometry, and find the measure of $\widehat{EAD}$ based on $\widehat{EBA}$, which defines the slope of the line $BE$, which was arbitrarily drawn in step 2 of the construction (considering the only constraint that it should meet $Circle1$). The general steps are:

Write the equations of the main circle, $Circle1$ and $BE$
Find $D$, the intersection of $BE$ and $Circle1$.
Find $E$, the intersection of $BE$ and the main circle.
Calculate the angle between $AD$ and $AE$.

4.Conclusion
Designers of the problem failed to mention all of the assumptions that they had when designing the problem. Without the particular assumption of tangency of $BC$ to the main circle, the question has an infinite number of answers. Moreover, without this assumption, the information given about point $C$ is useless. I was only able to figure out the assumptions of the designers from the multiple choices of the question. This is an example of a bad question that wastes the time of everyone who works on it. Therefore, while I respect the efforts made by the OP, I give a down vote to the question itself. I hope my act encourages OP and other MSE members to create for themselves some sort of a blacklist of sources that are not worthy of our time and effort.
Comment: @Usual_Learner Thank you for your comment, and thanks for correcting my mistake. I edited that part of the post. Like you, I spent much time looking for a solution using Euclidean geometry. It's a pity question designers ignored required information and confused us all. But in the effort, other things were revealed. For an interesting example: draw a line passing through $B$ and the midpoint of $OC$, and let it intersect the main circle at $F$. Then $OBCF$ is a rhombus!
Comment: @ACB Oh my! Thanks for telling me, I'll edit that part. I mixed up names of MSE members that I respect! As for the circles, the two that were added to the main figure are shown with dashed lines, so as to show added components while avoiding visual complexity.
Comment: Thank you sir for giving your precious time. It was helpful and interesting indeed. I believe you typed CIRCLE 2 instead of CIRCLE 1 in step 2 under the construction section. I have understood all of your points. After seeing this problem for the first time I was pondering whether $BC$ is a tangent or some secant to the main circle and so at first I considered $BC$ as a secant and started to work with it but I didn't try to make use of my knowledge of co-ordinate geometry as a result was unable to reach any conclusion. But, your general guideline has demonstrated the same. Thanks...


Producer consumer with qualifications

Question: I am new to clojure and am trying to understand how to properly use its concurrency features, so any critique/suggestions is appreciated.
So I am trying to write a small test program in clojure that works as follows:

 there 5 producers and 2 consumers
a producer waits for a random time and then pushes a number onto a shared queue.
a consumer should pull a number off the queue as soon as the queue is nonempty and then sleep for a short time to simulate doing work
 the consumers should block when the queue is empty
 producers should block when the queue has more than 4 items in it to prevent it from growing huge

Here is my plan for each step above:

 the producers and consumers will be agents that don't really care for their state (just nil values or something); i just use the agents to send-off a "consumer" or "producer" function to do at some time. Then the shared queue will be (def queue (ref [])). Perhaps this should be an atom though?
in the "producer" agent function, simply (Thread/sleep (rand-int 1000)) and then     (dosync (alter queue conj (rand-int 100))) to push onto the queue.
 I am thinking to make the consumer agents watch the queue for changes with add-watcher. Not sure about this though..it will wake up the consumers on any change, even if the change came from a consumer pulling something off (possibly making it empty) . Perhaps checking for this in the watcher function is sufficient. Another problem I see is that if all consumers are busy, then what happens when a producer adds something new to the queue? Does the watched event get queued up on some consumer agent or does it disappear?
see above
 I really don't know how to do this. I heard that clojure's seque may be useful, but I couldn't find enough doc on how to use it and my initial testing didn't seem to work (sorry don't have the code on me anymore)
Answer: Here's my take on it. I made a point of only using Clojure data structures to see how that would work out. Note that it would have been perfectly usual and idiomatic to take a blocking queue from the Java toolbox and use it here; the code would be easy to adapt, I think. Update: I actually did adapt it to java.util.concurrent.LinkedBlockingQueue, see below.
clojure.lang.PersistentQueue
Call (pro-con) to start a test run; then have a look at the contents of output to see if anything happened and queue-lengths to see if they stayed within the given bound.
Update: To explain why I felt the need to use ensure below (I was asked about this on IRC), this is to prevent write skew (see the Wikipedia article on Snapshot isolation for a definition). If I substituted @queue for (ensure queue), it would become possible for two or more producers to check the length of the queue, find that it is less than 4, then place additional items on the queue and possibly bring the total length of the queue above 4, breaking the constraint. Similarly, two consumers doing @queue could accept the same item for processing, then pop two items off the queue. ensure prevents either of these scenarios from happening.
(def go-on? (atom true))
(def queue (ref clojure.lang.PersistentQueue/EMPTY))
(def output (ref ()))
(def queue-lengths (ref ()))
(def *max-queue-length* 4)

(defn overseer
  ([] (overseer 20000))
  ([timeout]
     (Thread/sleep timeout)
     (swap! go-on? not)))

(defn queue-length-watch [_ _ _ new-queue-state]
  (dosync (alter queue-lengths conj (count new-queue-state))))

(add-watch queue :queue-length-watch queue-length-watch)

(defn producer [tag]
  (future
   (while @go-on?
     (if (dosync (let [l (count (ensure queue))]
                   (when (< l *max-queue-length*)
                     (alter queue conj tag)
                     true)))
       (Thread/sleep (rand-int 2000))))))

(defn consumer []
  (future
   (while @go-on?
     (Thread/sleep 100)       ; don't look at the queue too often
     (when-let [item (dosync (let [item (first (ensure queue))]
                               (alter queue pop)
                               item))]
       (Thread/sleep (rand-int 500))         ; do stuff
       (dosync (alter output conj item)))))) ; and let us know

(defn pro-con []
  (reset! go-on? true)
  (dorun (map #(%1 %2)
              (repeat 5 producer)
              (iterate inc 0)))
  (dorun (repeatedly 2 consumer))
  (overseer))

java.util.concurrent.LinkedBlockingQueue
A version of the above written using LinkedBlockingQueue. Note how the general outline of the code is basically the same, with some details actually being slightly cleaner. I removed queue-lengths from this version, as LBQ takes care of that constraint for us.
(def go-on? (atom true))
(def *max-queue-length* 4)
(def queue (java.util.concurrent.LinkedBlockingQueue. *max-queue-length*))
(def output (ref ()))

(defn overseer
  ([] (overseer 20000))
  ([timeout]
     (Thread/sleep timeout)
     (swap! go-on? not)))

(defn producer [tag]
  (future
   (while @go-on?
     (.put queue tag)
     (Thread/sleep (rand-int 2000)))))

(defn consumer []
  (future
   (while @go-on?
     ;; I'm using .poll on the next line so as not to block
     ;; indefinitely if we're done; note that this has the
     ;; side effect that nulls = nils on the queue will not
     ;; be handled; there's a number of other ways to go about
     ;; this if this is a problem, see docs on LinkedBlockingQueue
     (when-let [item (.poll queue)]
       (Thread/sleep (rand-int 500)) ; do stuff
       (dosync (alter output conj item)))))) ; and let us know

(defn pro-con []
  (reset! go-on? true)
  (dorun (map #(%1 %2)
              (repeat 5 producer)
              (iterate inc 0)))
  (dorun (repeatedly 2 consumer))
  (overseer))

Comment: Beware: java queues don't handle nil values correctly so you have to replace them by a special value. See http://clj-me.cgrand.net/2010/04/02/pipe-dreams-are-not-necessarily-made-of-promises/
Comment: Updated with a version based on `java.util.concurrent.LinkedBlockingQueue` -- it's actually cleaner than the "pure Clojure" version! And the changes from the `clojure.lang.PersistentQueue`-based original were completely local to were the queue is being handled. This just goes to show how great Clojure's Java interop really is. :-)
Comment: My initial answer failed to take into account the requirement that producers take care not to overfill the queue... Corrected now.
Comment: cgrand: Thanks for the heads up on that! I guess this also means that worrying about `nil` is not a reason not to use `.poll`. (Not to say that some other solution won't be more appropriate in some scenarios, like holding on to the promises and killing them off with `future-cancel` at the end.)
Comment: Out of curiosity, for the clojure version does the queue need to be held in a ref? Because you don't co-orindate updates to the queue with anything else, isn't an atom enough for such a purpose?
Comment: @djunforgetable: It's in a ref so that it is possible to `ensure` it. See the second paragraph of the `c.l.PersistentQueue` section of the answer for a discussion. I suppose `output` could have been an atom, though.

Producer consumer with qualifications