text:
Q: Entering formula into Latex - urgent issue Good evening everyone,
would anyone please help me out with transferring this screenshot into LaTex? It would be optimal, to have the equation in the same line. I have to hand it in within the next few hours and I am not very experienced in using the required math package. It would be of great help to me. Please find the screenshot attached. Thanks a lot!
Best regards,
Michael

A: Here it is (the \otherbeta command is specific to the fourier font, to have an upright lowercase Greek letter in maths):
\documentclass{article}
\usepackage{fourier}
\usepackage{showframe}
\renewcommand{\ShowFrameLinethickness}{0.3pt}
\usepackage{amsmath}

\newcommand*{\dd}{\mathop{}\!\mathrm{d}} %% differential symbol for integrals

\begin{document}

\[ U(1,\otherbeta) = \int_{1-p}^p \max\nolimits_B\bigl\{pu\bigl(w + 1-P)B\bigr) + (1-p)u(w-PB)\bigr\}\dd M_{\otherbeta}(P) \]%

\end{document}


text:
Q: MVC 3 Ajax Loading Icon when navigating to a new page/action method I have been searching extensively on how to create a navigation link that will display an ajax Loading icon while the action method is running in MVC 3 using the Razor view engine.
While I have found plenty of information regarding adding a loading icon, all of them seem to pertain to posting data within the current view.
I have a simple menu page that has actionlinks to call action methods on other pages, which in turn will render a view. An example to go to the OrdersController and Index action method is displayed below.
Menu.cshtml
@Html.ActionLink("Orders", "Index", "Orders",null,new { id = "OrderLink" })

I am trying to modify the link above in a way that while the Index action is processing and before the view is returned, to show an ajax loading icon.
I have created a div that contains the loading icon and placed it in my shared _Layout.cshtml page.
_Layout.cshtml

To try and display the ajax loading icon I tried changing my link to an Ajax ActionLink.
Menu.cshtml
@Ajax.ActionLink("Orders", "Index", "Orders", new AjaxOptions { LoadingElementId="ajaxLoaderDiv" });

This works in the sense that it displays the ajax Loading icon for a few seconds. And I can even put a breakpoint inside the Index action method of the OrdersController and it will hit it. But when the Action Method completes, the Orders\Index.cshtml never renders to the page. I just remain on the Menu\Index.cshtml page.
I know that the Orders/Index.cshtml is supposed to be rendering a view.
OrdersController.cs
public ActionResult Index()
{
    ....

return View(OrdersViewModel);
}

What am I doing wrong here? Is this view being returned to my ajax call rather than rendering? How can I get this functionality?
If I am going about this in the wrong manner, let me know.
Should I be doing this inside the target page's action method instead of on the link when making the request? Maybe by displaying the loading icon as the first line of code in the Index action method that I am requesting, and hiding it again just before returning the view?
I would maybe try and do this through through a JQuery Show/hide combination?

Thanks in advance for and and all help and advice
Chad

A: My Resolution:
I resolved my issue on my own, but thought I would post the resolution for any others that are attempting something similar.
I kept the link on my menu.cshtml page as an @Html.ActionLink rather than an ajax link.
But I added an onclick html attribute that called the javacript to show the spinner.
menu.cshtml
@{
    ViewBag.Title = "Menu";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

        @Html.ActionLink("Orders", "Index", "Orders", null, new { id = "OrderLink", onclick="showPageLoadingSpinner()" })

I have the scipt for the spinner in my _Layout.cshtml partial view. which is referenced in my menu.cshtml view:
    Layout = "~/Views/Shared/_Layout.cshtml";
Below is my full _Layout.cshtml page including the ajax div and script references.
_Layout.cshtml

    @Content.Script("jquery-1.5.1.min.js", Url)
    @Content.Script("jquery.unobtrusive-ajax.min.js", Url)

         @RenderBody()

This works for me because on the menu.cshtml page when you click the link the javascript will run display the spinner before the actionlink sends you to the next page. Therefore you will see the spinner while the page you are navigating to is loaded.
When the new page is ready, it will render, and display.
While the new page that you are sent to (Orders/Index.cshtml) uses the same layout page which contains the ajax div, it loads the new page with the ajaxloader div property display:none set by the layout. This ends up removing the ajax spinner that was displayed while loading the page.
Therefore there is no need to ever call the javascript to hide the spinner because it is always removed when the new page renders.
Unless someone else tells me that this is an inappropriate approach and successfully show me a better way, I am going to accept this as the answer.

A: Change your action method signature to something like this:
public PartialViewResult Index()
{
    ....

return PartialView(OrdersViewModel);
}

Also, for the Ajax.ActionLink to work properly, you need to add a reference to unobtrusive ajax:
Obtainable via nuget unless it's not in your scripts folder.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How i can concat one date with a string when i pass a property to a component with a pipe? I'm using one component of kendoUi that i need to pass in the property [title] my variable local.localNome (string) and local.LocalDataCadastro (Date with a pipe)
I try something like:
<kendo-panelbar-item *ngFor="let local of locaisList" [title]="local.LocalCadastroData | date + local.LocalNome">

But this way i receive:

Unexpected token '+' at column 32 in [local.LocalCadastroData | date +
  local.LocalNome]

How i can use my two variables in the [title] property with a pipe date?

A: Use parentheses.
<kendo-panelbar-item *ngFor="let local of locaisList"
    [title]="(local.LocalCadastroData | date) + local.LocalNome">

A: try putting date and local.LocalNome in brackets so that it executes it as JS.
<kendo-panelbar-item *ngFor="let local of locaisList" [title]="local.LocalCadastroData | {{date + local.LocalNome}}">

A: You can put the local.LocalCadastroData | date into the parentheses before the concatenation.
Like so:
<kendo-panelbar-item *ngFor="let local of locaisList" [title]="(local.LocalCadastroData | date) + local.LocalNome">

It would be better and more readable to add a formatting function in your component and pass in the local:
Template:
<kendo-panelbar-item *ngFor="let local of locaisList" [title]="getTitle(local)">

Component:
@Component({})
export class YourComponent {
  getTitle(local) {
    return formatDate(local.LocalCadastroData) + local.LocalNome;
  }

  private formatDate(date: Date) {
    // Format the date using custom code / existing libraries like moment.js
    return date.toDateString();
  }
}


text:
Q: Querying for a blank answer - lack of a row in a table I have a form that users fill out when a patient gets transferred to another location.
The relevant part of the form looks like this:

I want to count the number of patients that have a no Date of Return.
Relevant tables -
form_names - list of forms
select id, name from form_names where id = 47

id    name
----- ----------------------
47    Transfer of Health Information

form_items - listing of the questions for each of the form (form_name).
select id, form_name, text from form_items where form_name = 47

id          form_name   text
----------- ----------- ------------------------------------
1147        47          Date of Transfer:
1148        47          Sending Facility:
1155        47          Date of Return:

form_records - a record stating that a particular patient (pid) filled out a form (form_name).
select id, pid, date, form_name From form_records where pid = 260 and form_name = 47

id          pid         date                    form_name
----------- ----------- ----------------------- -----------
16409       260         2013-04-24 09:33:29.000 47

Now, the last relevant table is the form_answers table. Only completed answers will be populate in this table.
As you can see, since the Date of Return value was never filled out in the form, it never will be in this table:
select id, form_record, form_item, text from form_answers where form_record = 16409

id                   form_record form_item   text
-------------------- ----------- ----------- -----------------------------------------
354535               16409       1147        04-24-2013
354536               16409       1148        Lawrence Jail
354537               16409       1149        Lawrence County Hospital
354538               16409       1151        NKMA

I've tried something like this, and it doesn't work:
select
        count(*)
from
        form_names fn
                inner join form_items fi on fn.id = fi.form_name
                inner join form_records fr on fn.id = fr.form_name
                left outer join form_answers fa on fr.id = fa.form_record and fi.id = fa.form_item
where
        fn.name like '%Transfer of Health Information%'
        and dateadd(dd, 0, datediff(dd, 0, fr.date)) = dateadd(dd, 0, datediff(dd, 0, getdate()))
        and fi.text like '%receiving facility%'
        and fa.id is NULL

How do I find a count of patients that have NO Date Returned field

A: I think the join on the answer is not correct.  You need to join both to the item and to the fr.id:
select count(*)  -- should this be "count(distinct pid)"?
from form_names fn inner join
     form_items fi
     on fn.id = fi.form_name inner join
     form_records fr
     on fn.id = fr.form_name left outer join
     form_answers fa
     on fn.id = fa.form_item and fa.form_record = fr.id
where fn.name like '%Transfer of Health Information%'
      fn.text like '%Date of Return%' and
      dateadd(dd, 0, datediff(dd, 0, fr.date)) = dateadd(dd, 0, datediff(dd, 0, getdate())) and
      fi.text like '%receiving facility%' and
      fa.id is NULL;

You query failed because some other form was satisfying the condition.
By the way, I find it much easier to have foreign keys match the name of the primary key.  Barring that, foreign keys should be the name of the table followed by _id or Id.


text:
Q: What does 'back' mean in this context?
Half the Muggles killings back when You-Know-Who was in power were done for fun.

I figure that the word 'back' here is used as an adverb meaning "in the past". The sentence can be rephrased as: In the past when You-Know-Who was in power, half the Muggles killings were done for fun.
But I'm not quite sure if my understanding correct?

A: The word "back" in this case is being used in accordance with definition 1b in the Merriam-Webster's entry for "back" as an adverb:

in or into the past : backward in time

So you are correct; it is saying that when You-Know-Who was in power, which was in the past, half of the Muggle killings were done for fun. The exact way you rephrased it, though, may be slightly off on the nuances. Since you started off with "In the past" it might convey that you are speaking about the past in general, and then specifying a particular point in the past — namely, when You-Know-Who was in power. But the way the sentence was originally phrased it does not include any implications of the past in general; it is referring directly to the specific time when You-Know-Who was in power.


text:
Q: Away3d Camera Path How to know the coordinates of the path if you know the azimuthal angle. I wanna move my camera around an object in away 3d.

A: Move camera in Spherical coordinate system by Interpolating from  starting  azimuthal angle to target - it will be your trajectory.
You can convert from\to Cartesian coordinate system to retrive\pass current coordinate to away3d renderer.
You all so may want to use non-linear camera acceleration(for more realistic feel) it can be implemented with Bézier curves
PS. I will be thankful if your publish you realisation because i will need this functional in my next project. You will save me a lot of time :)
Or just use translation and rotation methods that camera inherits from Object3D  it's all covered in Away3D example projects. Allso Away3D has path helper package


text:
Q: SQL how to extract middle of string I want to only get the unit number out of this string:
'
The status for the Unit # 3546 has changed from % to OUTTOVENDOR
'

The note is always exactly the same but the unit number changes. How do I extract just the unit number?
Thanks!

A: declare @String varchar(500)

set @String = '
The status for the Unit # 3546 has changed from % to OUTTOVENDOR
'

select SUBSTRING(@String, charindex('# ', @String) + 2, charindex('has changed', @String) - charindex('# ', @String) - 2)

A: try:
  declare @S VarChar(1000)
  Set @S =
  '
The status for the Unit # 3546 has changed from % to OUTTOVENDOR
'
  Select Substring( @s,
         charIndex('#', @S)+1,
         charIndex('has', @S) - 2 - charIndex('#', @S))

A: You could do this any number of ways, use the REPLACE function to strip out either side, use SUBSTRING if you are guaranteed to know index numbers or mix a SUBSTRING with a CHARINDEX.

A: select substring(note, len('
The status for the Unit # '),4) from tbl

A: Something like this should work SUBSTRING(val, 30, CHARINDEX(' ', val, 30)-30)

A: Here's a version that uses PATINDEX.  It looks for the first number in a string.
declare @MyString varchar(100)
set @MyString = '
The status for the Unit # 3546 has changed from % to OUTTOVENDOR
'

select PATINDEX('%[0-9]%', @MyString), PATINDEX('%[^0-9]%', SUBSTRING(@MyString, PATINDEX('%[0-9]%', @MyString), len(@MyString)))

select SUBSTRING (@MyString, PATINDEX('%[0-9]%', @MyString),
    PATINDEX('%[^0-9]%', SUBSTRING(@MyString, PATINDEX('%[0-9]%', @MyString), len(@MyString))))


text:
Q: Twilio Not doing anything when receiving SMS I'm creating a sample application that will post alerts to the website in the event of a hurricane or service outage. I'm not using Laravel.
I set the URL of the page in my account settings. The first time I sent a message I received a HTTP error that it had timed out without being given a reponse. I edited the XML and tried again.
I'm not getting anything in the database and I'm not getting the response. I also wrote a sample page that posts a value to see if it would work and it did. It posted it into the database and showed correctly formatted XML.
<?php
$response = 'This number cannot handle automated replies...';
$twiml1 = '<response><sms>';
$twiml2 = '</sms></response>';
require_once '../settings/db.php';
if (isset($_POST['body'])) {
    $body = strip_tags($_POST['body']);

    $sql = "INSERT INTO alerts (message) VALUES ('$body')";
    $result = $db->query($sql);
    if ($result) {
        $response = 'Thanks. Your message was posted on the website.';
    } else {
        $response = 'There was a query error.';
    }

}
header('Content-type: application/xml');
echo $twiml1;
echo $response;
echo $twiml2;

A: Twilio developer evangelist here.
Parameters that are sent via webhooks from Twilio are case sensitive and start with a capital letter. The text for an incoming message is sent as the Body parameter so checking for $_POST['body'] won't work.
I'd update your conditional to:
if (isset($_POST['Body'])) {
    $body = strip_tags($_POST['Body']);

    // The rest
}

Also, just to note, the <Sms> element has been deprecated. I'd use the <Message> element instead. The tags are case sensitive too, so I'd update the TwiML section to this:
$twiml1 = '<Response><Message>';
$twiml2 = '</Message></Response>';

Let me know if that helps at all.


text:
Q: Is there a way to touch() a file in Amazon S3? I'm currently working with Amazon S3 and I am writing a program that uses the modified dates. I'm looking for a way to edit the modified dates.
I could loop trough all the files and save them as they are, but this sounds like a bad solution.
In PHP there is this function touch().
Does anyone know a solution, or has the same problem?

A: Here is another whay to upload a null (or o Byte) file to S3. I verified this works You can also use the S3 API to upload a file with no body, like so:
aws s3api put-object --bucket "myBucketName" --key "dir-1/my_null_file"

Normally you would specify a --body blob, but its option and will just add the key as expected. See more on S3 API put-object
The version of AWS CLI tested with is: aws-cli/2.0.4 Python/3.7.5 Windows/10 botocore/2.0.0dev8
Here's how I did it in PHP (even works in outdated 5.4, had to go way back):
// Init an S3Client
$awsConfig = $app->config('aws');
$aws       = Aws::factory($awsConfig);
$s3Bucket  = $app->config('S3_Bucket');
$s3Client  = $aws->get('s3');

// Set null/empty file.
$result = $s3Client->putObject([
    'Bucket' => $s3Bucket,
    'Key' => "dir-1/my_null_file",
    'Body' => '',
    'ServerSideEncryption' => 'AES256',
]);

A: I find myself performing the copy trick pretty often when testing, to the extent that I've added a handy function to my .bashrc:
s3-touch() {
  aws s3 cp \
    --metadata 'touched=touched' \
    --recursive --exclude="*" \
    --include="$2" \
    "${@:3}" \
    "$1" "$1"
}

Example usage:
# will do a dryrun on a copy operation
s3-touch s3://bucket/prefix/ "20200311*" --dryrun

# the real thing, creating events for all objects
# in s3://bucket/prefix/ that start with 20200311
s3-touch s3://bucket/prefix/ "20200311*"

I'm doing this mainly for the S3-events that I want to trigger.

A: In response to @Daniel Golden's comment on @tkotisis answer. It looks like at least the AWS CLI tools do not let you copy an item on to itself.  You can however 'force' a copy by updating the metadata.
$ aws s3 cp --metadata '{"touched":"now"}' s3://path/to/object s3://path/to/object

This recreates the object (downloads to the caller and reuploads it) replacing its content, owner and metadata. This will also trigger any attached Lambda events.

A: You can achieve the same through a copy object request, specifying the CopySource to be same as the target key.
In essence, this will issue a PUT Object - COPY request to S3 with the corresponding source and target bucket/key.

A: Following @g-io answer that simplified my day, here is another version of the same that makes it easy to touch a single file
s3-touch-single() {
  aws s3 cp \
    --metadata 'touched=touched' \
    "${@:3}" \
    "$1" "$1"
}

for example, looping an array of files we need to touch:
paths=("mydir/image.png" "mydir2/image2.png")
for i in "${paths[@]}"; do s3-touch-single "s3://my-bucket/$i"; done

A: check out https://github.com/emdgroup/awscli-s3touch
It's a plugin to the AWS CLI that adds a touch command.
Usage:
aws s3 touch my-bucket --prefix myfolder/

It works by reading the events attached to the bucket and simulating them client side.


text:
Q: Azure DevOps When Work Items Meet Iterations Is there a field that exposes WHEN a work item is assigned to its current iteration?
Seems like a pretty basic thing one might like to know, but I can't seem to find it anywhere. Can someone point me in the right direction?

A: There is No field that exposes when a work item is assigned to its iteration.
If you want to see this value, you can go to the page of the work item.

And then click "History". What you need to find is the record of the latest iteration update.

Of course, you can also get this value through the REST API:
GET https://dev.azure.com/{organization}/{project}/_apis/wit/workItems/{id}/updates

But just like getting it by website, you need to spend some time looking for this value, and you can't apply it to queries.
If you really need a field that exposes when a work item is assigned to its iteration. You can create a new process that inherits from your current process and change the process of your project. Click this document for detailed steps.
And then, add a new field to show the latest updates of iteration. Click this document for detailed steps.
This way you can treat the iteration change time as a real field. However, the defect is that when you make changes to an iteration, you need to manually change the value of this field.


text:
Q: Select from sub list only with children() The HTML:

One

Two

New list

New one

New Two

Third list

Third one

Third two

What I want to do: All sub lists with class of "hide_list" are hidden with CSS. When I click on li that contains the hidden list, I would like that hidden list to toggle open/close.
My jquery code:
$('.list_folder').on('click',function(){
    $(this).children('.hide_list').slideToggle();
}

The issue: it works on first sub list, but when I click on next sublist deeper it will select the next deeper list and also the outer lists, and in result the whole list will collapse.
What am i doing wrong? Any suggestions?

A: $('.list_folder').on('click',function(e){
    e.stopImmediatePropagation();
    $(this).find('.hide_list:first').slideToggle();
});

DEMO
Note
You don't need to use .children(), .find() will accomplish your job.

.stopImmediatePropagation() keeps the rest of the handlers from being
executed and prevents the event from bubbling up the DOM tree.

Read more about .stopImmediatePropagation()

A: your function is right. you have to add one more line event.stopImmediatePropagation().
$('.list_folder').on('click',function(event){
  /* add one more line */
  event.stopImmediatePropagation();
  $(this).children('.hide_list').slideToggle();
}


text:
Q: Hide Command Line when running a Ruby Program I recently finished my game for my AP Computer Science AB Final (if you know GIT and Git Bash and have ruby installed, you can clone the game here: https://github.com/gerberhe/Final_Game).
I made a shortcut called "Final Game", that when I double-click on it, it runs my game. This works fine with the code I used to do this, and it opens my game in a Gosu window.
However, double-clicking/running this shortcut file ALSO opens a blank command prompt/cmd window that does nothing, shows nothing, and just closes as soon as I close the game.
Question is, is there any code or any way I can make it so that when I run this shortcut file, the game appears, but the cmd line that also opens is hidden, or simply just doesn't open?
This isn't necessary, but would make the game seem a bit more professional and aesthetically pleasing. Thanks!
Also, if you decide to try the game, note that there are some bugs with it currently that I am planning on fixing, but that aren't necessary to the fluidity and work ability of the game.
Thanks again!

A: I'm having trouble dissecting the .lnk file, but I believe you can simulate what you want in the command line by running
ruby main.rb &

instead of ruby main.rb. Once you have that, I think you can create a .bat file with the above line and it should run correctly.
Explanation:
The common reason the command prompt runs is because the command prompt is actually running the game inside itself and waiting for you to finish before completing the "run the game" script. The & says "run the game outside of this command prompt (inside a new thread)". Then after creating the new thread, it sees that it has finished execution of the script and closes itself, leaving your game to run on it's own.

A: You can try forking in/around your main function.
That way it process will finish and release the shell but the new forked process will continue until terminated from the GUI.


text:
Q: Unpacking iterable in Python extension I'm trying to translate a, b, c, d = iterable to Python's C/API.
I'm looking for a function similar to PyArg_ParseTuple, just for iterables.
In other words, something in the area of PyIter_Parse or PyObject_ParseIterable, if such functions would have existed.
Any tips how to implement it?

A: No, there is no helper function that can do this for you.
You'd have to use PyIter_Next() up to max times to retrieve values, raise an exception when you can't get at least min values, and then just build a tuple from that.
Something like (untested, largely pilfered from PySequence_Tuple()):
int
PyIter_LimitedTuple(PyObject *v, Py_ssize_t min, Py_ssize_t max)
{
    PyObject *it;  /* iter(v) */
    PyObject *result = NULL;
    Py_ssize_t j;

    it = PyObject_GetIter(v);
    if (it == NULL)
        return NULL;

    /* allocate space. */
    result = PyTuple_New(max);
    if (result == NULL)
        goto Fail;

    /* Fill the tuple. */
    for (j = 0; ; ++j) {
        PyObject *item = PyIter_Next(it);
        if (item == NULL) {
            if (PyErr_Occurred())
                goto Fail;
            break;
        }

        if (j > max) {
            PyErr_Format(PyExc_ValueError,
                "too many values to unpack");
            goto Fail;
        }

        PyTuple_SET_ITEM(result, j, item);
    }

    if (j < min) {
        PyErr_Format(PyExc_ValueError,
            "need more than %d value to unpack",
            j);
        goto Fail;
    }

    /* Cut tuple back if fewer than max items were available. */
    if (j < max &&
        _PyTuple_Resize(&result, j) != 0)
        goto Fail;

    Py_DECREF(it);
    return result;

Fail:
    Py_XDECREF(result);
    Py_DECREF(it);
    return NULL;
}

then pass the resulting tuple to PyArg_UnpackTuple().


text:
Q: Jquery/JavaScript runs locally, but not on server I made a PHP form that has jquery inside, for input mask and a Postal code search.
On my local machine, it runs fine. But once i send to my server via FTP, it doesn't.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.mask/0.9.0/jquery.mask.min.js"></script>

A: JavaScript must be loaded first, and with the site you listed, I can see that the http (cloudflare) should be https ...
Try ...
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/0.9.0/jquery.mask.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

Here's the error on the http:

Mixed Content: The page at
  'https://ssl5929.websiteseguro.com/sbpsp2/psicorreio/emailmarketing/2015/teste/ficha_inscricao.php'
  was loaded over HTTPS, but requested an insecure resource
  'http://cdnjs.cloudflare.com/ajax/libs/jquery.mask/0.9.0/jquery.mask.min.js'.
  This request has been blocked; the content must be served over HTTPS.

A: try this:

Error: Bootstrap's JavaScript requires jQuery
  https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js
  Line 6

Error Says JavaScript requires jQuery
So you Need to run Jquery First
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.mask/0.9.0/jquery.mask.min.js">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->


text:
Q: fullpage.js incompatibility issue with mobile.js and camera.js while I was trying to setup an image gallery I encountered an issue when calling camera.js (here) and mobile.js (here) along with fullpage.js [(by Alvaro Trigo)]. The problem is that whenever I click on any of the hyperlinks in the top navbar, they just won't work. There's one that does though, but it redirects to another page instead of a section. It works perfectly fine without the gallery's scripts, and when imported, it all works except of the above. Can anyone help me out here?
Thanks in advanced.
Just in case, here's my navbar code:

Inicio

Qué es Rien Pipe

Descripción de Rien Pipe

La diferencia

Mecanismo

Quiénes somos

Preguntas frecuentes

Testimonios

Contacto

Hacer un pedido

and the gallery section:

A: It sounds like you are not initializing your other plugins inside the afterRender callback as detailed in fullpage.js documentation:

afterRender()
This callback is fired just after the structure of the page is generated. This is the callback you want to use to initialize other plugins or fire any code which requires the document to be ready (as this plugin modifies the DOM to create the resulting structure).

 $.fn.fullpage({
        afterRender: function(){
            //your plugins initialization here
            alert("The resulting DOM stucture is ready");
        }
 });


text:
Q: Understanding the CDF of the Exponential from the PDF? I was trying to get the CDF of the exponential through the pdf. I know that the relationship between the pdf and the cdf is that the pdf is the derivative $ \lambda \exp(-\lambda x) $. But I don't quite understand how the CDF is then $ 1 - \exp(-\lambda x) $.
When I tried to find the cdf I only put it as $\exp(-\lambda x)$. My guess is that this has something to do with the bounds of integration that I'm overlooking. Thank you for any help you can give!

A: The pdf is the derivative of the CDF, not the other way around. If you want to find the CDF, you integrate the pdf. You might have made the mistake when evaluating $\exp(0)$ and when accounting for a negative sign.
If $X \sim Exp(\lambda)$.
\begin{align*}
P(X \leq x) & = \int_0^{x} \lambda\exp(-\lambda y) \, dy\\
& = \lambda \int_{0}^{x}\exp(-\lambda y) \, dy\\
& = \dfrac{\lambda}{\lambda}  \left[ -\exp(-\lambda x) \right]^{x}_{0}\\
& = \exp(0) - \exp(-\lambda x)\\
& = 1 - \exp(-\lambda x).
\end{align*}


text:
Q: List of labels does not display in Picture Box I have a problem with Labels in VisulaStudio.
The version of VisualStudio I use is 2012.
The problem is, I need to show a grid and label the lines. The code I wrote seams identical to the solution of a similar problem here. It doesn't give me any compiler errors, but the labels still do not display in the pictureBox.
private void aResize()
{
       Size clientSize = this.ClientSize;
       int hToDraw, wToDraw;
       hToDraw = clientSize.Height - 2 * marginOfTab;
       wToDraw = clientSize.Width - 2 * marginOfTab;
       tabControl1.Size = new Size(wToDraw, hToDraw);
       piB1.Size = new Size(wToDraw, hToDraw);
       piB1.Image = new Bitmap(piB1.Size.Width, piB1.Size.Height);
       using (Graphics g = Graphics.FromImage(piB1.Image))
       {
           g.FillRectangle(new SolidBrush(Color.LightGray), 0, 0, W, H);
           Pen gridPen = new Pen(Color.White, 1f);
           int hDrawingStep = hToDraw / 10 -1;
           int wDrawingStep = wToDraw / 10 -1;
           for (int local = 1; local < 11; local++)
           {
           g.DrawLine(gridPen, 0,  hDrawingStep*local, wToDraw, hDrawingStep*local);     //horizontal axix
           g.DrawLine(gridPen, wDrawingStep*local, 0, wDrawingStep*local , hToDraw);     //vertical axis
           Label localLabel = new Label();
           localLabel.Name = "la" + local;
           localLabel.Visible = true;
           localLabel.Text = (local*100).ToString();
           localLabel.Location = new Point((int)local*hDrawingStep, (int)10);
           labelList.Add(localLabel);
           }
       }
}

All variables which are not declared in the code above are declared earlier. I didn't want to paste in too much. Thanks for any suggestion.

A: You don't set any parent for your localLabel, so how could it be rendered? Try this right before adding your localLabel to your labelList:
//...
localLabel.Parent = piB1;
labelList.Add(localLabel);


text:
Q: subprocess.Popen will not run my python program So I tried making a launcher for a text games that I am making and I need the launcher to run a part of the game based on what expansions I picked. However, after creating the launcher and testing it, I realised that everything works fine up until the part where the launcher is supposed to execute another python program. Instead of executing the program, it just ends and I am not sure why. Here is my code:
import easygui as e
import os
import subprocess
def Launch():
    expansions = []
    file = open("dlc.txt")
    reading = True
    while reading == True:
        temp = file.readline().strip()
        if temp == "":
            reading = False
        elif temp == "The Forgotten Lands":
            expansions.append("The Forgotten Lands (Main Game)")
        else:
            expansions.append(temp)
    game = e.choicebox("Welcome to The Forgotten Lands launcher. Please pick an expansion.","Launcher",choices=expansions)
    if game is None:
        os._exit(0)
    else:
        if game == "The Forgotten Lands (Main Game)":
            game = "The Forgotten Lands"
        dir_path = os.path.dirname(os.path.realpath(__file__))
        filepath = (dir_path + "/" + game + "/" + game + ".py")
        filepath = filepath.replace("/", "\/")
        filepath = filepath.replace("/", "")
        subprocess.Popen(filepath, shell=True)

Launch()

A: It should be:
subprocess.Popen("python " + filepath, shell=True)

If that doesn't work, would you be able to put the output of the code please?


text:
Q: How do I redirect to the login page in a AJAX Form (Ajax.BeginForm)? In MVC, how can I properly handle a page time out in an AJAX Form.  Currently when submitting an AJAX Form, the DOM of the AJAX form is replaced by the login page content.  I would like to redirect the entire page to the Login page.
I have an ASP.Net MVC application with a Partial Form inside an Ajax form (AJAX.BeginForm).  The application is using Windows Form Authentication.  Normally when the website times-out, you are correctly redirected to the Login page.  However when the AJAX Form submits and the website has timed-out, MVC returns the Login page as the content of the AJAX Form.  The Controller action method is never reached.  I have tried JQuery.load with the same result.
Controller
    public ActionResult Index()
    {
        ViewData["Now"] = DateTime.Now.ToString("HH:mm:ss");
        return View("Index");
    }
    public ActionResult AjaxTimeout()
    {
        ViewData["Now"] = DateTime.Now.ToString("HH:mm:ss");
        return PartialView("AjaxTimeout");
    }

Timeout.aspx
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<html>
<head>
<script src="/Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
</head>
<body>
    Parent page:
    <div id="ajaxtimeout" style="height:300px; width:300px;">
    <%= Html.Partial("AjaxTimeout") %>
</div>
</body>
</html>

AjaxTimeout.ascx
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<% using (Ajax.BeginForm("AjaxTimeout", new AjaxOptions { UpdateTargetId = "ajaxtimeout"})) { %>
    Return Time: <%= ViewData["Now"] %>
    <input type="submit" value="Submit" />
<% } %>

A: I don't use the Microsoft scripts for our apps, as we generally use jQuery for everything, so this solution will need to be investigated for your specific case, but here's how I solve it.
Whenever I have an ajax enabled app, I use a wrapper around jQuery's $.ajax function to make all my ajax requests with.  Inside the wrapper method, before it returns the response to the code that made the ajax request, it specifically checks for a 401 response to see if the authentication timed out.  If so, it just causes the whole window to do a redirect to the login page.
// The error handler for the ajax request.
            error: function (objXHR, status, errorThrown) {
...
                // Redirect to login if the ajax request returned a 401
                if (objXHR.status == "401") {
                    window.location.reload();
                    return;
                }
...
            }

If you can add an error handler to the Microsoft version of the ajax calls, you can probably do something similar.


text:
Q: MassTransit RabbitMq scheduling messages not sent to consumer I want to use MassTransit + RabbitMq bus for scheduling message from the bus. I write two C# console application, one for messages creator and send messages to schedular, and other for message consumer.
the following code for scheduling in the bus, so that send message to the scheduler one per second and then the scheduler send to consumer with 10 seconds delay. My problem is that No message is sent to the consumer or the consumer queue in rabbitMq client. Where is my mistake?
Note: UseInMemoryScheduler work fine but UseMessageScheduler doesn't work.
Bus message creator
class Program
{
    public static void Main(string[] args)
    {
        MainAsync(args).GetAwaiter().GetResult();

        Console.ReadKey();
    }

    static async Task MainAsync(string[] args)
    {
        var busControl = Bus.Factory.CreateUsingRabbitMq(rabbit =>
        {
            var host = rabbit.Host(new Uri("rabbitmq://localhost:5672"), settings =>
            {
                settings.Username("guest");
                settings.Password("guest");
            });

            //rabbit.UseInMemoryScheduler(); // This works
            rabbit.UseMessageScheduler(new Uri("rabbitmq://localhost/quartz"));// This doesn't work,
        });

        busControl.Start();

        var sendEndpoint = await busControl.GetSendEndpoint(new Uri("rabbitmq://localhost/quartz"));

        for (int i = 0; i < 1000000; i++)
        {
            await sendEndpoint.ScheduleSend(new Uri("rabbitmq://localhost/publisher"),
                DateTime.Now.AddSeconds(10),
                new MessageCreated()
                {
                    Text = $"message {i}"
                });

            Thread.Sleep(1000);
        }

        Console.ReadKey();

        busControl.Stop();
    }
}

message consumer.
class Program
{
    static void Main(string[] args)
    {
        var busControl = Bus.Factory.CreateUsingRabbitMq(rabbit =>
        {
            var host = rabbit.Host(new Uri("rabbitmq://localhost:5672"), settings =>
            {
                settings.Password("guest");
                settings.Username("guest");
            });

            rabbit.ReceiveEndpoint(host, "publisher", conf =>
            {
                conf.Consumer<Consumer>();
            });
        });

        busControl.Start();
        Console.ReadKey();
        busControl.Stop();
    }
}

public class Consumer : IConsumer<MessageCreated>
{
    public Task Consume(ConsumeContext<MessageCreated> context)
    {
        MessageCreated message = context.Message;
        Console.WriteLine(message.Text);

        context.Publish(new MessagePublished
        {
            Text = message.Text,
        });

        return Task.FromResult(context.Message);
    }
}

UPDATED
Based on @maldworth answer I changed my code for the following. But problem not solved.
class Program
{
    public static void Main(string[] args)
    {
        MainAsync(args).GetAwaiter().GetResult();

        Console.ReadKey();
    }

    private static async Task<IScheduler> CreateSchedulerAsync()
    {
        var schedulerFactory = new StdSchedulerFactory();

        var scheduler = await schedulerFactory.GetScheduler();

        return scheduler;
    }

    static async Task MainAsync(string[] args)
    {
        var busControl = Bus.Factory.CreateUsingRabbitMq(async cfg =>
        {
            var host = cfg.Host(new Uri("rabbitmq://localhost:5672"), settings =>
            {
                settings.Password("guest");
                settings.Username("guest");
            });

            var scheduler = await CreateSchedulerAsync();

            cfg.ReceiveEndpoint("quartz", e =>
            {
                cfg.UseMessageScheduler(e.InputAddress);

                e.Consumer(() => new ScheduleMessageConsumer(scheduler));
                e.Consumer(() => new CancelScheduledMessageConsumer(scheduler));
            });

            cfg.ReceiveEndpoint(host, "publisher", conf =>
            {
                conf.Consumer<PublisherConsumer>();
            });

            cfg.ReceiveEndpoint(host, "subscriber", conf =>
            {
                conf.Consumer<SubscriberConsumer>();
            });
        });

        busControl.Start();

        for (int i = 0; i < 1000000; i++)
        {
            var text = $"message {i}";

            Console.WriteLine($"Schedule: {text}");

            await busControl.ScheduleSend(new Uri("rabbitmq://localhost/publisher"),
                DateTime.Now.AddSeconds(30),
                new ScheduleMessage()
                {
                    Text = text
                });

            Thread.Sleep(10000);
        }

        Console.ReadKey();

        busControl.Stop();
    }
}

public class PublisherConsumer : IConsumer<ScheduleMessage>
{
    public Task Consume(ConsumeContext<ScheduleMessage> context)
    {
        Console.WriteLine($"In Publisher: {context.Message.Text}");

        context.Publish(new PublishMessage
        {
            Text = context.Message.Text,
        });

        return Task.FromResult(context.Message);
    }
}

public class SubscriberConsumer : IConsumer<PublishMessage>
{
    public Task Consume(ConsumeContext<PublishMessage> context)
    {
        Console.WriteLine($"In Subscriber: {context.Message.Text}");

        return Task.FromResult(context.Message);
    }
}

And App.config file content is:
  <configSections>
    <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
    </startup>
    <quartz>
      <add key="quartz.scheduler.instanceName" value="MassTransit-Quartz" />
      <add key="quartz.scheduler.instanceId" value="AUTO" />
      <add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz" />
      <add key="quartz.threadPool.threadCount" value="4" />
      <add key="quartz.jobStore.misfireThreshold" value="60000" />
      <add key="quartz.serializer.type" value="binary" />
      <add key="quartz.jobStore.type" value="Quartz.Impl.AdoJobStore.JobStoreTX, Quartz" />
      <add key="quartz.jobStore.useProperties" value="false" />
      <add key="quartz.jobStore.driverDelegateType" value="Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz" />
      <add key="quartz.jobStore.clustered" value="true" />
      <add key="quartz.jobStore.tablePrefix" value="QRTZ_" />
      <add key="quartz.jobStore.dataSource" value="quartzDS" />
      <add key="quartz.dataSource.quartzDS.connectionString" value="Server=.;Database=QuartzDB;Integrated Security=SSPI" />
      <add key="quartz.dataSource.quartzDS.provider" value="SqlServer" />
    </quartz>

A: You're almost there, just update the logic with this:
busControl.Start();
scheduler.JobFactory = new MassTransitJobFactory(busControl);
scheduler.Start().Wait();

Console.ReadKey();
busControl.Stop();

A: So you don't mention if you have a 3rd consumer running (in a 3rd console app). For scheduling to work with Quartz, you need the 3rd consumer specifically just for quartz. It has to be running, and in this case the quartz receive endpoint would be listening to the "quartz" queue.
[Updated]
Here's a sample of the configuration you will want for the 3rd console app (the quartz service):
var scheduler = CreateScheduler();
configurator.ReceiveEndpoint("quartz", e =>
{
    configurator.UseMessageScheduler(e.InputAddress);

    e.Consumer(() => new ScheduleMessageConsumer(scheduler));
    e.Consumer(() => new CancelScheduledMessageConsumer(scheduler));
});

...

private static IScheduler CreateScheduler()
{
    ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

    var scheduler = schedulerFactory.GetScheduler();

    return scheduler;
}

And you will also need to configure quartz to us a store (SQLite, MSSql, RAM if you want to test in memory). Please see the example configuration here.
[/Updated]
[Updated2]
Somebody posted a similar question in the groups. Fortunately, they provide a sample github with a bunch of different MT functionality, one of which is the separate scheduler. Please take a look, that should have everything you need.
[Updated2]
If you want to test without running a full blown quartz scheduler, then you can use an InMemory scheduler. But that is for testing purposes only, you shouldn't use that in production.
Also, in your first code snippit, you don't need to get the send endpoint for the scheduler: var sendEndpoint = await busControl.GetSendEndpoint(new Uri("rabbitmq://localhost/quartz"));
Because, in the bus configuration, rabbit.UseMessageScheduler(new Uri("rabbitmq://localhost/quartz")); indicates that anytime you call ScheduleSend (from a ConsumeContext, or IBus/IBusControl), it will always use that /quartz address.
And lastly, this line await sendEndpoint.ScheduleSend(new Uri("rabbitmq://localhost/publisher"),, you can then change to  busControl.ScheduleSend(...)


text:
Q: How to implement generic for a function I need to implement something like this
1. type ABC<X> = (x: X) => X
2.
3. const abc: ABC = (x: X) => {
4.   return x;
5. };
6.
7. const q: number = abc<number>(123);

but there are error in the line #3 - Generic type 'ABC' requires 1 type argument(s).
when I try to make something like
3. const abc: ABC<X> = (x: X) => {
4.   return x;
5. };

it shows new error - Cannot find name 'X'.. But I don't have type definition on that stage.
for sure I could make something like this
3. function abc<X>(x: X) {
4.   return x;
5. };

and remove type ABC at all
but the idea to have it. Thanks a lot for any help.


text:
Q: Android Edittext: Attempt to invoke interface method on a null object reference When I run the code below, the username in the edittext is never found. I have tested with and without a username, but when the button is clicked it sends a null object to the eventlistener. I am new to android and confused why it is not returning a string when the username edittext contains a username.
public class LoginFragment extends Fragment {

public static final String TAG = LoginFragment.class.getSimpleName();
public  EditText username = null;
public View root = null;

public interface eventListener {
    void someEvent(String s);
}

eventListener eventListener;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    root = inflater.inflate(R.layout.login_splashpage, null, false);
    username = (EditText) root.findViewById(R.id.login_username);
    Button login_button = (Button) root.findViewById(R.id.login_button);
    login_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String usernameString = username.getText().toString();
            Log.d(TAG, "Button Clicked" + usernameString);
            if (!usernameString.isEmpty()) {
                eventListener.someEvent(usernameString);
            } else {
                Snackbar.make(root, "No username provided. Try again", Snackbar.LENGTH_SHORT).show();
            }
        }
    });

    return root;
}

}
Anyway, thank you for your help and time

A: The eventListener is null that's why you get the NullPointerException.
Since raw interfaces only provide the contract on what the derived class should do, you must also create the logic behind it:
private interface eventListener {
  void onEvent(String string);
}

eventListener listener = new eventListener() {
  @Override
  public void onEvent(String string) {
    Log.e(TAG, "onEvent " + string);
  }
};

I'm not sure if you even want an interface here as a simple method would do:
public void onLogin(String username) {
  Log.e(TAG, "onLogin " + username)
}

A: I think the problem is at this line
eventListener.someEvent(usernameString);

Where Interface eventListener was not initialised,  Can you do something like this ?
eventListener ev = new eventListener(){
void someEvent(usernameString);
}


text:
Q: ember-cli duplicate config location setting for rootUrl and locationType? I'm using ember-cli and I noticed two places that seemingly serve the same purpose.
in config/environment.js
  var ENV = {
    baseURL: '/',
    locationType: ''

in app/router.js
var Router = Ember.Router.extend({
  rootUrl: config.baseUrl
  location: config.locationType,
});

Should these always be the same? What's the distinguishing factor between them?

A: Take a moment and look at router.js, notice the import config from './config/environment';?
The distinguishing factor between them is that config/environment.js is the module where all your settings are defined and router.js is making use of what was defined by calling config.baseUrl that depending on the environment that you are running your app will give a different result, it allows you to specify different values depending on the env
if (environment === 'production') {
  ENV.baseURL = '/';
}

and
if (environment === 'production') {
  ENV.baseURL = '/beta/';
}

So when you run ember build or ember build --environment production you don't have to manually modify every file you defined a baseUrl in.


text:
Q: Use object type output in javascript function I created this function in my application:

const test = (seconds) => {
  let dateType = "seconds";
  let time = seconds;

  if (seconds % 60 === 0) {
    dateType = "minutes";
    time = seconds / 60;
  }

  if (seconds % 3600 === 0) {
    dateType = "hours";
    time = seconds / 3600;
  }

  if (seconds % 86400 === 0) {
    dateType = "days";
    time = seconds / 86400;
  }

  return {
    dateType,
    time,
  };
};

I want to change the function above into something like this:

const test = (seconds) => {
  let dateType = "seconds";
  let time = seconds;

  const OUTPUT = {
    [seconds % 60 === 0]: {
      dateType: "minutes",
      time: seconds / 60,
    },
    [seconds % 3600 === 0]: {
      dateType: "hours",
      time: seconds / 3600,
    },
    [seconds % 86400 === 0]: {
      dateType: "days",
      time: seconds / 86400,
    },
  };

  return OUTPUT[seconds];
};

console.log(test(60)); // here i need to get the first item from OUTPUT

How to change the last function, because now i get undefined?

A: There is no item in OUTPUT with the key seconds. The keys of the objects are conditions that become true or false.
So if you want to get the first item return the item that has the key 'true' if there is one, else return the item that has the key 'false'.
Working example:

const test = (seconds) => {
  let dateType = "seconds";
  let time = seconds;

  const OUTPUT = {
    [seconds % 60 === 0]: {
      dateType: "minutes",
      time: seconds / 60,
    },
    [seconds % 3600 === 0]: {
      dateType: "hours",
      time: seconds / 3600,
    },
    [seconds % 86400 === 0]: {
      dateType: "days",
      time: seconds / 86400,
    },
  };

  console.log('OUTPUT: ', OUTPUT);

  return OUTPUT['true'] ? OUTPUT['true'] : OUTPUT['false'];
};

console.log('60: ', test(60));
console.log('61: ', test(61));
console.log('3600: ', test(3600));
console.log('86400: ', test(86400));


text:
Q: Spark issue with the class generated from avro schema I have piece of code written in spark that loads data from HDFS into java classes generated from avro idl. On RDD created in that way I am executing simple operation which results depends on fact whether I cache RDD before it or not
i.e if I run code below
val loadedData = loadFromHDFS[Data](path,...)
println(loadedData.map(x => x.getUserId + x.getDate).distinct().count()) // 200000

program will print 200000, on the other hand executing next code
val loadedData = loadFromHDFS[Data](path,...).cache()
println(loadedData.map(x => x.getUserId + x.getDate).distinct().count()) // 1

result in 1 printed to stdout.
When I inspect values of the fields after reading cached data it seems
I am pretty sure that root cause of described problem is issue with serialization of classes generated from avro idl, but I do not know how to resolve it. I tried to use Kryo, registering generated class (Data), registering different serializers from chill_avro for given class (SpecificRecordSerializer, SpecificRecordBinarySerializer, etc), but none of those ideas helps me.
How I can solve this problem?
Link to minimal, complete, and verifiable example.

A: Try the code below out -
val loadedData = loadFromHDFS[Data](path,...)
println(loadedData.map(x => x.getUserId + x.getDate).distinct().count()).cache()


text:
Q: Trick to proving a group has exactly one idempotent element - Fraleigh p. 48 4.31

If $*$ is a binary operation on a set $S$, an element $x \in S$ is an idempotent for $*$ if $x * x = x$.

Let $\langle G, *\rangle$ be a group and let $x\in G$ such that $x*x = x.$ Then $x*x = x*e$, and by left cancellation,  $x = e$, so $e$ is the only idempotent element in a group.

The trick here looks like writing $x$ as $x*e$. How can you prognosticate (please see profile) this? I didn't see it. It also looks like you have to prognosticate the 'one idempotent element' to be the identity element. Is this right? Can someone make this less magical and psychic?

A: This does not look so much like prognostication to me. The hint is trying to make explicitly clear something that is happening. You could instead start by right multiplying both sides by $x^{-1}$. Then you get $xxx^{-1} = xx^{-1} \implies x(e) = e \implies x = e$. By the uniqueness of the identity, there is only one such element.

A: There are two things I want to address here:
1) There aren't that many things we can actually do. We know group elements are closed under an operation, the operation is associative, and that every element has an inverse element, and that there is an identity for the group. What could the single, unique idempotent element be? It has to be the identity.
2) We multiply things by identities all the time. Think about rationalizing denominators, or finding GCDs to add fractions. You'll probably even do it again in regards to groups, since $gg^{-1} = 1$ could be helpful at some point.

A: I don't know Fraleigh's book, and I'm not near a library that has a copy right now so I can't check out his approach to elementary group theory, what he says, etc., but it looks like he wants to use "left cancellation", the property that $ab = ac$ implies $b = c$, to prove the only idempotent in a group is the identity element.  Left (and also right) cancellation of course hold in any group by virtue of the existence of inverses.  But is also possible to have cancellation in an algebraic structure without identity, for example the set $n \Bbb Z$ for integer $n > 1$, considering it equipped with only multiplication.  So perhaps Fraleigh is trying to show how this argument fits into a more general pattern.  Of course, if $G$ is finite and has an identity, then cancellation implies the existence of inverses, since in that case the map $g \to ag$ is injective, whence finiteness forces it to be surjective as well, so there must be some $b \in G$ with $ab = e$.  Then we could argue that $x^2 = x$ forces $x =e$, as shown by AWertheim in his answer, by simply multiplying by $x^{-1}$:  $x = x^{-1}x^2 = x^{-1}x = e$.  In any event, if one wants to proceed via cancellation, the equation  $x = xe$ is needed so that something is "left over" after one cancels out $x$!  It's not so much
prognostication as it is experience with such
maneuvers.  But it can
seem a bit mysterious the first time you see it.
These things being said, it seems easier, clearer and cleaner to me to simply write
$x^2 = x \Rightarrow x^{-1}x^2 = x^{-1}x = e \Rightarrow x =e. \tag{1}$
Hope this helps!  Merry Christmas to One and All,
and as always,
Fiat Lux!!!


text:
Q: How to make Custom Serializer from different models? I have 3 different models. I need to build a custom serializer with these 3 models. I tried using some code, but it didn't reach what I expected.
There is structure, but I was not able to get the data I was expecting
# Serializer
This my Serializer and ModelOne, ModelTwo, ModelThree these are my models.
class ModelOneSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelOne
        fields = ['id', 'obj_1', 'obj_2']

class ModelTwoSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelTwo
        fields = ['id', 'obj_1', 'obj_2']

class ModelThreeSerializer(WritableNestedModelSerializer):
    class Meta:
        model = ModelThree
        fields = ['id', 'obj_1', 'obj_2']

class CustomSerializer(serializers.Serializer):
    model_1 = ModelOneSerializer(many=True)
    model_2 = ModelTwoSerializer(many=True)
    model_3 = ModelThreeSerializer(many=True)

# View

class CustomView(APIView):
    def get(self, request, *args, **kwargs):
        serializer = CustomSerializer(context={'request': request})
        return Response({'response': 'ok', 'result': serializer.data})

# Expected Output

    {
    "response": "ok",
    "result": {
        "model_1": [
        {
        "id":"1",
        "obj_1":"test",
        "obj_2":"test",
        "obj_3":"test"
        },
        {
        "id":"1",
        "obj_1":"test",
        "obj_2":"test",
        "obj_3":"test"
        }
        ],
        "model_2": [
        {
        "id":"1",
        "obj_1":"test",
        "obj_2":"test",
        "obj_3":"test"
        }
        ],
        "model_3": [
        {
        "id":"1",
        "obj_1":"test",
        "obj_2":"test",
        "obj_3":"test"
        }
        ]
    }
}

The results may have multiple data in the model_2 and model_3 as in the model_1 structure

A: You didn't pass what to serialize for all the model serializers, so CustomSerializer doesn't have anything to serialize against.
You can pass the querysets of the models to CustomSerializer:
class CustomView(APIView):
    def get(self, request, *args, **kwargs):
        model_one_qset = ModelOne.objects.all()
        model_two_qset = ModelTwo.objects.all()
        model_three_qset = ModelThree.objects.all()

        qsets_map = {
            'model_1': model_one_qset,
            'model_2': model_two_qset,
            'model_3': model_three_qset,
        }

        serializer = CustomSerializer(qsets_map, context={'request': request})

        return Response({'response': 'ok', 'result': serializer.data})


text:
Q: ProseMirror / Tiptap: how to ScrollIntoView without focus? I am working on a note-taking app that uses ProseMirror as the editor. I want to achieve the feature that when the user searches, the editor will automatically scroll to the most relevant position calculated by other functions. Meanwhile, the search bar should NOT lose the input focus so the user can modify the search content. Therefore, the straightforward way of
editor.chain().focus().setTextSelection().run()

would not work.
I have found a way to set the editor selection without focus. But the view is not scrolled. I need it to scroll to the new selection.
Here is an illustration of the scenario

I tried
editor.commands.scrollIntoView()

It does not work. But
editor.commands.setTextSelection()

does change the selection of editor.view.

A: You can use ProseMirror directly (instead of TipTap objects), or finding the DOM node worked for me too:
/**
 * Scrolls to the current position/selection of the document. It does the same as scrollIntoView()
 * but without requiring the focus on the editor, thus it can be called from the search box while
 * typing or in shopping mode when the editor is disabled.
 * @param {Editor}  editor - A TipTap editor instance.
*/
function scrollToSelection(editor: Editor): void {
  const { node } = editor.view.domAtPos(editor.state.selection.anchor);
  if (node) {
      (node as any).scrollIntoView?.(false);
  }
}

Copied from SilentNotes


text:
Q: Android: formula to calculate minimum neccessary time for SCROLLER from A to B Scroller startScroll(int startX, int startY, int dx, int dy, int duration) method provides argument duration which is time that scroller MUST keep when performing our scroll call.
The problem is - sometimes scroller have not enough time to scroll to our destination given by dx or dy. So I'm asking. ; )
Is there any mathematical formula including acceleration, scrolling speed and deceleration that will count MINIMAL time that is necessary to perform FULL scroll given in dx dy?

A: No. The duration is used to calculate the speed and acceleration. Worst case, you use 0 for the duration, and your scroller will jump immedeately to the end position.


text:
Q:  is pushed down when border appears It is hard to learn "float" "overflow" "clear" and some other properties so please help me find good online websites to learn these properties ..
I opened some websites to make designs like them I found http://wix.com I admired its nav bar so i tried to make like it but i had a problem when mouse is over the il it is pushed down to show the top border how can I fix that
thanks and I am sorry for my weak English

body {
 background-color: lightblue;
}

ul {

 position: fixed;
 list-style-type: none;
 overflow: hidden;
 top: 0px;
 right: 0px;
 width: 100%;
 margin: 0px;
 padding: 0px;
 padding-top: 8px;
 padding-bottom: 8px;
 display: block;
 background-color:  #666666;
 transition:background-color, 1s;
}

ul:hover {
 background-color: #333;
}

il {
 transition:border-top,1s;
 float: left;
 padding-right: 10px;
 border-right: 1px solid white;

}

il:hover {
 border-top:5px solid lightblue;
}

#navl {
 font-family: Trebuchet MS', Helvetica, sans-serif;
 letter-spacing: 3px;
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

pre{

 font-family: Courier New,Courier,Lucida Sans Typewriter,Lucida Typewriter,monospace;
 letter-spacing: 2px;
 font-size: 30px;
 text-align: center;
 color: white;
 margin-top: 150px;
}

#plans:link, #plans:visited {
    background-color: white;
    color: black;
    padding: 14px 25px;
    text-align: center;
    text-decoration: none;
    display: block;
    border: 1px solid white;
    border-radius: 30px;
    margin: auto;
    width: 110px;
    padding-top: 20px;
    padding-bottom: 20px;
    font-size:20px;
    font-family: Courier New,Courier,Lucida Sans Typewriter,Lucida Typewriter,monospace;
}
<!DOCTYPE html>

<title>test</title>
<link rel="stylesheet" href="style.css">

<il>Home</il>
<il>Plans</il>
<il>About</il>
<il>Contact Us</il>

test

Plans

A: At first, replace those il with li, and add this style to your li:
li {
 border-top: 5px solid transparent;
}

And in ul, instead of padding-top:8px add padding-top:3px.

A: The reason this happens is because the border adds height to the element. To correct it, you can either remove height from the main element or shift it up:
li:hover {
  margin-top: -5px; //shifts the element up 5px
}

or you can have an invisible border as Teuta mentions that gets "covered up" by the new border.

A: Here is the link with a little work around I did.  I removed the padding top in ul. Changed the il to li. Because actually it is 'li' not 'il'. And I added a border top in li.
Here is the css code I changed.
ul:hover {
    background-color: #666666;
}

li {
    transition:border-top,1s;
    float: left;
    padding-right: 10px;
    border-right: 1px solid white;
    border-top:5px solid #666666;
}

li:hover {
    border-top:5px solid lightblue;
}

https://jsfiddle.net/7x7dy3jt/


text:
Q: CSS height in % doesn't work only with React I have a wierd problem. I have exactly the same DOM and CSS rendered with React and rendered with pure HTML. However, in React children of the div.container doesn't get the proper height when it's set in %. It works well when it's set with vh or with px, but I can't use those. Any idea why? And how to fix this problem?

div.form label:after, div.wrapper:after, div.container:after {
  display: block;
  content: '.';
  clear: both;
  height: 0;
  visibility: hidden;
  line-height: 0;
  padding: 0;
  margin: 0;
}
body {
  width: 100%;
  margin: 0;
  min-width: 319px;
  min-height: 479px;
  background-color:black;
}
div.container {
  margin: 0 auto;
  width: 100%;
  height: auto;
  max-height: 1368px;
  max-width: 1368px;
  min-width: 319px;
  min-height: 100%;
  position: relative;
  background-color:red;
}
nav {
  width: 82px;
  height: 100%;
  height: 100vh;
  max-height: 1368px;
  float: left;
  z-index: 1000;
  overflow: hidden;
  background-color: #55c7f9;
}
header {
  height: 15%;
  margin: 0 6%;
  float: initial;
  position: relative;
  width: calc(100% - 80px);
  background-color:orange;
}
div.wrapper {
  min-height: calc(100% - 62px);
  height: auto;
  width: calc(100% - 80px);
  float: right;
  background-color:yellow;
}
div.main {
  width: 90%;
  height: 100%;
  box-sizing: border-box;
  margin: auto;
  padding-bottom: 10px;
  height: calc(100% - 158px);
  background-color:green;
}

A: class is className inside react.

A: Some advice that might help you..
Add html, along with body.
html, body {
  height: 100%;
}

Make sure the div your bundle is being loaded to has height: 100%;. In the case below "root" would need it.

Last case, if you do something like this:

{this.props.children}

Make sure you give this div a className and add it to the list of things that need to be 100%


text:
Q: Java Spring Boot problem LoggiFailureAnalysisReporter I am new to Boot-Spring apparently, I mostly copy some code from youtube on this case. However, after modification, in the end, I got a message like this;
APPLICATION FAILED TO START

Description:
Field postService in com.example.demo.BlogController required a bean of type 'Server.PostService' that could not be found.
Action:
Consider defining a bean of type 'Server.PostService' in your configuration.
.....Any idea how to deal with this situation. Thank you for the support.
1stclass-BlogApplciation-----com.example.demo(package)
2nd-Blog Controller--------same package as BlogApplication
3rdclass-Post---entities
4rthclass-PostRepositories---Repositories
**package com.example.demo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class BlogApplication {

public static void main(String[] args) {

    SpringApplication.run(BlogApplication.class, args);
}

}**
  **package com.example.demo;
  import java.util.List;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RestController;
 import Server.PostService;
 import entities.Post;
 import java.util.Date;
  @RestController
  public class BlogController {
  @Autowired
  private PostService postService;
  @GetMapping(value="/")

  public String index() {
    return "index";
    }
  @GetMapping(value="/posts")
  public List<Post>posts(){
  return postService.getAllPosts();

    }
  @PostMapping(value="/post")
  public void publishPost(@RequestBody Post post) {

   if(post.getDatecreation() == null)
  post.setDatecreation(new Date());
      postService.insert(post);
     }
     }**

  **package entities;
    import java.util.Date;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    @Entity
     public class Post {
      @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
     private Long id;
     private String title;
    private String body;
    private Date Datecreation;

    public Post() {

     }
    public long getId() {
    return id;
     }
    public void setId(long id) {
    this.id = id;
    }
    public String gettitle() {
    return title;
     }
    public void settitle(String title) {
     this.title= title;
     }
    public String getBody() {
    return body;
     }
    public void setBody(String body) {
    this.body = body;
     }
    public Date getDatecreation() {
    return Datecreation;
    }
    public void setDatecreation(Date datecreation) {
    this.Datecreation = datecreation;
    }
    }**

   **package Repositories;

   import org.springframework.data.jpa.repository.JpaRepository;
   import org.springframework.stereotype.Repository;
   import entities.Post;
   @Repository
   public interface PostRepository extends JpaRepository<Post,Long>{
    }**

A: EDIT:
You are missing PostService class or you have imported incorrect class as Server.PostService.
try to create a service like this one:
@Component
public class PostService {
    public List<Post> getAllPosts(){
     //your code
    }
}

A: Your BlogApplication Class, which is the class annotated with @SpringBootApplication is in the package com.example.demo. That means that, by default, Spring is going to launch a Component Scan starting from that package.
The problem is that your class PostService and your interface PostRepository are not in the same package as (or in a sub-package of) com.example.demo, so Spring can't find them and won't automatically create these beans for you.
To correct this issue, move the packages you created inside your root package (com.example.demo).
You can find more information about the use of @SpringBootApplication here.


text:
Q: If $a\leq n,b\leq n,c\leq n$ and $a+b+c\leq 2n$, then $V_a\cap V_b\cap V_c=0$
I did part (a). For part (b) I proved if there are subspaces $V_a,V_b,V_c$ then $a\leq n,b\leq n,c\leq n$ and $a+b+c\leq 2n$. But stuck in proving the other direction. So I suppose there are positive(or zero) integers $a,b,c$ such that $a\leq n,b\leq n,c\leq n$ and $a+b+c\leq 2n$. First I was going to prove that there is at least one pair among $\{a,b,c\}$ such that their addition $\leq n$, and then use part (a). But later I figured out that it is impossible because for example if $n=5$, and $a=b=3, c=4$ then $a+b+c=10=2n$, but non of $a+b,b+c,a+c$ is less or equals $5$.
So, how can I prove it? Can anybody please give me at least a hint?

A: $\textbf{1)}$  If $a+b\le n$, then by part a) we can find subspaces $V_a, V_b$ with $V_a\cap V_b=0$,
so then $V_a\cap V_b\cap V_c=0$ for any subspace $V_c$ with dimension $c$.
$\textbf{2)}$ If $a+b>n,\;\;$ let $B=\{v_1,\cdots, v_n\}$ be a basis for V,
and let $V_a=\text{span}\{v_1,\cdots,v_a\}$ and let $V_b=\text{span}\{v_{n-b+1},\cdots,v_n\}$.
Since $a+b+c\le2n$, we can choose a subset $I$ of $\{1,\cdots,n-b,a+1,\cdots,n\}$ with $|I|=c$;
and then if we let $V_c=\text{span}\{v_l: l\in I\}$, $\;\;V_a\cap V_b\cap V_c=0$.


text:
Q: Are properties of the imaginary unit assumed or proved? Reading about the cyclic values returned by integral powers of $i$:
$$\begin{align*}
i^0&=\hphantom{-}1\\
i^1&=\hphantom{-}i\\
i^2&=-1\\
i^3&=-i\\
& \,\,\,\vdots
\end{align*}$$
and the pattern continues. Now, a simple question popped up in my mind:
$i^2 = -1\implies i\notin\mathbb{R}$. So, how did we come to the conclusion that:
$$i^3=i^2\cdot i=-1\cdot i=-i$$
because $i$ does not necessarily have the properties of reals. Is this just an assumption for the construction of the complex numbers, or is there a proof?

A: Although those are excellent answers I think the answer is even simpler.
$b^{m}b^{n} = b^{m+n}$ is not a "real number rule" but an "associative binary operation rule".
If we define/construct/invent any set of elements (these could be gumdrops or chess pieces for all we care) and create any operation between to elements ($a*b$ could be "melt the two gumdrops together an make a new one" or "always pick the second chess piece; always") so that:
--$a * b$ for any two elements of the set will result in $c$, also a member of the set and the same $a,b$ combined will always results in the same member $c$ (The term for this is $*$ is a "binary operation".
--If we evaluate $a*b*c*d$ it doesn't matter how we group them.  $(a*(b*c))*d$ (where we first do $b*c= e$ and then we do $a*e = f$ and then we do $f*d = g$) will give the same result as $(a*b)*(c*d)$ (where we do $a*b$ and get $h$ and then we do $c*d$ and get $i$ and then we do $h*i$ and get, amazingly, $g$).  Or more simply $(a*b)*c = a*(b*c)$.  (such an operation is called "associative".  An example of something that isn't associative is $(2^3)^2 \ne 2^{(3^2)}$.)
Then if we define as a matter of notation (it's just notation) that if $n\in \mathbb N$ than $a^n := a*a*a*....*a$ where a is operated $n$ times.
If we create such a system, (whether gumdrops, chess pieces, or numbers), then we will always have:
$b^mb^n = (b*.....*b)*(b*.....*b) = (b*....................*b) = b^{m+n}$.
Always.
So this is true for complex numbers.  (Assuming we defined what $c*d$ means and that $c*(d*e) = (c*d)*e$).
===
Just to be perverse, let's do this with chess pieces. And define $a*b = b$.  Then $(knight*pawn)*bishop = pawn*bishop = bishop$ which is equal to $knight*(pawn*bishop) = knight*bishop = bishop$.
Then $pawn^2*pawn = (pawn*pawn)*pawn=pawn*pawn= pawn; pawn*pawn^2 = pawn*(pawn*pawn) = pawn*pawn = pawn; pawn^3 = pawn*pawn*pawn = pawn*pawn = pawn$.
So $pawn^2pawn=pawn*pawn^2 = pawn^3$.
That was kind of boring.
=====
To go to Noah Schweber's excellent answer.  If $i = (0,1)$ and $(a,b)*(c,d)= (ac - bd, ad + bc)$ is the definition of complex numbers then:
-- yes, it is binary.  ($(a,b)*(c,d)= (ac - bd, ad + bc)$ results in a real value pair.)
-- yes it is associative. ($(a,b)*[(c,d)*(e,f)] = (a,b)*(ce-df,cf+de)=(a(ce-df)-b(cf+de), b(ce-df) + a(cf+de))=(ace-adf-bcf-bde,bce-bdf+acf+ade)$ while ($[(a,b)*(c,d)]*(e,f) = (ac - bd,bc+ad)*(e,f)=((ac-bd)e-(bc+ad)f,(bc+ad)e + f(bc+ad))=(ace-adf-bcf-bde,bce-bdf+acf+ade)$ so $(a,b)*[(c,d)*(e,f)] = [(a,b)*(c,d)]*(e,f)$.
Then
$(a,b)^3 = (a,b)(a,b)(a,b)=(a^2 - b^2,2ab)(a,b) = (a^3 - 3ab^2,3a^b-b^3)$
$(a,b)^2(a,b) = [(a,b)(a,b)](a,b)=(a^2 - b^2,2ab)(a,b) = (a^3 - 3ab^2,3a^b-b^3)$
$(a,b)(a,b)^2 = (a,b)(a^2 - b^2,2ab)=(a^3 - 3ab^2,3a^b-b^3)$
all equal.

A: It does indeed have a proof. But this involves going back to exactly how the complex numbers are defined in the first place.
Let's say for the moment that we're happy with the real numbers and their properties. (Of course, there's a separate question - "how do we construct the reals?" - but let's leave that aside for now.) There are now a number of ways to rigorously define the complex numbers. Here's probably the simplest (although not the most useful): we let $\mathbb{C}$ be the set of ordered pairs $(a, b)$ where $a, b\in\mathbb{R}$, and we define the operations $+$ and $\times$ on $\mathbb{C}$ as follows (intuitively, the pair $(a, b)$ represents the number $a+bi$):

*

*$(a, b)+(c, d)=(a+b, c+d)$.

*$(a, b)\times (c, d)=(a\times c-b\times d, a\times d+b\times c)$.
Note that on the right hand side of each of those expressions, I'm using the notion of $+$ and $\times$ (and $-$) for real numbers. Arguably, a better way to write this would be

*

*$(a, b)+_\mathbb{C}(c, d)=(a+_\mathbb{R}b, c+_\mathbb{R}d)$.

*$(a, b)\times_\mathbb{C} (c, d)=(a\times_\mathbb{R} c-_\mathbb{R}b\times_\mathbb{R} d, a\times_\mathbb{R} d+_\mathbb{R}b\times_\mathbb{R} c)$.
That is, I've already defined operations $+_\mathbb{R}, \times_\mathbb{R}, -_\mathbb{R}$ for the reals, and now I'm defining new operations $+_\mathbb{C}, \times_\mathbb{C}$ for the complex numbers. In general, it will always be clear from context which is meant; but it's a good habit when learning this material to get into to clarify things with subscripts whenever we're using both types of operation.
We can use this explicit definition to verify basic claims about complex numbers. For example,

*

*Check that $(0, 1)\times(0, 1)=(-1, 0)$, and that $(0, 1)$ and $(0, -1)$ are the only complex numbers with this property. We call the former "$i$" (but it doesn't really matter which one we pick).

*Now, we can compute $(0, 1)^3=(0, 1)\times (0, 1)\times (0, 1)=(0, -1)$. This shows that indeed $i^3=-i$.
What about more general claims? For example, I implicitly used the associativity of $\times$ above, in writing out $(0, 1)^3$. We can also use the definition of $\mathbb{C}$ to prove that $\times$ is associative, and more generally that $\mathbb{C}$ is a field). This gets a bit messy; let me give as an example the proof that addition of complex numbers is commutative, which is simpler:
$$(a, b)+_\mathbb{C}(c, d)=(a+_\mathbb{R}c, b+_\mathbb{R}d)=(c+_\mathbb{R}a, d+_\mathbb{R}b)=(c, d)+_\mathbb{C}(a, b).$$
Note how we use (at the second "$=$" sign) the commutativity of $+_\mathbb{R}$; we're building on facts we already know about the reals, to prove facts about the complex numbers, and this is justified because of how the complex numbers are constructed from the reals.

EDIT: Just to tie up a loose end, what did I mean above when I said that this was "not the most useful" way to construct the complex numbers?
Well, it turns out that there is a much more abstract approach we can use, that - while much harder at first - ultimately turns out to be much more mathematically useful. The key point is to notice that essentially the whole point of the complex numbers is to solve a single equation, $x^2=-1$. In some sense, they are what you get when you start with the reals and "fill in" the hole left by that equation.
This suggests that we should look for some tool for doing the following: if $\mathbb{S}$ is some number system (reals, complexes, integers, rationals, quaternions, hyperbolic sedenions, or thing-I-just-made-upions) and $E$ is some equation in $\mathbb{S}$, there should be a way to build a thing like $\mathbb{S}$ but that can also solve $E$. This is really really vague, but ultimately leads to a bunch of ideas in abstract algebra; for example, algebraic extensions of fields. In this context, there's a precise sense in which the complex numbers are the "smallest" number system containing the reals where $x^2=-1$ has a solution, and the relevant notation is $\mathbb{R}[x]/\langle x^2+1\rangle$ - which is probably gibberish right now but down the road you'll see how to view this as a "recipe" for building the complex numbers from the real numbers.

A:
Are properties of the imaginary unit assumed or proved?

Both.  The intuitive approach of assuming a solution to a previously unsolvable equation (such as an $i$ solving $i^2= -1$) that satisfies other algebraic properties of the number system, came into use in the 1400-1700's and was later proved to create a consistent number system that works as expected (such as any element of the system with $i$ being uniquely expressible as $x+yi$).
Today the sequence is similar: it is assumed to work in high school, and proved to work at university.

A: There are various logically rigorous ways to prove that the set of all complex numbers is a field, i.e. it satisfies certain axioms about addition, subtraction, multiplication, and division, but there is also another point of view worth knowing about:

*

*Multiplication by any complex number $z = x+iy$ amounts to rotating through the angle whose sine is $y/|z|$ and whose cosine is $x/|z|$ and then multiplying by the real number $|z|$.

*In particular, multiplying by $i$ means rotating $90^\circ$ counterclockwise.  Thus multiplying by $i^3$ amounts to rotationg $270^\circ$ counterclockwise, whcih gives you $-i$.

A: As you point out, any integral power of $i$ is $i$ or $-1$, or $-i$ or $1$.
Complex 'multiplication' is defined by $(a,b).(c,d)=(ac-bd,ad+bc)$ where $a,b,c,d\in\mathbb{R}$. Also note that the complex number $(0,1)=0+i.1$ is defined by the notation $i$, the imaginary unit.
So, $i^2=(0,1)(0,1)=(-1,0)=-1$ and we can similarly show that $i^3=(0,-1)=-i$.

A: Define $ i $ as the root of $ x^2 + 1 $, define $ \mathbb C = \mathbb R(i) $, a finite field extension of the reals. From this definition, the field axioms are preserved, and you can thus apply associativity to obtain your statement.


text:
Q: Get the latest record by date for a user in MySQL I've two tables
user_conversation
-----------------
id
from_user_id
to_user_id
item_id
offer_detail_id
message_type
deleted_by_sender
deleted_by_receiver

user_conversation_reply
-----------------------
id
from_user_id
message_text
sent_date
conversation_id
is_read

Whenever a new conversation starts against any item a record will be entered in the user_conversation_table and message will be recorded in the user_conversation_reply table for that conversation. Similarly, different messages can be added for that conversation in the user_conversation_table.
I want to get the all the conversation of a user. (i.e. from_user_id,to_user_id,item_id makes up a combination) and along with that I need to have the last message of this conversation.
user_conversation

id     from_user_id     to_user_id     item_id
1           8              2             1

user_conversation_reply

id     from_user_id     message     conversation_id   sent_date
1           8              helo             1         2014-12-07
2           8           how r u             1         2014-12-08

A user can be a part of multiple conversation. So, I want to get the last conversation message of each conversation of a user.
I'm using this query to filter out the records for a user.
Select * from user_conversation where to_user_id = 2;

Please, suggest.
Thanks,
Faisal Nasir

A: Assumming that user_conversation_reply.id is an auto-incremented primary key,
and the last message has always the highest id
SELECT *
FROM (
  Select uc.id, max( ucr.id ) max_ucr
  from user_conversation uc
  JOIN user_conversation_reply ucr ON ucr.conversation_id = uc.id
  where uc.to_user_id = 2
  GROUP BY uc.id
) q
JOIN user_conversation uc ON q.id = uc.id
JOIN user_conversation_reply ucr ON q.max_ucr = ucr.id
;


text:
Q: Conditionally color portion of the text of the UITextField I've a UITextField, I need to color some specific word in a gray
Is there a direct solution?
If not, I think If I got the Source code for setTextColor method, try to conditinoally change its implementation (may be through a Category or even subclassing).

A: It's not possible as is. To implement that kind of feature you have to use CoreText.
For more info read this great tutorial: http://www.cocoanetics.com/2011/01/befriending-core-text/


text:
Q: How to solve Java IOException: Negative Seek Offset? (Java ID3 Tag Library) I'm trying to manipulate ID3 tags in MP3 Files using Java ID3 Tag Library. However, when i try to do ANYTHING using an "MP3File" class, i'm getting IOException: Negative Seek Offset;
Here's an example code and the stacktrace:
package com.test;

import java.io.File;
import java.io.IOException;

import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;

public class MP3Test {

    public static void main(String[] args) throws IOException, TagException {

        File f = new File("test.mp3");

        MP3File mp = new MP3File(f);

        System.out.println(mp.getFrequency());
    }

    }
--------------------------------------------------------------------------------

Exception in thread "main" java.io.IOException: Negative seek offset
    at java.io.RandomAccessFile.seek(Native Method)
    at org.farng.mp3.id3.ID3v1.seek(Unknown Source)
    at org.farng.mp3.id3.ID3v1.read(Unknown Source)
    at org.farng.mp3.id3.ID3v1.<init>(Unknown Source)
    at org.farng.mp3.MP3File.<init>(Unknown Source)
    at org.farng.mp3.MP3File.<init>(Unknown Source)
    at com.test.MP3Test.main(MP3Test.java:15)

As you see, even an basic operation throws me an exception, making it really hard for me to really develop something... The MP3 file that i'm trying to read is working perfectly fine. So, any ideas on why is this happening and/or how to solve it??

A:
So, any ideas on why is this happening and/or how to solve it??

At the risk of stating the obvious, there are 2 possible cause for the problem:

*

*The MP3 file is broken in some subtle way that doesn't prevent it from "working" ... which I presume means playing in some non-Java player.

*The library is buggy and it is not handling something properly.

Solutions?

*

*Try a different MP3 file.

*Try multiple files from different sources, in case it is something to do with MP3 files produced by a particular piece of software.

*Run the library using a Java debugger to find out what is actually causing the exception.  This will probably entail reading the MP3 specs to decide whether there is some mismatch between 1) the code, 2) the spec and 3) the bytes in the file.

You asked this as a programming question so I assume that you are a programmer, and are capable of troubleshooting in general, and in particular in finding / reading specs, and debugging Java.

OK ... since you don't appear to have made any progress with this yourself, I took a look at the source code I found here.  (Of course, this might be the wrong version, but you didn't say what version of the library you were using ...)
It appears that the problem is occurring in line 309 of org.farng.mp3.id3.ID3v1.java in the seek method:
// If there's a tag, it's 127 bytes long and we'll find the tag
file.seek(file.length() - 128);

Now the only way that that could possibly give a negative seek offset exception is if file.length() returns a file length less than 128.  That should never happen for a valid MP3 file.
So my guess is that either you are trying to read truncated MP3 files, or files that are not MP3 files at all, or you are trying to read the files from some device/file system that doesn't report file sizes properly.
(It is worth reading the javadocs for File.length() for clues as to why it might return a strange value; e.g. zero.)


text:
Q: Ext JS 4 - How to display other views inside a view? In an MVC style Ext JS 4 application, assuming I have a single controller/view/store/model and that loads up properly- for an example, let's say this example is my code base.
My application loads up a view with a grid (list of Users), then when a row is clicked it opens and edit (User) view with a form.
Now, I want to add additional views to be displayed inside that form.
For example, I want to show a 'last 10 logins' (a list of activity records for the user) below the fields in the User form.   I will have a separate view/controller/model/store for 'ActivityLog'.    So I need to create the ActivityLog List view/controller and place it inside my User view  (it will also have it's own code/logic to handle clicks on those records in it's grid, etc.).
Is that the correct approach?
Would the User controller load the view/controller of ActivityLog and somehow place it in to the User edit view, or do I have config data directly inside the User edit view that loads it in ?

A: Ok. Probably you can use something like this
// Navigation controller
    Ext.define('App.controller.Navigation', {
        extend: 'Ext.app.Controller',
        models: [],
        stores: [],
        views: ['navigation.TabHost'],
        init: function() {
             this.control({
                'tabhost': {
                    'render': function(tabHost) {
                       // Grid panels are panels too. So It does not make any sense to use additional container.
                       tabHost.add(Ext.create('App.view.users.List'));
                       tabHost.add(Ext.create('App.view.activitylogs.List'));
                    }
                }
        }
});

// Users controller
Ext.define('App.controller.Users', {
    extend: 'Ext.app.Controller',
    models: [],
    stores: [],
    views: ['users.List'],
    init: function() {
         this.control({
            'userslist': {
                'render': function(gridPanel) {
                   console.info('Im here');
                }
            }
    }
});

// ActivityLog controller
Ext.define('App.controller.ActivityLog', {
        extend: 'Ext.app.Controller',
        models: [],
        stores: [],
        views: ['activitylogs.List'],
        init: function() {
             this.control({
                'loglist': {
                    'render': function(gridPanel) {
                       console.info('Im here');
                    }
                }
        }
    });

// Also you should have tree view files
// navigation.TabHost
Ext.define('App.view.navigation.TabHost', {
    extend: 'Ext.tab.Panel',
    alias: 'widget.tabhost',
    initComponent: function() {
      // ......
    }
});

// users.List
 Ext.define('App.view.users.List', {
        extend: 'Ext.grid.Panel',
        alias: 'widget.userslist',
        initComponent: function() {
          // ......
        }
    });

// activitylog.List
Ext.define('App.view.activitylogs.List', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.logslist',
    initComponent: function() {
      // ......
    }
});

Navigation controller will create widges and insert them to its tabhost.
But ActivityLog and Users Controllers will manipulate their views.

A:
Would the User controller load the view/controller

Yes, you can do this.
User controller can use view from another controller. In other case controller can listen to view which was added in the another controller.
First off all you should register controllers in app.js
Ext.application({

    name: 'App',

    autoCreateViewport: true,

    appFolder: 'js/App',

    controllers: [

        'User',
        'ActivityLog'
    ],

    launch: function() {

    }

});

After that all views/stores/models, which was described in the controllers files, will be loaded automatically.
You will have ability to manipulate (add/remove) views wherever you want. But controllers will be listening to the views that you definitely specified.


text:
Q: Is it really necessary to override the `*_type=` method for ActiveRecord Polymorphic Association with Single Table Inheritance? I'm refactoring some piece of code that deals with polymorphic belongs_to association that can receive a model that implements Single Table Inheritance. The current code follows an advice from ActiveRecord documentation here, namely that it is best to override attachable_type= so that the base class name of the STI model gets stored in the attachable_type field:
class Asset < ActiveRecord::Base
  belongs_to :attachable, polymorphic: true

  def attachable_type=(class_name)
     super(class_name.constantize.base_class.to_s)
  end
end

class Post < ActiveRecord::Base
  # because we store "Post" in attachable_type now dependent: :destroy will work
  has_many :assets, as: :attachable, dependent: :destroy
end

class GuestPost < Post
end

class MemberPost < Post
end

I understand that we want to store that base class so that ActiveRecord works as expected. However, when I tested a few scenarios including the scenario in the documentation, it seems that overriding attachable_type= is unnecessary. ActiveRecord seems to already handle this case and always stores the base model Post rather than GuestPost or MemberPost.
I created a repo that implements the models in the documentation and allows you to play with some data and see for yourself. I cannot reproduce the issue that the documentation attempts to circumvent all the way up to ActiveRecord version 3.2.22.5 (I haven't tried beyond that).
Does anyone know if there is truly a need to override attachable_type=? Is the documentation out of date? Or is it just solving the use case of directly running Asset.new attachable_type: 'MemberPost', attachable_id: member_post.id instead of Asset.new attachable: member_post?
The reason why this matters to me is that we have 5 models that could be affected by this. Our current code implements overriding 3 of those, and I'm refactoring to DRY it up and potentially introduce it to the additional 2 other models in which we forgot to follow this advice.

A: OK, I believe I better understand the reasoning behind it. This is an issue when the model needs to be created or updated from a form.
In such scenario, attachable_type and attachable_id are sent to the controller, which typically passes-through this data to the model. Without overriding attachable_type= the model will end up having attachable_type be one of the child classes GuestPost or MemberPost.
This in turn causes a range of issues. For example, assets won't be destroyed when the owner of the asset is destroyed even when dependent: :destroy is specified on the has_many association.
Therefore, if your model is expected to receive data for the polymorphic association field via a form, you should override this method.
I updated the repo to demonstrate this issue.


text:
Q: Create Course API not working in Moodle I am new to Moodle. I have done creating user by using web service api and that is running successfully. Now I want to create a course same way. I am using 'core_course_create_courses' function to do this. The post body of my request is
$courses=array("courses" =>
            array(
                0=>array(
                    "fullname" => $fullname,
                    "shortname" => $shortname,
                    "categoryid" => $categoryid,
                    "idnumber" =>$idnumber,
                    "summary"=>$summary,
                    "summaryformat"=>$summaryformat
                )
            )
        );

Whenever I am running this it is giving me response "{\"exception\":\"moodle_exception\",\"errorcode\":\"errorcatcontextnotvalid\",\"message\":\"You cannot execute functions in the category context (category id:101). The context error message was: Invalid parameter value detected\"}".
But the course category 'programming' with id 101 exists in my moodle site. Please help me. Thanks in advance.

A: I was wrong ,the categoryid is not the id of the category,it is the sequence id of the category.Now if I give 2 ,it works fine.

A: $token = $this->config->item('id_token');
    $domainname = $this->config->item('domainname');
    $functionname = 'core_course_create_courses';
    $restformat = 'json';

    //crear objeto de acuerdo a la estructura para crear Categoría en Moodle

    $curso = new stdClass();
    $curso->fullname = $data['patron']['nombre'];
    $curso->shortname = $data['patron']['nombre']; // Is unique
    **$curso->idnumber = $id; // consecutive
    $curso->visible = 1;
    $curso->categoryid = 6;

    $modulos = array($curso);

    $params = array('courses' => $modulos);

    header('Content-Type: text/plain');
    $serverurl = $domainname . '/webservice/rest/server.php' . '?wstoken=' . $token . '&wsfunction=' . $functionname;
    require_once(APPPATH . 'libraries/curl.php');
    $curl = new curl;

    $restformat = ($restformat == 'json') ? '&moodlewsrestformat=' . $restformat : '';
    $resp = $curl->post($serverurl . $restformat, $params);
    return $resp;


text:
Q: Scala some_case_class paramet is not a member of Option[some_case_class] I'm trying to rewrite this script https://www.kaggle.com/paulantoine/light-gbm-benchmark-0-3692/code to Scala, and need to take info from two Case Classes and put it into one. Donor classes are:
case class Prods1(product_name: String, aisle_id: Int, department_id: Int)
case class Prods2(orders: Int, reorders: Int)

after join they look like this:
(Int, (Prods1, Option[Prods2]))

then I need to convert them to:
case class Product(product_id: Int, product_name: String, aisle_id: Int, department_id: Int, orders: Option[Int], reorders: Option[Int])

it is done by following function:
def parse_products(product_data: (Int, (Prods1Data, Option[Prods2Data]))) = {
    val product_id = product_data._1
    val product_name = product_data._2._1.product_name
    val aisle_id = product_data._2._1.aisle_id
    val department_id = product_data._2._1.department_id
    var orders = None
    var reorders = None
    if(product_data._2._2.isDefined){
        val p2 = product_data._2._2
        orders = p2.orders
        reorders = p2.reorders
    }
    Product(product_id, product_name, aisle_id, department_id, orders, reorders)
}

I get following errors:
error: value orders is not a member of Option[Prods2]
   orders = p2.orders
               ^
error: value reorders is not a member of Option[Prods2]
   reorders = p2.reorders
                 ^

I tried another option also:
def parse_products(product_data: (Int, (Prods1, Option[Prods2]))) = {
    val product_id = product_data._1
    val product_name = product_data._2._1.product_name
    val aisle_id = product_data._2._1.aisle_id
    val department_id = product_data._2._1.department_id
    product_data._2._2 match {
        case Some(p2) => {
            val orders = p2.orders
            val reorders = p2.reorders
        }
        case None => {
            val orders = None
            val reorders = None
        }
    }
    Product(product_id, product_name, aisle_id, department_id, orders, reorders, reorder_ratio)
}

That way I get another errors:
error: not found: value orders
   Product(product_id, product_name, aisle_id, department_id, orders, reorders)
                                                              ^
error: not found: value reorders
   Product(product_id, product_name, aisle_id, department_id, orders, reorders)
                                                                      ^

If you find it possible please correct both options, as I'm doing that to learn and both constructions would be really useful for me, thank you in advance.

A: Finally, I made it like this, comment about "get" was useful, but there were some more corrections needed:
def parse_products(product_data: (Int, (Prod1, Option[Prod2]))) = {
    val product_id = product_data._1
    val product_name = product_data._2._1.product_name
    val aisle_id = product_data._2._1.aisle_id
    val department_id = product_data._2._1.department_id
    var orders: Option[Int] = None
    var reorders: Option[Int] = None
    if(product_data._2._2.isDefined){
        val p2 = product_data._2._2.get
        orders = Some(p2.orders)
        reorders = Some(p2.reorders)
    }
    Product(product_id, product_name, aisle_id, department_id, orders, reorders)
}

A: You can return a tuple from the match and assign to two separate variables, it makes the code shorter and look a bit cleaner.
def parse_products(product_data: (Int, (Prods1, Option[Prods2]))): Product = {
    val product_id = product_data._1
    val product_name = product_data._2._1.product_name
    val aisle_id = product_data._2._1.aisle_id
    val department_id = product_data._2._1.department_id
    val (orders, reorders) = product_data._2._2 match {
        case Some(p2) => (Some(p2.orders), Some(p2.reorders))
        case None => (None, None)
    }
    Product(product_id, product_name, aisle_id, department_id, orders, reorders)
}