How to update address of a facebook page through API

Question: I am trying to update address/location of a facebook business page through API using koala ruby gem, so far no working solution.
<code>page_access_token = "gw4t3434"
page_api = Koala::Facebook::API.new(page_access_token)
page_api.graph_call('me', {:location => {:street => "my street"}}, 'post') #error. Koala::Facebook::APIError: OAuthException: (#100) Parameters do not match any fields that can be updated
page_api.graph_call('me', {:location => {:address => "my street"}}, 'post') #error. Koala::Facebook::APIError: OAuthException: (#100) Parameters do not match any fields that can be updated
page_api.graph_call('me', {:address => "my street"}}, 'post')# not raise error but not working
page_api.graph_call('me', {:street => "my street"}}, 'post')# not raise error but not working
</code>
I can not find clear explanation either in facebook api reference regarding updating address in a page. I may missing something...
Answer: You can't write to the location object, only read. See "Updating Page Attributes" in the API. Also, there is no permission to request for writing to a location object.
An alternative is that you write to the Page's about section - this is allowed. Perhaps you can place an address reference here to meet the requirement of making address changes visible to the end user.


How to use object values and retrieve it in antd form

Question: I am using antd Form and I am not getting how to use the object values and retrieve them back as in the same order(i.e. after submitting the form I want values as in the toys)

const toys = {
    "Car": {
        "color": "Black",
        "available": false
    },
    "Truck": {
        "color": "White",
        "available": true
    },
    "Bus": {
        "color": "Red",
        "available": false
    },
    "Bike": {
        "color": "Blue",
        "available": true
    }
}

Object.entries(
  toys
).map(([key, value]) => {
  return (

      <Row type="flex">
        <Col>
          <Input value={key} readOnly />
        </Col>
        <Col>
          <Form.Item className="mb-0">
            {getFieldDecorator(`toys.${value.color}`, {
              initialValue: value.color
            })(<Input />)}
          </Form.Item>
        </Col>
        <Col>
        <Row type="flex">

Available

          <Form.Item
            className="mr-3 mt-1"
          >
            {getFieldDecorator(`toys.${value.available}`, {
              initialValue: value.available,
              valuePropName: 'checked'
            })(<Switch checkedChildren="Yes" unCheckedChildren="No" />)}
          </Form.Item>
          </Row>
        </Col>
      </Row>

  )
})

When we edit and save this form I want the form values below
{
    "Car": {
        "color": "Black",
        "available": true
    },
    "Truck": {
        "color": "White",
        "available": true
    },
    "Bus": {
        "color": "Red",
        "available": true
    },
    "Bike": {
        "color": "Blue",
        "available": true
    }
}

Right now I am getting values as below and the switch is not working(changing all switches if I toggle one).
toys: {
    "Black": "White",
    "false": false,
    "White": "White",
    "true": true,
    "Red": "Red",
    "Blue": "Blue"
}

Can Anyone help me? Thanks
Answer: To do this you need to create a custom form item.
// to pass values to form the Item need props onChange and value
const CustomObjectCreator = ({ onChange, value }) => {
  const defaultValue = value || {
    color: "",
    available: false
  };
  const [state, setState] = useState(defaultValue);

  useEffect(() => {
    onChange(state);
  }, [state, onChange]);

  const handleChangeSwitch = (available) => {
    setState((oldState) => ({
      ...oldState,
      available
    }));
  };

  const handleChangeInput = (e) => {
    setState((oldState) => ({
      ...oldState,
      color: e.target.value
    }));
  };

  return (
    <Row gutter={32} justify="center">
      <Col span={8}>
        <Input placeholder="color" onChange={handleChangeInput} />
      </Col>
      <Col span={4}>
        <Switch
          checked={state.available}
          checkedChildren="yes"
          unCheckedChildren="no"
          onChange={handleChangeSwitch}
        />
      </Col>
    </Row>
  );
};

I create a codesandbox example:


Is it possible to use a function which uses $node without the expense of node_load

Question: In cases where $node is not available but I know the nid, is it possible to mimic $node rather than using node load. I would like to try and cut the expense of performing a full node load..
For example to find a nodes taxonomy by vocab:
  $nid = 1;
  $vid = 1;
  $node = stdClass();
  $node->nid = $nid;
  $terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);

I have tried the above but it doesnt seem to work. I want to use the taxonomy_node_get_terms_by_vocabulary function but dont want the expense of having to use node_load to get the $node object
Answer: In this case, I would just look at the source for taxonomy_node_get_terms_by_vocabulary:
function taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid') {
  $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.vid = %d ORDER BY weight', 't', 'tid'), $vid, $node->vid);
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
  }
  return $terms;
}

The only thing needed is $node->vid.  Note that vid in this particular referes to node revision and not vocabulary ID.  If you knew the vid, then you could just create your own function:
function mytaxonomy_node_get_terms_by_vocabulary($nodevid, $vid, $key = 'tid') {
  $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.vid = %d ORDER BY weight', 't', 'tid'), $vid, nodevid);
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
  }
  return $terms;
}

The problem is that in most cases you don't know the $node->vid without doing a node_load.  Just querying using the nid may or may not be right if you use revisions or start using revisions in the futures.  The proper way to do it would be to JOIN the node table into the query so you can use $node->nid as an argument instead of $node->vid.
Comment: @WestieUK - This is a better answer than mine, so check this one out first :)
Comment: Thanks for the insight, I didn't realise Drupal depended on vid so much for nodes. Makes perfect sense now though.
Comment: No problem.  As a general rule of thumb, if you are using the API then you use $node or $node->nid.  If you are using a direct query then there is a very good chance you need to use $node->vid.
Answer: You could just write a query yourself if you don't want to load a whole node object.
It should look something like this:
SELECT td.name
FROM {term_data} td
INNER JOIN {term_node} tn ON tn.tid = td.tid
WHERE td.vid = 1
AND tn.nid = 1

Then you can just loop through your results and do whatever you need with them.
I don't have easy access to a Drupal database at the moment, so the query might be slightly out..but it should be enough to get you started :)
Answer: I asked a similar question a couple days ago.  Check the answers here and here.


Does uniform subsampling of a biased sample reduce the bias?

Question: In a paper I am reading now I found the following statement:

Then, of 200 candidates for the study, 50 were at random selected using a computer-generated randomization list (MS Excel). This way, even if a certain "selection bias" would have been present, at least this bias would be "diluted" 1–4 by the random selection procedure.

I don't see how this method helps to reduce the bias, because I assume that the sampled candidates would have the same distribution as the original candidates.
How does it work and is this practice used often?
Comment: Can you provide a link to the paper ?
Comment: I agree with your assessment, I cannot see how this could possibly alter the bias.
Answer: Not true. For example, if we have a 2-fold bias for women developing hyperthyroidism and 200 sequential hyperthyroid cases in a particular clinic accepting all patients sent, looking at 50 randomized or sequential cases would not change the underlying bias. Moreover, if we introduced a collection bias by only examining the first 100 males, which would take longer, and the first 100 females to introduce a bias that balances the sexes, we would not change that selection bias by randomly sub-selecting only 50 cases. We would make the selection bias less statistically obvious for the smaller case numbers, but the bias itself would be unchanged. In the extreme, if we randomly choose only one patient, the sex will be either but not both, so our certainty of sex selection bias, i.e., via its significance testing, is extremely low.


Exporting an Android Project based on Eclipse

Question: i developed an android project using google-play-services_lib ( using google map ), my project is compiling and working fine as i want , but i want export my project in order to send it to someone else who should continue work on it , how can i include the google-play-services_lib's project in the same package.
PS :i have included the google-play-services_lib as lib
Answer: Send the project and your remote partner has to install "Google Play Services" with the Android SDK Manager.

So, the library project of "Google Play Services" is included into the sdk, and is located in <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/ , he only need to import the project to his Workspace.
If you are using Eclipse, import the library project into your workspace.
Click File > Import, select Android > Existing Android Code into Workspace, and browse to the copy of the library project to import it.
Update:
or just copy the google-play-services.jar from google-play-services_lib/libs to the folder /libs of your project.
and delete the reference of google-play-services_lib of your project.
more info: Set Up Google Play Services SDK
Comment: thanks for your answer , but i am looking for a way to package the whole projects in one , so the other partner doesn't have to import the library to the workspace.
Comment: have you tried copying the google-play-services.jar file into your project´s folder /lib?
Comment: yes i did , but then i have an error on my manifest file in this tag


Delete duplicate records that do not exist in other table

Question: I have 2 table EnquiryMaster and Requirement.
I want to delete the duplicate Company from the table EnquiryMaster whose enqiryid do not exist in Requirement table
  CREATE TABLE [dbo].[EnquiryMaster](
[EnquiryId] [int] IDENTITY(1,1) NOT NULL,
[orgid] [int] NULL,
[uid] [int] NULL,
[Company] [varchar](160) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[HeadOfficeAddress] [varchar](460) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_EnquiryMaster] PRIMARY KEY CLUSTERED
    (
[EnquiryId] ASC
     )WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
    ) ON [PRIMARY]

    CREATE TABLE [dbo].[Requirement](
[RequirementID] [int] IDENTITY(1,1) NOT NULL,
[uid] [int] NULL,
[orgid] [int] NULL,
[EnquiryID] [int] NULL,
[Company] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,

    CONSTRAINT [PK_Requirement] PRIMARY KEY CLUSTERED
     (
[RequirementID] ASC
     )WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
     ) ON [PRIMARY]

Comment: do you mean you want to delete duplicate Company or the whole row from EnquiryMaster table where EnquiryID does not exist in Requirement?
Comment: Whole row of the record that is duplicated
Comment: i have 2 rows with company "Infosys". I  want to delete 1 and keep only that whose enquiry id is not in requirement table
Answer: DELETE FROM [dbo].[EnquiryMaster]
WHERE [EnquiryId] NOT IN
(SELECT [EnquiryID] FROM [dbo].[Requirement])

But it is not clear why you call such rows as duplicates.
UPD. Considering duplicates.
DELETE T1
FROM dbo.EnquiryMaster T1
WHERE EXISTS (
    SELECT 1
    FROM dbo.EnquiryMaster T2
    WHERE T1.Company = T2.Company AND T1.EnquiryId <> T2.EnquiryId
) AND T1.EnquiryId NOT IN (
    SELECT EnquiryID
    FROM dbo.Requirement
)

Comment: i have 2 rows with company "Infosys" in EnquiryMaster table. I want to delete 1 and keep only that whose enquiry id is in requirement table
Answer: Delete from EnquiryMaster E1 where exist(select 1 from EnquiryMaster E2
where E1.Company = E2.Company and E1.EnquiryId<>E2.EnquiryId)
and E1.EnquiryId Not In(select EnquiryId from Requirement)


Group Property of element

Question: True or false? If $G$ is a group with the property that $g=g^{-1}$
 for all g element  $G$, then $G$ is abelian .prove
true ,inverse exits which is in G,for it to be abelian ,it means that it is commutative that is $ab=ba$
Comment: so i am right the answer is true
Comment: See [this](http://math.stackexchange.com/questions/910640/proof-that-group-is-commutative-if-every-element-is-its-inverse-feedback-wanted).
Comment: Please try the search first next time. There are already a handful of posts on this question.
Answer: Let $a,b\in G$ then
$$ab=(ab)^{-1}=b^{-1}a^{-1}=ba$$
and we conclude.

Group Property of element


Kronecker quiver and tensor product

Question: Good day, based on representation theory of Assem,

and the definition of tensor product

I need to find $\varphi^1_{21}$ and its domain in the kronecker quiver. I did the next:

but Im confused to find $F_0$ and therefore $F/F_0$ to deduce the domain $\varepsilon _2KQ\varepsilon _1\otimes  \varepsilon _1KQ\varepsilon _1$. Depends it of the field $K$ and of the external operation $ka$, $k\in K, a\in \varepsilon _2KQ\varepsilon _1$?
Comment: Is the first reference from the book of Assem, Simson and Skowroński? If so, it would be better to list all of the authors.
Comment: yes, at the beginning I said it, and the second is Frobenius Algebras I of Skowronski, Kunio.
Comment: You only name Assem.  My comment is that you should name all authors, not only one. (Also, Kunio is Yamagata's first name).
Answer: As $\varepsilon_{2}KQ \varepsilon_1 \cong K^2$, $\varepsilon_{i}KQ \varepsilon_i \cong K$, then $\varphi_{21}^1:K^2 \otimes K\rightarrow K^2$ and for properties of tensor product  $K^2 \otimes K\cong K^2.$

Kronecker quiver and tensor product


A random sample of 15 adults was drawn. Determine the probability that 5 or less have a below average IQ.

Question: A random sample of 15 adults was drawn. Determine the probability that 5 or less have a below average IQ. N(100,16)
Comment: It would be helpful if you include your work and clearly indicate where you are stuck. Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: This raises another question : Imagine that the person who is going to answer you has a below-the-average IQ : will you be confident in his/her answer ?
Comment: More seriously, why don't you answer to @Max about your work on the subject, and the result you propose ?
Comment: I have done a little simulation on Matlab. The result I find is $\approx 0.151$. Wish it helps you to check your result found by a more classical way...
Answer: You have the mean and the standard deviation, you can find the probability of any event happening in your space of events, here mean is 100 and standard deviation is 16,this is a statistic problem.
https://www.math.stackexchange.com/questions/482530/given-mean-and-standard-deviation-find-the-probability
you may want to search for Chebyshev's inequality.


Can two projects of a solution build to two paths?

Question: I am using Visual Studio C# 2008 Express Edition. I have a solutions with two projects, one is the main program itself, another one is an nunit test project.
I want each project to build to different paths, so physical test fixtures will not appear in the release folder. I opened up the project properties's build tab, and specified the test_project's "output to" to be bin\Test\. The main_project's output path is set to be bin\Release\.

Now when I build, all the output files goes to the bin/Test folder, and the bin/Release folder is never touched. I even deleted the contents in the release folder, but building will not recreate the output files in the release folder.
Am I doing something wrong?
Answer: There are a few concepts here - Main project vs Test and Debug vs Release mode and finally Deployment
Where is code compiled to?
A project's output will by default go under the project structure under bin\Debug.  There's no need to change it usually.
So the main project output would go to MainProject\bin\debug and the test project to TestProject\bin\debug.  Within the TestProject bin\debug you'd get copies of the MainProject files because they are referenced by the TestProject.
Release version and other Build configurations
If you want to build a Release version of your code (without the pdb files) then you need to change the Build Configuration - at the top of VS you should see a dropdown that says Debug (currently) - this is why its building to Debug.  You can also see this within the project properties - Build - Configuration: Active(Debug).  This is nothing to do with whether its a Main Project/Test whatever.  In each configuration (see Build - Configuration Manager) you specify the projects that you want to include - obviously normally you don't include an NUnit Test project in a Release output but there's nothing to stop you doing it)
Deployment
Then you get to the bigger picture question about what you're actually deploying - this depends on how you're deploying it - if just copying files then obviously you just want to look at one of the folders under the main project.  If producing an installer then you select the main project output (and not the test project) as things to deploy.
Comment: thanks! how was I so careless and didn't notice I was in the test_project folder


Verification of Active element by WebDriver using java

Question: During sign in on Yahoo mail, cursor is focused on Yahoo ID text field automatically. I want to verify whether cursor is focused or not on Yahoo ID text field. HTML for the text field is below:
<input name="login" id="username" maxlength="96" tabindex="1" value="">

How can I verify that Yahoo ID text field is focused or active?
BTW, I am using WebDriver (Selenium 2) with java, TestNG as test framework
Comment: You can use JavaScript in WebDriver for doing that
Answer: I think, the following code would work. Please try the following:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
WebElement actualYahooId = (WebElement)jse.executeScript("return document.getElementById('username');");
WebElement expectedYahooId = (WebElement)jse.executeScript("return document.activeElement;");
assertEquals(actualYahooId, expectedYahooId);


Taxonomy term relationships

Question: I have 3 taxonomy terms that I would like to expose as filters but I would like to use JavaScript to disable filters as you make selections in the other related exposed filters. For example:

Styles
Makes
Models

Cars
BMW
750i

Trucks
Ford
F-150

If you select "Cars" then the "Makes - Ford" and "Models - F-150" would be disabled. I currently have each item assigned a proper CSS class for hooks but I am needing to find a way to add a CSS class to each "Makes" item and "Models" item that would be available if the user selected "Styles - Cars".
I need to do this on form field change and without refreshing the page. Is this possible?
Much thanks in advanced.
Comment: You might want to consider one of these modules: https://www.drupal.org/project/cshs or https://www.drupal.org/project/shs
Answer: @beltouche, thanks for the module ideas. I ended up going another route because I needed the filters to update as each one changed. Basically, just like a facet but without reloading the page. I'm sure there are a few ways to go about this and probably in a more efficient way but for the amount of items and the functionality I needed this seems to be working pretty good.
For anyone else that is looking to try and accomplish the same, here are the steps I took to accomplish what I needed.

I have a content type called "inventory" that hold about 700 entries
There are 3 fields in "inventory" that I would like to use to filter by
I created a view showing content of type "inventory"
Name the view "Custom Quick Search"
Check to "create a block"
Set the view to "show Fields"
Add the 3 fields, style, make, model
Set items per page to "all"
Create custom view templates:
views-view-unformatted--custom-quick-search
views-view-fields--custom-quick-search
views-view-field--field-style
views-view-field--field-make
views-view-field--field-model

The code for each are as follows:
views-view-unformatted--custom-quick-search
{% for row in rows %}
  {% if row|render|trim is not empty %}
    {{ row.content }}
  {% endif %}
{% endfor %}

views-view-fields--custom-quick-search
{% set category_name = fields.field_category.content|striptags %}
{% set category_id = fields.field_category.content|preg_replace('(.*)','$1') %}

{% set make_name = fields.field_make.content|striptags %}
{% set make_id = fields.field_make.content|preg_replace('(.*)','$1') %}

{% set model_name = fields.field_model.content|striptags %}
{% set model_id = fields.field_model.content|preg_replace('(.*)','$1') %}

      <input type="checkbox" name="{{ category_name|trim }}" value="{{ category_id|trim }}" class="{{ category_name|trim|clean_class }}" id="{{ category_name|trim|clean_class }}" />
    {{ category_name|trim }}

      <input type="checkbox" name="{{ make_name|trim }}" value="{{ make_id|trim }}" class="{{ make_name|trim|clean_class }}" id="{{ make_name|trim|clean_class }}" />
    {{ make_name|trim }}

      <input type="checkbox" name="{{ model_name|trim }}" value="{{ model_id|trim }}" class="{{ model_name|trim|clean_class }}" id="{{ model_name|trim|clean_class }}" />
    {{ model_name|trim }}

views-view-field--field-style
views-view-field--field-make
views-view-field--field-model
{{ output }}

Place the block on a page wrapped in the following:

Styles

Makes

Models

            <input data-drupal-selector="edit-submit-custom-search-inventory" type="submit" id="edit-submit-custom-search-inventory" value="Search" class="button js-form-submit form-submit -brand-01">

            {{ drupal_entity('block', 'views_block__custom_quick_search_block_quick_search', check_access=false) }}

            {{ drupal_entity('block_content', '8') }}

The rest of the code is the JavaScript that swaps out the fields
/**
     * Clear disabled from makes and models on front page
     * Clone makes into unsorted
     * Remove duplicate entries
     * Reorder into alpha desc and move into dropdown
     */
 function loadMakes(show_styles){
  console.log(show_styles);
  if( show_styles == 'all' ){
    jQuery('.quickSearch .item .-makes').clone().prependTo('.quickSearch .unsorted__makes');
  }
  else{
    jQuery('.quickSearch .item .-makes[data-category="'+show_styles+'"]').clone().prependTo('.quickSearch .unsorted__makes');
  }
  //
  // Remove duplicates from makes dropdown.
  var makes = {};
  jQuery('.unsorted__makes .-makes').each(function() {
    var make = jQuery(this).attr('data-make');
    if (makes[make])
      jQuery(this).remove();
    else
      makes[make] = true;
  });
  // Reorder alpha and move to drop downs.
  jQuery(function(){
    jQuery('.unsorted__makes .-makes').sort(sort_makes).clone().prependTo('.filters-widget.-makes .filters-widget__copy');
    function sort_makes(a, b){
      return(jQuery(b).data('make')) < (jQuery(a).data('make')) ? 1 : -1;
    }
  });
}

/**
 *
 * Clone models into unsorted
 * Remove duplicate entries
 * Reorder into alpha desc and move into dropdown
 */
function loadModels(show_styles,show_makes){
  if( show_makes == 'all' ){
    jQuery('.quickSearch .item .-models').clone().prependTo('.quickSearch .unsorted__models');
  }
  else{
    jQuery('.quickSearch .item .-models[data-category="'+show_styles+'"][data-make="'+show_makes+'"]').clone().prependTo('.quickSearch .unsorted__models');
  }
  //
  // Remove duplicates from models dropdown.
  var models = {};
  jQuery('.unsorted__models .-models').each(function() {
    var model = jQuery(this).attr('data-model');
    if (models[model])
      jQuery(this).remove();
    else
      models[model] = true;
  });
  // Reorder alpha and move to drop downs.
  jQuery(function(){
    jQuery('.unsorted__models .-models').sort(sort_models).clone().prependTo('.filters-widget.-models .filters-widget__copy');
    function sort_models(a, b){
      return(jQuery(b).data('model')) < (jQuery(a).data('model')) ? 1 : -1;
    }
  });
}

/**
         * Move styles into unsorted
         * Remove empty entries
         * Remove duplicate entries
         * Reorder into alpha desc and move into dropdown
         */
        // Remove empty entries
        jQuery('.quickSearch .item').each(function(){
            if( jQuery(this).data('make') == undefined || jQuery(this).data('make') == null || jQuery(this).data('make') == ''){
                jQuery(this).remove();
            }
        });
        jQuery('.quickSearch .item .-styles').prependTo('.quickSearch .unsorted__styles');
        // Remove duplicates from styles dropdown.
        var styles = {};
        jQuery('.unsorted__styles .-styles').each(function() {
            var style = jQuery(this).attr('data-category');
            if (styles[style])
                jQuery(this).remove();
            else
                styles[style] = true;
        });
        // Reorder alpha and move to drop downs.
        jQuery(function(){
            jQuery('.unsorted__styles .-styles').sort(sort_styles).prependTo('.filters-widget.-styles .filters-widget__copy');
            function sort_styles(a, b){
                return(jQuery(b).data('category')) < (jQuery(a).data('category')) ? 1 : -1;
            }
        });

        // Show and hide makes and models based on selected style
        var show_styles = '';
        jQuery('.-styles input[type=checkbox]').change(function(){
            jQuery('.-styles input[type=checkbox]').not(this).prop('checked', false);
            jQuery('.-makes .filters-widget__copy, .-models .filters-widget__copy').html('');
            jQuery('.unsorted__makes, .unsorted__models').html('');
            show_styles = jQuery(this).parent().data('category');
            loadMakes(show_styles);
            loadModels(show_styles,show_styles);
        });

        // Show and hide makes and models based on selected style
        var show_makes = '';
        jQuery('.-makes').on('change', 'input[type=checkbox]', function(){
            jQuery('.-makes input[type=checkbox]').not(this).prop('checked', false);
            jQuery('.-models .filters-widget__copy').html('');
            jQuery('.unsorted__models').html('');
            show_styles = jQuery(this).parent().data('category');
            show_makes = jQuery(this).parent().data('make');
            loadModels(show_styles,show_makes);
        });

        // Quick Search submit button
        jQuery('.quickSearch .form-submit').on('click', function(){
            styles = jQuery('.-styles input:checked').val();
            makes = jQuery('.-makes input:checked').val();
            models = jQuery('.-models input:checked').val();
            var quick_search_url = '';
            if( styles && !makes && !models ){
                quick_search_url = 'category/'+styles;
            }
            else if( styles && makes && !models ){
                quick_search_url = 'category/'+styles;
                quick_search_url += '/make/'+makes;
            }
            else if( styles && !makes && models ){
                quick_search_url = 'category/'+styles;
                quick_search_url += '/model/'+models;
            }
            else if( styles && makes && models ){
                quick_search_url = 'category/'+styles;
                quick_search_url += '/make/'+makes;
                quick_search_url += '/model/'+models;
            }
            else if( !styles && makes && !models ){
                quick_search_url += '/make/'+makes;
            }
            else if( !styles && makes && models ){
                quick_search_url += '/make/'+makes;
                quick_search_url += '/model/'+models;
            }
            else if( !styles && !makes && models ){
                quick_search_url += '/model/'+models;
            }

            window.location.href = '/inventory-search/'+quick_search_url;
        });

        loadMakes('all');
        loadModels('all','all');

    }

Taxonomy term relationships


using Poisson or gaussian when modelling income

Question: Simplified scenario. I want to model income depending on gender and education. I have to possibility using glms:
<code>glm(income ~ gender + education, family = poisson, data=bla)
glm(income ~ gender + education, family = gaussian, data=bla)
</code>
Is poisson or gaussian a better choice? I read that when there are more than 30 observations gaussian should be used but I thought I better ask the experts.
Comment: I think Gamma GLMs have usually been used to model incomes.  Poisson isn't usually a good model since it is only supported on the integers (and income is continuous).  If the incomes are large enough the differences between the gamma and the normal may not be very big.  Its worth fitting both models and comparing on aspects salient to your study.
Comment: Additionally, the "30 or more observations" rule of thumb you quote is a perversion of the t-test rule of thumb for using z quantiles as the critical value.  It does not apply to GLMs, and is wrong so far as I am concerned.
Comment: Thanks I will have a look at this.
Answer: Maybe some economist or statistician here could give a theoretical answer, but I would tackle the problem empirically, by fitting both the models and checking how they perform in terms of residuals, metrics such as AIC/BIC, and using validation procedures such as cross-validation.
Comment: I feel very strongly that family selection for GLM is not something that can be done via AIC or other information criteria.  Family is a choice which is made prior to modelling.  [See this answer](https://stats.stackexchange.com/a/469374/111259) here for more.
Comment: Thanks. Yeah thought about aic comparison or anova


Remote desktop server for AVD?

Question: Virtualbox has this handy feature that I can enable a remote desktop server of the virtual machine. Does such a feature exists for AVDs? If you would enable the remote desktop server for the AVD, you could connect to it as if it were a remote desktop, and see and control the emulated screen from remote.
Answer: qemu has built-in support for VNC. You can run the emulator with the following options emulator @AVD -qemu -enable-kvm -vnc 0.0.0.0:32  Then you can connect on localhost:5932.
Comment: what if (1) you want to use vnc with emulator on a windows machine?
also, what if (2) you use it to emulate arm?

Remote desktop server for AVD?


Custom xylophone sticks?

Question: I just bought a second hand xylophone - without sticks. (It was just under $9...) So I wonder, what can I use as a substitute? Right now, I can't get to a music store but I in a few weeks I can, if that is necessary. But for now, anything someone may have at home that works?
EDIT: The bars are made in metal. Maybe it's a metallophone...?
Comment: If it's metal, it's not a xylophone. Xylo = wood. More likely to be a glockenspiel.Try the internet. Not much that can't be found to buy there.Hard rubber ends on sticks work best.
Comment: Hmm.  Stale marshmallows on a stick?  Or wrap cotton balls with electrical tape?  Basically I'm thinking soft, but not too much so.  Oh -- and is it wood or metal?  In the former case my suggestions may be no good.
Comment: @MatthewRead It's metal. But it doesn't really sound much - I tried a round stick, pretty much no sound. Am I supposed to use something really soft or really hard?
Comment: @Tim Yeah, probably a glockenspiel. Looks exactly like this: http://upload.wikimedia.org/wikipedia/commons/7/72/Glockenspiel.jpg but it's slightly bigger.
Comment: Use a bow! https://www.youtube.com/watch?v=uU290O2BjKg
Answer: If you have any small hard rubber balls especially the kind that used to be called Super Balls which bounce very high you can mount those on chopsticks or drum sticks. Drill the holes a little smaller than the diameter of the sticks and try using epoxy, super glue or hot glue to fix them.

Custom xylophone sticks?


HTML com bootstrap layout responsivo

Question: Não consigo deixar meu layout como deveria, a idéia é deixar do seguinte modo:
  +-------------------------------------------------+
  |  logo      |          Menu Superior             |
  |            |------------------------------------+
  |------------|                                    |
  |            |                                    |
  |Menu        |         Conteudo                   |
  |            |                                    |
  |            |                                    |
  |            |                                    |
  |            |                                    |
  |            |                                    |
  |            |                                    |
  |------------|------------------------------------|
  | outra logo |          Rodapé                    |
  +-------------------------------------------------+

esta e minha tela principal, preciso que funciona os menus, pois se copiar isto e executar com o bootstrap, vai ver que o rodapé fica no meio da tela, o menu fica maior que a parte do conteúdo e etc. O ideal é deixar todo responsivo, tanto a parte da esquerda quanto a da direita.

                @Html.Partial("_Menu")

                            Toggle navigation

                            Home

                        nome da loja - bla bla - bla bla

                            Negrini

                                        Alterar imagem da conta

                                        Alterar senha

                                        Histórico de acessos

                                        Trocar loja

                                        Bloquear

                                        Sobre

                                        Trocar usuário

                                        Sair

                                    @**@ Cadastros
                                    @*12*@

                                    @**@ Movimentações
                                    @*12*@

                                    @**@ Financeiro
                                    @*12*@

                                    @**@ Comercial
                                    @*12*@

                                    @**@ Configurações
                                    @*12*@

                                    @**@ Relatórios
                                    @*12*@

                rodapé

<-- scripts -->

Situação atual:

como da para notar, nenhuma das partes chega até o final da tela.
UPDATE:
quando o conteúdo central é inserido e não é pouca informação, o layout volta a quebrar como na imagem abaixo.
Comment: Você quer que a área do conteúdo expanda até que a área do rodapé toque na parte inferior da tela? É esse o problema? Se for precisas usar javascript, daí eu te passo uma fórmula que uso.
Comment: exatamente, a área do conteudo vai váriar bastante, ou seja, ela deve se adaptar, mas sempre ficar até a parte de baixo da tela, a mesma coisa com o menu lateral esquerdo, a logo 'infoworld' deve ficar sempre alinhada ao rodapé
Comment: @KaduAmaral ve em cima por favor.
Comment: Acho que você poderia resolver isso com uma certa facilidade usando CSS com medidas em %. Basicamente deixando a logo marca com 20% da altura do browser, os menus com 80%. E uma dica: **css in-line é** uma **dor de cabeça** pra dar manutenção.
Comment: @LuizNegrini pronta a resposta, qualquer dúvida dá um toque.
Answer: A formula para fixar a altura do conteiner é bem simples:
WindowHeight - MenuHeight - FooterHeight

Ou seja, altura da janela, menos a altura do menu e do rodapé, com o menu lateral é a mesma coisa com a logo do topo e do rodapé. Atribua o IDs nesses blocos para manipular suas alturas e faça-o.

// Guarda os elementos em variáveis.
var $logotop = $('#logo-top');
var $sidemenu = $('#side-menu');
var $logobot = $('#logo-bot');

var $menutop = $('#menu-top');
var $maincontent = $('#main-content');
var $footer = $('#footer');

$(window).resize(function(event){

  var windowheight = $(window).height(); // Guarda a altura da janela

  // Altura da logo do topo e do rodapé
  var loff = $logotop.outerHeight(true) + $logobot.outerHeight(true);
  // Altura do menu do topo e do rodapé
  var roff = $menutop.outerHeight(true) + $footer.outerHeight(true);

  // Altura da coluna esquerda
  var lh = $sidemenu.outerHeight(true) + loff;

  // Altura da coluna direita
  var rh = $maincontent.outerHeight(true) + roff;

  // Se ambas alturas ultrapassarem a da janela pega a maior
  if (lh > windowheight && rh > windowheight){
    var mh = (lh > rh ? lh : rh);
  } else if (lh > windowheight){ // Se apenas a coluna esquera for maior
    var mh = lh;
  } else if (rh > windowheight){ // Se apenas a coluna direita for maior
    var mh = rh;
  } else { // Se ambas forem menores, pega altura da janela
      var mh = windowheight - 10; // Esse -10 é algum bug que ainda não olhei
  }

  // Atribui altura mínima para menu lateral
  $sidemenu.css('min-height', mh - loff + 10); // Obs esse +10 é algum bug que ainda não olhei.
  // Atribui altura mínima para conteúdo
  $maincontent.css('min-height', mh - roff);
}).resize();
#logo-top {background-color:yellow;}
#footer{background-color:green;}
#side-menu, #logo-bot, #main-content{color:white;}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

       Logo

Menu

       Logo Rodapé

      Menu

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

       Rodapé

Note que como estamos alterando a propriedade min-height, não haverá nenhum problema o conteúdo ultrapasse essa altura. E também estamos realizando essas modificações no evento resize da janela, assim caso o usuário redimensione a janela do navegador as alturas acompanharão a janela até o limite da altura do conteúdo.
Comment: Alguma coisa você fez errado então @LuizNegrini. Atribuiu os IDs aos elementos? Está usando jQuery? Colocou o código após a renderização do layout (de preferência no `$(document).ready`)?
Comment: acabei de tentar de outra forma e funcionou! Valeu a ajuda @KaduAmaral ficou bem como queria.
Comment: realizei as modificações e ele ficou como estava antes. Parece que ignorou os cálculos....
Comment: agora passando para outra página, quando o conteúdo esta grande na parte de conteudo mesmo, o menu esquerdo não o acompanha, fica como no link que coloquei no update da pergunta.
Comment: acredito que a solução é inserir um max-height na minha tabela que esta no conteudo de acordo com o tamanho da tela....
Comment: A solução é calcular qual o maio valor, o do conteúdo ou o do menu e comparar com o tamanho disponível se ultrapassam e aplicar a maior altura encontrada @LuizNegrini
Comment: pode atualizar a resposta?
Comment: Fetio @LuizNegrini...
Comment: Valeu, ainda não ficou como eu quero, mas acredito que a partir daqui eu consiga me virar hehe.
Answer: Luiz Negrini, independente de está usando Bootstrap, voçê pode usar a estrategia abaixo, no caso você vai precisar apenas de css para definir a posição de cada elemento na pagina.
Note que tudo depende da posição das divs e suas respectivas "ancoras".

div {
    box-sizing: border-box;
}

#container {
    position: fixed;
    padding: 0px;
    margin: 0px;
    top: 0px;
    right: 0px;
    left: 0px;
    bottom: 0px;
}

#logo1 {
    position: absolute;
    top: 0px;
    right: 0px;
    left: 0px;
    height: 96px;
}

#sideMenu {
    position: absolute;
    top: 96px;
    right: 0px;
    left: 0px;
    bottom: 48px;
    overflow-y: auto;
}

#logo2 {
    position: absolute;
    right: 0px;
    bottom: 0px;
    left: 0px;
    height: 48px;
}

#topMenu {
    position: absolute;
    top: 0px;
    right: 0px;
    left: 0px;
    height: 48px;
}

#content {
    position: absolute;
    top: 48px;
    right: 0px;
    left: 0px;
    bottom: 48px;
    overflow-y: auto;
}

#esquerda, #direita {
    position: relative;
    height: 100%;
}

#footer {
    position: absolute;
    right: 0px;
    bottom: 0px;
    left: 0px;
    height: 48px;
}

#logo1, #sideMenu, #logo2,
#topMenu, #content, #footer {
    border: 1px solid black;
}

.linha {
    width: 100%
    clear: both;
}

.celula {
    float: left;
}

.celula-2 {
    width: 16.66%;
}

.celula-10 {
    width: 83.33%;
}

      logo

      Menu

      outra logo

      Menu Superior

        Conteudo

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dignissim efficitur lorem, lobortis rhoncus erat elementum nec. Sed imperdiet in ante sit amet consectetur. Nullam ac nisl gravida, fermentum ex vitae, hendrerit orci. Proin ullamcorper sapien vitae odio pellentesque, ac volutpat urna accumsan. Suspendisse risus felis, iaculis eu sagittis in, posuere a purus. Morbi eget hendrerit mi. Nulla dapibus magna faucibus lobortis malesuada. Praesent vehicula dui tortor, scelerisque commodo nunc lacinia nec. Nulla condimentum erat eu est auctor aliquam. Fusce nec neque rutrum, cursus tortor in, luctus sapien. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer eleifend odio in nunc porta tristique. Nam luctus ultrices ex, sit amet maximus mauris iaculis finibus. Nulla fringilla erat in mattis fermentum. Suspendisse hendrerit lacinia nisi quis interdum. Duis pellentesque dignissim lacus, quis imperdiet tellus mattis nec.

        Quisque ac arcu turpis. Fusce suscipit fermentum arcu. Donec porta, elit eget finibus bibendum, neque lorem accumsan eros, in ultrices turpis neque ut nulla. Donec dolor mi, tristique sit amet fringilla non, malesuada ac ante. Cras porttitor sed nisl sit amet dignissim. Aenean convallis quis magna quis cursus. Nam fringilla tincidunt nibh vel porttitor.

        Nam vitae luctus justo. Donec ac volutpat odio. Vivamus in justo risus. Aenean pharetra orci tellus, quis accumsan sem convallis at. In non mauris rhoncus, faucibus tortor at, bibendum nibh. Pellentesque faucibus, nisi blandit viverra sodales, felis quam faucibus turpis, ornare condimentum ex risus nec elit. Nam ullamcorper aliquet bibendum. Curabitur eu diam auctor nulla auctor fringilla. Nunc eleifend sollicitudin sagittis. Aliquam erat volutpat. Suspendisse eget lobortis libero. In venenatis egestas dui, sed tincidunt lectus commodo ut. Nulla ultrices convallis purus, eu faucibus turpis luctus sed. Morbi nec tellus id odio ultrices posuere eu vel odio. Fusce tincidunt at eros a cursus. Vestibulum cursus rhoncus est, quis commodo sem scelerisque vel.

        Donec tellus nisl, semper quis blandit sit amet, iaculis vel nulla. Proin metus arcu, fringilla et varius et, pretium non nisl. Sed erat justo, efficitur quis ipsum ac, cursus congue ipsum. Suspendisse ut convallis libero, nec commodo nibh. Nam et pretium ante. Sed sit amet tincidunt lacus, ac egestas urna. Integer auctor enim nulla, vel molestie justo luctus eget.

        Duis a libero in nisl vestibulum dapibus. Sed vulputate odio quis eros pretium, eu vehicula mauris ornare. Curabitur ornare neque sed mattis pretium. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus efficitur sollicitudin ipsum sed varius. Vivamus congue consectetur est, viverra luctus risus venenatis ac. Phasellus ultricies dignissim arcu, et venenatis est sagittis pulvinar. In et rhoncus mauris. Proin egestas eu mauris id gravida. Donec ac tincidunt neque.

      Rodapé

tentei simular as classes do boostrap usando as classes linha e celula-2 e celula-10.
Caso precise que o Menu Lateral tenha um tamanho fixo, basta usar position: absolute e definir um width para ele para o painel da esquerda, enquanto que no painel da direira você coloca o valor da "ancora" left igual ao width do painel da esquerda
Comment: A solução com CSS é boa (+1 por isso), mas depende do caso se a pessoa quer que o rodapé fique sempre aparecendo...

HTML com bootstrap layout responsivo


Cant see split html file

Question: I'm trying to split html file into 2 different files:

<frameset cols="25%,75%">
   <frame src="addNewEvent.html" />
   <frame src="totalEvents.html" />
</frameset>

addNewEvent.html:

Left

totalEvents.html:

Right

The 3 files (main html and addNewEvent.html, totalEvents.html) are in the same directory.
(I just learning html, so for now, I'm not using server, and open the main page with the browser.
When opening the main page in the browser, is seems that the addNewEvent.html, totalEvents.html are not loaded. (There is no error in console log)

What an I doing wrong ?
Is it right to split the page into little pages with frameset ?
Comment: Are you sure you want to use HTML4? It's the 21st century and HTML5 is de facto for HTML
Answer:
What an I doing wrong ?

You didn't use a validator which would have told you that a <frameset> element is not allowed inside a  element.
Frameset documents have a <frameset> instead of a  element. Since the HTML document already had its own , the browser ignored the <frameset>.

Is it right to split the page into little pages with frameset ?

That's largely a matter of opinion. They do cause various issues with how they interact with browser navigation controls and do not exist in HTML 5.

Cant see split html file


Best critical region and Neyman-Pearson lemma?

Question: I'm reading an online course and I'm really confused about the Neyman-Pearson lemma. It states

From my understanding, does it mean that critical region could be any region like (a,b) and (c,+00)?

And I'm very confused with most powerful critical region according to its definition

what does K mean? Can K be any constant number?
Comment: It means *a* constant number, which you need to determine so that the test has the required significance level.
Comment: I posted an illustrated account of this theory at http://stats.stackexchange.com/a/130772.
Answer: Both of the regions you shaded correspond to $\alpha=0.05$, assuming that your plot represents the null distribution.
The best critical region would be the one of these that would be most likely under the alternative hypothesis. If the alternative hypothesis was $H_a:\mu = C$ for any $C>0$, then the tail critical region would be the best critical region because it would be the critical region with the largest probability under the alternative.
K is a unique constant so that the test has the specified significant level, as the commentator JohnK noted.


How to copy public private key to linux

Question: I mostly work on windows. I have a public\private key which I use with git source control(github n other repos). Now, I want to use same keys from a linux machine. I have setup a virtual machine on windows with ubuntu. Can I use the same keys? How do I copy them to the linux instance?
Comment: Are they OpenSSL keys generated with a tool like ssh-keygen?
Comment: I had used puttygen to generate in SSh-2 RSA format
Comment: I seem to have got it working but it won't accept the passphrase I used on windows
Comment: this link has steps which solved my problem. http://stackoverflow.com/questions/2224066/how-to-convert-ssh-keypairs-generated-using-puttygenwindows-into-key-pairs-used
Answer: You do not want to share the same key with another machine. No, you don't, really.
Each private key should be restricted to one user on one machine only. Do not copy private keys around, since by doing this you are exposing your key to an increased risk of it being stolen or inadvertently copied via untrusted channels, or left on untrusted storage devices.
What you should do is generate a new key pair on the new machine, then transmit your second public key to github. Any decent SSH-based service that allows the use of PKI also allows you to store multiple public keys, github is no exception. Give suggestive names to each key (for SSH keys, they are in the form of "username@hostname") so that you know the device associated to each public key.
This has the benefits of keeping your private keys safe, and you can revoke keys individually when only one of them is compromised.
Comment: Why is it such a big deal?  I mean, am I the only one who uses a strong passphrase and an agent?  I am just curious here if you different keys with strong passphrases for every box you have. For me that is a lot and sometimes I need a little convenience in my life.  I am just curious about others like you, because what you said is definitely the little voice in my head when I know I should "know better."
Comment: Has got the answer spot on. The reasons why you should **never** move a private key are described in the 2nd and 4th paragraphs.
Comment: @alharaka: I'm unable to understand your concern. Strong passphrases are mandatory, of course, and an SSH Agent actually helps a lot with the key management when you have multiple key pairs. For example, to manage the servers at work, I need a key that is only in my work computer, not in my laptop. But the key in my laptop allows me to connect to my work computer. If I have to connect to the servers from my laptop, I can SSH into my work computer, load its keys into my laptop's SSH Agent, then I can connect to the servers from my laptop.
Comment: I get what you mean. My point here is, let's say I originally configured Github to work with a USB key and different types of SSH clients loadable from the USB key in the event I was not at a computer that was customized by me the way I like. In the event someone steals my USB key, what will they do with the private key?  With the passphrase, it is not that useful anyway, and I can trash it for a new one. Reusing my SSH key is potentially dangerous from a theoretical viewpoint, but I have always felt practically the real risk is limited. Then again, I am not discussing work stuff.
Comment: @alharaka The point of using passphrase-protected keys is so that if either the key or the passphrase is stolen, it will only result in a partial compromise, which doesn't give the thief access to the system. With the passphrase set, you have time to revoke the key before the attacker has full access to the system. But having a key in a USB stick and plugging it in any computer you may not trust is inherently dangerous practice. You may have an emergency one-time key in a USB stick, that you revoke as soon as you have to use it once.
Answer: -SCP (PuTTY)
-Use a SMB share that's accessible to both machines and transfer it that way
-FTP server
Then you always have the "I have no idea what I'm doing" methods like uploading the key to google docs on the windows machine and then downloading it on the linux machine.
Answer: I like the first answer, use puttý´s scp tool, or also another easy way would be to copy the keys to flash drive from windows, and then connect the flash drive to the VM instead, if that is possible with your VM software.
Answer: Most virtual machines (e.g. VMWare, VirtualBox) support file shares between host and VM. Create a file share on the host, mount it in the VM and you have an easy way to share files between the two.
If your key doesn't work, it's probably because it is actually a putty key. You need to use puttygen to export this into a ssh key.

How to copy public private key to linux


How to write a pickup measure with 5/16 duration in Lilypond?

Question: I'm trying to write sheet music for a piece with a pickup measure of 5 sixteenth notes. Lilypond has the \partial command for this, but it only accepts a single duration. That duration may be dotted, but that doesn't help since I need 5 notes, not 3, 6 or 7.
I've tried various combinations of partials, e.g. using the command twice:
\version "2.16.0"

\relative c'' {
    \key g \major
    \partial 4 \partial 16 g16 g fis d b | e2
}

which produces a barcheck warning

warning: barcheck failed at: 1/4
   \partial 4 \partial 16 g16 g fis d b
                                        | e2

and a wrong result:

I've tried other things like \partial { 4 16 } or \partial 4~16 but nothing seems to work; either the pickup measure is ignored or it has a wrong length.
Is there any solution for this? I don't want to use a pickup measure of one half note with 3 sixteenth rests.
Answer: \partial 16*5.  Some people prefer writing \partial 1*5/16 which scales \partial 1 by the fraction 5/16, but I'd lean towards the simpler version.
Comment: Clever! I've seen that `*` for multi-measure rests, but never for notes or things like this. I even't can't find a definition for this notation in the documentation. Or is it a general Scheme trick?
Comment: @Glorfindel It's documented [here](https://lilypond.org/doc/v2.24/Documentation/notation/writing-rhythms#scaling-durations). `\partial` isn't mentioned, but it works anywhere a note-like duration is expected. It has nothing to do with Scheme, although you can use a Scheme expression as the scaling factor as mentioned in the documentation.
Answer: I've found one workaround, but I'm not sure I really like it since the sum of the \partial durations is longer than the actual pickup measure:
\version "2.16.0"

\relative c'' {
    \key g \major
    \partial 4 g16 \partial 4 g fis d b | e2
}

and Lilypond warns about this:

trying to use \partial after the start of a piece
   \partial 4 g16
                  \partial 4 g fis d b | e2

but the result is correct:

Using \partial 4 g16 g fis d \partial 16 b | e2 instead doesn't work properly, since it inserts a bar line after the d already (and produces a warning in the compiler):

I'm really interested in a better solution (if it exists)!
Answer: Try: \partial 16 * 5 g16 g16 fes16 d16 b16 |  e2
Comment: Is this any different to user72605's answer?
Comment: @ElementsinSpace yes - it replaces the `fis` in my question with a different, wrong note. For someone who has severe problems reading staffs with more than two flats, that even borders on an insult ...


add sharethis button to a slideshow

Question: I'm trying to add a button Sharethis to a slideshow "views_slideshow" that shows the whole content to the specific element in the slideshow.
the problem is I can't add this button to the slideshow, and I have it to show inside a block.
Answer: Figured it out, you just add "shareThis" to your content type you want this to show in a slide show, and since we are showing the whole content it will show with the rest of the node.

add sharethis button to a slideshow


Complex SelectQuery with multiple left joins and conditions with OR

Question: I have a view and in hook_views_pre_execute() I have to add multiple left joins with conditions. Currently I'm doing this:
$or = db_or();
foreach ($fields as $field) {
    $query->leftJoin($field->table, $field->table, '(node.nid = ' . $field->table . '.entity_id)');
    $or = $or->condition($field->table . '.' . $field->field, '%' . $string . '%', 'LIKE');
}

$query->condition($or);

but it doesn't seem to work.
Comment: May you show the code that is executed in `hook_views_pre_execute()`, including the part you are already showing?
Comment: inside your "foreach" remove the $or = you're currently only going to get the last $or condition once it exits.
Comment: While setting `$or` to the value returned from `$or->condition()` is not necessary, that is not the reason why the code doesn't work. `$or->condition()` just returns the pointer to the object that is already in `$or`.
Answer: It seems that the problem was $field->field. For example if I have a field called field_book_author in database the $field->table would be field_data_field_book_author and the value of the field would be in field_book_author_value.
So the correct code is:
$or = db_or();
foreach ($fields as $field) {
    $query->leftJoin($field->table, $field->table, '(node.nid = ' . $field->table . '.entity_id)');

    if (property_exists($field, 'additional_fields') && (count($field->additional_fields) > 3)) {
        $field_name = $field->additional_fields[3];
    }else {
        $field_name = $field->field;
    }
    $or->condition($field->table . '.' . $field_name, '%' . $string . '%', 'LIKE');
}

$query->condition($or);

Comment: Instead of using additional_fields, correct field name can be retrieved from $field->real_name


State a necessary and sufficient condition for a finite dimensional vector space $V$ over a field $F$ has precisely one basis.

Question: State a necessary and sufficient condition for a finite dimensional vector space $V$ over a field $F$ has precisely one basis.
I tried solving this problem as follows:
Let $\dim V=n.$ So, we can assume, $B=\{v_1,v_2,...,v_n\}$ to be a basis for $V.$
Let $c\neq 0$ be in $F.$
Claim: $cB$ is a basis for $V.$
This can be verified easily. Suppose $c_1,...,c_n$ be scalars such that $\sum _{i=1}^nc_icv_i=0\implies cc_1=cc_2=...=cc_n=0\implies c_1=c_2=...=c_n=0$ as, $c^{-1}$ exists.
Now, for $x\in V$ $\exists b_1,...,b_n\in F$ such that $\sum _{i=1}^nb_iv_i=x=\sum _{i=1}^nb_ic^{-1}(cv_i).$ Thus, $x\in \text{span}(cB)\implies V\subseteq \text{span}(cB)\implies V=\text{span}(cB),$ as $\text{span}(cB)\subseteq V.$
This proves our claim.
As, $B$ is the only basis for $V$ so, $cB=B$ is the only possibility. This implies that every element in the basis can be expressed as a non-zero scalar multiple of another element in the same basis.
We note that, $c\neq 0$ is an arbitrary non-zero scalar of $F.$ So, if  $V$ has only one basis then every element in the basis can be expressed as a non-zero scalar multiple of another element in the same basis.

But I don't understand whether the converse of this statement holds as well, i.e, "If every element in a basis of a vector space $V$ can be expressed as a non-zero scalar multiple of another element in the same basis, then $V$ has precisely one basis."
If this converse statement holds, then I am having a hard time proving this as well. Any help regarding this question will be greatly appreciated.
Answer: If $\{v_1,v_2,\ldots,v_n\}$ is a basis of $V$, then $\{v_1+v_2,v_2,\ldots,v_n\}$ is another basis of $V$. Therefore, if $V$ has exactly one basis, then $\dim V<2$.
If $\dim V=1$ and $v\neq0$, $\alpha\in F$ and $\alpha\neq0,1$, then $v$ and $\alpha v$ are  different bases.
Hence, if $V$ has precisely one basis, then $\dim V=1$ and $|F|=2$. The converse is obvious.
PS. The empty set is sometimes thought to be the basis of the null space. In this case it is necessary to change the formulation.
Here we go:
If $V$ has precisely one basis, then  either $\dim V=1$ and $|F|=2$ or
$\dim V=0$ and $F$ is an arbitrary field.
The converse is still obvious.


React Native - Is there a way to use bluetooth in peripheral mode?

Question: I am developing an app in ReactNative offline.
One of the functionalities is to use bluetooth to synchronize the data (that the app was collecting) with other devices that use the same app.
I started to develop this task with the react-native-ble-manager library, i can connect from device A to device B, but I don't understand how to listen to the incoming connection in device B. I need to know this to show a certain view.
can anybody help me?
I am using the correct library?
Thanks!
Comment: I'm guessing device A is a smartphone with your app installed. What kind is device B?
Comment: Device A and B use the same app, and can be a Tablet or Smartphone. I must show a certain view when receiving a bluetooth communication on device B from device A. This is to synchronize the forms that were created by both devices. The place where this app is going to be used does not have an internet connection.
Answer: Note: This answer is iOS only since react-native-peripheral has not implemented Android support yet.
You can't use only the react-native-ble-manager for this project. The library states in its readme that it is based on cordova-plugin-ble-central, which can only act as a central. For a BLE connection you need a central and a peripheral.
Take a look at react-native-peripheral. It allows you to act as a perihperal, create a characteristic with some data, add it to a service and register it so other devices can find it. This is their usage example:
import Peripheral, { Service, Characteristic } from 'react-native-peripheral'

Peripheral.onStateChanged(state => {
  // wait until Bluetooth is ready
  if (state === 'poweredOn') {
    // first, define a characteristic with a value
    const ch = new Characteristic({
      uuid: '...',
      value: '...', // Base64-encoded string
      properties: ['read', 'write'],
      permissions: ['readable', 'writeable'],
    })

    // add the characteristic to a service
    const service = new Service({
      uuid: '...',
      characteristics: [ch],
    })

    // register GATT services that your device provides
    Peripheral.addService(service).then(() => {
      // start advertising to make your device discoverable
      Peripheral.startAdvertising({
        name: 'My BLE device',
        serviceUuids: ['...'],
      })
    })
  }
})

There is a section about dynamic values where they explain how you can use the onReadRequest and  onWriteRequest callbacks to listen to read and write operations on the peripheral and even return dynamic values on each read request:
new Characteristic({
  uuid: '...',
  properties: ['read', 'write'],
  permissions: ['readable', 'writeable'],
  onReadRequest: async (offset?: number) => {
    const value = '...' // calculate the value
    return value // you can also return a promise
  },
  onWriteRequest: async (value: string, offset?: number) => {
    // store or do something with the value
    this.value = value
  },
})

Comment: Thanks for replying but react-native-peripheral doesn't have android support. The app must work on both IOS and Android. Any other library to recommend that works on both?
Comment: Oh sorry, I missed that! I'm not aware of any other library that can do that. I believe your best shot would be to use [native modules](https://reactnative.dev/docs/native-modules-intro)
Answer: I'm facing a similar situation. What do you think if you use this library https://github.com/himelbrand/react-native-ble-peripheral?  It seems to support Android and iOS according to npm notes here
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/35140107)


Move application servers from one domain to another

Question: I have built a new domain and created a trust between the new domain and old domain. I have migrated the users and PCs but have yet to move the servers.  Does anyone have any suggestions as to the best way to perform this?  We have 2 application servers, an Exchange '10 server, and 1 DC. All servers are '08 R2  Any input would be appreciated.
Thanks
Answer: it sounds like what you are after is a domain migration.
this is not a simple task and you need to do some reading and careful planing of how to do it.
there is a lot of things that can and will go wrong.
also the most important thing is to test your plan so you know what will happen and problems you will run into.
a few pointers:
i don't think you can migrate the dc as is, what you need to do is to setup a new dc and then decommission the old one and then move the old dc as if it was a regular member server without any dc.
but note that you of course need a functioning domain until everything else is done.
i also am pretty sure there is additional complications with exchange mailboxes, most likely you need to setup a new server in the new domain and then move the mailboxes over.
how to handle application servers depends very much on what you have on them.
as a minimum you will need to go thru any dependencies on the old domain including services running as a domain account.
a quick search gave the following links
http://technet.microsoft.com/en-us/library/cc974332%28v=ws.10%29.aspx
http://blogs.technet.com/b/meamcs/archive/2011/06/10/exchange-2010-cross-forest-migration-step-by-step-guide-part-i.aspx
so, do some reading, testing and make sure you have backups in case something goes wrong.


Como resolver este problema

Question: Preciso fazer este código funcionar da forma que se conter a palavra na url eu mude para opção predefinida como segue:

$('#servico').val(Sispostag.getParameterValue('servico'));
var url = location.href;
if(url.indexOf('undefined')==-1) {
    $('#servico').val(Sispostag.getParameterValue('servico'));
    var elementS = document.getElementById('servico');
    elementS.dispatchEvent(new Event('change'));
} else {
    $('#servico').val('123');
    var elementS = '123';
    elementS.dispatchEvent(new Event('change'));
}

Porém sempre retorna este erro: Uncaught TypeError: elementS.dispatchEvent is not a function.
Alguém pode me ajudar a solucionar este erro?
Answer: Se estás a usar jQuery, usa .change() para disparar o evento.
O erro em questão vem desta linha:
var elementS = '123';

e acontece é que estás a sobreescrever o valor da variável, e não do elemento. Depois quando chamas dispatchEvent é o mesmo que
123.dispatchEvent(new Event('change'))

e isso dá erro.
Sugestão de código:
var url = location.href;
if(url.indexOf('undefined')==-1) {
    $('#servico').val(Sispostag.getParameterValue('servico')).change();
} else {
    $('#servico').val('123').change();
}

Como resolver este problema


Whats wrong with my AutoResetEvent code?

Question: I have this code which seems pretty straightforward but the AutoResetEvent never gets signalled. Nothing seems to get returned from the web services and the WaitAll just times out after ten seconds. Everything works fine without the threading jiggerypokery so its not a web service issue. What am I doing wrong?
<code>    AutoResetEvent[] autoEvents;
    ObservableCollection<Tx3.ResourceService.ResourceTime> resourceTime;
    ObservableCollection<Tx3.ResourceService.ResourceTimeDetail> resourceTimeDetail;

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        autoEvents = new AutoResetEvent[]
        {
            new AutoResetEvent(false),
            new AutoResetEvent(false),
        };

        var resourceService = getResourceServiceClient();

        // Get ResourceTime data for this user
        resourceService.ListResourceTimeAsync(CategoryWorkItemId, ResourceId);
        resourceService.ListResourceTimeCompleted += new EventHandler<Tx3.ResourceService.ListResourceTimeCompletedEventArgs>(resourceService_ListResourceTimeCompleted);

        // Get ResourceTimeDetails
        resourceService.ListResourceTimeDetailAsync(CategoryWorkItemId, ResourceId);
        resourceService.ListResourceTimeDetailCompleted += new EventHandler<ListResourceTimeDetailCompletedEventArgs>(resourceService_ListResourceTimeDetailCompleted);

        WaitHandle.WaitAll(autoEvents, 10000);

        System.Diagnostics.Debug.WriteLine("do something with both datasets");
    }

    void resourceService_ListResourceTimeCompleted(object sender, Tx3.ResourceService.ListResourceTimeCompletedEventArgs e)
    {
        resourceTime = e.Result;
        autoEvents[0].Set();
    }

    void resourceService_ListResourceTimeDetailCompleted(object sender, ListResourceTimeDetailCompletedEventArgs e)
    {
        resourceTimeDetail = e.Result;
        autoEvents[1].Set();
    }
</code>
Answer: I can offer a naive first guess: it looks like you're adding the event handlers after calling the methods that start the asynchronous operations; it's possible there's a race condition in there or some other issue.  Could you switch the order of operations so you attach the event handler, and then begin the operation?
Comment: What a silly sausage(!) Lets assume I've written the handlers the correct way around.
Comment: If this is a web service, you should be able to rig up Wireshark and verify whether it's working correctly; can you verify that the responses are coming back?  If they are, try setting breakpoints in the callback methods and see if you make it there.  Basically just try to check every step along the way that you can until you see where it falls apart.
Comment: Theres nothing wrong with the web services, they terminate correctly if I remove all the autoevent stuff... just not synced.
Answer: These are AutoResetEvent objects -- looks like you want a ManualResetEvent -- the auto version triggers anything waiting, but immediately resets.  Manual ones stay triggered so if the callback happens before you get to the WaitAll, it'll just fall through immediately.
Also, qid is correct -- you're attaching your event handlers too late too...so there's two different bugs going on here.
Comment: I thought that might be the case too - but according to the MSDN docs the event is reset only after it signals a thread.
Comment: Oh, you're right -- silly me.  qid likely has the answer, then
Answer: Are you using this code on a thread that is marked with the STA attribute, for example the main UI thread? If so, the WaitAll method is not supported on these threads.
Check here.


Good way to design mqtt topic?

Question: I am very new with mqtt design.
As I see from some tutorials in the internet, common mqtt topic has this format: /home/room/device_type/device_id
I could not see the benefit to do that. And have no idea how to use this kind of design.
From my point of view, the device (dev) might subscribe (sub) to control topic and publish (pub) to status topic. Like this:

pub: clients/dev/devid/stat
sub: clients/dev/devid/ctrl

In this way, it seems sub,pub logic is very simple for both clients and devices
Could someone please tell me some good way to design mqtt topic ?
(!) Please do not start topic with '/' (This one has been recommended by HiveMQ Team)
EDIT:
I just figured out that for whatever kind of design, the model must serve-able at least:

Individual control: send control command to a particular device.
Group control: send control command to a group of devices: type, defined group
Able to recieve the status of device.

Thank you very much
Comment: First off, topics should NOT start with a leading `/`
Comment: It adds a null to the start of the topic tree which makes it harder to use wild cards properly.
Comment: It is an extra level of tree to search and more a problem for `+` wild card matches. Also as it is documented bad practice it makes interoperability harder so just DON'T DO IT
Comment: From: https://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices. They said: "That should be avoided, because it doesn't provide any benefit and often leads to confusion.". I'm sorry, but I see no reason to avoid that. '/' stand for top level, it simpler than any kind of word: top, boss, father, etc.
Comment: Yes that agrees with me
Comment: Did you mean: /# and # ? If so, I'm sorry, just from my point of view, I see it's not really a meaning issue. Or is there any issue with performance ?
Comment: Thanks for your helpful info, I just edited the post.
Answer: I found that the following topic split scheme works very well in multiple applications
protocol_prefix / src_id / dest_id / message_id / extra_properties

protocol_prefix is used to differentiate between different protocols / application that can be used at the same time
src_id is the ID of the mqtt client that publishes the message. It is expected to be the same as "client ID" used to connect to MQTT broker. It allows quick ACL control to check whether the client is allowed to publish specific topic.
dest_id is client ID of the "destination" unit, i.e. to whom the message is intended. Also allows quick ACL control on the broker of whether client is allowed to subscribe to a particular topic. There can be reserved "destination" strings to specify that the message is broadcasted to anyone who is interested. For example all.
message_id is actual ID of the message within used protocol. I usually use numeric value (as string of course), because the IOT or other embedded system that is connected to MQTT broker can have other I/O links and I would like to use the same protocol (but with different transport framing) to control the device using these other I/O links. I usually use numeric message IDs in such communication links.
extra_properties is an optional subtopic which can be used to communicate other MQTT specific extra information (comma separated key=value pairs for example). Good example would be reporting timestamp of the message when it was actually sent by the client. In case of "retained" messages it can help to identify the relevance of the received message. With MQTTv5 protocol that is expected to arrive soon, the need for this subtopic may disappear because there will be other way to communicate extra properties.

Hope it helps.
Comment: I like the idea to integrate src and dst in the topic. Subscriber can use wildcards to get topics from "all senders" or "all destinations". Seems to be a quite flexible approach.
Comment: Including a dest_id,  "i.e. to whom the message is intended". Seems wrong-headed in  any sub/pub model.   A client doesn't "intend" any destination.  There *may* be zero or more subscribers. TWIMC applies.
Answer: We have done some work on that for the domain of manufacturing (Industrial-IoT, not IoT!).
In our scenario there are lots of serverside apps of different companies communicating through MQTT. Thus we needed some overall structure. We call this "Manufacturing Message Stack".
The bottom layer is MQTT, then there is the "Messaging Layer". It consists mainly of

basic topic specs
basic payload specs

On top of the messaging layer there are domain message layers covering various domain specific topics as system messages, alerting, physical device / digital twin messages or other manufacturing related messages.
Topics
The topics are roughly defined as <senderapp>/<app-id>/<message-name>/<args> e.g. pacman/pacman-1/gameover (this is a sample for illustration only!)
The developer of an app which publishes MQTT messages defines <message-name> and <args> depending on the semantics of the payload.
The  <senderapp> and <app-id> refers to the sending App and allows to quickly select messages from a defines origin (publisher). We deploy Apps in a microservice environment built with Docker, Rancher - and soon - Kubernetes.
Payload
The payload is specified in JSON format. There is a JSON schema reference URL in each
build an URL to an API of the publishing app which holds further information (e.g. JSON schema) of the message sent. Thus a subscriber can get meta data of a MQTT message on demand. Static meta data is not sent with a message to reduce the payload size.
Payload sample:
{
    "$schema": "http://app/api/messages/message1.json",
    "score": 1234,
    "highscore": false
}

Publisher's message meta data
The publishing app holds an index of all messages which can be sent in an API at
http://<app>/api/messages/index.json:
{
    "message1": "message1.json",
    ...
}

Each message is described by its JSON schema message1.json:
{
    "$schema": "http://json-schema.org/draft-06/schema#",
    "title": "Pacman end of game",
    "properties": {
        "score": {
            "description": "Players score at the end of game",
            "type": "integer"
        },
        ...
    }
}

Unfortunately we did not publish our manufacturing message stack yet. Publishing is planned in the next months. Feedback is welcome.
Answer: I think if topics are to reflect the physical world, we should look at something like Signal K.
EDIT:
That spec is also still maturing, but it includes concepts like "self" for the server/broker, and a tree that can start at the current vessel/home, but easily extends upwards to other vessels/aircraft/things.
My two cents:

All topics are read-only unless they end in "/set"
Ideally, topics are reasonably normalized and granular. I can understand grouping values up into a group topic.  IMHO, this kind of decision should be application-specific.
Payloads should be strings, to avoid endian-ness issues

Here's one suggested tree:

broker = information of this specific broker

broker/clients
broker/clients/count
broker/clients/0/name or broker/clients[0]/name
broker/topics

home = this current location (could also be "here" or something)

home/kitchen/temperature "19C"
home/kitchen/temperature/hardware/type "ESP8266"
home/garage/maindoor/set "closed"

locations = list of all known locations

locations/0/uuid
locations/0/name
locations/0/address
Comment: I just added 1 like for broker idea. But I also found-out that why we need to do that ? because each broker contains its particular IP/Port. Should we reduce this one to reduce the complexity of topic ?
Comment: If I understand your question correctly, I think the broker topic is really more like a namespace.  There's a bunch of information about the broker itself that you might want, and that topic separates those subtopics from the others that are more "mission specific" (kitchen lights, porch temperature, etc)
Comment: After playing around with topics a little bit, I'd like to amend my list.  I think there should be a "devices" topic, and each device should have a unique id on that list.  This would be how new devices connect to the broker.

From there, users can, through the broker, give client a logical name/location as a "header" for publishing.

ex:
* "devices" - returns a list of all devices connected to the broker
* "devices/ESP1337/location/set" = "home/garage" - tells device ESP1337 to publish its sensor data under that topic, like "home/garage/temperature"
Comment: All topics are "read-only" except "set" makes zero sense.

Good way to design mqtt topic?


Sorting and running functions

Question: I was given a question where I needed to check if in the given array, there's a value where the power of it existed in the array.
For example: the array - A { 4,16,3,2,15,7 }
It'll return True because 4^2 = 16, and 16 is in the array.

I know I need first to sort the array but I am not sure what to do next if I want to make it as efficient as possible. Should I run the check inside the sorting code or once it finish sorting?
Should I use Bubble Sort? Which sorting method is most efficient for arrays?

Thanks, guys!
Comment: why do you need to sort ?
Comment: I was told I need to sort it in order to have it as efficient as possible.
Comment: @Mor - Sorting is not an efficient.
Answer: There is no need of sorting, you can use some with includes.

const arr = [4,8,3,2,15,7];

console.log(arr.some(e => arr.includes(e*2)));

Sorting and running functions


Como mudar o nível de logging de uma dependência?

Question: Estou tentando lidar com o nível de logging de uma dependência, onde ela esta mostrando INFO e eu não gostaria que ela mostrasse esse nível, pois a informação não é pertinente, no meu caso é o nível de logging do JUnit 5.
Segue o resultado do logging da dependência quando rodo meu código:
Sep 19, 2019 12:17:47 AM org.junit.platform.launcher.core.LauncherConfigurationParameters fromClasspathResource
INFO: Loading JUnit Platform configuration parameters from classpath resource [file:/E:/root/scalableapitesting/target/classes/junit-platform.properties].

Sum result is : 10
Subtraction result is : 5

Sep 19, 2019 12:17:47 AM org.junit.jupiter.engine.config.EnumConfigurationParameterConverter get
INFO: Using parallel execution mode 'SAME_THREAD' set via the 'junit.jupiter.execution.parallel.mode.default' configuration parameter.
Sep 19, 2019 12:17:47 AM org.junit.jupiter.engine.config.EnumConfigurationParameterConverter get
INFO: Using parallel execution mode 'CONCURRENT' set via the 'junit.jupiter.execution.parallel.mode.classes.default' configuration parameter.

Process finished with exit code 0

Toda parte do INFO, eu gostaria de remover.
Pelo pesquisei, a api de logging que o JUnit 5 usa:
JUnit uses the Java Logging APIs in the java.util.logging package (a.k.a. JUL) to emit warnings and debug information. Please refer to the official documentation of LogManager for configuration options.
Vi coisas sobre o logging.properties, log4j.properties porém ainda não consegui mudar o nível, acredito que algum arquivo de configuração será possível modificar isso.
Dependência no pom.xml que esta gerando o logging:
<dependency>
   <groupId>org.junit.jupiter</groupId>
   <artifactId>junit-jupiter-engine</artifactId>
   <version>5.5.2</version>
</dependency>

Comment: Você pode regular o nível de log por pacotes, por exemplo, configurar o nível para o pacote `org.junit.platform` como `INFO`. Poste seu `log4j.properties` ou `logging.properties` ou `slf4j` ...
Comment: Bom, depois de mais investigacoes, descobri que, quando usando o JUL, se voce quiser apontar pra um logging.properties diferente, alem de criar o arquivo voce deve apontar pelo java.
Answer: Bom, a solução final foi "apontar" onde esta o arquivo que tem as propriedades que eu quero no java, nesse caso ele ta na pasta resources.
Isso é:
//Solução
String loggingPath = Main.class.getClassLoader().getResource("logging.properties").getFile();
System.setProperty("java.util.logging.config.file", loggingPath);

Na documentação do JUL, o standard é procurar a nível de JRE (o que eu achei um tanto quanto estranho) pois alterar para a aplicação X pode causar efeito na aplicação Y.
Sobre alterar propriedades do sistema, como estou rodando cada jar em contêineres isolados não sera um problema alterar a propriedade do sistema.
No meu arquivo de configuração (que já existia), a linha que faz oque eu quero é essa:
org.junit.level=WARNING


correctly tokenize english contractions with unicode apostrophes

Question: How do you modify the default spacy (v3.0.5) tokenizer to correctly split english contractions if unicode apostrophes (not ') are used.
import spacy

nlp = spacy.load('en_core_web_sm')
apostrophes = ["'",'\u02B9', '\u02BB', '\u02BC', '\u02BD', '\u02C8', '\u02CA', '\u02CB', '\u0060', '\u00B4']
for apo in apostrophes:
    text = f"don{apo}t"
    print([t for t in nlp(text)])
>>>
 [do, n't]
 [donʹt]
 [donʻt]
 [don't]
 [donʽt]
 [donˈt]
 [donˊt]
 [donˋt]
 [don`t]
 [don´t]

The desired output for all examples is [do, n't]
My best guess was to extend the default tokenizer_exceptions with all possible apostrophe variations. But this does not work as Tokenizer special cases are not allowed to modify text.
import spacy
from spacy.util import compile_prefix_regex, compile_suffix_regex, compile_infix_regex

nlp = spacy.load('en_core_web_sm')

apostrophes = ['\u02B9', '\u02BB', '\u02BC', '\u02BD', '\u02C8', '\u02CA', '\u02CB', '\u0060', '\u00B4']
default_rules = nlp.Defaults.tokenizer_exceptions
extended_rules = default_rules.copy()
for key, val in default_rules.items():
    if "'" in key:
        for apo in apostrophes:
            extended_rules[key.replace("'", apo)] = val

rules = nlp.Defaults.tokenizer_exceptions
infix_re = compile_infix_regex(nlp.Defaults.infixes)
prefix_re = compile_prefix_regex(nlp.Defaults.prefixes)
suffix_re = compile_suffix_regex(nlp.Defaults.suffixes)

nlp.tokenizer =  spacy.tokenizer.Tokenizer(
        nlp.vocab,
        rules = extended_rules,
        prefix_search=prefix_re.search,
        suffix_search=suffix_re.search,
        infix_finditer=infix_re.finditer,
    )

apostrophes = ["'",'\u02B9', '\u02BB', '\u02BC', '\u02BD', '\u02C8', '\u02CA', '\u02CB', '\u0060', '\u00B4']
for apo in apostrophes:
    text = f"don{apo}t"
    print([t for t in nlp(text)])

>>> ValueError: [E997] Tokenizer special cases are not allowed to modify the text. This would map ':`(' to ':'(' given token attributes '[{65: ":'("}]'.

Answer: You just need to add an exception without changing the text.
import spacy

nlp = spacy.load('en_core_web_sm')

from spacy.attrs import ORTH, NORM
case = [{ORTH: "do"}, {ORTH: "n`t", NORM: "not"}]
tokenizer = nlp.tokenizer
tokenizer.add_special_case("don`t", case)

doc =  nlp("I don`t believe in bugs")

print(list(doc))
# => [I, do, n`t, believe, in, bugs]

If you want to change the text you should do it as a preprocessing step.
Comment: yes, i implemented the functionality now as full-string preprocessing step replacing all apostrophes before using the tokenizer.
I had the wish to include this functionality in the tokenizer and not have a dedicated extra pre-processing step, but apparently this is the best way to solve it.
Comment: yes this works. But this apostrophe is not only existing in the word `don't` . It may appear anywhere, so i would need to write down all possible occurences of apostrophes anywhere. This seems quite a lot work with this method.
Comment: If you want something simpler, you could use a regex to replace the weird punctuation as a preprocessing step, something like `n[]t`. That wouldn't preserve the input but it seems like that probably isn't important?


Definite integral $\int_0^{\pi/4}\log\left(\tan{x}\right)\ dx$

Question: $$\int_0^{\pi/4}\log\left(\tan{x}\right)\ dx$$
My turn :
$$I=\int_0^{\pi/4}\log\left(\sin{x}\right)-\log\left(\cos{x}\right)\ dx$$
$$I_1=\int_0^{\pi/4}\log\left(\sin{x}\right)\ dx$$
let
$$u=2x$$
$$I_1=\frac{1}{2}\int_0^{\pi/2}\log\left(\sin{\frac{u}{2}}\right)\ du$$
But i could not evaluate the last integral ?
Comment: The integral of $\ln(\sin(x))$ is not expressible in terms of elementary functions. Yet by a mere knowledge of special functions, you can easily find that

$$\int \ln(\sin(x))\ \text{d}x = \frac{1}{2} i \left(x^2+\text{Li}_2\left(e^{2 i x}\right)\right)-x \log \left(1-e^{2 i x}\right)+x \log (\sin (x))$$

Where $\text{Li}_n$ defines the Poly-Logarithm special function.
Comment: Does it work with $$\log\left(\cos{x}\right)$$
Comment: It does. In particular:

$$\int\ln\cos(x))\ \text{d}x = \frac{1}{2} i \text{Li}_2\left(-e^{2 i x}\right)+\frac{i x^2}{2}-x \log \left(1+e^{2 i x}\right)+x \log (\cos (x))$$
Answer: Under $\tan x\to x$, one has
\begin{eqnarray}
&&\int_0^{\pi/4}\ln(\tan x)dx\\
&=&\int_0^1\frac{\ln x}{1+x^2}dx\\
&=&\int_0^1\ln x\sum_{n=0}^\infty(-1)^nx^{2n}dx\\
&=&-\sum_{n=0}^\infty\int_0^1(-1)^nx^{2n}\ln xdx\\
&=&-\sum_{n=0}^\infty(-1)^n\frac{1}{(2n+1)^2}\\
&=&-C
\end{eqnarray}
where $C$ is the Catalan constant.
Answer: Another way is to use the Fourier expansion of $\log\sin x$ and $\log\cos x$ and integrate the expression term-wise. Since

$$\begin{align*}\log\cos x & =\sum\limits_{k\geq1}(-1)^{k-1}\frac {\cos 2kx}k-\log 2\\\log\sin x & =-\sum\limits_{k\geq1}\frac {\cos 2kx}k-\log 2\end{align*}$$

Therefore$$\begin{align*}I & =\int\limits_0^{\pi/4}dx\,\log\tan x\\ & =\int\limits_0^{\pi/4}dx\,\log\sin x-\int\limits_0^{\pi/4}dx\,\log\cos x\\ & =-\sum\limits_{k\geq1}\int\limits_0^{\pi/4}dx\,\frac {\cos 2kx}k+\sum\limits_{k\geq1}\int\limits_0^{\pi/4}dx\, (-1)^k\frac {\cos 2kx}k\end{align*}$$
Now integrate within the limits to get$$\begin{align*}I & =\frac 12\sum\limits_{k\geq1}\frac {(-1)^k\sin\left(\frac {\pi k}2\right)}{k^2}-\frac 12\sum\limits_{k\geq1}\frac {\sin\left(\frac {\pi k}2\right)}{k^2}\\ & =-\frac 12\sum\limits_{k\geq1}\frac {(-1)^k}{(2k-1)^2}-\frac 12\sum\limits_{k\geq1}\frac {(-1)^k}{(2k-1)^2}\\ & =-G\end{align*}$$Where $G$ is Catalan's Constant.


How to switch OG group members in bulk to another group

Question: D7. I have Organic Group (OG) installed. Out of the approximately 150 groups on my website, one is sticky and titled "Welcome New Members." It has about 2,000 members.
Recently, a problem developed with that group only and a user gets a 500 error when posting. Another kind of error is "The website encountered a difficulty. Please... blah blah."
The other groups seem to be working fine.
I could be wrong, but it seems to me that the easiest way to fix this is to create another group and transfer all the group members, along with their posts to the new group. Then I could delete the original group and its content.
Looking at the data base table "og_membership" I see that all members of all groups are mixed together in the same table.
I need to extract those nodes and users that belong to that one group. I guess a dump of selected users and nodes based on the group ID could do the trick. But how do I upload them back into the same table with a different gid or etid so they also belong to the new group? Or is there a way in the data base to "search and replace" a group ID (gid) with another?
I have tried the following formula but I am being told it is the wrong syntax (etid is the entity ID:)
update [og_membership] set [etid] = replace([etid],'[776]','[10177]');

Any pointer would be greatly appreciated. :)
Answer: OK. Finally got it right. The easiest way to do this is to do a dump of the og_membership table into a text file.
Then run a "search and replace" for the gid, replacing the old gid with the new one. A simple word processor is ideal for this. Any string replacement can be handled this way.
Then importing that text file into the og_membership table.
Voila! All members have switched to the new group and they don't even know it! :)


There is a natural isomorphism of chain complexes $K_{.}(x) \simeq K_{.}(x_1) \otimes_R ... \otimes_R K_{.}(x_n).$ where $K_{.}(x)$

Question: I try to solve exercise 1.3.1, (d)(page 4) from here http://www.math.utah.edu/vigre/minicourses/algebra/sather-wagstaff.pdf
For $x = x_1,... ,x_n$, there is a natural isomorphism of chain complexes
$$K_{.}(x) \simeq K_{.}(x_1) \otimes_R ... \otimes_R K_{.}(x_n),$$ where $K_{.}(x)$ is the Koszul complex associated to $x$.
I supposed that it can be proved by induction on $n$, using (b).
Answer: By the definition you are supposed to use in this exercise, the Koszul complex
$$K (x) = K (x_1, \ldots, x_n)$$
is the following thing. One considers a free $R$-module $F$ of rank $n$ and its exterior powers:
$$0 \to \Lambda^n (F) \to \Lambda^{n-1} (F) \to \cdots \to \Lambda^2 (F) \to F \to R \to 0$$
Let $e_1,\ldots,e_n$ be a basis of $F$. Then the differentials
$$d_k\colon \Lambda^k (F) \to \Lambda^{k-1} (F)$$
are given by
$$e_{i_1}\wedge \cdots \wedge e_{i_k} \mapsto \sum_{1 \le j\le k} (-1)^{j+1} \, x_{i_j} \, e_{i_1}\wedge \cdots \wedge \widehat{e_{i_j}} \wedge \cdots \wedge e_{i_k}$$
(here $\widehat{e_{i_j}}$ means that this term is being omitted from the exterior product).
Now the key observation is that we have natural isomorphisms
$$\tag{*} \bigoplus_{p+q = k} \Lambda^p (F_1) \otimes_R \Lambda^q (F_2) \xrightarrow{\cong} \Lambda^k (F_1\oplus F_2)$$
given by
$$a_1 \wedge \cdots \wedge a_p \otimes b_1 \wedge \cdots \wedge b_q \mapsto a_1 \wedge \cdots \wedge a_p \wedge b_1 \wedge \cdots \wedge b_q.$$
This gives an isomorphism of complexes
$$\tag{**} K (x_1,\ldots,x_{n_1}) \otimes_R K (y_1,\ldots,y_{n_2}) \cong K (x_1,\ldots,x_{n_1},y_1,\ldots,y_{n_2}).$$
Namely, (*) is an isomorphism of objects in each degree $k$, and I'll leave it to you to check that it commutes with the differentials.
Then by induction, (**) implies that
$$K (x_1) \otimes_R \cdots \otimes_R K (x_n) \cong K (x_1,\ldots,x_n).$$

In the exercise you refer to, one is supposed to check that
$$K (x_1,\ldots,x_n) \cong K (x_1,\ldots,x_{n-1}) \otimes_R K (x_n),$$
so feel free to rewrite (**) for $n_1 = n-1$ and $n_2 = 1$. However, the general isomorphism (*) is very important; in particular, it implies Vandermonde's identity
$$\sum_{p+q=k} {m\choose p}\,{n\choose q} = {m+n \choose k}.$$
Answer: We'll prove it by induction on $n$.
For $n=1$ it's true.
$n\geq 2$.
Let $x=x_1,...,x_{n+1}$.
We suppose that $ K_{.}(x_1) \otimes_R ... \otimes_R K_{.}(x_n) \simeq K_{.}(x_1,...,x_n)$.
We want to show that $K_{.}(x_1,...,x_n)\otimes_R K_{.}(x_{n+1})\simeq K_{.}(x_1,...,x_{n+1})$.
$(K_{.}(x_1,...,x_n)\otimes_R K_{.}(x_{n+1}))_i\simeq  (K_{.}(x_1,...,x_n))_i\bigoplus (K_{.}(x_1,...,x_n))_{i-1}=\bigwedge ^ i R^n \bigoplus \bigwedge^{i-1}R^n$
has rank $C_n^i +C_n^{i-1}=C_{n+1}^i$.
On the other hand $(K_{.}(x_1,...,x_{n+1}))_i=\bigwedge^{i} R^{n+1}$ has rank $C_{n+1}^i$.
They have the same rank, so they are isomorphic.
Comment: This is not a full proof. You just checked that for two chain complexes $C_\bullet$ and $D_\bullet$, you have $\operatorname{rk} C_i = \operatorname{rk} D_i$ for each $i$. What is missing is a family of isomorphisms $f_i\colon C_i \xrightarrow{\cong} D_i$ commuting with the differentials on $C_\bullet$ and $D_\bullet$.


How often do 0-0 scores at the completion of regulation occur in major sports?

Question: Have been watching hockey a bit more recently and tonight's game didn't have a lot of scoring early on.  That got me wondering how often the dreaded 0-0 scoreline comes up in different sports (defensive struggles aren't so bad, but I've certainly heard disparaging nicknames for them!).
Specifically, I am thinking of soccer, hockey, baseball, and (American) football as the four team sports where 0-0 seems fairly feasible.  I suppose there are a few others like lacrosse and water polo.
Whether they have overtime, shootouts, or draws, I'm just interested in how often they complete regulation 0-0 (though statistics on how often extended time also ends 0-0 aren't discouraged).
Comment: Here are some stats from EPL: [In 126 Years, English Football Has Seen 13,475 Nil-Nil Draws](https://fivethirtyeight.com/features/in-126-years-english-football-has-seen-13475-nil-nil-draws/).
Comment: There was not much digging involved. All I did was to enter [nil nil draw statistics](https://www.google.com/search?q=nil+nil+draw+statistics) into Google. If you really think that this might be a start for an answer about football part, feel free to make an answer out of it. (Perhaps making it [community wiki](https://sports.meta.stackexchange.com/tags/community-wiki/info) might be a good idea, if you want other users to contribute to the answer.)
Comment: @ᴍᴀsᴛᴇʀᴍɪɴᴅ_ᴇᴅ Great to see there's such discussion, as I was at a loss how to tag it!  I was definitely hopeful to go a bit beyond major 4, at least into soccer, and hopeful to see a few others in the comparison too.  The inclusion of the phrase was more to prevent it from being wildly open-ended (indeed, no interest in tiddly winks or middle school football stats) and getting ire/deflecting it from the main interest subjects.  I'll certainly weigh in on the tags, as I think they'd be useful!
Comment: Great!  Sounds quite near being a good answer to me if you gave a few of the salient points.  I expect there may well be separate answers for each sport, since different people know the sources for such information (if they're even easy to get)?  I appreciate you digging that up!
Comment: Both rugby variants (union and league) occasionally have 0-0 draws as well.
Comment: When you say "major sports," do you mean "most popular" sports or "professional" sports? I ask because of a current [meta discussion](https://sports.meta.stackexchange.com/q/776) being discussed in [chat](https://chat.stackexchange.com/transcript/message/37597470#37597470).
Answer: In the NHL, there have been 41 games tied 0-0 after overtime since the introduction of the shootout in 2005 (meaning they would have been recorded as a 0-0 tie in the past), which is 0.25% of games.  And there have been 189 0-0 ties in history (dating back to 1924) [games are double-counted in link]. There have been 122 games that were 0-0 after regulation only to be ended in overtime (not a shootout). This gives 352 total 0-0 games after regulation. Note that this is just regular season, and not playoffs.
In the NFL, there have only been two 0-0 games [games are double-counted in link]. The last one occurred in 1943. I couldn't find any other games that went into overtime tied 0-0 (checked each box score individually), either, which surprises me. Those 0-0 ties were Detroit against the Chicago Cardinals, and Detroit again against the NY Giants.
For the MLB, I was able to find at least 620 games that were tied 0-0 after 9 innings by looking up games where that took extra innings and the losing team had 0 runs. There appear to be a handful every year by changing the dates. I am not a subscriber, so I cannot verify the total or see more games.  This also does not take into account games that were tied 0-0 after 9 innings where the losing team managed at least 1 runs, so there are more.
In the top 4 tiers of English soccer, from 1888 through 2014, 13,475 games (7.2% of matches) ended 0-0.
Seems like it's nearly impossible in the NFL, not too uncommon in the NHL, very common in the MLB, and almost weekly in English soccer.
Comment: An important point is that baseball can't end with a tie while the other sports can. So while it may be common to have 0-0 after 9, the game never ends that way.  And I wouldn't consider a handful common. There are about 2,430 baseball games in one year.
Comment: for soccer the answer just will be too long.. is not unusual...


Manipulating SurveyMonkey Results & data

Question: we wud like to webscrape / import surveymonkey results into a html page then approve/decline each survey from/on that page.
We can also use wordpress as a last resort if we must.
Any ideas/tip how we can do this programatically ?  Api Tips ???
Tnx
Answer: You can use the SurveyMonkey API to fetch the responses and render them how you like.
You can fetch the survey details like this:
GET /v3/surveys/<survey_id>/details

You can fetch the survey responses like this:
GET /v3/surveys/<survey_id>/responses

You can then join the two data together to fill it out. This may be quite a bit of work to render all that yourself though, you may just want to have a list of edit/analyze URLs (provided in the body when fetching responses) and then click through to SurveyMonkey to view the response and decide.
Fetch them in bulk like this:
GET /v3/surveys/<survey_id>/responses/bulk

and make a table with a list of URLs to work with. You may think of other ideas by looking at the API docs.