Custom webform Element not rendered

Question: It looks like this is a frequent question, but I still can not figure out, why my custom webform element is not showing up. (I read already this post and also the example module)
web/modules/custom/site_registration/src/Plugin/WebformElement/PersonCountElement.php:
<?php

namespace Drupal\site_registration\Plugin\WebformElement;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Annotation\WebformElement;
use Drupal\webform\Plugin\WebformElement\Hidden;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Provides a 'site_person_count' element.
 *
 * @WebformElement(
 *   id = "site_person_count",
 *   label = @Translation("Person Count"),
 *   description = @Translation("Provides a fancy person counter."),
 *   category = @Translation("Custom"),
 * )
 *
 * @see \Drupal\webform_example_element\Element\WebformExampleElement
 * @see \Drupal\webform\Plugin\WebformElementBase
 * @see \Drupal\webform\Plugin\WebformElementInterface
 * @see WebformElement
 */
class PersonCountElement extends Hidden {

  /**
   * {@inheritdoc}
   */
  public function prepare(array &$element, WebformSubmissionInterface $webform_submission = NULL) {
    parent::prepare($element, $webform_submission);

    // Here you can customize the webform element's properties.
    // You can also customize the form/render element's properties via the
    // FormElement.
    //
    // @see \Drupal\webform_example_element\Element\WebformExampleElement::processWebformElementExample
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    // Here you can define and alter a webform element's properties UI.
    // Form element property visibility and default values are defined via
    // ::defaultProperties.
    //
    // @see \Drupal\webform\Plugin\WebformElementBase::form
    // @see \Drupal\webform\Plugin\WebformElement\TextBase::form
    return $form;
  }

}

web/modules/custom/site_registration/src/Element /PersonCountElement.php:
<?php

namespace Drupal\site_registration\Element;

use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\Render\Element\Hidden;

/**
 * Provides a 'site_person_count'.
 *
 * Webform elements are just wrappers around form elements, therefore every
 * webform element must have correspond FormElement.
 *
 * Below is the definition for a custom 'site_person_count' which just
 * renders a simple text field.
 *
 * @FormElement("site_person_count")
 *
 * @see FormElement
 * @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21FormElement.php/class/FormElement
 * @see \Drupal\Core\Render\Element\RenderElement
 * @see https://api.drupal.org/api/drupal/namespace/Drupal%21Core%21Render%21Element
 * @see \Drupal\webform_example_element\Element\WebformExampleElement
 */
class PersonCountElement extends Hidden {

  public function getInfo() {
    $properties = parent::getInfo();

    // $properties['#theme'] = 'input__site_person_count';
    return $properties;
  }

}

Is there anything more to it?
Answer: Ok, this was a really stupid mistake! my src/Element folder had actually a space in the name.
correct: src/Element/PersonCountElement.php
wrong: src/Element /PersonCountElement.php
With the correct folder name, it works like a charm.

Custom webform Element not rendered


Multithreading and connection pool

Question: I have problems with asp.net web service that randomly getting errors like "sql transaction completed no longer usable", "transaction is already commited..."
After read lot of posts I think its problem of shared connection problem bet I was unable to find where the problem is.
Starting from 0 I want to create a "class for 2 porpuoses
- Ensure Connections are closed
- Coding less
The simply class have 2 methods GDT (Give DataTable) and Ejecutar (execute in spanish)
¿Can anybody tell me if this class is well designed for non having problems of sharing connections?
Public Class clsAccesoBD2

Public Function GDT(ByVal strSql As String) As DataTable
    Try
        Using Cnn As New SqlConnection(ConfigurationManager.ConnectionStrings("CadenaPEA").ConnectionString)
            Using da As New SqlDataAdapter(strSql, Cnn)
                Using dt As New DataTable
                    da.Fill(dt)
                    Return dt
                End Using
            End Using
        End Using
    Catch ex As Exception
        'Log code here

Throw
        End Try
    End Function
Public Function Ejecutar(ByVal strSql As String) As Integer
    Try
        Using Cnn As New SqlConnection(ConfigurationManager.ConnectionStrings("CadenaPEA").ConnectionString)
            Using Cb As New SqlCommand(strSql, Cnn)
                Dim RegistrosAfectados As Integer
                Cnn.Open()
                RegistrosAfectados = Cb.ExecuteNonQuery()
                Cnn.Close()
                Return RegistrosAfectados
            End Using
        End Using
    Catch ex As Exception
        'Log code here
        Throw
    End Try

End Function

End Class
este
Answer: close db connection (i.e. Cnn.Close()) in finally block of try-catch-finally construct
Comment: i thought when using "using" statament and an error occurs and the focus moves to catch blcok, the connection automatically closes (because this is out of using block).

Multithreading and connection pool


redirecting output from telnet / nc to file in script fails when cron'd

Question: So, I have device on my network which sits there listening on a port for a connection, and when a connection is made it dumps ascii data out. I need to capture that data to a file. I wrote a dead simple shell script that does this:
<code>#!/bin/bash

#Config Variables. Age is in Days.
DATA_ROOT=/root/data
FILENAME=data_`date +%F`.dat
HOST=device
COMPRESS_AGE=3

#Sanity Checks
if [ ! -e $DATA_ROOT ]
then
        echo "The directory $DATA_ROOT seems to not exist. Please create it."
        exit 1
fi

if [ -e $DATA_ROOT/$FILENAME ]
then
        echo "You seem to have extracted data already today. Aborting"
        exit 1
fi

#Get Data
nc $HOST 2202 > $DATA_ROOT/$FILENAME
#Compress old Data
find $DATA_ROOT -type f -mtime +$COMPRESS_AGE -exec gzip {} \;

exit 0
</code>
It works great when I run it by hand, but when I run it from cron, it doesn't capture any of the output. If I replace nc with telnet I see the initial telnet headers about escape sequences and whatnot, but not the data.
Ideas? I've tried forcing bash to act like an interactive shell with -i. I've tried redirecting both stderr and stdout. I know it's got to be some silly simple thing, but I'm utterly failing. This is driving me nuts...
EDIT I also just noticed that the nc processes from all my previous attempts at this have been siting sleeping, and when I killed them, cron sent me a bunch of non-sensical error messages. At least now I have something to dig into!
Comment: Check that all paths are set correctly. Whenever I've had something that works not work in cron, it's because cron doesn't inherit the correct PATH(s).
Comment: Under which account is your cron running?  You are sure it has permissions to the location where it is writing?
Comment: Add this line immediately before the `nc` line: `echo 'Starting' > $DATA_ROOT/$FILENAME.test` as a test and see if you get that line in the file with ".test" appended to the expected name. (Also, does the file you expect get created? Is it zero bytes long? What happens if you specify the full path to `nc` such as `/bin/nc $HOST 2022 ...` or wherever it's located on your system - find out by doing `type -a nc`?).
Comment: Cory J - The PATH is correct and/or I'm using absolute paths in the script.
Zoredache - Everything is owned by root, and it is being run out of root's crontab
Dennis - Adding an "echo starting...." and that does get captured in the file. The file does get created, even without that, but it only has a few bogus characters in it. Specifying the full path doesn't change anything.

Thanks for the input! Anything else?
Answer: It's possible that your script is working, and it's just the output that's getting lost.  You could try capturing the nc output into a variable of it's own, and then echoing that variable out to
<code>#Get Data
ncoutput=$( /path/to/nc $HOST 2202 2>&1 )
printf "%s\n" "$ncoutput" > $DATA_ROOT/$FILENAME
#Compress old Data
find $DATA_ROOT -type f -mtime +$COMPRESS_AGE -exec gzip {} \;

exit 0
</code>
printf preserves the formating of the output, whereas echo doesn't.


Trouble double tonguing on trumpet

Question: I am a "come-back" trumpet player. Consider being Intermediate level. Have a Yamaha YTR 3335 Trumpet. I try to warm-up and practice daily for 1 hour.
I have been concentrating on Single and Double Tonguing to try to improve these techniques.
I have read and studied a large number of articles, videos and listened to well-known trumpeters.
I still have a problem with the "Ka", (or similar) syllable.
I find it difficult to pronounce the "Ka" syllable and blow a note on the trumpet. The lip formation is not conducive to blowing a note. ( I understand that the "ka" is to be obtained at the back of the tongue.) I do not appear to have this problem with the "Tu" syllable.
Comment: I have trouble reading your question title three times rapidly ;))
Comment: @Tetsujin Sorry, that was my fault.
Comment: See also here: https://music.stackexchange.com/q/7439/9426
Answer: A few practice tips:

Keep the vowel consistent: rather than "tu ka", try "tu ku" or "ta ka".
Try different vowels: "tee kee" or even "toh koh" might work better for you.
Try different consonants: "D" and "G" are often taught instead of "T" and "K". I use both depending on the musical demands of what I'm playing, but "D/G" might get you started and "T/K" can come later.
Practice without the trumpet: This was a key for me, just being able to quickly produce the syllables and then to speak them continuously.
Practice with mouthpiece only: In addition to playing without the full resistance of the trumpet, it can also be helpful to speak into the mouthpiece to get some tactile feedback on whether your lips are changing shape, which they should not. The rest our your mouth shape may change, but the lips should remain consistent.
Practice "ha" with no tonguing: This is to reinforce your air support. With the regular "T" tonguing, you can get away with using only the air in your mouth, so to speak, because the air is behind the consonant. This doesn't work with "K", because the air is in front of the consonant and because of the tendency to close the throat. Making sure you've got a solid "H", will help preserve the feel of it when reintroducing the "K".
Comment: Be aware that using 'D' and 'G' will give a muddier articulation than 'T' and 'K'. I would add: start slow! Focus on getting the 'T/K' or 'D/G' part right, and worry about speed later.
Answer: In addition to Aaron's useful suggestions:

Practise the 'K' sound on its own. You could alternately play a scale or simple melodic motif using 'T' articulation then 'K'. The goal here is to make the 'K' sound as incisive as the 'T'. Bear in mind that what you hear by conduction through your skull to your ears is not the same as the room sound that everyone else hears. Try using a sound recorder to see what you actually sound like. You could also do simple rhythmic patters like TTTT Ta and then KKKK Ka.
It's important that both 'T' and 'K' articulations are as rapid as possible (think of a snake darting its tongue in and out). Most of the time your tongue should be low in your mouth, only moving when you need to articulate the next note.
Lots of players double tongue in a way that makes each note really short. The overall effect is to sound constipated. I'd suggest instead you try to make each articulated note as long as you possibly can; imagine that instead of producing tiny packets of air, you're producing a constant stream of air that you're 'notching' with your tongue; so the air doesn't stop.
When you start playing 16th note passages using double tonguing (alternating 'T' and 'K' articulation on each successive note) try switching it around so that you lead with the 'K', so you'd be able to switch between TKTK and KTKT patterns.
Be patient and don't beat yourself up. Double tonguing is not magic, it's an acquirable skill but there's no fast way to learn. You need to use good practice habits and repeat the exercises until it's second nature.
In all aspects of practice there's a concept like Venn diagrams (you know those overlapping circles from school?) If we try to practice a technique without proper thought, we end up trying to play loud and high and fast all at the same time (e.g. combining two or more techniques) what we're practising is the overlap of three circles of technique. Far better to think about what you practise and then you can practice one technique on its own. So for double tonguing, get all the other techniques out of the way - don't use valves, don't play high, don't play too loud or too quiet - that way you can focus on the one technique you are trying to practise.
Comment: Big ups for the "K"-only practice. And shame on me for forgetting that one.:-)
Answer: wikihow suggests using the word "ticket" as a way to think about tongue placement - I think it also encourages small tongue movement and repetition (thereby better control and faster) between the "t" and the "k", by keeping the tongue arched a bit, compared to using "ta" and "ka". May not work for everyone and important to start slow.

Trouble double tonguing on trumpet


Cannot submit forms in Drupal 7

Question: When I submit forms(all forms) in Drupal 7 it shows the Your configuration settings have been saved message, but the form values are still the same as the values before submission. I have cleared the cache but the problem still exists.
Any suggestion?
Comment: Are you overriding the variables in $conf array, e.g settings.php?
Comment: Yes. It was working...
Comment: @DavidThomas NO!
Comment: Any errors in the watchdog log (admin/reports/dblog)?
Comment: Are you getting the same error when you create new content?
Comment: Do you use any CDN caching on your server? This could be the problem and to resolve you would have to deal with whoever administrates this.
Comment: @hpn, you are going to have to provide more information.  Without it, the root cause could really be anything.  What do the forms do?  Webforms, or Drupal forms API?  Did you disable browser autocomplete / test multiple browsers?
Answer: I can suggest how you can test what's happening:

Create custom test form with submit function.
Install Xdebug on your LAMP, or WAMP or MAMP
Than watch callstack. look what functions have been called.

Looks you've done some specific changes in your instalation.
Also try to download clear drupal instalation and check forms there.
(P.S. If you have opportunity switch to new instalation).
Answer: Your form returns not the elements of the form. But your return part of function is something like:
...
return system_settings_form($form);
}

if we look to this function:
function system_settings_form($form) {
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save configuration'),
  );

  if (!empty($_POST) && form_get_errors()) {
    drupal_set_message(t('The settings have not been saved because of the errors.'), 'error');
  }

  $form['#submit'][] = 'system_settings_form_submit';
  // By default, render the form using theme_system_settings_form().
  if (!isset($form['#theme'])) {
    $form['#theme'] = 'system_settings_form';
  }
  return $form;
}

Your problem is:  $form['#submit'][] = 'system_settings_form_submit';
this adds another submit function to form. And this function saves variables through variable_set() function:
function system_settings_form_submit($form, &$form_state) {
  // Exclude unnecessary elements.
  form_state_values_clean($form_state);

  foreach ($form_state['values'] as $key => $value) {
    if (is_array($value) && isset($form_state['values']['array_filter'])) {
      $value = array_keys(array_filter($value));
    }
    variable_set($key, $value);
  }

  drupal_set_message(t('The configuration options have been saved.'));
}

So you have to get your settings  variables with function variable_get();

Cannot submit forms in Drupal 7


Unable to play the RTMP url in AVPlayer?

Question: <code>- (void)playMethod {

 NSURL *url = [[NSURL alloc] initWithString:@"rtmp://126.96.36.199:1935/CVIEW_alpha/24"];

    player = [AVPlayer playerWithURL:url];
    controller = [[AVPlayerViewController alloc] init];
    [self addChildViewController:controller];
    [self.view addSubview:controller.view];

    //to rotate to the landscape on click of play button
    [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft) forKey:@"orientation"];
    [UINavigationController attemptRotationToDeviceOrientation];

    //to open the view
    controller.view.frame = CGRectMake(0,0,667,375);
    controller.player = player;
    controller.showsPlaybackControls = YES;

    // to add the back button on player
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [button1 addTarget:self
                action:@selector(backMethod)
      forControlEvents:UIControlEventTouchUpInside];
    [button1 setTitle:@"Back" forState:UIControlStateNormal];
    [button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button1.frame = CGRectMake(50.0, CGRectGetMinY(controller.view.frame)+10, 160.0, 40.0);
    button1.tag = 1001;
    [self.view addSubview:button1];
    [controller.view  bringSubviewToFront:button1];
    [player pause];
    [player play];
}
</code>
I am trying to play the above URL in AVPlayer and getting the following errors.

2018-06-08 14:55:00.326842+0530 vedio[14773:4486922] NSURLConnection finished with error - code -1002
  2018-06-08 14:55:00.605227+0530 vedio[14773:4485935] [] <<<< AVOutputDeviceDiscoverySession (FigRouteDiscoverer) >>>> -[AVFigRouteDiscovererOutputDeviceDiscoverySessionImpl outputDeviceDiscoverySessionDidChangeDiscoveryMode:]: Setting device discovery mode to DiscoveryMode_None (client: vedio)
  2018-06-08 14:55:00.652598+0530 vedio[14773:4485935] [] <<<< AVOutputDeviceDiscoverySession (FigRouteDiscoverer) >>>> -[AVFigRouteDiscovererOutputDeviceDiscoverySessionImpl outputDeviceDiscoverySessionDidChangeDiscoveryMode:]: Setting device discovery mode to DiscoveryMode_Presence (client: vedio)
  2018-06-08 14:55:01.013628+0530 vedio[14773:4485935] [App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction
  2018-06-08 14:55:01.013766+0530 vedio[14773:4485935] [App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction
Comment: I think you need to add `rtmp://` in info.plist -> url schema
Comment: @MahendraGP still getting the same error.
Answer: AVPlayer does not have support for rtmp. You must use a different player, or protocol.


Programmatically embed fields of one content type in the create/edit form of another content type and store all

Question: I have drupal 6.x.
How to programmatically (with a custom module) embed fields of one content type (content type X) in the create/edit form of another content type (content type Y) and store all the data for when the node is created/updated (store X and Y data when Y is stored).
If is not possible this in drupal 6.x I could be to work in drupal 7.x.
Thanks in advance.
Answer: I think it would be tricky as you would need a way of tracking a relationship between the two nodes as well. You would need to decide on which way the relationship would go if you were to use node reference as its only one way in drupal 6.
This is what I would do
1. Add a node reference field to Y
2. Use hook_form_alter to add the required fields (Embedding cck fields will be tricky better of just sticking to fapi fields)
3. add a custom validation handler for the x fields if required
3. Save x field values as a node programticaly when presave is triggered by hook_node_api http://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook_nodeapi/6
4. Update the noderefrence in Y with the new X nid
5. Use hook_node_api to update X when Y is updated
Another possibility might be to use Rules to create and update for you
Answer: http://drupal.org/project/field_reference There's another cck reference field module that should do the same thing for 6 & maybe 7 I cannot recall the name though.
http://drupal.org/project/nodereference_field is different sort of thing where you would create a node that both other nodes could reference which can be nice if your referencing several points of data however there's some bloat to your database & extra time to look up and process the queries from a full node. It's also only v6 so no upgrade path.
http://drupal.org/project/references & http://drupal.org/project/entityreference are the 7+ equivalent of nodereference.
Note: modules aren't what's asked for but they should show you the path if you dissect them.


What's the Best Way to Write Text to Blob in an Azure Webjob

Question: I have an Azure Webjob. It's dequeuing a message and processing it. When it dequeues the message it uses the default model binder to enable me to have a strong-typed parameter. At the moment, the signature to that function looks like this:
DequeueCUWebinarMessages([QueueTrigger("tts-cuw-notifications-queue")] NotificationMessage notificationMessage, int dequeueCount, TextWriter log)

I want to store one of the properties of that NotificationMessage object to blob storage. The property in question is a string (specifically, html).
I am aware of the fact that there are Blob attributes which you can use in your WebJobs functions. So my question is, should I use one of those blob attributes? And if so, what would my new function signature look like?
Or, should I just use the storage client API to "upload" the string to a blob container?
What would be the best practice?
Answer: You can use the WebJobs SDK to do that. Here is how the function could look like:
DequeueCUWebinarMessages(
    [QueueTrigger("tts-cuw-notifications-queue")] NotificationMessage notificationMessage,
    [Blob("output/blob.txt")] out string blob,
    int dequeueCount,
    TextWriter log)
{
     blob = "blob content";
}

Instead of string you can also use Stream, TextWriter, CloudBlockBlob, ICloudBlob or your own custom type if you implement a customer serializer.
Comment: Take a look at our samples: https://github.com/Azure/azure-webjobs-sdk-samples/tree/master/BasicSamples . There are examples on how to have a dynamic name either based on some properties of the trigger or from a name resolver
Comment: Thanks, that did work. My next step is to name it dynamically. I think there was some kind of token you can use in the Blob attribute. I'll research that. Thanks.
Comment: Thanks Victor. That's been really helpful.


How do you transfer ownership of a Drupal contrib module to someone else?

Question: I own the S3FS and Date iCal Drupal contrib modules, though I abandoned development on them quite a while ago, due to moving all my work to another platform. However, I am still on the record as the "owner" of these modules, despite there being other maintainers who have taken over.
There's no obvious way to remove myself as owner. I can't uncheck any of my permissions from the Maintainers listing. There doesn't appear to be any UI that lets me designate an existing maintainer as the new owner.
What do I do?
Comment: You have to file an issue with the drupal.org webmasters queue, who have control to reassign ownership.
Comment: Well that's extremely onerous... Thanks, though.
Answer: You can either:

Open an issue on the Drupal.org project ownership queue, asking to make the new project owner a user on drupal.org that you know be willing to become the new project owner
Open an issue on the same queue, asking to make the new project owner the maintainer who did more commits or who was more active in following and answering the project issues
Open an issue in the same queue, stating you are seeking for a new project owner, using Needs maintainers as Component value

Once you open the issue queue, the procedure will be handled by Drupal.org site moderators.
As alternative, you could simply set the Maintenance status field of the project to Seeking new maintainer and (eventually) the Development status to No further development. Users who need the project, and who are able to develop code for a project, seeing you set that status, could ask to be the new project owner or maintainer, if they are interested.
Finally, if you think you won't maintain anymore a project hosted on drupal.org and you won't use Drupal, you could delete your account on drupal.org. Authenticated user are now able to delete their account on drupal.org, for any reason they could have.


How to get value without brackets using JQuery plugin inputmask?

Question: There is the following code:
$("#ce_clientphone").inputmask("+9(999)9999999")
...
console.log($('#ce_clientphone').unmask())

As you can see I try to get value from '#ce_clientphone' without brackets. How can I do it? I need to allow user to input valid phone, but to save it in the database I need to remove brackets. Thanks in advance.
Comment: $(selector).inputmask('unmaskedvalue');

https://github.com/RobinHerbots/jquery.inputmask#unmaskedvalue
Comment: possible duplicate of [javascript Regex get string inside brackets,removing brackets](http://stackoverflow.com/questions/18559762/javascript-regex-get-string-inside-brackets-removing-brackets)
Answer: You could do regular expressions and replace to remove the brackets
"+9(999)9999999".replace(/[()]/g,'');

Answer: Try this:
$('#ce_clientphone').unmask().replace(/[()]/g, '');

For example:
"+9(999)9999999".replace(/[()]/g, '');

Returns:
"+99999999999"

So, how does this work?
We're using a regex to replace the brackets:
/  // Start of regex
[  // Start of character group
() // match either of these characters in the group (So match `(` OR `)`)
]  // End of character group
/  // End of regex
g  // `Global` flag. This means the regex won't stop searching after the first replace

Answer: var str="+9(999)9999999";
alert(str.replace(/[()]/g,''));

DEMO


Flex Slider issues after upgrading Drupal to v7.39

Question: I've been researching this issue for a week to no avail.  Perhaps someone has some suggestions?
Upgraded a site from Drupal 7.34 to 7.39 rather seamlessly.  Also updated all modules that were down level.  All seemed OK.  But then the flex slider just stopped displaying.  I've checked all I could in the various display and definitions pages and all looks fine.  I've tried different browsers and even a different server instance with on luck.
I'm just hoping someone who may have experienced this anomalie can shet some light on what to look for next?
Answer: Don't know why but in the admin/config/development/performance section I unchecked the compress javascript option, saved the page and suddenly my flex-slider images returned.  Strange though, isn't it?
Anyway - solved.


minor tetratonic scales

Question: I've read somewhere that tetratonic scales have been extensively played in jazz from Lester Young to Mulgrew Miller. I understand they are derived from the melodic minor scale. Could anyone explain to me how they are built and which chords they can be played over?
UPDATE:
I think I have answered my own question:
The tetratonic scales should contain the tonic, the minor third, the fifth and the sixth of any melodic minor scale.
For example, the tetratonic scale of C would be C-Eb-G-A.
Now one needs to figure out the only major scale which has these notes; in this instance, it is Bb MAJ.
When you play the C melodic minor tetratonic scale over the Bbmajor scale, you highlight the 9th, the 4th, the 6th and the 7th of that scale.
It's interesting because you leave the tonic and the fifth aside.
I took a step further with a very simple progression (eddie harris's "listen here") Bb7 and Eb7.
Now I decided that the key is Ab; in Roman numerals that would make the song a II7 - V7
The tetratonic scale for Ab is Bb-Db-F-G and it works nicely on Bb7 because Db is the b5 of the G blues scale and also over Eb7 because Db is the b7 of that chord.
So the tetratonic scale can work on the whole cadence and is very useful to add approach notes. You can also spot the third of the chord easily if you want it.
Answer: You are almost right :)
In fact any substructure (smaller scale contained) of any scale can be used to improvise over the current chord's chord-scale
The fewer the notes in your substructure the better defined the sound is. Triads are great to use as substructures, and also Tetratonic scales, Pentatonic and even HexaTonic scales. In praticular bi-triadic hexatonics are great for improvisation.
Look, here's an example of using substructures to improvise over a 7b5 chord when considering the Enigmatic Scale as it's chord's scale
Using Substructures For Improvisation
And here is an explanation on how to use bi-triadic hexatonics for composition and improvisation
Bi-Triadic Hexatonics
Answer: tetratonic scales aren't necessarily derived from the melodic minor scale. They can be arbitrarily constructed from the chromatic scale since a tetratonic scale simply means to have four notes in the scale. Though of course some choices are going to inherently sound better than others and will be more versatile. e.g. if you constructed a tetratonic scale made of C, Db, D, Eb (theoretically meets the requirements of being a tetratonic scale) it probably wouldn't sound as good as C, Eb, G and A as you mentioned above and would be far less versatile because not all chords would be able to accommodate for the chromaticism.
In terms of which chords you can play them over, that in a way is arbitrary as well and depends on the scale that you have made. So the two aspects are interdependent of each other. You may want to increase the tension of the music by playing a scale that doesn't have many of the chord tones of the chord in it. Or by making a scale whose notes are a semitone away from some of the notes in the chord that you are playing it over. onversely you may want the music to be less tense (dissonant) so then you may opt to create a scale that uses some of the notes of the chords you are playing or use notes that have a greater distance from the chord tones.

minor tetratonic scales


Under what choice assumptions is there a monoid structure on every set?

Question: The question arose when discussing possible cardinalities of hom-sets of whether it's any weaker than the axiom of choice that there exists a monoid of every cardinality. It's well known, or at least known, that the axiom of choice holds just if every set $S$ has a group structure. One direction follows from Lowenheim-Skolem, and the other from using the group structure to inject $S$ into $h(S)\times h(S)$, $h$ the Hartogs number.
So, a proof of choice from monoid structures would certainly have to proceed differently. If the monoid is commutative and infinite, then I guess its Grothendieck group will share its cardinality, and we see the existence of commutative monoid structures on every set implies AC. Is the left adjoint of the forgetful functor from all groups to monoids any worse than the Grothendieck group functor? Or does anyone suggest a different proof?
Answer: Every non-empty set admits a commutative monoid structure:

The 1-element set is a monoid in a unique way.
If $X$ has at least two distinct elements, say $0$ and $1$, then we can make $X$ into a commutative monoid as follows:
$$x \cdot y = \begin{cases}
x & \text{if } y = 1 \\
y & \text{if } x = 1 \\
0 & \text{otherwise}
\end{cases}$$
Of course, $X$ is not a cancellative monoid in this case.
Answer: If you're willing to think about semigroups rather than monoids, then some further comments are in order.
First comment. Every set $X$ carries two canonical semigroup structures:

The "left zero" semigroup: $xy=x$ for all $x,y \in X$.
The "right zero" semigroup: $xy=y$ for all $x,y \in X$.

This gives two non-equivalent functors
$$\mathbf{SemiGrp} \leftarrow \mathbf{Set}.$$
Obviously, both are sections of the forgetful functor
$$\mathbf{SemiGrp} \rightarrow \mathbf{Set}.$$
Second comment. By a pointed semigroup, I mean a semigroup $X$ together with a distinguished absorbing element $\bot$. This can be equivalently defined as a semigroup object in the monoidal category of pointed sets with smash product.
Its interesting to observe that every pointed set $(X,\bot)$ can be made into a pointed semigroup in the following ways:

The "Zhen Lin" semigroup: we declare that $xy=\bot$ for all $x,y \in X$.
The "equality" semigroup: we declare that $x^2=x$ for all $x \in X,$ and $xy=\bot$ for all distinct $x,y \in X$.

This gives two non-equivalent functors
$$\mathbf{\bot SemiGrp} \leftarrow \mathbf{\bot Set}.$$
Obviously, both are sections of the forgetful functor
$$\mathbf{\bot SemiGrp} \rightarrow \mathbf{\bot Set}.$$
Third comment.
What we're talking about here is really a kind of "categorified idempotency."
Let me explain.
If $x$ is an element of some monoid, then $x$ is said to be idempotent iff $x=x^2$. It makes sense to write $\mathrm{isIdem}(x)$ for the statement $x=x^2$. Okay, but what happens if we're given an object $X$ living in a monoidal category? Well, we could choose to define that $\mathrm{isIdem}(X)$ means "the set of all isomorphisms $X \leftarrow X \otimes X$." But such isomorphisms seem not to arise very often in practice. Another option would be to defined that $\mathrm{isIdem}(X)$ means "the set of all morphisms $X \leftarrow X \otimes X$." So basically, its the set of all ways of making $X$ into a magma. But darn it, magmas are just so uselessly general! So to make the concept more useful, lets define that $\mathrm{isIdem}(X)$ is the set of all associative morphisms $f : X \leftarrow X \otimes X$. In other words, its the collection of all ways of making $X$ into a semigroup.
Under the philosophy of propositions as types and in light of the above paragraph, we can think of the proposition "$X$ is idempotent" as denoting the collection of all ways of making the object $X$ into a semigroup. Hence if $\mathbf{C}$ is a monoidal category, we can think of the proposition "every object of $\mathbf{C}$ is idempotent" as denoting the collection of all sections of the forgetful functor $$\mathbf{C} \leftarrow \mathrm{Semi}(\mathbf{C}),$$ which are thought of as "proofs" for this statement. Hence, the first comment really consisted of defining two non-equivalent "proofs" that "every object of $(\mathbf{Set},\times,1)$ is idempotent," and the second comment really consisted of defining two non-equivalent "proofs" that "every object of $(\bot\mathbf{Set},\otimes,\{0,\bot\})$ is idempotent."


Mongoose - Query a nested property of Schema.Type.Mixed as a specified data type (Date)

Question: I have a schema setup in Mongoose with
var MySchema = new Schema({
data: {
type: Schema.Types.Mixed
}
});

My issue is that on this 'data' object i am storing a date value as a nested property, it all works fine until i try and do a find() query with Mongoose and search using the nested field. Because Mongoose doesn't know it is a Date it cant use the usual '$gte', '$lte' and similar operators im guessing because it sees that data as just a String.
One of my objects looks similar to this
{
title:"My object",
data:{
 publishDate: "2016-07-12T05:00:48.985Z"
}

Is there anyway that i can explicitly tell Mongoose to expect the value to be a date so i can use '$gte' as an operator?
Model.find({
"data.publishDate":{
 $gte:new Date()
}
})

Answer: Turns out i had to strictly type the value as a date before saving to the database. Otherwise the date operators '$gte', '$lte' etc would not work.
Solution is to do this
{
title:"My object",
data:{
 publishDate: new Date("2016-07-12T05:00:48.985Z")
}

At this point i don't believe you can type the data dynamically when running a query.


How can I correct for using latent variables in mediation analysis?

Question: I have 1 binary treatment and 7 latent factors as possible outcomes and would like to explore the association among them through a mediation analysis (using a structural Equation Model). Unfortunately, the number of items generating each of these latent factors is really huge (from 13 to 55, depending on the factor: 246 in total) making a full model (using observed variables) computationally unfeasible (I tried with 2 factors, one with 32 and the other with 54 items). I thought I could use factors from the Item-Response Theory model; however, there is an obvious error due to the fact that they are latent, thus only estimated. Is there a correction I can use for it, so that I can use such items for my mediation analysis? Alternatively, is there a way how I can reduce the number of items in my final analysis to make my model computationally feasible? I was thinking at something as described here:
(pdf)
but with a continuous latent variable, and in a mediation analysis setting.
Or should I give up on SEM's and look for something simpler?
Comment: Why do you think that the fact that they are latent is a problem?
Comment: Because latent factors are the results of an estimation process rather than observed. Otherwise I wouldn't understand why one should build a model by simultaneously creating the latent factors and exploring the relationship between treatment, mediator(s) and outcome(s) instead of always using a two-step procedure.
Answer: I've found a paper addressing this issue:
(pdf)
A two-stage model where first factor scores are calculated then used in a regression (in the way I was asking) is called factor-score regression and the fact that factor scores are estimated introduces a bias. The paper compares (among others) two methods to address this bias:  the bias avoiding method of Skrondal and Laake, and the bias correcting method of Croon.
Answer: Factor scores do not have to introduce a bias but they do necessarily contain an arbitrary component, though with dozens of items the arbitrary component could be quite small(e.g., Rigdon, Becker, & Sarstedt 2019). The arbitrary component means that estimates will vary depending on exactly how the arbitrary component is chosen.
If your inability to estimate the factor model is not just a matter of sample size, you might consider Bollen's (e.g., 2019) Model-Implied Instrumental Variable (MIIVsem) method, using two stage least squares.


How do I analyze these two sets of data

Question: I am doing a research study on self efficacy and birth month (when children enter school, if they are oldest in class or youngest).
I have each of the participants scores on their self efficacy scale (rated on a 14 point likert scale) and I have ranked their birth months (starting with Sept = 1, Oct = 2, etc.).
I am wondering how I can analyze this data to find statistical significance, variance, etc.
Thanks!.
Answer: First, a 14 point Likert scale is quite unusual. I don't think I've ever seen one. Is this the sum of two 7 point questions?
Second, given that you are actually interested not in birth month, per se, but in time in school, why not use that? Beware that, by using birth month as a proxy for this, you are assuming that all the children in your study go to schools with the same cut-off. This isn't necessarily the case.  In NY city, for instance, public schools have one cutoff and private and parochial schools have another (last I checked, these were Dec. 1 and Aug 1, but my memory might be off).
Third With that assumption, birth month is usable as an IV. You could do either ordinal logistic regression or possibly ordinary least squares regression. 14 points is a lot for ordinal but not enough really for OLS.  In situations like this, I usually run both models, then I compare the predictions. If they are similar, I use the simpler model (in this case, OLS).
Comment: +1 in general, but I want to second the suggestion to use age or time-in-school over some coded version of the birth month too. Unless I'm missing something domain specific, I don't see any upside and a lot downside to using the birth month....
Comment: Is 14 different categories really not enough to treat the variable as continuous in OLS regression and satisfy all the assumptions?
Comment: @PatrickCoulombe I think you have to run the model and check the residuals.

How do I analyze these two sets of data


How to mask a 3D tensor with 2D mask and keep the dimensions of original vector?

Question: Suppose, I have a 3D tensor A
A = torch.arange(24).view(4, 3, 2)
print(A)

and require masking it using 2D tensor
mask = torch.zeros((4, 3), dtype=torch.int64)  # or dtype=torch.ByteTensor
mask[0, 0] = 1
mask[1, 1] = 1
mask[3, 0] = 1
print('Mask: ', mask)

Using masked_select functionality from PyTorch leads to the following error.
torch.masked_select(X, (mask == 1))

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-72-fd6809d2c4cc> in <module>
     12
     13 # Select based on new mask
---> 14 Y = torch.masked_select(X, (mask == 1))
     15 #Y = X * mask_
     16 print(Y)

RuntimeError: The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 2

How to mask a 3D tensor with a 2D mask and keep the dimensions of the original vector? Any hints will be appreciated.
Answer: Essentially, we need to match the dimension of the tensor mask with the tensor being masked.
There are two ways to do it.
Approach 1: Does not preserve original tensor dimensions.
X = torch.arange(24).view(4, 3, 2)
print(X)

mask = torch.zeros((4, 3), dtype=torch.int64)  # or dtype=torch.ByteTensor
mask[0, 0] = 1
mask[1, 1] = 1
mask[3, 0] = 1
print('Mask: ', mask)

# Add a dimension to the mask tensor and expand it to the size of original tensor
mask_ = mask.unsqueeze(-1).expand(X.size())
print(mask_)

# Select based on the new expanded mask
Y = torch.masked_select(X, (mask_ == 1)) # does not preserve the dims
print(Y)

The output for approach 1:
tensor([ 0,  1,  8,  9, 18, 19])

Approach 2: Preserves the original tensor dimensions (by padding).
X = torch.arange(24).view(4, 3, 2)
print(X)

mask = torch.zeros((4, 3), dtype=torch.int64)  # or dtype=torch.ByteTensor
mask[0, 0] = 1
mask[1, 1] = 1
mask[3, 0] = 1
print('Mask: ', mask)

# Add a dimension to the mask tensor and expand it to the size of original tensor
mask_ = mask.unsqueeze(-1).expand(X.size())
print(mask_)

# Select based on the new expanded mask
Y = X * mask_
print(Y)

The output for approach 2:
tensor([[[ 0,  1],
         [ 2,  3],
         [ 4,  5]],

        [[ 6,  7],
         [ 8,  9],
         [10, 11]],

        [[12, 13],
         [14, 15],
         [16, 17]],

        [[18, 19],
         [20, 21],
         [22, 23]]])
Mask:  tensor([[1, 0, 0],
        [0, 1, 0],
        [0, 0, 0],
        [1, 0, 0]])
tensor([[[1, 1],
         [0, 0],
         [0, 0]],

        [[0, 0],
         [1, 1],
         [0, 0]],

        [[0, 0],
         [0, 0],
         [0, 0]],

        [[1, 1],
         [0, 0],
         [0, 0]]])
tensor([[[ 0,  1],
         [ 0,  0],
         [ 0,  0]],

        [[ 0,  0],
         [ 8,  9],
         [ 0,  0]],

        [[ 0,  0],
         [ 0,  0],
         [ 0,  0]],

        [[18, 19],
         [ 0,  0],
         [ 0,  0]]]

Answer: There is a simple way to preserve dims as follows:
torch.mul(X, mask.unsqueeze(-1))

the results is also:
tensor([[[ 0,  1],
     [ 0,  0],
     [ 0,  0]],

    [[ 0,  0],
     [ 8,  9],
     [ 0,  0]],

    [[ 0,  0],
     [ 0,  0],
     [ 0,  0]],

    [[18, 19],
     [ 0,  0],
     [ 0,  0]]])


Odds of picking letters from the alphabet

Question: I want to know how to work out the odds of randomly picking specific letters for a given word from the alphabet.

Let's call the random word: "bobdylan"
Total letters: 8
Total chances to randomly pick: 7 (since b appears twice)
With each pick, the chosen letter will be removed from the pool.
The order chosen does not matter

What I want to work out is the odds of 0, 1, 2, 3, 4, 5, 6, 7 correct letters.
What I have done is to write a program to randomly pick letters and I have found that it nearly always picks 1 - 4 correct letters in any given go with very few 0 correct answers.
Answer: In the case of 7 distinct letters, we can partition the alphabet into 2 groups, one with correct letters (7) and wrong letters (26-7=19).
If we choose 7 letters and want x correct letters, we need x to be from the correct letters and 7-x to be from the wrong letters.
We note that the sample space if given by the fact that we are choosing 7 letters from the alphabet of 26.
That means, for any x $\leq 7$, the probability is:
$$ \frac{\binom{7}{x} \binom{19}{7-x}}{\binom{26}{7}}$$
Comment: So how do I know the actual maths for matching 7 correct letter? i.e. 1 in 200 chance?
Comment: @HappyCoder I gave the probability for matching all 7 correct letters in my answer., it isn't close to 1 in 200.  It is closer to 1 in 100000.
Answer: Rephrased... you have an urn with $26$ balls (representing the letters), $7$ of which are gold (representing the letters present in bobdylan) and the remaining $19$ of which are red.  You ask what the probability (not odds, related but different definition) is that given the player picks $7$ balls that exactly $k$ of them are gold?  This follows the Hypergeometric Distribution.
The probability of getting exactly $k$ gold balls will be:
$$\dfrac{\binom{7}{k}\binom{19}{7-k}}{\binom{26}{7}}$$
The probabilities themselves being:
$\begin{array}{l|l}Pr(X=k)&\dfrac{\binom{7}{k}\binom{19}{7-k}}{\binom{26}{7}}\\
\hline
Pr(X=0)&\approx 0.0766\\
Pr(X=1)&\approx 0.28873\\
Pr(X=2)&\approx 0.3712\\
\vdots
\\
Pr(X=7)&\approx 1.5\cdot 10^{-6}\end{array}$
The above uses the notation of binomial coefficients.  $\binom{n}{k}$, read aloud as "$n$ choose $k$" is the number of $k$-kelement subsets of an $n$-element set.  We recognize that $\binom{n}{k}=\frac{n!}{k!(n-k)!}$.  Here, $n!$ represents the number of permutations of an $n$-element set.  We recognize that $n! = n\times (n-1)!$ and $0!=1!=1$.  These together imply (for natural $n$) that $n! = \prod\limits_{i=1}^n i$, for example $3! = 1\times 2\times 3=6$ and $5! = 1\times 2\times 3\times 4\times 5=120$ and $6!=1\times 2\times 3\times 4\times 5\times 6 = 720$ etc...
Breaking down one of the entries of the above table in more detail then, we have for example:
$$Pr(X=0)=\dfrac{\binom{7}{0}\binom{19}{7-0}}{\binom{26}{7}} = \dfrac{\frac{7!}{0!7!}\cdot \frac{19!}{7!12!}}{\frac{26!}{7!19!}} = \dots$$
$n!$ grows incredibly large incredibly quickly and so we do not bother evaluating each individually and then multiplying them and dividing them by hand except for very small cases.  For example, if we were to try to calculate $\binom{26}{7}$ using and evaluating the factorials first as $\frac{26!}{7!19!}$ this would be $\binom{26}{7}=\dfrac{403291461126605635584000000}{5040\times 121645100408832000}$ which simplifies nicely to $657800$ but doing that by hand is not feasible.
Instead, plugging the above into a calculator such as wolframalpha we get after simplifications that:
$$Pr(X=0)=\frac{969}{12650}\approx 0.07660\dots$$
Comment: If k = 7, would this not be a division by zero? (7/7 x 19/0) / (26/7)
Comment: @happycoder those are binomial coefficients, *not fractions!*
Comment: @happycoder the binomial coefficient, $\binom{n}{k}$ (read aloud as "n choose k"), is the number of subsets of size k from an n- element set.  It is used in various counting problems like this one.  There is no division by zero going on.
Comment: Ok got it... how do I do the actual calculation? i.e, Pr(X=0) = 0.0766
Comment: @happycoder Pr(X=0) = (7 choose 0)(19 choose 7)/(26 choose 7).  To calculate binomial coefficients the most common way is as (n choose k)$=\dfrac{n!}{k!(n-k)!}$ where the exclamation marks represent the factorial, $n!$ counting the number of permutations of n elements, i.e. the number of ways you can line n distinct elements in a row using each exactly once.  Note, $0!=1$ and $n!=(n-1)!\times n$ so you have for example $5!= 5\cdot 4\cdot 3\cdot 2\cdot 1=120$


Choosing a password with constraints

Question: Password length is either 5 or 6 characters long.
Allowed characters are a-z, A-Z and 0-9.
The password should have at least one character from a-z, at least one character from A-Z and at least one character from 0-9.
How many legal passwords are there?
My answer:
|a-z| + |A-Z| + |0-9| = 62
A_5 = D(62, 5 - 3)
A_6 = D(62, 6 - 3)
Answer = |A_5| + |A_6|
Amy I correct?
Thanks
Comment: What does $D(x,y)$ mean?
Comment: Number of y combinations in group of x
Answer: Let us count the legal passwords of length $5$. If there were no restrictions, it would be $62^5$.
But some of these strings are bad. We count the bad strings of length $5$.  There are $52^5$ strings with no digit. There are $36^5$ strings with nothing from A-Z. And there are $36^5$ with nothing from a-z.
If we add these three numbers, we will have double-counted the all digit words,  the all caps word, and the all a-z words. There is a total of $10^5+26^5+26^5$ of these. Thus the number of bad strings of length $5$ is
$$52^5+36^5+36^5-10^5-26^5-26^5.$$
Subtract from $62^5$ to get the number of legal passwords of length $5$.
Repeat for $6$ characters and add.
Remark: The fancy name for the idea we used is the Principle of Inclusion/Exclusion.
Comment: Nice. Thanks a lot
Comment: You are welcome.

Choosing a password with constraints


Direct recording

Question: When I record I use a Fender Superchamp XD. I run a cord from the "out" jack to the recorder and then unplug the speaker in the amp. I have been doing this for years. Is this safe for the amp?
ML
Comment: I'm sparing my neighbors the noise.
Comment: Why do you need to disconnect the amp's speaker?
Answer: It's a tube amp with a tube output stage, and the answer for using a tube amp without load in general is that it can destroy the output circuit.  Whether the Superchamp XD is specifically protected against this (particularly as it is a more modern rerelease) by substituting a load resistor or other measures when no speaker is plugged in, I have not been able to determine from the manual to be found online.
So in general the advice would be not to do this.
Answer: The traditional advice is not to run a valve amp without a load.   But this hybrid device is not an old-school valve amp.  And if you've been "doing this for years" it would probably have blown up by now if it was going to.
Answer: Although it may not be an ideal way to record, I've heard of others doing just what you've done and claiming success. Output levels are probably less than ideal and impedances are probably mismatched and I would expect elevated noise levels, but sometimes we work with what we have to work with. All that said, I think it's probably safe to assume the amp can handle it if you've been doing it that way for years. If memory serves me correctly, that model amplifier is solid-state and my experience tells me if a solid-state amp doesn't like the load you plug it into, it will fail as quick as it takes to overheat, which might actually happen within seconds. So my recommendation would be to look around for a direct box, also known as a D.I. box to facilitate recording in this manner. It is probably much safer for your amp and recorder.

Direct recording


How to do this interesting integration?

Question:
$$\lim_{\Delta x\rightarrow0}\sum_{k=1}^{n-1}\int_{k+\Delta x}^{k+1-\Delta x}x^m dx$$

How to integrate the above integral?
Edit1:
$$\lim_{\Delta x\rightarrow0}\int_{2-\Delta x}^{2+\Delta x}x^m dx$$
Does this intergral give $\space\space\space\space$ $2^m\space\space$  as the output?
Edit2:
Are my following steps correct?
$\lim_{\Delta x\rightarrow0}\sum_{k=1}^{n-1}\int_{k+\Delta x}^{k+1-\Delta x}x^m dx$ =
$\lim_{\Delta x\rightarrow0}\sum_{k=1}^{n-1}\int_{k+\Delta x}^{k+1-\Delta x}x^m dx$ $+$ $\lim_{\Delta x\rightarrow0}\sum_{k=1}^{n-1}\int_{k+1-\Delta x}^{k+1+\Delta x}x^m dx$  $-$ $\lim_{\Delta x\rightarrow0}\sum_{k=1}^{n-1}\int_{k+1-\Delta x}^{k+1 +\Delta x}x^m dx$ =
$\lim_{\Delta x\rightarrow0}\int_{1+\Delta x}^{n+\Delta x}x^m dx$ $-$ $\lim_{\Delta x\rightarrow0}\sum_{k=1}^{n-1}\int_{k+1-\Delta x}^{k+1 +\Delta x}x^m dx$ =
$\lim_{\Delta x\rightarrow0}\int_{1}^{n}x^m dx$ $+$$\lim_{\Delta x\rightarrow0}\int_{n}^{n+\Delta x}x^m dx$ $-$  $\lim_{\Delta x\rightarrow0}\int_{1}^{1+\Delta x}x^m dx$ $-$
$\lim_{\Delta x\rightarrow0}\sum_{k=1}^{n-1}\int_{k+1-\Delta x}^{k+1 +\Delta x}x^m dx$ =
$\lim_{\Delta x\rightarrow0}\int_{1}^{n}x^m dx$ + 0 - 0 - 0 = $\lim_{\Delta x\rightarrow0}\int_{1}^{n}x^m dx$
= $\int_{1}^{n}x^m dx$
Comment: This version of Edit2 looks good.
Answer: HINT:
$$\sum_{k=1}^{n-1}\int_{k+\Delta x}^{k+1-\Delta x}x^m dx=\int_1^nx^mdx-\left(\int_1^{1+\Delta x}x^mdx+\sum_{k=2}^{n-1}\int_{k-\Delta x}^{k+\Delta x}x^mdx+\int_{n-\Delta x}^nx^mdx\right)$$
Let $M$ be any upper bound for $x^m$ on $[1,n]$; then
$$\begin{align*}
\int_1^{1+\Delta x}x^mdx+\sum_{k=2}^{n-1}\int_{k-\Delta x}^{k+\Delta x}x^mdx+\int_{n-\Delta x}^nx^mdx&\le M\left(\Delta x+2(n-2)\Delta x+\Delta x\right)\\
&=2M\Delta x(n-1)\;.
\end{align*}$$
Added: The same reasoning shows that
$$\lim_{\Delta x\rightarrow0}\int_{2-\Delta x}^{2+\Delta x}x^m dx=0\;:$$
if $M$ is any bound on $x^m$ over the interval $[1,3]$, say, the integral is bounded by $2M\Delta x$.
By the way, you really shouldn't use $x$ both in $\Delta x$ and as the variable of integration. The new limit, for instance, ought to be
$$\lim_{\Delta x\rightarrow0}\int_{2-\Delta x}^{2+\Delta x}t^m dt$$
or the like, with similar changes in the original problem.
Answer: For the first question:
$$
\begin{align}
\lim_{\Delta x\to0}\,\left|\,\int_k^{k+1}x^m\,\mathrm{d}x-\int_{k+\Delta x}^{k+1-\Delta x}x^m\,\mathrm{d}x\,\right|
&=\lim_{\Delta x\to0}\,\left|\,\int_k^{k+\Delta x}x^m\,\mathrm{d}x+\int_{k+1-\Delta x}^{k+1}x^m\,\mathrm{d}x\,\right|\\
&\le\lim_{\Delta x\to0}2\Delta x(k+1)^m\\
&=0
\end{align}
$$
we get
$$
\begin{align}
\lim_{\Delta x\to0}\sum_{k=1}^{n-1}\int_{k+\Delta x}^{k+1-\Delta x}x^m\,\mathrm{d}x
&=\sum_{k=1}^{n-1}\int_k^{k+1}x^m\,\mathrm{d}x\\
&=\int_1^nx^m\,\mathrm{d}x
\end{align}
$$
For the Edit:
For $\Delta x<1$,
$$
\left|\,\int_{2-\Delta x}^{2+\Delta x}x^m\,\mathrm{d}x\,\right|\le2\cdot3^m\Delta x
$$
Therefore,
$$
\lim_{\Delta x\to0}\,\int_{2-\Delta x}^{2+\Delta x}x^m\,\mathrm{d}x=0
$$
For your steps:
If you would give the justification for each step, it would help us in commenting on what is correct and what might be wrong and help you in seeing what is right.
Comment: Ok, I didn't notice this answer.
Answer: $$\lim_{s\rightarrow0}\frac1s\int_{2-s}^{2+s}x^m\mathrm dx=2\cdot2^m$$

How to do this interesting integration?


alternative to using or operator java?

Question: I understand the the or operator is only for boolean expressions. So I was wondering if there is a good way to go about doing the code below without using the or operator?
if(hh.getName() != "apple" || "Health Potion" || "roatisary chicken" || "backpack")

Comment: `if (!Set.of("apple", "Health Potion" /* etc */).contains(hh.getName()))`.
Comment: Need a bit more context. Are all of these Strings relative?
Comment: @Jason what does "relative" mean in relation to Strings?
Comment: all Strings are in the constructor of subclasses of the same superclass called item that i use as an identifier as to which instance of the class is being used and to print out to the user which item is being used. But now i'm wondering if it would have been better to use instanceof in this scenario instead
Comment: @AndyTurner relative means in relation-to. The question is simply are all of these Strings related-to each other.
Comment: @AndyTurner cannot find Symble variable Set, do i need to import stuff?
Comment: @QuestionHaver99 Check below for an answer I provided.
Comment: @QuestionHaver99 I believe Set#of is only available in JDK9+ so you will need to update your JDK or use a third-party API like guava for ImmutableSet.
Comment: @Jason I still don't understand what you mean. Why does it matter if the strings are related to each other, beyond the fact they are all instances of String?
Comment: @AndyTurner I.e like Wednesday and Tuesday are both days of the week, they are related to eschother. In Java we have the DayOfWeek enum to represent this easily. I was asking because we might be able to create an Enum to replace and represent these Strings.
Answer: One possible solution if these are all related in some way is to store them in a Set of String objects. It is worth noting that this solution depends on each String being case sensitive.
Set<String> values = new HashSet<>(Arrays.asList("apple", "Health Poition", "roatisary chicken", "backpack"));

Then, check if set contains the String hh.getName()
if (values.contains(hh.getName()) {

}

A better solution
A potentially even better solution would be to use an enumeration instead of a bunch of Strings.
enum Item {
   APPLE,
   HEALTH_POTION,
   ROATISARY_CHICKEN,
   BACKPACK
}

Set<Item> items = ImmutableMap.copyOf(EnumSet.allOf(Item.class));

Item myItem = ...;

if (items.contains(myItem)) {

}

alternative to using or operator java?


Is it possible to get the Identity value in the ItemInserted event in a listView?

Question: I'd rather not make a call to the database to query @@IDENTITY.  Is there some way to get the identity value for what was just inserted through code?
Comment: I think it would help if you provide information about the type of datasource and data access technic (SqlDataSource? Linq to SQL? Linq to Entities? ObjectDataSource? etc.) you are using with the ListView. The ListView won't know anything about the inserted data on its own since it's fed through a datasource. I guess returning the identity will be a capability of the data source, not of the ListView.
Answer: Found a solution by adding an OnInserted event to my LinqDataSource that my listview was using.  See below:
protected void lds_Personnel_OnInserted(object sender, LinqDataSourceStatusEventArgs e)
{
    int id= ((Personnel)e.Result).IdentityNameHere;
.
.
.
}

Hope it's helpful to someone.
Answer: Try using SCOPE_IDENTITY() instead.
Comment: My point is that I don't want to query the DB.  Can i get this from code?
Comment: I'm not sure then what you're trying to achieve. If you insert something with an automated Identity column into the DB, then the DB is the only place from where you can retrieve that value. It is common practice thhough to add a SELECT SCOPE_IDENTITY() call at the end of your INSERT statement, in order to retrieve the idenity value w/o having to query the DB multiple times. This is also the most reliable way to make sure you retrieve the correct ID.
Comment: What I'm wondering is if it is possible to get the Identity value through the ListView event args rather than the database.  I understand that the DB is the source of the Identity, but ListViews often pull these values in automatically.  That's why I can iterate through each item in my ListView and look at the DataKey value.  My question is if there is a way to find the Identity (DataKey) value of a record that I inserted through my list view but have not bound yet.  My end goal is to insert records into a child table using this id from within the ItemInserted event.


Extract Jest step definition to a separate file

Question: I'm doing some e2e tests with Jest and Puppeteer and I hit a bottleneck.
I want to move step definitions to separate file so that I can reuse them across different tests.
I encounter the following issue:

Here is my setup:
File dummyTest.test.js:
import {loginUser} from '../steps/test';

describe(
'dummy test',
() => {
    let page;
    beforeAll( async () => {
        const context = await browser.createIncognitoBrowserContext();
        page = await context.newPage();
        await page.setViewport( { width: 1200, height: 960 } );
        await page.goto( 'http://localhost:8080' );
    }, timeout );

    afterAll( async () => {
        await page.close();
        delay( 1000 );
        console.log( 'killing all chromium zombies' );
        exec( 'kill -9 $(ps aux | grep \'chromium\' | awk \'{print $2})\'' );
        exec( 'kill -9 $(ps aux | grep \'http-server\' | awk \'{print $2})\'' );
    }, 10000 );

    it( 'should see login page', loginUser, 10000 );
},
10000 );

File test.js:
export const loginUser = async () => {
await page.waitForSelector( 'form' );
await page.click( 'input[name=email]' );
await page.type( 'input[name=email]', 'email@example.com' );
await page.click( 'input[name=password]' );
await page.type( 'input[name=password]', 'test123' );
await page.screenshot( { path: './test-results/PrefilledLogin.png' } );
await page.keyboard.down( 'Enter' );
await page.screenshot( { path: './test-results/LoginSubmit.png' } );
};

What am I doing wrong?
Answer: I solved it.
In order for this to work, I had to pass the page object, and the done callback to the function:
it( 'should see login page', ( done ) => loginUser( done, page ), 10000 );


Getting an error when I make a switch with a string

Question: I am getting an error message when I try to make a switch with a String. Here is the error:
incompatible types found:
java.lang.String
required: int
switch(monthName){

This makes it seem like I can only make a switch with an int but I was pretty sure that in the more recent Java versions you can make a switch with a String. Here's the code that is giving me the error:
switch(monthName){
        case "December"://Always has 31 days
            daysLeft = 31;
            daysLeft -= dayOfMonth;
            break;
        case "November"://Always has 30 days
            daysLeft = 61;
            daysLeft -= dayOfMonth;
            break;
        case "October"://Always has 31 days
            daysLeft = 92;
            daysLeft -= dayOfMonth;
            break;
        case "September"://Always has 30 days
            daysLeft = 122;
            daysLeft -= dayOfMonth;
            break;

Comment: What version of Java are you using? Switch on strings is available since Java 7.
Comment: This was the problem. I updated java and restarted and now it compiles correctly. Thanks!
Answer: Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum constants are permitted
Answer: Define enum in your class:
public enum MonthName {
    December, November, October, September
}

Use val variable to provide switch functionality on basis of string input-
String val = "December";//can be taken from user through Scanner class
MonthName monthName = MonthName.valueOf(val);//Enum class object

switch (monthName) {
    case December://Always has 31 days
        daysLeft = 31;
        daysLeft -= dayOfMonth;
        break;
    case November://Always has 30 days
        daysLeft = 61;
        daysLeft -= dayOfMonth;
        break;
    case October://Always has 31 days
        daysLeft = 92;
        daysLeft -= dayOfMonth;
        break;
    case September://Always has 30 days
        daysLeft = 122;
        daysLeft -= dayOfMonth;
        break;
    }
    System.out.println(dayOfMonth + "---" + daysLeft);//Test of output
}

Comment: Hello. I edited your answer a little to change "Code snippet" tool to "Code sample". Use "Code snippet" to present HTML/CSS/JS examples (code which can actually be run via browser). To format code like Java use "Code sample" (marked with `{}` in editor).


About the remark 3 about Fubini's Theorem in "Calculus on Manifolds" by Michael Spivak on p.60

Question:
I am reading "Calculus on Manifolds" by Michael Spivak.
On p.60, there is a remark(remark 3) about Fubini's theorem in this book.
Spivak wrote:

Since $\int_A \mathcal{L}$ remains unchanged if $\mathcal{L}$ is redefined at a finite number of points, we can still write $\int_{A \times B} f = \int_A (\int_B f(x, y) dy) dx$, provided that $\int_B f(x, y) dy$ is defined arbitrarily, say as $0$, when it does not exist.

What is the meaning of "$\int_B f(x, y) dy$ is defined as $0$"?
I think the meaning of $\int_B f(x, y) dy$ is already defined (and in this case $\int_B f(x, y) dy$ does not exist), so we cannot define arbitrarily the value of $\int_B f(x, y) dy$.
Instead, for some $a \in A$, we can redefine the values of $f$ like $f(a, y) = 0$ for all $y \in B$, then $\int_B f(a, y) dy = 0$ .
Comment: The integral is usually thought of as not defined whenever it does not exist. Similarly, if $f$ is a function that takes members of $X$ into $Y$, then $f$ is not defined wherever $f(x)$ does not exist.
Answer: What's the meaning of the symbol $\int_B f(x,y) \, dy$? It means we're fixing some $x \in A$, and considering the function $y \mapsto f_x(y):= f(x,y)$ from $B \to \Bbb{R}$, and if this function $f_x(\cdot) = f(x,\cdot)$ is integrable on $B$, we get a number
\begin{align}
\int_B f_x \equiv \int_B f(x,y) \, dy \in \Bbb{R}
\end{align}
(where $\equiv$ means same thing, but in different notation). So, we now have a function
\begin{align}
\phi: D_{\phi} :=\{x \in A| \, \, \text{$f_x:B \to \Bbb{R}$ is integrable on $B$}\} &\to \Bbb{R}
\end{align}
defined by the rule
\begin{align}
\phi(x) := \int_B f_x = \int_B f(x,y) \, dy
\end{align}
What Spivak is saying is that one possible extension of $\phi$ is the map $\Phi:A \to \Bbb{R}$ defined by
\begin{align}
\Phi(x) &:=
\begin{cases}
\phi(x) & \text{ if $x \in D_{\phi}$}\\
0 & \text{otherwise}
\end{cases} \\\\
&= \begin{cases}
\int_B f(x,y) \, dy & \text{if $f_x(\cdot) = f(x,\cdot)$ is integrable on $B$} \\
0 & \text{otherwise}
\end{cases}
\end{align}
Pretty much the point of this remark is to try to give meaning to the equation $\int_{A \times B}f = \int_A \int_B f(x,y) \, dy \, dx$, in the unfortunate circumstance that the RHS strictly speaking doesn't make sense (because of the lack of regularity).


Getting Forbidden (CSRF cookie not set.) error from django in C#

Question: I'm sending data to a django application using C# code:
using (WebClient client = new WebClient())
{
    NameValueCollection postData = new NameValueCollection()
           {
              { "user_id", "12345" }
           };
    string pagesource = Encoding.UTF8.GetString(client.UploadValues(url_ad, postData));
}

But I'm getting this error:

Forbidden (CSRF cookie not set.)

Code to get data in django views.py:
def get_user_id(request):
    if request.method == 'POST':
        user_id = request.POST.get('user_id')
        record = User.objects.filter(user=user_id)
        if not record:
            new_user = User(user = user_id)
            new_user.save()
        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )
    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )

I know what the error is and how to fix it in web applications, But I don't know how to solve it when sending data using C#.
Also since I'm not using .NET framework 4.5+ I can't use HttpContent which I heard is able to somehow fix this.
So how can I fix it with WebClient or any other available solutions for .NET framework 4?
Answer: You can exempt the csrf check by putting the following decorator in your function:
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def get_user_id(request):
   ...

Comment: Although its not a great idea to disable this protection, I tried it but it just did shutdown the error but the code stopped working for some reason
Comment: Probably because response_data is not defined.
Comment: Yeah I guess that was the problem. But still I think its not the right solution


how to hide liferay version and type to prevent hacking

Question: Liferay shows its type and version when /documents/ are used as URI:
http://mydomainname.zzz/documents/

/documents/
Name    Modified    Size    Description
redele/     -   0
Liferay Portal Community Edition / 6.0.6

How can I hide that info to hackers?
Thanx in advance
Comment: Not sure if [adding friendly URL mapping](http://www.liferay.com/documentation/liferay-portal/6.1/development/-/ai/adding-friendly-url-mapping-to-the-portlet) helps..
Answer: I've checked with Liferay 6.1 (EE), there this information is not given (so you might want to upgrade to the latest version, 6.1 (CE or EE).
Also there's a setting that you can change in portal-ext.properties that you might want to change. This is the default:
#
# Set the level of verbosity to use in the server information line printed
# by the web server servlet. Valid values are "full", which gives all of the
# version information (e.g. Liferay Portal Community Edition 6.1.0 CE etc.)
# or "partial", which gives only the name portion (e.g. Liferay Portal
# Community Edition).
#
web.server.servlet.version.verbosity=full

However, the main recommendation for security is to stay on the latest version and always fix it. If you don't want to upgrade when the next major CE version is released: EE is supported for 5 years (if this statement is considered marketing and not ok here, feel free to delete it)


Como abrir processo externo no segundo Monitor

Question: Estou precisando abrir um programa externo para ficar na segunda tela. Preciso que fique exatamente encaixado no segundo monitor.
Vamos supor que quero abrir o bloco de notas, não quero abrir ele no primeiro monitor, e sim no segundo monitor. Esse é o meu objetivo.
Estou pegando as informações da segunda tela para mover o notepad para ela. Perceba que a segunda tela está em forma de array[1], esse array é a informação da segunda tela extendida. Para executar o código abaixo, precisa estender a tela e deixa o notepad aberto.
public Form1() {
  InitializeComponent();
  Rectangle area = Screen.AllScreens[1].WorkingArea;
  ScreenMove(area.X, area.Y, area.Width, area.Height);

 }
 [DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll", SetLastError = true)]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

const uint SWP_NOSIZE = 0x0001;
const uint SWP_NOZORDER = 0x0004;

public static void ScreenMove(int x, int y, int lx, int ly) {
 IntPtr hWnd = FindWindow("Notepad", null);
 if (hWnd != IntPtr.Zero) {
  SetWindowPos(hWnd, IntPtr.Zero, x, y, lx, ly, SWP_NOSIZE | SWP_NOZORDER);
 }
}

É isso que não consigo, deve ter alguma forma para mover a janela do notepad para a segunda tela, mas não sei qual.
Answer: sYsTeM, você precisa saber se a máquina tem dois monitores... Use "System.Windows.Forms":
if (Screen.AllScreens.Length > 1)
{
 //Estendido
}
else
{
 //Duplicado, ou apenas 1 tela
}

Veja em:
Como saber se a tela está no modo de "Estender"?
Comment: Obrigado pela resposta, mas tipo, o que coloco dentro do primeiro IF?
Comment: No primeiro IF você coloca o código para apontar para a outra tela. Para fazer isso, você precisa mudar o posicionamento do form.
Comment: Como mudo o posicionamento do Form? É que sou leigo nisso :(
Comment: Err... é... no caso de um "CALL" ou algo assim para um programa externo... não sei se tem como passar algum "parâmetro" para o Windows reposicionar na tela. Sorry...
Comment: Espere! Tive uma ideia, mas é preciso testar. Veja a propriedade: "ProcessStartInfo.CreateNoWindow", ela inicia o processo em uma nova janela... será que é possível controlar a posição dessa nova janela? Veja: Process.Start Method - https://docs.microsoft.com/pt-br/dotnet/api/system.diagnostics.process.start?view=netframework-4.7.2
Answer: Pode fazer da seguinte forma:
[Flags]
public enum SetWindowPosFlags : uint
{
    // ReSharper disable InconsistentNaming

    ///
    ///     If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
    ///
    SWP_ASYNCWINDOWPOS = 0x4000,

    ///
    ///     Prevents generation of the WM_SYNCPAINT message.
    ///
    SWP_DEFERERASE = 0x2000,

    ///
    ///     Draws a frame (defined in the window's class description) around the window.
    ///
    SWP_DRAWFRAME = 0x0020,

    ///
    ///     Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
    ///
    SWP_FRAMECHANGED = 0x0020,

    ///
    ///     Hides the window.
    ///
    SWP_HIDEWINDOW = 0x0080,

    ///
    ///     Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
    ///
    SWP_NOACTIVATE = 0x0010,

    ///
    ///     Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
    ///
    SWP_NOCOPYBITS = 0x0100,

    ///
    ///     Retains the current position (ignores X and Y parameters).
    ///
    SWP_NOMOVE = 0x0002,

    ///
    ///     Does not change the owner window's position in the Z order.
    ///
    SWP_NOOWNERZORDER = 0x0200,

    ///
    ///     Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
    ///
    SWP_NOREDRAW = 0x0008,

    ///
    ///     Same as the SWP_NOOWNERZORDER flag.
    ///
    SWP_NOREPOSITION = 0x0200,

    ///
    ///     Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
    ///
    SWP_NOSENDCHANGING = 0x0400,

    ///
    ///     Retains the current size (ignores the cx and cy parameters).
    ///
    SWP_NOSIZE = 0x0001,

    ///
    ///     Retains the current Z order (ignores the hWndInsertAfter parameter).
    ///
    SWP_NOZORDER = 0x0004,

    ///
    ///     Displays the window.
    ///
    SWP_SHOWWINDOW = 0x0040,

    // ReSharper restore InconsistentNaming
}

public static bool MoveToMonitor(IntPtr windowHandle, int monitor)
{
    monitor = monitor - 1;
    return WinApi.SetWindowPos(windowHandle, IntPtr.Zero, Screen.AllScreens[monitor].WorkingArea.Left,
     Screen.AllScreens[monitor].WorkingArea.Top, 1000, 800, SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOREDRAW);
}

var p = Process.Start("notepad");
MoveToMonitor(p.MainWindowHandle, 2);

Agradeça ao SOEN
Comment: Bruno Onde consigo a classe WinApi?
Comment: @sYsTeM oops esqueci-me dessa dependencia. Está aqui https://github.com/alex-tomin/Tomin.Tools.KioskMode/blob/master/Tomin.Tools.KioskMode/WinApi.cs
Comment: Certinho agr, muito obrigado!


Does HtmlUnit and jasmine-maven-plugin support HTML5 sessionStorage?

Question: I am trying to test a JavaScript function that uses HTML5 sessionStorage on jasmine-maven-plugin. Jasmine uses HtmlUnit to emulate a web browser.
The problem is that when the automated tests are running during maven build, it says:

Error: Expected a spy, but got Function.

I have tried this How to deal with sessionStorage locally in FF (for testing) and then I've got this error:

TypeError: Expected argument of type object, but instead had type object in file: ...

But if I try to run Jasmine on a web page importing jasmine.js, the test works perfectly.
I have tried this too Can I access HTML5 storages using HTMLUnit , but without success.
An example of code that works on http://tryjasmine.com/ and not in jasmine-maven-plugin:
<code>function alertItem(id) {
console.log("start");
var x = sessionStorage.getItem(id);
alert(x);
}

describe("sessionStorage test", function () {
console = {
    log : function() {},
    error : function() {},
    warn : function() {}
};

var mockup = function() {
    var table = {};
    return {
        getItem: function(key) {
            return table[key];
        },
        setItem: function(key, value) {
            table[key] = value.toString();
        },
        removeItem: function(key) {
            table.pop();
        },
        clear: function() {
            table = {};
        }
    };
}();

Object.defineProperty(window, 'sessionStorage', {
    value: mockup
});

it("must work", function () {
    console.log("testing...");
    spyOn(sessionStorage, 'getItem').andReturn("my value");
    alertItem("id");
    expect(sessionStorage.getItem).toHaveBeenCalled();
});
});
</code>
Does anyone have an idea?
Thanks.
Answer: HTMLUnit does not support many HTML5 features - while your browser does, this is why it will work in the browser but not as part of the build with HTMLUnit.
Comment: Support for using the jasmine-maven-plugin with PhantomJS instead of HtmlUnit was recently added. There is an example configuration here: http://searls.github.io/jasmine-maven-plugin/phantomjs.html
Comment: Thanks @Mike for the answer. Do you know any maven plugin that runs jasmine without HTMLUnit? Or are HTMLUnit team  working to support HTML5?
Comment: I have submitted a bug on HTMLUnit sourceforge but they seems not to be working on it, because it includes jasmine maven: http://sourceforge.net/p/htmlunit/bugs/1413/
Answer: As @Kyle suggested, using sessionStorage on jasmine-maven-plugin with PhantomJS instead of HtmlUnit worked!
More information at: http://searls.github.io/jasmine-maven-plugin/phantomjs.html
Thank you!


Ajuda com loop em Javascript

Question: Olá, estou com esse código abaixo:
        <div class="" style="background:<?php echo $res['fundosite_cor']; ?>; width:588px; float:left;">

    <?php
    include "conexao.php";
    $codigo = $_POST['codigo'];
    $img01 = $_POST['img01'];
    $img02 = $_POST['img02'];
    $img03 = $_POST['img03'];
    $img04 = $_POST['img04'];
    $titulo = $_POST['titulo'];
    $preco = $_POST['preco'];
    $query = mysql_query("SELECT * FROM produto ORDER BY RAND() LIMIT 9");

    while($res = mysql_fetch_array($query)){
    ?>

    <div style="background-color:<?php echo $res['fundosite_cor']; ?>;; padding:11px;" class="center_prod_box">

                <?php echo $res['titulo']; ?>

        <div id="slider20_container" style="position: relative; top: 0px; left: 0px; width: 173px;
            height: 173px; background-color:<?php echo $res['fundosite_cor']; ?>;">

            <div u="slides" style="background-color:<?php echo $res['fundosite_cor']; ?>;cursor: move; position: absolute; left: 0px; top: 2px; height:150px; width:173px; text-align:center;
                overflow: hidden;">

                    <a href="prod_detalhe.php?codigo=<?php echo $res['codigo']; ?>">
                        <img style="position:relative; top:50%; transform:translateY(-50%);"width="100" src="img_produtos/<?php echo $res['img01']; ?>" />

                    <a href="prod_detalhe.php?codigo=<?php echo $res['codigo']; ?>">
                        <img style="position:relative; top:50%; transform:translateY(-50%);"width="100" src="img_produtos/<?php echo $res['img02']; ?>" />

                    <a href="prod_detalhe.php?codigo=<?php echo $res['codigo']; ?>">
                        <img style="position:relative; top:50%; transform:translateY(-50%);"width="100" src="img_produtos/<?php echo $res['img03']; ?>" />

                    <a href="prod_detalhe.php?codigo=<?php echo $res['codigo']; ?>">
                        <img style="position:relative; top:50%; transform:translateY(-50%);"width="100" src="img_produtos/<?php echo $res['img04']; ?>" />

                R$ <?php echo $res['preco']; ?>

                <a href="prod_carrinho.php?acao=add&codigo=<?php echo $res['codigo']; ?>">

    <?php
    }
    ?>

A finalidade é ao acessar a página gostaria que aparecesse 9 produtos aleatórios (No momento tenho apenas 02 produtos listados). Para isso achei que somente dando um WHILE no código php funcionaria, mas puro engano, pois somente consigo dar loop nos arquivos que estão na tabela produtos, mas não consigo fazer com que o script funcione no segundo produto listado.
Não estou sabendo fazer com que o script se repita (LOOP). Já pesquisei alguns poster ate mesmo no W3schools, mas não consegui aplicar a logica em meu script, talvez por ser muito leigo em JavaScript.
Estou anexando abaixo o endereço de acesso para que os amigos possam dar uma analisada e me dizer o que esta faltando ou como posso faze-lo funcionar.
Página com o Problema - http://lccinformatica.com.br/prod_index.php
Espero ter conseguido me expressar ao modo que os amigos possam entender a minha necessidade.
Abraços à todos e no aguardo se possível de respostas positivas.
Answer: Murilo Cabral, o loop e feito em PHP e montado no HTML com o próprio PHP, correto?
Depois disse você deseja fazer o que com o Javascript que não esta acontecendo?
Obs.: Acessando o link com o firebug aberto vejo que ele não esta conseguindo achar o Jquery

"NetworkError: 404 Not Found - http://lccinformatica.com.br/js/jquery-1.12.1.min.js"
Comment: OK Henrique, realmente eu não tinha enviado via FTP o JQuery "jquery-1.12.1.min.js", mas acabei de enviar. Vamos lá, quando entro na página prod_index.php, ele manda o primeiro produto corretamente, ou seja funcionando. Porém no produto seguinte, me parece que ele não aplica a função do JavaScript, que faz com que eu possa passar as imagens via botões enumerados e não esta criando o carrossel das imagens como no primeiro. Mas o loop do php com o while esta funcionando pois esta trazendo os dados do BD referente a cada produto listado. Me parece que ele não esta dando continuidade no script.
Comment: Na verdade eu não estou sabendo é criar ou montar o loop, seja ele em PHP ou em JavaScript... HEEELLLPPPP... preciso de ajuda... HEEELLLPPP... Rsrsrsrs...
Answer: Consegui resolver o problema!!!
A solução foi iniciar o loop antes do Script, inserir o código de cada produto cadastrado na tabela produtos na linha do script referente ao mesmo, na _container" e lá no final do código passei o segundo script para dentro do Loop com o código dos produtos inserido nele tambem, ficando assim o código:
        <?php
    include "conexao.php";
    $codigo = $_POST['codigo'];
    $img01 = $_POST['img01'];
    $img02 = $_POST['img02'];
    $img03 = $_POST['img03'];
    $img04 = $_POST['img04'];
    $titulo = $_POST['titulo'];
    $preco = $_POST['preco'];
    $query = mysql_query("SELECT * FROM produto ORDER BY RAND() LIMIT 9");

    while($res = mysql_fetch_array($query)){
    ?>

    <div style="background-color:<?php echo $res['fundosite_cor']; ?>;; padding:11px;" class="center_prod_box">

                <?php echo $res['titulo']; ?>

        <div id="slider<?php echo $res['codigo']; ?>_container" style="position: relative; top: 0px; left: 0px; width: 173px;
            height: 173px; background-color:<?php echo $res['fundosite_cor']; ?>;">

            <div u="slides" style="background-color:<?php echo $res['fundosite_cor']; ?>;cursor: move; position: absolute; left: 0px; top: 2px; height:150px; width:173px; text-align:center;
                overflow: hidden;">

                    <a href="prod_detalhe.php?codigo=<?php echo $res['codigo']; ?>">
                        <img style="position:relative; top:50%; transform:translateY(-50%);"width="100" src="img_produtos/<?php echo $res['img01']; ?>" />

                    <a href="prod_detalhe.php?codigo=<?php echo $res['codigo']; ?>">
                        <img style="position:relative; top:50%; transform:translateY(-50%);"width="100" src="img_produtos/<?php echo $res['img02']; ?>" />

                    <a href="prod_detalhe.php?codigo=<?php echo $res['codigo']; ?>">
                        <img style="position:relative; top:50%; transform:translateY(-50%);"width="100" src="img_produtos/<?php echo $res['img03']; ?>" />

                    <a href="prod_detalhe.php?codigo=<?php echo $res['codigo']; ?>">
                        <img style="position:relative; top:50%; transform:translateY(-50%);"width="100" src="img_produtos/<?php echo $res['img04']; ?>" />

                R$ <?php echo $res['preco']; ?>

                <a href="prod_carrinho.php?acao=add&codigo=<?php echo $res['codigo']; ?>">

    <?php
    }
    ?>

Endereço para verificar o resultado - http://lccinformatica.com.br/prod_index.php
Espero que esse post venha ajudar a outros usuários com o mesmo problema.
Agradeço a atenção, e grande abraço à todos.

Ajuda com loop em Javascript


Simultaneous Equations year 9 please solve

Question: $$xy=4\tag1$$
$$2x - y - 7 = 0\tag2$$
Simultaneous Equations Please Solve in in year 9.
Comment: @Hayden: Welcome to math.SE: since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level. Consider editing you question
Answer: This is how I will explain to a 9 year old kid :-)
Equations
$$xy=4\tag1$$
$$y=2x-7\tag2$$
Multiplying by $x$, both sides of $(2)$

One important thing to note here is the implied assumption that
  $x\ne0$. If it wasn't then $y$ would be a very large number which is always greater than the number you can imagine and dividing any number with it, would be equal to $0$. Such numbers are called (Infinity) $\infty$. So from here on we will assume $x \ne 0$

$$xy = 2\cdot x^2 - 7x$$
Using Equation $(1)$
$$4 = 2\cdot x^2 - 7x$$
$$2\cdot x^2 - 7x -4=0\tag3$$
To factorize the function, express it in the form
$$Ax^2+Bx+C=0$$
Find all the factors of the product $A\cdot C = 2*-4 = -8$
$${(8,-1),(-8,1),(4,2),(4,-2),(4,-2)}$$
From the above set, choose the pair $(a,b)$ that matches the equation
$$a+b=B$$
In this case it is $B=-7=-8+1$
Substitute it for B in the $(3)$
$$2\cdot x^2 + (-8+1)x -4=0$$
$$2\cdot x^2 - 8x + x -4=0$$
Group by common factors
$$2x(x - 4) + 1(x -4)=0$$
$$(2x+1)(x - 4)=0$$
So, either $2x+1=0;x=-\frac{1}{2}\text{ or }x-4=0;x=4$
So, x is one of $\{-\frac{1}{2},4\}$
Now use equation (1) to determine $y$
From (1), we have
$$xy=4$$
if $x = -1/2$
$$y=-8$$
if $x = 4$
$$y=1$$
$$$$
So the solution to the given equation is one of $\{(-\frac{1}{2},-8),(4,1)\}$
A picture is worth a thousand words and here is one such picture for you
Comment: You have numbered two of your questions as (3) -- I'm not sure whether this was on purpose.
Comment: But also for a 9 year old one should mention that the solution set doesn't change after multiplication with $x$ since there is no solution for $x=0$. Otherwise there is the "famous" example where one can deduce from $x=y$ that $2=1$.
Comment: This is what I was talking about. Very nice brother.
Comment: "Find all the factors of the product $A\cdot B = 2*4 = -8$" should be replaced with "Find all the factors of the product $A\cdot C = 2*4 = -8$".
Answer: You are probably expected to do it like this. We have $y=2x-7$. Substitute for $y$ in $xy=4$. We get $x(2x-7)=4$. Rewrite as $2x^2-7x-4=0$.
Then use the Quadratic Formula, or factor and obtain $(2x+1)(x-4)=0$.  Thus $x=-\frac{1}{2}$ or $x=4$, and now you can find the corresponding values of $y$.
Another way: Here is a different way, perhaps a little harder. Note the identity
$$(2x+y)^2=(2x-y)^2+8xy.$$
From $2x-y=7$ and $xy=4$ we get that $(2x+y)^2=49+32=81$.
So $2x+y=9$ or $2x+y=-9$.
From $2x-y=7$ and $2x+y=9$, we get $x=4$, $y=1$.
From $2x-y=7$ and $2x+y=-9$ we get $x=-\frac{1}{2}$, $y=-8$.
Answer: Using the first expression $xy = 4$, we can get an expression for $x$ in terms of $y$ i.e $x = \frac{4}{y}$.
Then in the second expression substitute for the $x$. i.e the expression $2x - y -7 = 0$ would become $\frac{8}{y} - y - 7 = 0$.
Further simplifying this leads to $8 - y^2 -7y = 0$ which is nothing but $y^2 + 7y - 8 = 0$.
Solving this using quadratic equations or factorization method, gives the values of $x$ and $y$ as $(4 , 1)$ or $(-\frac{1}{2} , -8)$.
Comment: you should also consider the case for $y=0$ there is no solution. Hence it is allowed to divide by $y$.
Answer: {x = 4, y = 1}  and  {x = -1/2, y = -8}
For simple problems there are simple solutions: use WolframAlpha
Comment: can you show me how  you did it please kind sir?
Comment: @user958624: I don't think that saying what the answer is well help the OP deal with similar problems once he encounters them. An answer should be a way to solve the equations or hints to solving. The use of WA is recommended ONLY when you know how to solve it by yourself!
Comment: @DennisGulko: What does he mean by year 9? Does he say that he is 9 year old?
Comment: @Inceptio: Why do you ask me? How could *I* know what *he* meant by that? :)
Comment: @DennisGulko: If **he** meant **he** was 9 year old. Then, there should be a basic way of making him understand. Right? Drawing figures and all? :)


App Dev ::Windows 8::how to provide news updates

Question: I am trying to build a Sports App for Windows Store .I am not able to understand how am I suppose to change the data day on day. The App initially will have some static content and the data has to be updated daily. Kindly guide me how to do this , since this is my first App for windows store.
Answer: I assume you have the data on a server somewhere. So use the HttpClient control to access the data, use Linq/XML to parse it, and then load it in your UI however you've designed it to do so.
You can show updates in a live tile with this sample: http://code.msdn.microsoft.com/Simple-Live-Tiles-575b1d66
Also look at Windows Azure Mobile Services: http://www.windowsazure.com/en-us/develop/mobile/


Listar Categorias em Árvore no Laravel 5.1

Question: Estou começando com Laravel 5.1 e estou um pouco perdido ainda.
Preciso listar categorias, subcategorias e "sub-subcategorias".
Tabela:
Categorias
------------------------
id            | int
nome          | varchar
categoria_pai | int

Dados:
id  | nome         | categoria_pai
----------------------------------
1   | Informática  | NULL
2   | Mouse        | 1
3   | Sem fio      | 2
4   | Eletrônicos  | NULL

Model:
class Categoria extends Model
{
    protected $table = 'categorias';
    protected $fillable = ['nome', 'descricao', 'categoria_pai'];

    public function produtos() {
      $this->belongsToMany('App\Produto');
    }

    public function categoriaPai()
    {
        return $this->belongsTo('App\Categoria');
    }

    public function categoriaFilho()
    {
        return $this->hasMany('App\Categoria');
    }
}

Controller:
Método que monta o select na hora de adicionar outra categoria. Funciona, mas não sei como filtrar isso para fazer optgroup e separar.
public function create()
{
    $categorias = Categoria::all()->lists('nome', 'id');
    return view('categorias.adicionar', compact('categorias'));
}

Não tenho ideia de como começar, já busquei coisas parecidas mas não encontrei.
Com PHP puro eu já fiz, mas usando o Laravel, estou quebrando cabeça.
Comment: Mas o que você precisa ? Fazer o relacionamento no SELECT ou no Model ?
Comment: @DiegoSouza, no model. Coloquei o meu Model na pergunta.
Answer:
No caso eu preciso listar todas e podem haver infinitos níveis

Então para listar todas as subcategorias de uma categoria independente da quantidade de níveis. Você pode fazer dessa maneira:
mysql> select * from  categoria;
+----+------+--------------+
| id | nome | categoria_id |
+----+------+--------------+
|  1 | cat1 |         NULL |
|  2 | cat2 |            1 |
|  3 | cat3 |            2 |
|  4 | cat4 |            2 |
+----+------+--------------+

class Categoria extends Model{
  ...
   public function subcategorias()
    {
        return $this->hasMany(Categoria::class, 'categoria_id','id');
    }

    public function allSubcategorias()
    {
        return $this->subcategorias()->with('allSubcategorias');
    }
}

Busque todas as subcategorias dessa forma:
$categoria = Categoria::where('id', 1)->with('allSubcategorias')->first();
return $categoria;

Resultado:

{
    id: 1,
    nome: "cat1",
    categoria_id: null,
    all_subcategorias: [
        {
            id: 2,
            nome: "cat2",
            categoria_id: 1,
            all_subcategorias: [
                {
                    id: 3,
                    nome: "cat3",
                    categoria_id: 2,
                    all_subcategorias: [ ]
                },
                {
                    id: 4,
                    nome: "cat4",
                    categoria_id: 2,
                    all_subcategorias: [ ]
                }
            ]
        }
    ]
}

SQL gerado:
    select * from `categoria` where `id` = 1 limit 1;
    select * from `categoria` where `categoria`.`categoria_id` in 1;
    select * from `categoria` where `categoria`.`categoria_id` in 2;
    select * from `categoria` where `categoria`.`categoria_id` in (3, 4);

Comment: isso: "Categoria::all()->with('allSubcategorias')->first(); " nao funciona.
isso sim: " Categoria::with('allSubcategorias')->get();"
Comment: você pode querer buscar como ponto de partida apenas as categorias raízes.
$categorias = Categoria::whereNull('categoria_id')->with('allSubcategorias')->get();
Comment: Show.. Estou sem PC agora, mas já me ajudou a entender. E se eu não quiser setar um id no where('id', 1)? Se eu usar $categoria = Categoria::all()->with('allSubcategorias')->first(); Funciona? Muito obrigado.
Answer: No relacionamento faltou apenas especificar a coluna do relacionamento:
class Categoria {

    public function categoriaPai() {
        return $this->belongsTo('App\Categoria','categoria_pai');
    }

    public function categoriaFilho() {
        return $this->hasMany('App\Categoria','categoria_pai');
    }

}

E pra capturar de um registro especifico, poderia fazer dessa forma:
$categoria = App\Categoria::find(1);
$subcategorias = $categoria->categoriaPai()->get();

foreach ($subcategorias as $sub) {
    $subsubcategorias = $sub->categoriaPai()->get();
}

Comment: @buback Neste caso crie uma função que faça a recursividade!
Comment: Obrigado pela resposta. Neste caso seria pra eu mostrar uma categoria especifica e suas subcategorias. No caso eu preciso listar todas e podem haver infinitos níveis.
Comment: Alguém conhece outra forma?


Move data between listboxes when one gets values from table

Question: I have a webpage with 2 listboxes and I need to be able to move data back and forth between them. I had it working perfectly until I needed one of the listboxes (ColumnsList) to get its data from an Access DB.
The values are populated on the server side, so the jquery code I was using now always returns a count of the selected items as 0. I assume I would now need to move these items in the server side vb code. I was able to do that successfully, but that was then causing a postback of the form, which I cannot have.
I attempted to use javascript to call a webmethod to perform the move, but that won't work unless I use the "Public Shared Function" declaration, which then causes an issue with the listboxes not being able to be seen by the code (cannot refer to an instance member of a class from within a shared method...).
Anyway, here is the button control to move the items to the listbox on the right:
<button id="MoveRight" runat="server" style="position:absolute; left:845px; top:250px; width:30px; height:30px;" type="button">></button>

Here is the button declared on the server side:
Protected WithEvents MoveRight As System.Web.UI.HtmlControls.HtmlButton

Here is my code-behind, server-side code:
Private Sub MoveRight() Handles MoveRight.ServerClick
    Dim LeftSideCount As Integer = 0
    Dim RightSideCount As Integer = 0
    Dim SelectedItemsArray(111) As ListItem

    For x As Integer = 0 To ColumnsList.Items.Count - 1
        If ColumnsList.Items.Item(x).Selected Then
            LeftSideCount += 1
            SelectedItemsArray(x) = ColumnsList.Items.Item(x)
        End If

    Next

    For y As Integer = 0 To SelectedColumns.Items.Count - 1
        RightSideCount += 1
    Next

    If LeftSideCount + RightSideCount <= 15 Then
        'move items right

        For z As Integer = 0 To LeftSideCount - 1
            SelectedColumns.Items.Add(SelectedItemsArray(z))

            ColumnsList.Items.Remove(SelectedItemsArray(z))

        Next

    Else
        'don't move items right
    End If

End Sub

Is there any way I can do this without a postback occurring?
Thanks in advance for any suggestions anyone may have!
Answer: Nevermind, I figured it out. Originally I thought that this:
How to prevent page being postbacked when i transfer item from one listbox to other
wouldn't work in my case as there were several differences between what that poster and I were trying exactly to do. It turns out, however, that this is the solution I needed. Thanks anyway!