Bridge design pattern with inheritance where abstract base class has member data

Question: I use bridge design pattern regularly. But I am confused as to how to use it effectively in an inherited object. Using struct apple::impl :public fruit results in double object fruits. I want to use the abstract base class data member in the implementation
class fruit
{
public:
    virtual void print() = 0;
private:
    int count_;
};

class apple: public fruit
{
public:
    virtual void print();
private:
    int apple_count_;
    struct impl;
    std::unique_ptr<impl> impl_;
};

struct apple::impl
{
    virtual void print() { cout << "apple"; }
};

void apple::print(){ impl_->print(); }

Comment: there are three access modifiers: `public`, `private`, and `protected`. Perhaps take a look at the third.
Answer: The point of the Bridge pattern is to separate interface from implementation.  Data members are part of the implementation, so they do not belong on an interface class or on any of its superclasses.
If you want inheritable implementation components, such as your data member, then perform the interface / implementation split at a higher level -- e.g. create a fruit::impl to hold the member, and have apple::impl inherit from that.  Note, too, that the classes on the implementation side do not need to inherit from any of the classes on the interface side, and it would be a clearer and cleaner design for them not to do.
Comment: Agreed. But as a special case I want some member data in the abstract base class which itself can be designed with bridge pattern
Comment: @ark1974, I'm not seeing how that's a special case.  I suppose you must attribute more significance to being "designed with [the] bridge pattern" than just the type of the member, but I'm afraid my crystal ball is a bit cloudy today.


Prove that if a number N is divisible by x, then all the permutations of N's digits are also divisible by x

Question: Given an ordered list of digits (6,5,4,3,2,1), in integer form would be 654321 which is divisible by 3. Any permutation, for example (5,6,4,3,2,1) or 564321 would also be divisible by 3. Prove (or disprove) this.
This is actually a problem I found in a programming exercise, so I was using a brute force method to check if all permutations are divisible by an x. It's not clear to me if the list of digits I chose happened to all be divisible, or if this is a rule that applies to any list of digits. It is also not clear if any number would be divisible, or only the example 3 I chose. I don't possess the mathematical skill to prove it with anything other than brute force.
Comment: It works only for $3$ and $9$ because a number is divisible by $3$ or $9$ if the sum of its digits is divisible by $3$ or $9$.
So for any permutation of the digits the some remain the same.
Comment: The question in the title is very different from the question in the body. In particular, the question in the title has an easy counterexample, while the phrasing in the body has a simple proof.
Comment: No it doesn't work for $11$  : $121$ is divisible by $11$ but $112$ not.
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognize and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: $12$ is divisible by $2$ but $21$ not.
Comment: Hopefully the edit i made adds context.
Comment: @Essaidi it also works for $11$
Answer: We're in base 10, and it's a well-known fact that an arbitrary number is divisible by 3 if and only if the sum of its digits is divisible by 3.
However, this is not true for e.g. divisibility by 2: Essaldi's example from the comments is 12, which is even (so divisible by 2) vs 21, which is odd (so not divisible by 2).
But of course, for any number x and natural number n, you can cook up a number N with n digits and all of whose "permutations" are also divisible by x. Just use x as every digit, e.g. 22, 222, ...


How to create a non-unique index in sqlite?

Question: How to create a non-unique index in sqlite?
I'm using vb.net to create the tables.
Answer: To create a non-unique index you would use the CREATE INDEX statement without the UNIQUE keyword. See the documentation for more information.
http://www.sqlite.org/lang_createindex.html
UPDATE: If you are using the System.Data.SQLite provider, it has design time support in Visual Studio, so you can use it to create your indexes via Visual Studio.


Django, cant save form

Question: I try to rewrite a App from a older 1.11 Django to the newest 2.2. But when I click on the save button. There is nothing. No error, no saved form, nothing happend.
models.py
class BlogPost(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="itemauthor", on_delete=models.SET_NULL)
    image = models.ImageField(_('Featured image'), upload_to='item_pictures/%Y/%m/%d/', default=False)
    timestamp = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=255, null=False, unique=True)
    slug = models.SlugField(max_length=80, null=True, blank=True)
    content = MarkdownxField()
    status = models.SmallIntegerField(choices=BLOG_STATUS)
    ... some more fields

forms.py
class CreateForm(forms.ModelForm):
    edited = forms.BooleanField(widget=forms.HiddenInput(), required=False, initial=False)
    content = MarkdownxFormField()
        class Meta:
            model = BlogPost
            fields = ["title", "content", "image", "edited"]

views.py
class CreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
    permission_required = 'is_active'
    model = BlogPost
    form_class = CreateForm
    template_name = 'blog/create.html'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('blog:home')

create.html
{% extends 'base.html' %}
{% load static i18n %}
{% load crispy_forms_tags %}

{% block head %}
{% endblock head %}

{% block content %}

  <form action="{% url 'blog:write_new' %}" enctype="multipart/form-data"  id="item-form" method="post" role="form">
    {% csrf_token %}
    {{ form|crispy }}

      <button type="button" class="btn btn-primary publish">{% trans 'Publish' %}</button>

  </form>
  {{ form.media }}

{% endblock content %}

{% block modal %}

{% endblock modal %}

blog.js
$(function () {

    $(".update").click(function () {
        $("input[name='status']").val("1");
        $("input[name='edited']").val("True");
        $("#article-form").submit();
    });

        $(".publish").click(function () {
        $("input[name='status']").val("1");
        $("#article-form").submit();
    });

});

what have I forgotten? I've been looking for this bug the hole day, but unfortunately I can't find it.
Answer: change from
<form action="{% url 'blog:write_new' %}" enctype="multipart/form-data"  id="item-form" method="post" role="form">

to id="article-form"
and yes, the class change also:
class BlogClassName(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
permission_required = 'is_active'
model = BlogPost
form_class = CreateForm
template_name = 'blog/create.html'

def form_valid(self, form):
    form.instance.user = self.request.user
    return super().form_valid(form)

def get_success_url(self):
    return reverse('blog:home')

And on the end change your urls to the new class
The main issue was in the .html form ID
Answer: first, it would be better to do not use same class name with its base class.
class OtherClassName(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
second, you didn't call save().
def form_valid(self, form):
    form.instance.user = self.request.user
    form.save()
    return super(OtherClassName, self).form_valid(form)

Django, cant save form


Emacs indent after :config emacs-lisp

Question: I have the code block:
<code>(use-package dired
  :config
  (setq dired-auto-revert-buffer t))
</code>
I want this to instead be indented like:
<code>(use-package dired
  :config
    (setq dired-auto-revert-buffer t))
</code>
How do I do this?
Answer: Pretty sure that's not possible. The closest I could get was <code>(put 'use-package 'lisp-indent-function '2)</code>, which gave me
<code>(use-package dired
    :config
  (setq dired-auto-revert-buffer t))
</code>
This just makes it indented the same was as
<code>(if cond
    a
  b)
</code>
I don't think there's a way to make it indented like you wanted, since that's not a standard way to indent lisp code.

Emacs indent after :config emacs-lisp


How to recover XFS file system which xfs_repair not work because of busy?

Question: I got problem in disk of my database which is xfs file system. I tried to repair
[root@scan /]# xfs_repair /dev/md127
xfs_repair: cannot open /dev/md127: Device or resource busy
[root@scan /]# ls /data
ls: cannot access /data: Input/output error

and dmesg
[35749034.608871] XFS (md127): Metadata corruption detected at xfs_inode_buf_verify+0x142/0x150 [xfs], xfs_inode block 0x410 xfs_inode_buf_verify
[35749034.610913] XFS (md127): Unmount and run xfs_repair
[35749034.611909] XFS (md127): First 128 bytes of corrupted metadata buffer:
[35749034.612903] 00000000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
[35749034.613902] 00000010: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
[35749034.614885] 00000020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
[35749034.615569] 00000030: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
[35749034.616161] 00000040: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
[35749034.616747] 00000050: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
[35749034.617320] 00000060: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
[35749034.617888] 00000070: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
[35749034.618482] XFS (md127): metadata I/O error in "xfs_trans_read_buf_map" at daddr 0x410 len 16 error 117
[35749034.620782] XFS (md127): xfs_do_force_shutdown(0x1) called from line 325 of file fs/xfs/xfs_trans_buf.c. Return address = 00000000bbf8b06c
[35749034.620785] XFS (md127): I/O Error Detected. Shutting down filesystem
[35749034.622724] XFS (md127): Please unmount the filesystem and rectify the problem(s)
[35749034.624653] XFS (md127): xfs_imap_to_bp: xfs_trans_read_buf() returned error -117.

Answer: It looks like some processes still using /data filesystem. You will need to stop all the processes using /data and then try repair.

Check lsof | grep /data output and probably stop/kill processes using file kept in /data.
Unmount the filesystem using umount /data.
Then repair /data using xfs_repair.


Problems with RD, RT import and RT export in MPLS VPN and BGP

Question: I'm learning MPLS VPN with MP-BGP and I'm finding difficulties with undertstanding the RD value and the RT import and export values.
From what I've already understand, RD (route distinguisher) identifies the VRFs from a network that compose the same virtual network and change routing info between them. RT import says what VRFs in a network are known by the local VRF and RT export is send to identify the information from the local VRF.
 To decide in what VRF install the rout, when a package comes to the PE, if the RT export the package has and the RT import our VRF have are the same, it adds the route to the VRF, otherwise it delete it.
I don't know if all I've written is correct. But I don't get to understand it properly when I find something like THIS.
Let's talk about sites PE1, PE2, PE3 and PEC (central PE).
What sites does PE3 know?
As the RT import is the RT export of PEC, PE3 just knows PEC.
What sites does PEC know?
I think PEC knows PE1 a PE2 because RT export from PE1 and PE2 matchs with RT import from PEC.
Am I correct? Please I need help to understand it.
Answer:
From what I've already understand, RD (route distinguisher) identifies the VRFs from a network that compose the same virtual network and change routing info between them.

That's not right. RD is added to the IP address to make them unique. It does not define virtual networks.

RT import says what VRFs in a network are known by the local VRF and RT export is send to identify the information from the local VRF.

Nope. Think of route targets as a "tag" that identifies routes. Export tags the routes and Import selects which tags are imported into the VRF.

To decide in what VRF install the route, when a package comes to the PE, if the RT export the package has and the RT import our VRF have are the same, it adds the route to the VRF, otherwise it delete it.

Also not right. MP BGP carries all the routes. Import/export is used to select which ones are included in a VRF.
Comment: Thank you very much for the answer. It helped me. Can you tell me if I'm wrong too in my exercise?
Comment: Your answers are wrong.  Look at the information I provided and see how you would change your answers.


Adding a form to Views Bulk Operation for configurable operations

Question: I have a view with a list of nodes that I want to operate with, but I need additional user input for the function. Until now, I have been handing this by having many similar, but slightly different 'Execute arbitrary PHP script' actions. Is there any way to add a sort of form to accept user input other than the nodes to operate on?
Answer: Instead of running a PHP script. You would have to create a custom module and a custom Action. The action may be configurable (requiring a Form) and you can check the form for errors before proceeding.
An example template of what would go into your .module file can be seen at ( am not the author):
http://dropbucket.org/node/841
In case that website is taken offline, here is the code sample, which I believe to be self explanitory:
/**
 * Implements hook_action_info().
 */
function custom_action_info() {
  return array(
    'custom_action_callback_name' => array(
      'type' => 'entity', // Can be file, term, user, etc.
      'label' => t('Your label'),
      'configurable' => TRUE, //  Needs config form
      'behavior' => array('view_property'), // Uses view access rights
      'triggers' => array('any'), // Works always
    ),
  );
}

/**
 * Return a form definition so the action can be configured.
 */
function custom_action_callback_name_form($context) {
  // Set default values for form.
  if (!isset($context['recipient'])) {
    $context['recipient'] = '';
  }

  $form['recipient'] = array(
    '#type' => 'textfield',
    '#title' => t('Recipient'),
    '#default_value' => $context['recipient'],
    '#maxlength' => '254',
    '#description' => t('The email address to which the message should be sent OR enter [node:author:mail], [comment:author:mail], etc. if you would like to send an e-mail to the author of the original post.'),
  );

  return $form;
}

/**
 * Validate custom_action_callback_name form submissions.
 */
function custom_vbo_action_send_node_validate($form, $form_state) {
  $form_values = $form_state['values'];
  // Validate the configuration form.
  if (!valid_email_address($form_values['recipient'])) {
    form_set_error('recipient', t('Enter a valid email address.'));
  }
}

/**
 * Process custom_action_callback_name form submissions.
 */
function custom_vbo_action_send_node_submit($form, $form_state) {
  $form_values = $form_state['values'];
  // Process the HTML form to store configuration. The keyed array that
  // we return will be serialized to the database.
  $params = array(
    'recipient' => $form_values['recipient'],
  );
  return $params;
}

/**
 * Add action callback where you perform the action.
 */
function custom_action_callback_name($entity, $context) {
  // Do the magic here.
}

EDIT
If you just want VBO validation rules and no form for your action, look at VBO Validation which supplies easy to use Hooks.
Comment: Could you please clarify: Do you mean that after the first form (created by views bulk operations) gets submitted, the user would get a second form created by a custom module, that includes the additional option(s)? Is there a way to instead combine this on one form, to avoid a two-step process?
Comment: This makes an `action` (the action is _exactly_ the same thing as your custom php-script) you can select in a drop-down list as a Bulk Operation. After selecting all the nodes/items to do work on. A form is  shown that requests an email address in this example. After successfully providing the email -- the bulk operation is performed.


How do I use reflection to dynamically call a type?

Question: I have a DataGrid and I need to convert it to a DataTable. The problem is that I need To be able to get the type of my DataSource dynamically. The grid DataSource is of type 'Observable' which is a class I have in my project, but my task is to be able to dynamically create the DataTable without needing to specify the type only using the DataSource. How can I generate a method that I can use to place in <T> without getting the error " 'mytype' is a variable but is used like a type" .
Type mytype = Grid_Job.DataSource.GetType();

DataTable dt = CreateDataTable<mytype>((IEnumerable<mytype>)Grid_Job.DataSource);

public static DataTable CreateDataTable<T>(IEnumerable<T> list)
        {
            Type type = typeof(T);
            var properties = type.GetProperties();

            DataTable dataTable = new DataTable();
            foreach (PropertyInfo info in properties)
            {
                dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
            }

            foreach (T entity in list)
            {
                object[] values = new object[properties.Length];
                for (int i = 0; i < properties.Length; i++)
                {
                    values[i] = properties[i].GetValue(entity);
                }

                dataTable.Rows.Add(values);
            }

            return dataTable;
        }

My Observable class is
public class Observable
{
    public int JobNo { get; set; }
    public string JobName { get; set; }
    public string JobDescription { get; set; }
    public string Job_Type { get; set; }
    public string Job_Status { get; set; }
}

Comment: Can you show your `Observable` class. Does it implement `IEnumerable'?
Comment: yes when I use IEnumerable the code works just fine and Type mytype = Grid_Job.DataSource.GetType(); returns "Observable" correctly but I can't use it in the code.
Comment: What are the *actual* types that might be in the `DataSource` here? it matters, because there are a range of ways of doing this, and a few particularly relevant abstractions that need to be used in some cases. So: if you did `Grid_Job.DataSource.GetType()`: what is it?
Comment: so I used  string s = mytype.ToString(); and string s returned literally "System.Collections.ObjectModel.ObservableCollection' 1 [ERP_UI.Job.Observable]" where ERP_UI is the name of my project and Job is the folder containing the class Observable
Comment: and myType.Name returns "Observable"
Comment: k, that type doesn't implement any of the abstractions I had in mind, so that means you need to look for the `T` via reflection; there are some options here: https://stackoverflow.com/questions/1043755/c-sharp-generic-list-t-how-to-get-the-type-of-t
Comment: again same problem with the code provided in the link...I get the type in a variable but I can't insert it to the list CreateDataTable((IEnumerable)Grid_Job.DataSource); I can't use the type I get to generate a list of this type....
Comment: @NourMawla agreed; then *just don't* - your method doesn't need to be generic - posting an answer that shows this
Comment: Note that in `CreateDataTable` you are not using generic type `T` for anything useful. You can just make method non-generic and accept `Type type` argument instead.
Answer: Effectively, you need to discard the generics and think in terms of the collection at runtime - discovering the element type itself. For example:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Reflection;

static class P
{
    static object GetData()
        => new ObservableCollection<Observable>
        {
            new Observable { JobName = "abc", JobNo = 123 },
            new Observable { JobName = "def", JobNo = 456 },
            new Observable { JobName = "ghi", JobNo = 789 },
        };
    static void Main()
    {
        // note that we don't know *anything* about the data source here
        object dataSource = GetData();
        DataTable dt = CreateDataTable((IEnumerable)dataSource);

        foreach (DataColumn col in dt.Columns)
        {
            Console.Write(col.ColumnName);
            Console.Write("\t");
        }
        Console.WriteLine();
        foreach (DataRow row in dt.Rows)
        {
            foreach (DataColumn col in dt.Columns)
            {
                Console.Write(row[col]);
                Console.Write("\t");
            }
            Console.WriteLine();
        }
    }

    public static DataTable CreateDataTable(IEnumerable list)
    {
        Type type = GetElementType(list.GetType());
        var properties = type.GetProperties();

        DataTable dataTable = new DataTable();
        foreach (PropertyInfo info in properties)
        {
            dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
        }

        object[] values = new object[properties.Length];
        foreach (object entity in list)
        {
            for (int i = 0; i < properties.Length; i++)
            {
                values[i] = properties[i].GetValue(entity);
            }
            dataTable.Rows.Add(values);
        }
        return dataTable;
    }
    static Type GetElementType(Type type)
    {
        foreach (Type interfaceType in type.GetInterfaces())
        {
            if (interfaceType.IsGenericType &&
                interfaceType.GetGenericTypeDefinition()
                == typeof(IList<>))
            {
                return  type.GetGenericArguments()[0];
            }
        }
        return null;
    }
}
public class Observable
{
    public int JobNo { get; set; }
    public string JobName { get; set; }
    public string JobDescription { get; set; }
    public string Job_Type { get; set; }
    public string Job_Status { get; set; }
}

Note that in some cases you should prefer the TypeDescriptor model over reflection, as this allows runtime definition of properties; this is a niche area and probably doesn't apply to you, but it relevant to know about. As an example, this is how DataTable itself chooses to expose the properties it has as discoverable at runtime to general purpose tools. There are also a few list indirection APIs that need to be considered in those cases.


Is this the most efficient way of doing recursion for checking whether a string is a palindrome?

Question: public boolean isPalindrome3(String input, int index, int length)
{
    if(index > (length-1-index))
        return true;

    else if(input.charAt(index)!=input.charAt(length-1-index))
        return false;

    else
        return isPalindrome3(input, index + 1, length);

}

Here initially i pass the input string, 0, input.length()
Comment: I would just pass the `start` and `end` *indices*. Passing the `length` (besides *already* being a property of a String) makes for extra math. Then the recursive case is `f(str,start+1,end-1)` which is easier [for me] to visualize as well ..
Comment: @Razvan As a general rule, when non-essential recursion is requested, it's homework.
Comment: recursivity is not necessary for checking whether a string is a palindrome. It's correct and probably there is no other version but it's less efficient than the non-recursive version.
Comment: corsiKa I assure you it is not homework. I usually don't end up implementing recursion in the most simplified way and I read this question somewhere which said you need to use recursion. As you can see I have implemented something that is correct and I'm not clueless. I posted a question on SO because I thought the whole point of using SO is to better your skills through learning if there are simpler ways of doing something or not.
Comment: I don't know where you read that you need to use recursion for this, but that is most definitely wrong. It's easy to do using iteration and any (sane) iterative solution will be more efficient than using recursion.
Comment: You don't really even need iteration either. Just reverse the string and check equality. `yourString.equals(new StringBuffer(yourString).reverse().toString())`. Less efficient than your solution but much simpler to read and debug.
Answer: If you don't have to use recursion, here's a much more efficient check for palindrome:
public boolean isPalindrome3(String input)
{
    for (int start = 0, end = input.length() - 1; start < end; ) {
        if (input.charAt(start++) != input.charAt(end--)) {
            return false;
        }
    }
    return true;
}

Answer: I would write it like this:
public boolean isPalindrome(String str, int offset)
{
    int rightOffset = str.length() - offset - 1;
    if (offset <= rightOffset)
    {
        char c1 = str.charAt(offset);
        char c2 = str.charAt(rightOffset);
        if (c1 != c2) return false;

        return isPalindrome(str, offset + 1);
    } else
    {
        return true;
    }
}

Differences with your code:

Do not pass the length, because that is a String property
unwrap the character comparation
nice code formatting
improved efficiency, by creating a local variable rightOffset.
Comment: @Phoenix: Maybe you are a C++ guy? But the String.length() method in Java simply returns an int. It doesn't calculate the length. The length of the string is stored inside the String class as a class member.
Comment: Why would you write it like that? It requires a multiply and it looks up the characters before checking whether you're already done. (By the way, OP's code only goes halfway through the string as well.)
Comment: @TedHopp: Fair point, I edited it :) The multiplication is to make sure we only check the half of the string. (Edit to your edit: oh, yes. Indeed I see, now. A bit confusing code)
Comment: @TedHopp: Yes, indeed. You are right again :) But I made it even better, check out the new code :)
Comment: why is it better to calculate string length everytime than passing a length parameter ?
Comment: Okay. Then why is it better to create a local variable as opposed to computing the right offset twice?
Comment: Because, you're obviously computing it twice. Plus: computing it requires a push to the stack. So, you save one calculation and one push (and probably a some other things since the code runs in a JVM and not native).
Answer: public static String reverseString(String s) {
    byte[] array = s.getBytes();
    byte swap;

    for( int i = 0, j = array.length - 1; i < array.length / 2; i++, j--) {
        swap = array[ j ];
        array[ j ] = array[ i ];
        array[ i ] = swap;
    }

    return (new String(array));
}

if(myString.equals(reverseString(myString)))
    // is palindrome


Attach a script to a particular node ID or view

Question: In Drupal 7, you can use the following code to attach a script to a particular content type:
function THEMENAME_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT_CONTENT_TYPE') {

        // include javascript
        drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');

      }

    }

What code do you need to use to attach a script to a particular Node ID or a specific View?
I have tried swapping variables['type'] with various items, but none seem to work.
Comment: Where are you adding this code? Some preprocess function?
Comment: Hi I have updated my answer to make it clearer
Answer: Node ID:
function THEMENAME_preprocess_node(&$variables) {
  if ($variables['nid'] == 'INSERT_NODE_ID') {
    // include javascript
    drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');
  }
}

View:
function THEMENAME_preprocess_views_view(&$variables){
  if ($variables['name'] == 'INSERT_VIEW_MACHINE_NAME') {
    // include javascript
    drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');
  }
}

Comment: Thanks! This gets the bounty as it is the cleanest solution and works for both node and view.
Comment: I'm pretty sure that you need a "/" before "INSERT_SCRIPT". (e.g. /scripts/custom.js)
Answer: If you are using D6. Try using JS injector to insert custom javascript to a page or view.
Comment: Hi I am using Drupal 7 and would like to do it without an extra module.
Answer: If I understand well your question, why not display your script accoring the alias of your view or your node or view? (also is possible using the node ID)
I have tested these functions with _preprocess_node (nodes) an also with _preprocess_page (for views and nodes) in Drupal 6 and 7.
this is for node with ID with _preprocess_node:
function seven_preprocess_node(&$vars) {
    if(isset($_GET['q'])){
        $nodeID = '9';
          if(arg(1) == $nodeID){
              drupal_add_js(path_to_theme() . '/test.js');
          }
      }
}

this is for node with alias with _preprocess_node:
function THEMENAME_preprocess_node(&$variables) {
    if(isset($_GET['q'])){
          $path = drupal_get_path_alias($_GET['q']);
          if(preg_match('#test_page#', $path)){
              drupal_add_js(path_to_theme() . '/test.js');
          }
      }
}

and this function with _preprocess_page will be useful for nodes and/or views (alias):
function THEMENAME_preprocess_page(&$variables) {
    if(isset($_GET['q'])){
          $path = drupal_get_path_alias($_GET['q']);
          if(preg_match('#test_page#', $path)){
              drupal_add_js(path_to_theme() . '/test.js');
          }
      }
}

this last function is only to show an example of a function seeking alias of your view/node or node ID:
function THEMENAME_preprocess_page(&$variables) {
    if(isset($_GET['q'])){
        $script = '/test.js';//script name
        $currentPath = drupal_get_path_alias($_GET['q']);//current alias
        $targetPath = '#test_view#';//alias to match (delimiter is #), is for example of your view's page.
        $targetNodeID = '9';//node ID to match
          if(arg(1) == $targetNodeID || preg_match($targetPath, $currentPath)){
              drupal_add_js(path_to_theme() . $script);
          }
     }
}

I hope information be useful.
Answer: Try this:
function THEMENAME_preprocess_node($node) {
    if ($node->nid == INSERT_NODE_ID) {
        // include javascript
        drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');
    }
}

Answer: nothing worked for me, so i checked with 'preprocess' hook, that works fine as follows:-
function MYMODULE-or-THEME_preprocess(){
    if(isset($_GET['q'])){
    $nodeID = '232'; //NODE ID TO CHECK
          if(arg(1) == $nodeID){
     drupal_add_js(drupal_get_path('module', 'MYMODULE').'/js/myscript.js');
         }
    }
}


MySQL - How to get total number of matches within a column

Question: I tried this code:
SELECT SUM(bookingstatus)
FROM beo_eventorder AS TotalBookingStatu
WHERE bookingstatus = 'Tentative';

But this returns 0. There are 6 matches in the table.
Why does this not return 6?
Screenshot of column:
Comment: @timgavin string sir
Comment: in mysql, is `bookingstatus` an `int` or a string?
Comment: @Harsh Got it sir. THANK YOU! :)
Answer: You should use count instead of sum:
SELECT count(bookingstatus) FROM beo_eventorder AS TotalBookingStatus WHERE bookingstatus = 'Tentative';

Answer: SUM adds all the elements on the column, in your case, it added all the strings to be 0. You should use a COUNT function instead.


Erro The requested URL was not found on this server

Question: Olá, atualmente sou iniciante em codeiginiter e preciso entregar um CRUD de projeto na faculdade, até o momento fiz conexão com o banco, listei tudo.
Mas quando clico em adicionar novo ocorre o erro, acredito que seja erro de configurações.. Então quando clico no Cadastrar Novo, que está no add.php, ocorre o erro, nem sei mais oq fazer...
Segue:
ERRO ESTA AQUI:
http://prntscr.com/kz21eg
config.php
http://prntscr.com/kys0jm
controllers/Estado.php

load->model('estado_m', 'm');
    }

    function index(){
        // "estados" é referência ao armazenamento de tudo que vier de "estado"
        $data['estados'] = $this->m->getEstado();
        $this->load->view('layout/header');
        $this->load->view('estado/index', $data);
        $this->load->view('layout/footer');
    }

    // Agora vou criar a Função adicionar novo registro
    public function add(){
        $this->load->view('layout/header');
        $this->load->view('estado/add');
        $this->load->view('layout/footer');
    }

}

models/Estado_m.php

db->get('estado');
        if($query->num_rows() > 0){
            return $query->result();
        }else{
            return false;
        }
    }

}

views/estado/add.php

Adicionar Estado
    " class="btn btn-success">Página Principal

views/estado/index.php

        " class="btn btn-success">Cadastrar Novo

                    Código
                    Nome
                    Sigla
                    Criado
                    Opções

                <?php echo $estado->idestado; ?>
                <?php echo $estado->nome; ?>
                <?php echo $estado->sigla; ?>
                <?php echo $estado->criado; ?>

                    Alterar
                    Excluir

            <?php
                    }
                }
            ?>

Comment: Qual erro está apresentando?
Comment: Nossa cara, esqueci do principal... Erro está aqui: http://prntscr.com/kz21eg (sempre que clico em adicionar novo)
Answer: Resolvi o problema, era erro com mod_rewrite.
Agradeço à atenção!


How do I consume query parameters from POST in FastAPI?

Question: I want to write a route in FastAPI to consume a POST request. I have the following URL example:
https://URL.com/api/FlexfoneCall/outgoing?AccountId=1234&TimeStamp=2021-05-20+08%3a30%3a56&UniqueCallId=SIP%2f%2b4512345678-0000e4a81463430317&EmployeeLocalNumber=200&ANumber=12345678&BNumber=87654321&PhoneLocalNumber=123456

However, I'm only used to consuming the body from request. How do I "fetch" the path parameter data from the above example?
EDIT:
I'm trying to write a service that receives the above URL from an external service. I tried doing the following because I thougth that since it was a POST my route should look like this:
@app.post('/callout', response_model=CallIn)
async def create_call_out(callout: CallOut, db: Session = Depends(get_db)):
    db_write_call_out = write_call_out(db, callout)

    return db_write_call_out

With the following Pydantic model:
class CallOut(BaseModel):
    accountid: str = None
    timestamp: str = None
    uniquecallid: str = None
    employeelocalnumber: str = None
    anumber: str = None
    bnumber: str = None
    phonelocalnumber: str = None

    class Config:
        orm_mode = True

And CRUD function:
def write_call_out(db: Session, callout: CallOut):
    db_write_call_out = DBCallOut(**callout.dict())
    db.add(db_write_call_out)
    db.commit()
    db.refresh(db_write_call_out)

    return db_write_call_out

SQLAlchemy ORM model for writing the query params to a SQL DB:
class DBCallOut(Base):
    __tablename__ = "call_out"

    accountid = Column('AccountId', String(250))
    uniquecallid = Column('UniqueCallId', String(250))
    employeelocalnumber = Column('EmployeeLocalNumber', String(250))
    anumber = Column('ANumber', String(250))
    timestamp = Column('TimeStamp', String(250))
    phonelocalnumber = Column('PhoneLocalNumber', String(250))
    bnumber = Column('BNumber', String(250))
    ID = Column(Integer,  primary_key=True,  index=True, autoincrement=True)

But I keep getting a 422 Error.
EDIT 2:
Ended up changing my route to the following:
@app.get('/call')
async def outgoing(AccountId: str,
                   TimeStamp: str,
                   UniqueCallId: str,
                   EmployeeLocalNumber: str,
                   ANumber: str,
                   BNumber: str,
                   PhoneLocalNumber: str, db: Session = Depends(get_db)):
    callout = {"AccountId": AccountId,
                "TimeStamp": TimeStamp,
                "UniqueCallId": UniqueCallId,
                "EmployeeLocalNumber": EmployeeLocalNumber,
                "ANumber": ANumber,
                "BNumber": BNumber,
                "PhoneLocalNumber": PhoneLocalNumber}
    db_write_call_out = write_call_out(db, callout)

    return db_write_call_out

This is working, but it's somewhat clunky.
Comment: https://fastapi.tiangolo.com/tutorial/query-params/ ?
Comment: unsure of what ? What have you tried ? The code in the documentaion is pretty easy
Comment: Share your actual code that handles `/api/FlexfoneCall/outgoing` please
Comment: I haven't written anything, because I'm rather confused about the type of route I need to use, and why the example is sending parameters in the URL directly.
Answer: I am not sure if you want to consume Path parameters (part of the url path, as in google.co/youtube/videos/1) or if you want to consume query parameters (a variable named after the path url, as in google.co?video=1) but either way you just declare the path parameters as parameters of the of the method decoration (@app(params)) and for query parameters you declare them in the method parameters (def get_video(params)).
so for the given link, if you want to get the query parameters you would do:
@app.post("outgoing/")
async def do_something(
      AccountId: int,
      TimeStamp: str,
      UniqueCallId: str,
      EmployeeLocalNumber: str,
      ANumber: int,
      BNumber: int,
      PhoneLocalNumber: int
    ):
    # do some stuff
    save_to_db(owner=AccountId,time=TimeStamp,contact=PhoneLocalNumber)

and to get path variables (sticking to the example I gave above) you do this:
@app.post("video/{video_id}")
async def do_something():
    # do something
    save_to_db(video_id)

Whichever on you choose to implement will take the parameter values (by location in the path for path params, or from the query parameter by the same name in the query params) from the request url the client sends and place them into the variable names you declare. then you use them as normal like the example shows.
The docs are very newcomer friendly so for query parameters refer here, and for path parameters refer here.
as a side note, for more pythonic code, I suggest you use snake case to name your variables
Comment: For the example with `video_id` you miss the method parameters, it's SAME as query param, see https://fastapi.tiangolo.com/tutorial/query-params/#multiple-path-and-query-parameters
Comment: What does you request body look like @Artem? it seems you are either missing a variable or misspelling one in your POST request. if accountid is the DB key I suggest you make it an optional variable in a supper class `Callout(BaseModel)`, then inherit from it in `CallOutPost(CallOut)`  where the rest of the mandatory variables sit
Comment: @azro I intentionally left them out to avoid confusion. I made an example the *ONLY* uses path parameters so the distinction can be clear and nonconfusing
Comment: Made all variables optional in the BaseModel. Still keep getting a 422.
Comment: @ItIsEntropy If I replace the BaseModel in `create_call_out()` with the query params, the request goes through. Is the BaseModel/Pydantic model case sensitive or anything?
Comment: Yes it is. Pydantic uses JSON which is case sensitive. do you post anything in the request body? if you don't then that's your problem. you are posting information in the query params, but the `callout: CallOut` part is telling fastAPI to look for content in the request body; content which does not exist.
Edit: HTTP: 422 means that your request is valid, but semantically makes no sense, so in this case everything about your request was right, but you were asking it to parse an empty JSON request
Comment: @Artem if this answer helped you out please accept it and give an upcote. Thanks
Comment: @ItIsEntropy So yes, the request body is empty for some reason. I've updated the question with the new route that works. I think it's somewhat clunky though. Pydantic is only for the body, when I guess? Essentially, if the URL had 20 query parameters, would I then have to declare all 20 in the function?
Comment: Yes you would have to declare all 20 params cos that's the only way to consume them. and yes Pydantic is only for the body. if you are sending JSON objects to the route use it, otherwise use query or form parameters and it's not needed, also no need to make models off of its `BaseModel` class.
Comment: to use the old one simply send a JSON object to the endpoint as it was.. i find using Postman to test my requests very useful, but if you're on javascript it has a builtin JSON object so make the model, then post it with JSON stringify, thn you'll have cleaner code


CakePHP 2 pagination gives 404 address not found error

Question: I am developing an application with CakePHP 2.3 and am having a problem with pagination. When I click on any of the pagination links I am getting a /cab/ServiceDirectory/refine/page:2 (or which ever link) was not found on this server. If I go to /cab/ServiceDirectory/refine I see the pagination links showing there should be 5 pages. If I remove the pagination code from the controller and the view I see all the results I should see.
In my ServiceDirectoryResultsController I have
public function index() {
  $this->ServiceLocation->recursive=0;
}

public function refine ($id=null) (

 // All my code to get the ServiceLocations from the DB

$this->paginate->array(
  'conditions' => array('ServiceLocation.state' => $states[$state], 'ServiceLocation.solution_categories' => $active_cat),
  'limit' => 8,
);

$results = $this->paginate('ServiceLocation');
$this->set('serviceLocation' ,$results);

}

In my View I have

  <?php
    echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
    echo $this->Paginator->numbers(array('separator' => ''));
    echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
  ?>

<?php foreach ($serviceLocation as $Location): ?>

  // I echo a few things from the $Location array

<?php endforeach; ?>

  <?php
    echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
    echo $this->Paginator->numbers(array('separator' => ''));
    echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
  ?>

Without the paging and use doing  a find all and sending that to the view I see the 40 results I would expect.
With the pagination in I see the pagination links and if I hover over them I see my url /cab/ServiceDirectoryResults/refine/page:2 or page:3 or page:4 or page:5
If I click on any of these links with the :pageX on them I get an error
Error: The requested address '/cab/ServiceDirectoryResults/refine/page:2 was not found on this server'
I have done a lot of reading about the CakePHP paging and can not find any reason for this behaviour. Can anyone suggest a reason or a possible solution or a path to follow to debug this error?
Regards
Richard
I checked the error level and it was already set to level 2
Here is the last entry in the error log
2013-05-22 17:09:28 Error: [NotFoundException] Not Found
Request URL: /cab/ServiceDirectoryResults/refine/page:2
Stack Trace:
#0 /var/www/html/cab/lib/Cake/Controller/Controller.php(1074): PaginatorComponent->paginate('ServiceLocation', Array, Array)
#1 /var/www/html/cab/app/Controller/ServiceDirectoryResultsController.php(381): Controller->paginate('ServiceLocation')
#2 [internal function]: ServiceDirectoryResultsController->refine()
#3 /var/www/html/cab/lib/Cake/Controller/Controller.php(486): ReflectionMethod->invokeArgs(Object(ServiceDirectoryResultsController), Array)
#4 /var/www/html/cab/lib/Cake/Routing/Dispatcher.php(187): Controller->invokeAction(Object(CakeRequest))
#5 /var/www/html/cab/lib/Cake/Routing/Dispatcher.php(162): Dispatcher->_invoke(Object(ServiceDirectoryResultsController), Object(CakeRequest), Object(CakeResponse))
#6 /var/www/html/cab/app/webroot/index.php(109): Dispatcher-   >dispatch(Object(CakeRequest), Object(CakeResponse))
#7 {main}

Hope that helps
Comment: In app/Config/core.php you will be able to see debug. Set the value to 2 and see what is the error.
Comment: I had to answer in by editing the original post because it will not let me answer my own post for 8 hours and the error message was too long for a comment
Comment: public function refine ($id=null) the bracket after this should be a curly brackt. do not use $results = $this->paginate('ServiceLocation'); If you model is ServiceLocation simple use $this->paginate();
Comment: If I change the $this->paginate('ServiceLocation'); to just $this->paginate(); I get an error that the table service_directory_results for model ServiceDirectorResults does not exist. The model I am using is ServiceLocation and I loaded that earlier in the function with a $this->loadModel('ServiceLocation');

The missing curly bracket on the refine function was a typo when I copied from my development box
Comment: Have you tried to remove the optional `$id=null` parameter from your `refine()` action? Or are you using that? If so, please add the code that uses that $id
Comment: The $id=null has been removed. It was left over from some earlier development and should have been long gone. I made no difference removing it
Comment: Have you made changes to routes.php?
Comment: No the routes.php has not been touched at all
Answer: FYI: I'm using Cakephp 2.4, I've only tested it on this version.
I ran into this same issue. I store the pagination variables in the user's session.
This way when a user navigates away from a page, they don't loose their place (page/sort field/direction) when they come back to the page.
Because I store the variables in the session, then retrieve them from the session, if say the user clicks on a link that causes the results to be less then the page they were on, I'll get a 404.
Example (The page they were on):
http://localhost/products/index/page:5/sort:Product.name
I send them this link:
http://localhost/products/index/search:[search_term]
This filters the results to only 2 pages.
 In this case, actual (perma)link, with the session variables restored, would look like:
http://localhost/products/index/page:5/sort:Product.name/search:[search_term]
Page 5 is out of the scope of the 2 pages from the new results.
This will throw the NotFoundException(); seen here:
http://api.cakephp.org/2.4/source-class-PaginatorComponent.html#238
How I resolved this was to catch the exception, then redirect them to the first page.
Since all of the pagination variables (including the 'search') are stored in the session, I only need to pass the page variable:
Example:
http://localhost/products/index/page:1
Cakephp recommended this as a possible way to overcome it:
http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html#out-of-range-page-requests
However, I wanted this available for all of my 'index' pages, so I overwrote the Controller::paginate() method in the AppController.
Original paginate method seen here:
http://api.cakephp.org/2.4/source-class-Controller.html#1070-1081
Here is how I did it in my Controller/AppController.php:
<?php

class CommonAppController extends Controller
{
    // ..... other code
    public function paginate($object = null, $scope = array(), $whitelist = array())
    {
    /*
     * Used to see if we get an exception thrown,
     * If so, send them to the first page, and set the flash so they know
     */
        try
        {
            // taken from their current paginate();
            // http://api.cakephp.org/2.4/source-class-Controller.html#1070-1081
            return $this->Components->load('Paginator', $this->paginate)->paginate($object, $scope, $whitelist);
        }
        catch (NotFoundException $e)
        {
            //Do something here like redirecting to first or last page.
            //$this->request->params['paging'] will give you required info.
            $page = (isset($this->request->params['named']['page'])?$this->request->params['named']['page']:1);

            $this->Session->setFlash(__('Unable to find results on page: %s. Redirected you to page 1.', $page));
            return $this->redirect(array('page' => 1));
        }
    }
    // ..... other code
}
?>

Answer: 8 months later...I just bumped into the same issue, and thought I could leave my findings here to avoid somebody else spending a couple of hours looking for a solution like I have been.
I had the same issue as Richard, when a GET request onto any other link of the pagination split bar, from 2 to n, was to generate a 404 error.
This 404 error originates from the PaginatorComponent (CORE/Cake/Controller/Component/PaginatorComponent.php), in these lines:
$pageCount = intval(ceil($count / $limit));
$requestedPage = $page;
$page = max(min($page, $pageCount), 1);

if ($requestedPage > $page) {
  throw new NotFoundException();
}

In a nutshell, this happens when the predicative conditions member has become so restrictive as to create a much smaller recordset than for page #1.
What can create this is that it now contains more predicates in it, that you just do not want. A way to see what it contains for page #2+ is to add this call:
FirePHP($parameters);

just before the lines above. You may be surprised.
The question is "why does conditions, that you should build in your controller and pass to the find() method, has changed so much from page #1 that works, to page #2+ that does not?
I cannot just answer for you without seing the rest of your code, but I can tell you what was happening for my case:
I was storing some values in $_SESSION so that my search could be remembered, and I was relying on isset($this->request->data[$objectName]) to know if I should add that particular predicate to my 'conditions' array. But that was without thinking that only page #1 is the result of a POST method, not the subsequent paginated requests pages, which are got through GET method. Therefore from page #2 onwards, $this->request->data[$objectName] is empty, but SESSION was still set because I had forgottent to reset it.
The conclusion is: remember page #2+ calls are GET, and the request data that you may have used and were working for POST are no more valid, creating a different set of conditions now, reducing your recordset, and creating a total count that may be 0, voiding the pagination system, hence the 404.
Answer: I came across the same issue for CakePHP3. The quickest way to solve is to change the form action so that it do not grab the "?page=x" part of the URL. For example, change it to current page URL like
<form action="<?=\Cake\Core\Configure::::read('App.domain')?>/page_url" ...


Convert ^I delimited file to pandas dataframe

Question: I am downloading a csv file from gmail attachment using below code. The output file generated looks like ^I delimited and I am not sure how to change it to some other delimiter so that I can load it into a pandas dataframe.
message = service.users().messages().get(userId=user_id, id=msg_id).execute()
for part in message['payload'].get('parts', ''):
    if part['filename']:
        file_name = part['filename']
        att_id = part['body']['attachmentId']
        att = service.users().messages().attachments().get(userId=user_id, messageId=msg_id,
                                                               id=att_id).execute()
        data = att['data']
file_data = base64.urlsafe_b64decode(data.encode('UTF-8'))
with open(path, 'wb') as f:
    f.write(file_data)

Output file content is separated like below -
Location ID^IProcessed Currency Code^IExternal MID^IDBA Name
Edit 1:
Now I am using tab as separator but get a different error while reading file into dataframe. Perhaps, it has got something to do with urlsafe_b64decode or data.encode('UTF-8') but I am not able to understand. The actual attachment file in gmail is a tab separated file.

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position
  0: invalid start byte
Comment: `^I` is another way of representing a tab, so this is likely a tab-separated file.  See the dupe target for how to load.
Comment: The actual column names are Location ID, Processed Currency Code, External MID, DBA Name
Comment: You can specify the separator while reading a csv with pandas: `pd.read_csv(filename, sep='^|')`
Comment: Possible duplicate of [How to load a tsv file into a Pandas DataFrame?](https://stackoverflow.com/questions/9652832/how-to-load-a-tsv-file-into-a-pandas-dataframe)
Comment: @Erfan - I tried that but it is not able to find ^I in file and puts everything into a single column
Comment: Then see the question that is tagged by @snakecharmerb, its `sep='\t'`
Comment: @snakecharmerb - Tried using df = pd.read_csv(path, header=0, sep='\t') and get following error -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Answer: There are two issues here:

the column delimiter '^I'
the encoding of the data

The delimiter
'^I' is another way of representing the tab character. Some applications may choose to represent tab characters in this way rather than using the '\t' escape sequence.  For example vim displays tabs as '^I' when instructed to display non-printing characters.
Encoding
'0xff' is part of a byte-order-mark or BOM - an invisible character sequence used to tell applications about the encoding used to encode text.  The UTF-16 encoding uses the sequence '0xfe0xff' to denote big-endian UTF-16 (Python codec 'utf-16-be').  '0xff0xfe' denotes little-endian UTF-16 (Python codec 'utf-16-le').  UTf-16 uses two bytes to encode characters, so the order of the bytes is important.
So, to successfully open the attachment, it's necessary to specify that the column delimiter is a tab, and the encoding is UTF-16 (Python can use the BOM to work out which version of UTF-16):
pd.read_csv(path, header=0, sep='\t', encoding='utf-16')


If there is a total order on $A$ and there is surjection $A\rightarrow B$ then can $B$ be totally ordered?

Question: I constructed a following theorem and I wish to (dis)prove it:

Let $\leq$ be a total order on $A$ and let there be surjection $\varphi:A\rightarrow B$. Then there exists total order on $B$.

This seems really trivial and obvious to me. For any $b_1,b_2\in B$, because $\varphi$ is surjection, we can find $a_1,a_2\in A$ such that $\varphi(a_1)=b_1$ and $\varphi(a_2)=b_2$. Then, if I define $R\subseteq B\times B$ as follows:$$(b_1,b_2)\in R\Leftrightarrow (a_1,a_2)\in\leq$$
where, as mentioned, $b_1=\varphi(a_1),b_2=\varphi(a_2)$, am I done?
EDIT: this is obviously wrong. What I'm dealing with is a set $A$ of all possible strings of finite length of given alphabet $\Sigma$ (with some additional, not so important property, thus in fact $A\subsetneq \Sigma^*$). The total order of $\Sigma^*$ is given
1.) by the length of the strings,
2.) lexicographically (I assume, there exists some total ordering of an alphabet)
Now because $A\subsetneq \Sigma^*$ by the property of linear order, $A$ is lineary ordered too.
Now to any $b\in B$ i assign some $a\in A$ such that $a\mapsto b$. Giving surjection $A\rightarrow B$
Comment: Just as a simple example, if you want to construct the total order of $B$ from the one on $A$ in some way, how would you do it for $\Bbb R\to S^1$ given by $t\to e^{it}$?
Comment: But these $a_1$ and $a_2$ are not necessary unique. What if there are also $c_1$,$c_2$ such that $\varphi(c_1)=b_1$,$\varphi(c_2)=b_2$ and you have $(c_1,c_2)\notin\leq$?
Comment: @Arthur good example. So basically, do you guys say that i need an injection, thus a bijection, right?
Comment: Then I could have $b_1=\varphi(a_1)=\varphi(a_1')$ and that would imply $a_1=a_1'$ or basically, because i would be able to compare $a_1, a_1'$ i would be able to compare $\varphi(a_1),\varphi(a_1')$ and because I have a bijection the converse would be true aswell and my defined ordering would work, am i right?
Comment: If you have a bijection then for sure you can send the order from $A$ to $B$ by $b_1\leq b_2\Leftrightarrow \varphi^{-1}(b_1)\leq\varphi^{-1}(b_2)$.
Comment: Can anyone say what happens without the axiom of choice ? Is "for every set $A$, there is a totally orderable set $B$ and a surjection $B\to A$" provable in ZF ? Implies AC ? Is strictly inbetween ?
Comment: What if $b_1=\varphi(a_1)=\varphi(a_1')$ with $a_1\neq a_1'$, $a_1\leq a_2$ and $a_2\leq a_1'$? It seems not to be well defined since it depends on the preimage you take.
Comment: True, let me edit my original post, i have different idea.
Comment: By the way, since you didn't ask for a total order $B$ compatible with $\varphi$ in any sense, this might interest you https://mathoverflow.net/questions/37272/are-all-sets-totally-ordered
Comment: Well, I know something about that, but, as there mentioned, it is equivalent to AC, which I'm not sure that i want to assume. In fact, if i could assume that anything can be totally ordered then half of my proof I'm working on, is pointless.
To my different idea: It actually failed too, but let me give more details on what order I have etc.
Comment: Or else, I can start assigning $b$ members to $a$ constructing a bijection from $A\rightarrow C\subset B$ and by the property of linear ordering, $C$ is totally ordered and thus $A$ can be totally ordered.
Answer: If you accept the axiom of choice, then any set $B$ can be well-ordered. This gives you a total order on $B$. However, there is no relation to the order $\le_A$ on $A$, and that is probably not what you want.
Using the axiom of choice again, you get a section for $p$ which is a function $i : B \to A$ such that $p \circ i = id_B$. Obviuosly $i$ is injective.
In concrete situations you may even be able to construct explicitly a section for $p$.
Given any section, the subset $i(B)$ inherits an order $\le_{i(B)}$ from $A$. This is again a total order. Now you can give $B$ the unique order $\le_i$ defined by $b \le_i b_2$ if $i(b_1) \le_A i(b_2)$. Then $(B,\le_i)$ and $(i(B),\le_{i(B)})$ are isomorphic as ordered sets. In general $\le_i$ depends on the choice of a section, so you get a whole collection of total orders which are somehow related to $\le_A$. But you cannot expect that there exists a section $i$ such that $a_1 \le_A a_2$ implies $p(a_1) \le_i p(a_2)$ for all $a_1,a_2$.
Moreover, if there exists an order $\le_B$ on $B$ (which is not required to be a total order) such that $p$ is order-preserving, then for any section $i$ the orders $\le_B$ and $\le_i$ agree. In particular, $\le_B$ is a total order.
(1) Let $b_1 \le_i b_2$. Then $i(b_1) \le_A i(b_2)$ and $b_1 = p(i(b_1) \le_B p(i(b_2) = b_2$.
(2) Let $b_1 \le_B b_2$. If $b_1 \le_i b_2$, we are done. If $b_2 \le_i b_1$, use (1) to see $b_2 \le_B b_1$. Therefore $b_1 = b_2$ and in particular $b_1 \le_i b_2$.
Comment: If I can make some 'section' of P that is, say $P'=\{p_1,...p_k\}$ and from this set i choose, wlog $p_1$ as the minimal element (it exists, because $P$ is totally ordered, because $P'\subseteq P$ and then construct an injection thus bijection and the order will work. If i declare the function explicitly, does that  mean I am using AC?
Comment: @MichalDvořák There are situations where you do not need AC. For example, if you know that each $p^{-1}(b)$ has a minimum, you get a section for $p$ by defining $i(b) = \min p^{-1}(b)$. This occurs when all $p^{-1}(b)$ are finite or when $A$ is well-ordered. But certainly you need "good luck".


How do I make several displays of one image field in a node?

Question: I'm trying to implement a JS image gallery to my project. I've created three image styles:

thumbnails 135x105
gallery 690x430
full 1600x900 (responsive)

Thumbnails are used as a pager for the gallery. By clicking the zoom button, the full image should be loaded and opened in a modal.
The question is, how to use all three image styles with one image field and display them in one node?
On Drupal 7 I've used Gallery Formatter module, but on Drupal 8 it's not working properly.
The task seems to be quite trivial, but i didn't find any answer. May be there is some module or i can set image style to the field in twig template? Thanks in advance!
Answer: The right solution would be an image formatter, which is configurable to have multiple instances of the same image with different display options.
If you can't find this in a module, you can improvise in preprocess of the node template:
mytheme.theme:
<code>function mytheme_preprocess_node(&$variables) {
   if (isset($variables['content']['field_image'])) {
    $image = $variables['content']['field_image'];
    $image['0']['#image_style'] = 'gallery';
    $variables['content']['field_image_gallery'] = $image;
    $image['0']['#image_style'] = 'full';
    $variables['content']['field_image_full'] = $image;
}
</code>
This code makes a copy of the image field and puts it in two additional fields, each with a different image style. This is for a single value field. I suppose your gallery is a view of multiple nodes with a single image. If there are multiple images in one node you would have to process the images in a loop (a bit more improvisation needed).
If it is a responsive image use this line to change the image style:
<code>$image['0']['#responsive_image_style_id'] = 'gallery';
</code>
All three images should be of the same kind (standard or responsive), otherwise there would be some more work to do.


why is insertRowsAfter() not working in my spreadsheet?

Question: I want to write a script that insert a row after the row where cursor is currently located.
For example if my cursor is on "A3" in the spreadsheet, I want to insert a row at 4th row from the script.
I run the following script.
function insertChild(){
var sheet = SpreadsheetApp.getActiveSheet();
var active=sheet.getActiveCell();
sheet.insertRowsAfter(active.getRow(), 1)
}

But this code inserts a row at the second row, instead of fourth row. It seems that getActiveCell() points at "A1" instead of "A3".
Is there any way to insert a row based on the current cursor location?
Comment: Oh I'm sorry, there's typos. My cursor is on "A3" now. And want to insert a row at "4:4" area.
Comment: I edit my original post related to A1 notations.
Comment: Are you sure the cursor points on A3 I'll do a test an come back
Comment: it works form me, your code is ok make sure your cursor points on the correct cell
Comment: https://docs.google.com/spreadsheets/d/1IdYFgeSt1oUzYafpRGi5sKlZhx2fXxgCsDrpQt843cA/edit?usp=sharing
Comment: I shared the spreadsheet. I freeze the 1st&2nd rows. I make sure that I set my cursor on A3 but always new row is inserted at 2nd row.
Answer: Your code is totally fine and works.
By the way you could use insertRowAfter(row) if you just want to add one row.
function insertChild(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var cell = sheet.getActiveCell();
  sheet.insertRowAfter(cell.getRow());
}


Built one MySQL INSERT using two different arrays using for each

Question: I hope someone is able to help me with the problem I'm facing for hours already. I'm trying to built a MySQL INSERT from two arrays. One array ($bms) holds 6 values and the second one holds 3 values (I want to use the array with 3 values inside the INSERT query where I'm using the placeholder group right now). Each value of the (group array) needs to be used 2 times. I hope you understand with my example below:

The 2 arrays – always include 6 respectively 3 values:
Array ( [0] => 8 [1] => 3 [2] => 4 [3] => 121 [4] => 13 [5] => 154 ) // $bms
Array ( [0] => 266 [1] => 267 [2] => 268 ) // group

The query with foreach loops:
$query = "INSERT INTO userlinks (linkpool_id, group, userid) VALUES ";
foreach($bms as $bm) {
    $query .= "('".$bm."', group, '".$userid."'),";
}
echo $query;

The output so far:
INSERT INTO userlinks (linkpool_id, group, userid) VALUES ('8', group, '19'),('3', group, '19'),('4', group, '19'),('121', group, '19'),('13', group, '19'),('154', group, '19')

WHAT I'M TRYING TO ACHIEVE:
INSERT INTO userlinks (linkpool_id, group, userid) VALUES ('8', '266', '19'),('3', '266', '19'),('4', '267', '19'),('121', '267', '19'),('13', '268', '19'),('154', '268', '19')

I really appreciate your help and invested time – awesome community!
Comment: The two first values of `$bms` needs to be associated with the first value of `$group`, the 3rd and 4th of `$bms` with the second of `$group` etc ... So each value of `group` will be used twice.
Comment: 3x2 = 6, I don't see the problem ?! @RajdeepPaul
Comment: @Treast Ah, now it's clear. Perhaps I need some more coffee. :-)
Answer: You can use a for loop instead :
$query = "INSERT INTO userlinks (linkpool_id, group, userid) VALUES ";

for($i = 0; $i < count($bms); $i++) {
  $j = (int) $i/2; //[0,1] will return 0, [2,3] return 1 etc...
  $query .= "('".$bms[$i]."', '".$groups[$j]."', '".$userid."'),";
}

rtrim($query, ",");
echo $query;

Edit: Thanks @RajdeepPaul for more precision.
Comment: `group` is a MySQL reserved word, encapsulate the table and column names using backticks. Also, remove the trailing `,` from the final query, do `echo rtrim($query, ",");`
Comment: @Treast, ok so I've tried the code you suggested above, but the output looks like this ->

`INSERT INTO userlinks (linkpool_id, group, userid) VALUES ('8', '', '19'),('3', '', '19'),('4', '', '19'),('121', '', '19'),('13', '', '19'),('154', '', '19')`

How do I assign the value of the groups array to it? I don't get it, sorry.
Comment: My mistake, sorry! Yes the code you provided above works just fine! Thanks a lot!


Source of chapter

Question: I came accross a chapter of some book about "quadrilaterals" and I would like to know what book / document it originates from.
Here is the link to the said chapter link
Thanks in advance.
Answer: The book should be
AN INTRODUCTION TO QUADRILATERAL GEOMETRY
By Ovidiu T. Pop, Nicu¸sor Minculete, and Mih´aly Bencze
Editura Didactica Si Pedagogica, R. A., Bucuresti, 2013.
300 pp. ISBN 978-973-30-3324-0.

One possibility to find out something like this is to take a chapter title / some sentence, that doesn't sound too general and just google it, often you will find it out then.

Source of chapter


Is $\int_{1}^{+\infty}\frac{dx}{x\log^2(1+x)}\approx 2$ just a mathematical coincidence?

Question: When providing a counterexample for $0<f(x)=O(x^{1+\varepsilon})\;\forall\epsilon>0\Longrightarrow \int_{1}^{+\infty}\frac{dx}{f(x)}=+\infty$
I realized that the error of the approximation
$$ \mathcal{J}=\int_{1}^{+\infty}\frac{dx}{x\log^2(x+1)}\approx 2$$
is less than $7\cdot 10^{-3}$.

Q: Is such approximate identity just a numerical coincidence, or is there some reason for expecting in advance that the RHS is very close to $2$?

Of course from
$$ \mathcal{J}=\int_{0}^{+\infty}\frac{2\,dt}{\left(t+\log\left(2\cosh t\right)\right)^2}$$
it is not hard to believe that $\mathcal{J}\approx\int_{0}^{+\infty}\frac{2\,dt}{(t+\log 2)^2}=\frac{2}{\log 2}$ or that
$$ \mathcal{J}\approx\int_{0}^{+\infty}\frac{2\,dt}{\left(t+\log(2)-1+\sqrt{1+t^2}\right)^2}$$
where the RHS has an explicit form involving a lot of $(\log 2)$s, namely
$$ \frac{2\log\log 2+\frac{2}{\log 2}-\log^2 2+2\log 2-3}{(1-\log 2)^3}=2.014532719\ldots$$
Small addendum: by exploiting $\frac{1}{\log^2(x+1)}=\int_{0}^{+\infty}s(x+1)^{-s}\,ds$ we also have
$$ \mathcal{J}= \int_{0}^{+\infty}{}_2 F_1\left(s,s;s+1;-1\right)\,ds$$
where the integrand function is way less elementary but much more well-behaved.
Comment: Are you sure it IS close to 2? When I integrate from $1$ to $1,000,000$ I get $1.921177267644058$
Comment: What is even more strange is this:

$$\int_1^{10^9} f(x)\ dx \approx 1.9453$$

$$\int_1^{10^{12}} f(x)\ dx \approx 1.95737$$

$$\int_1^{10^{17}} f(x)\ dx \approx 1.9453$$

$$\int_1^{10^{21}} f(x)\ dx \approx 1.96212$$

$$\int_1^{10^{23}} f(x)\ dx \approx 2.01638$$

$$\int_1^{10^{40}} f(x)\ dx \approx 0.841742$$

and so on.
Comment: @sku: for obvious reasons, the original integral is extremely slow-convergent. A numerical evaluation is simpler by using the second form of $\mathcal{J}$, and we actually have $$ \mathcal{J}=1.99355968\ldots $$
Comment: @VonNeumann: which procedure have you used to compute such approximations? I guess numerical errors are accumulating there, beyond the $10^{20}$ threshold.
Comment: The explicit approximation we get by using the second form and replacing $\log\cosh(t)$ with $\sqrt{1+t^2}-1$ is $$ \frac{2\log\log 2+\frac{2}{\log 2}-\log^2 2+2\log 2-3}{(1-\log 2)^3}=2.014532719\ldots$$
Comment: @VonNeumann: the integrand is everywhere positive, so there's some numerical error going on there.
Comment: @MichaelLugo I am going to check again!
Comment: @JackD'Aurizio Probably a wrong one xD lol.
Comment: Per Mathematica, the value of the integral is $1.99355968066536384786\dots$; I have the rest of an expansion which Mathematica believes is correct to about 600 decimal places.
Comment: @Patrick Stevens Pari/GP agrees that $$\frac2{\log2}-\sum^\infty_{k=2}(k-1)\,\text{E}_1((k-1)\log2)=1.9935596806653638478646067568180177\ldots$$
Answer: Thoughts:

I think it is just a mathematical coincidence. A few months ago, I asked this question about integrating $x^{-x}$ from $0$ to $+\infty$ and you gave a rather neat answer showing that it is just below the threshold of $2$ - note that Wolfram has the exact value of $1.9954$ ($5$.d.p.). I suspect that it is the same with your integral, and many other variants.
Integrating by parts with $f(x)=\log^{-2}(x+1)$ and $g'(x)=x^{-1}$ gives $$\mathcal{J}=\left[\frac{\log x}{\log^2(x+1)}\right]_1^{+\infty}+2\int_1^{+\infty}\frac{\log x}{(x+1)\log^3(x+1)}\,dx$$ so it is a case of showing that $$\mathcal{K}=\int_1^{+\infty}\frac{\log x}{(x+1)\log^3(x+1)}\,dx=\int_2^{+\infty}\frac{\log(u-1)}{u\log^3u}\,du\approx1$$ But unfortunately, there is no closed form of the indefinite integral of $\mathcal{K}$.
We can attempt to find a Maclaurin series for the integrand. It is not that tedious actually since the denominator fits nicely with the standard series of $\log(x+1)$. The first three terms are $$\frac1{x^3}+\frac1{x^2}+\frac1{12x}$$ but note that this diverges due to the final term. However, integrating this from $1$ to $500$ gives a value of around $2.02$.


Can we throw exception in one method and handle it in different method?

Question: I have two methods in which method 1 throw's an exception. Method 2 calls method 1 and if it throws exception it should be handled in method 2.
Here is my method 1
 private Customer GetCustomer(string unformatedTaxId)
        {
            if (loan.GetCustomerByTaxId(new TaxId(unformatedTaxId)) == null)
            {
                throw new NotFoundException("Could not find the customer corresponding to the taxId '{0}' Applicant address will not be imported.", new TaxId(unformatedTaxId));

            }

            return loan.GetCustomerByTaxId(new TaxId(unformatedTaxId));
         }

Now in the following method i am calling method 1
public void ProcessApplicantAddress(ApplicantAddress line)
        {
            try
            {
                Customer customer = GetCustomer(line.TaxId);

                Address address = new Address();
                address.AddressLine1 = line.StreetAddress;
                address.City = line.City;
                address.State = State.TryFindById<State>(line.State);
                address.Zip = ZipPlusFour(line.Zip, line.ZipCodePlusFour);
              }
              catch(NotFoundException e)
            {
                    eventListener.HandleEvent(Severity.Informational, line.GetType().Name, e.Message);
            }

My problem is i am getting an unhandled exception, but i should catch it in the method 2. Please help me from this.
My NotFoundException Class
//  class NotFoundException

  public class NotFoundException : Exception
    {

    public NotFoundException() : base()
    {
    }

    public NotFoundException(string message): base(message)
    {
    }

    public NotFoundException(string format, params object[] args): base(string.Format(format, args))
    {
    }

    public NotFoundException(string message, Exception innerException) : base(message, innerException)
    {
    }

    public NotFoundException(string format, Exception innerException, params object[] args) : base(string.Format(format, args), innerException)
    {
    }
}

Comment: This should work. What is the detail of the unhandled exception? Maybe it's not the exception you think it is.
Comment: Your NotFoundException has a (string, TaxID) constructor?  Why that over just a string?
Comment: As a debugging tip: press Ctlr + Alt + E, which brings up the Exceptions dialog. Select `Thrown` for `Common Language Runtime Exceptions`.
Comment: can you please post the code for the class NotFoundException specially the constructor method
Comment: When the indenting is messed up like this, we almost always look at a code snippet that doesn't match the real code.  And cannot show the cause of the problem.
Answer: Try-Catch blocks are relatively expensive operations, and they can make debugging difficult.  I highly recommend you avoid using an error handling pattern with try-catch.  Instead, you could just skip the method that throws and check for null:
public void ProcessApplicantAddress(ApplicantAddress line)
{

    var customer = loan.GetCustomerByTaxId(new TaxId(line.TaxId));

    if (customer == null)
    {
        eventListener.HandleEvent(Severity.Informational, "ApplicantAddress", String.Format(""Could not find the customer corresponding to the taxId '{0}' Applicant address will not be imported."", line.TaxId));
    }
    else
    {
        var address = new Address();
        address.AddressLine1 = line.StreetAddress;
        address.City = line.City;
        address.State = State.TryFindById<State>(line.State);
        address.Zip = ZipPlusFour(line.Zip, line.ZipCodePlusFour);
        //do whatever else you need to do with address here.
    }
}

Your originally posted code should work, but I am guessing that GetCustomerByTaxId is throwing an exception of its own when the customer isn't found.  You might consider stepping through that method and making sure it is actually going to return null when no customer is found.
Comment: Yea this is my previous version and it is working fine. But my manager told me to get rid of that and throw an exception in GetCustomer() method and handle it in ProcessApplicantAddress() method using try catch blocks. Any clue to solve this issue?
Comment: To be honest, if you are being directed to do something a certain way, I'd ask your manager to explain in detail the pattern he's looking for, and why.  The only other way you'll be able to get help from Stack Overflow is if you post the details of the Unhandled Exception.
Comment: Like what kind of details?
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Answer: Your throw is never triggered because the functions executed within if statement raised another exception, so the catch isn't trigger because it's another type of exception.
Comment: How can i fix this issue? Any clue
Comment: Ofcourse, but throwing an exception of returning null is much different. If the method throws any exception, do you want to throw a new one? Or only when the result for the `loan.GetCustomerByTaxId == null`
Comment: When my result is null.
Comment: Then your function is right this way. And the results are as aspected.
Comment: Sorry i didn't get you @Jeroen
Comment: The specs you gave are, when the `loan.GetCustomerByTaxId` returns `null` it should raise an NotFoundException. But the `loan.GetCustomerByTaxId` never returns any value, but that method raises an exception. And because you didn't caught that type of exception, your visual studio will say that there is one unhandled exception. So if you want to fix this, you should fix the `loan.GetCustomerByTaxId` method.
Comment: Can you provide me a solution for this issue please?
Comment: If the TaxId is correct then it will return a customer object for that particular taxId, otherwise it returns null then i should throw the exception. I am getting the TaxId field from the imported file
Comment: What type of exception is raised (the unhandled one)
Comment: Yep, Unhandled exception by user code, but i need to handle that in processapplicantaddress() method which i can't. :(
Comment: You could ask the teacher. I advise to read this: http://stackoverflow.com/questions/406385/handling-unhandled-exceptions-problem


Parent div position ignored after setting float to child div's

Question: Please help me to understand whats going on.
I have html - relevant code:

#sk_head {
  display: block;
}

.h_title {
  float: left;
}

.h_instr {
  float: right;
  font-size: 12px;
}

#sk_body {
  text-align: center;
  padding: 20px;
  display: block;
}

#skaiciuokle {
  text-align: left;
  display: inline-block;
}

Title

More less important title title

Link to user guide

<form action="" method="post">

    <fieldset id="skaiciuokle">

        /* table with form for entry data */

    </fieldset>

I expect page to display everything like this:

But for some reason parent sk_head div is getting ignored and contend squeezes in between h_title and h_inst div's.
I am completely baffled since nearly identical (differences after <fieldset> level) set for another page is displaying everything as intended.
What I am missing here? Why parent div is getting ignored?
Answer: Instead of float use display flex for sk_head.Element comes out of flow when float is given.

#sk_head {
    display: flex;
    justify-content: space-between;
}

.h_instr {

    font-size: 12px;
}

#sk_body {
    text-align: center;
    padding: 20px;
    display: block;
}

#skaiciuokle {
    text-align: left;
    display: inline-block;
}

Title

More less important title title

Link to user guide

    <form action="" method="post">

           <fieldset id="skaiciuokle">

                   /* table with form for entry data */

           </fieldset>

Comment: Or add the pseudo ::after on the sk_head. With `content: ""; display: block; clear: both;`
Answer: You're displaying your container div as block where it should be inline-block (or even better, flex). See below for a fix:

#sk_head {
  display:inline-block;
  width:100%;
}

.h_title {
  float:left;
}

.h_instr {
  float:right;
}

#sk_form {
  display:block;
}

Title

More less important title title

Link to user guide

  <form action="" method="post">

      <fieldset id="skaiciuokle">

          /* table with form for entry data */

      </fieldset>

  </form>

JSFiddle
Comment: I don't recommend `display: inline-block;` because of it's inaccuracy. If you make 2 elements next to each other `width: 50%` and add `display: inline-block;` elements will go under each other, while with `float: left;` they will display next to each other.
Answer: You can use flexbox as Tanvi says, but if you wish to keep the floating divs, you can add the following CSS to your file:
#sk_head::after {
  content: "";
  display: block;
  clear: both;
}

Answer: The floating elements are not cleared before your content element.
This means the space they are using is not being associated with sk_head, therefore sk_body can use it.
You could try something like this:
#sk_head::after {
  content: "";
  display: block;
  clear: both;
}

From: https://developer.mozilla.org/en-US/docs/Web/CSS/clear


An idea for faster DB upgrade when upgrade Magento

Question: Last days I am testing and doing benchmarks in order to find out how long it takes to upgrade Magento DB when we upgrade between major Magento versions.
I am testing kind of large DB. This DB contains only vital data and all unnecessary tables are truncated (log tables, import batches and etc.)
Where is the bottle neck?
The catalog data is not large but sales history tables are gigantic. I did couple of dry runs and noticed that adding / dropping indexes, adding / removing columns take ages. Basically I observed what MySql was doing … it was creating temporary tables like crazy (this obviously increased time for upgrade)
Plan of attack:
I see a possibility how to save some time but it needs preparation.

Use DB version in which large sales tables are empty.
Run Magento upgrade.
Import the data in sales tables.
Run some data-upgrade scripts again because new column were created during upgrade and I have to fill them with values.

My hope is that with step (3) I could reduce time which was wasted of creating temporary table every time when indexes was added / dropped and column was added / dropped.
What the community thinks about this approach? Do you see any risk for data inconsistency when the shop goes live after upgrade?
Comment: I doubt that the question is hard to find here for normal users, therefore I think it might be better at magento.se I neither think it is off topic there nor wrong...
Comment: @FabianBlechschmidt "what does the community think of this approach" is not a good fit for the regular site. It solicits opinion, not fact.
Comment: I'm migrating this to meta as there isn't one true answer for this, but it's a very interesting discussion.
Comment: How big is your database? (with all the data)
Comment: Its not only interesting but also very important so it should be remain in magento.
Answer: I think you'd find this to be a very interesting approach to what you're trying to do:
https://github.com/magento-ecg/Magento-Upgrade-Replay
ECG (Magento Expert Consulting Group) created this module to aggregate all db changes to then replay in bulk. This is really helpful for certain upgrade scenarios such as 1.10EE to 1.12EE which had a tremendous number of changes for the sales tables. If you had a very very large sales_flat_order table you would have found that there were dozens of small db migration scripts that added one column at a time.
If you have a very large table it copies the contents of the table into a table with the new schema and swaps. This is very inefficient to do dozens and dozens of times over and over; especially when all of the statements could be aggregated and take place all at once.
Hope that helps! Best of luck!
Answer: Try it with other hardware. I know you asked not directly for this. But maybe it is faster than your research.
Updating from 1.4 to 1.7 took 18 hours with our shop on a dedicated server with SAS disks (RAID 10). Also after emptying all tables not needed (logs etc.).
Running the update on a local dedicated server with a RAID 0 and SSD reduced time to 5 hours.
Today I would run it on upcloud.com*. Their server are faster than our local SSD system.
*I'm not sponsored or related to them :)


How does Airbnb implement geo searching?

Question: I'm exploring how does Airbnb stuff work and interested in geo searching. I don't understand how does Airbnb finds their ads by New Zealand for example?
If to look at query string parameters:
page:1
location:New Zealand
ss_id:3sdsi3ff

Only location string New Zealand goes to the server but not coordinates like lng, lat.
But in the response we get back the following:
center_lat: -40.900557
center_lng: 174.885971,
geo: {accuracy: 1, district: null, city: null, state: null, country: "New Zealand", country_code: "NZ",…}
accuracy: 1
city: null
colloquial_area: null
country: "New Zealand"
country_code: "NZ"
district: null
market: "Other (International)"
natural_feature: null
result_type: "country"
state: null
state_short: null
success?: true

we see that we get center_lat: -40.900557 center_lng: 174.885971 coordinates, country: "New Zealand", country_code: "NZ"
So how does Airbnb could detect this data based on "New Zealand" string passed from client in GET request?
Answer: They either have a server that stored every single city in the world (name as key) and the position.... (Well... One can get all those information from Wikipedia)
Or they must had used some services like the google map geocoding services:
https://developers.google.com/maps/documentation/javascript/geocoding
Open street map provide solution API like the google geocoding too.
Comment: So is it possible to use geocoding on a server side? I'm using nodejs server
Comment: Do you mean Google Maps API?
Comment: Yup the Google map api
Comment: Thanks for the help. I'm realy interested in how does Airbnb sovled this :)


How to ensure X509Certificate2 class does not return duplicate signing certificates?

Question: I have a C# windows form application. The user types in message, subject, to, and selects a signing certificate from a drop down to sign the email as well using X509Certificate2 class.
Here is how the snippet for how the dropdown (ComboBox SigningCertList) is populated:
try
{
    X509Certificate2[] certs;
    certs = CryptoHelper.GetSigningCertificateList();
    SigningCertList.Items.AddRange(certs);
    SigningCertList.ValueMember = "SerialNumber";
    SigningCertList.DisplayMember = "FriendlyName";
    SigningCertList.SelectedIndexChanged += new System.EventHandler(SigningCertList_SelectedIndexChanged);
    SigningCertList.SelectedItem = 0;
}

Symptoms are odd. The combobox will show my signing certificate (installed from a p12 file). However, if I load the Windows Certificates MMC snapin, I cannot find it when doing a search. Upon reinstalling the certificate, I see it in the Windows Certificates MMC snapin, and now duplicated in the dropdown. Only the second (or last / recent) signing cert in the list actually signs it.
So how can I ensure X509Certificate2 class does not return duplicate signing certificates?
Here is the GetSigningCertificateList() method below:
`public static X509Certificate2[] GetSigningCertificateList()
        {
            var list = new List();
        int matches = 0;
        X509Store localStore = new X509Store(StoreLocation.LocalMachine);
        localStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

        try
        {
            foreach (X509Certificate2 cert in localStore.Certificates)
                {
                    foreach (X509Extension extension in cert.Extensions)
                    {
                        X509KeyUsageExtension usageExtension = extension as X509KeyUsageExtension;

                        if (usageExtension != null)
                        {
                            bool matchesUsageRequirements = ((X509KeyUsageFlags.DigitalSignature & usageExtension.KeyUsages) == X509KeyUsageFlags.DigitalSignature);

                            if (matchesUsageRequirements)
                            {
                                list.Add(cert);
                                matches += 1;
                            }
                        }
                    }
                }
        }
        finally
        {
            localStore.Close();
        }

        X509Store userStore = new X509Store(StoreLocation.CurrentUser);
        userStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

        try
        {
            foreach (X509Certificate2 cert in userStore.Certificates)
            {
                foreach (X509Extension extension in cert.Extensions)
                {
                    X509KeyUsageExtension usageExtension = extension as X509KeyUsageExtension;

                    if (usageExtension != null)
                    {
                        bool matchesUsageRequirements = ((X509KeyUsageFlags.DigitalSignature & usageExtension.KeyUsages) == X509KeyUsageFlags.DigitalSignature);

                        if ((matchesUsageRequirements) && cert.FriendlyName.IndexOf("MYcompanyname.",0) >= 0)
                        {
                            list.Add(cert);
                            matches += 1;
                        }
                    }
                }
            }
        }
        finally
        {
            userStore.Close();
        }

        return list.ToArray();
    }

}`

Comment: You don't show the helper code so not sure where it searches. Please note that in MMC it allows you to see both your account as well as the computer account. If you never knew what is the computer account, learn it and you might have a duplicate certificate there.
Comment: The try code is called on FormLoad, so the search is executed with the GetSigningCertificateList() method. Remember per my post, the dropdown shows signing cert in dropdown even though its not found (searching all stores) in MMC Snapin. After installing the cert, MMC Snapin shows it in personal store, now the app shows the signing cert listed twice in the dropdown menu. Only the 2nd one in the dropdown will sign the email.
Comment: Agree with @LexLi, show helper code.
Comment: No problem. Can you identify what you mean by "helper code".
Comment: `CryptoHelper.GetSigningCertificateList` is your "helper code".  It's where the relevant code to your question actually lives.
Comment: I've added the GetSigningCertificateList() method as requested to the original post.
Answer: You mention that you don't see a cert in MMC, but do in your app; and that when you install the cert via MMC it shows up twice.  This suggests that you're using MMC to view the user My store (or the computer My store) but the certificate in question is normally present in the other location.
Once the certificate has been registered in two different stores (same store name, different location => different store) then Windows no longer considers it to be a duplicate (for one, the two instances can have different private key permissions). So while there's a duplicate to your application, there's not (intrinsically) to Windows or .NET.
You can prevent duplicates by standard dedup tactics, such as using a HashSet<X509Certificate2> instead of a List<X509Certificate2>.  The default .Equals check (which is performed by the default comparator) will match if the issuer and serial number are the same. That should be unique as long as your certificates come from a public CA; but private PKI could recycle serial numbers or not guarantee uniqueness.  If you're concerned you could use a custom comparator which uses whatever match logic you like.
So the easy dedup is to replace list = new List<X509Certificate2>() with list = new HashSet<X509Certificate2>() (though you should probably change the variable name).
A HashSet keeps only the first of the collisions; so if you want LocalMachine to be preferred you've already achieved that.  If CurrentUser should win, you may want to switch your blocks around.
Two other things of note:

If a certificate has no key usage extension at all it's considered valid for all usages.  Your code doesn't do that.  (If you know that a "correct" cert in your application always will then there's no problem)
X509Store.Certificates returns new objects every call; you could reduce finalizations by calling Dispose on the certificates you don't return (or Reset for .NET 4.5.2 and below).
Comment: Your first two paragraphs hit part of the issue. I didn't think about the chance that it could be installed in two different stores. I coded it so that I would get "all the unique certs in both Current and Local stores". Very interesting. Knowing this, you're suggestion to use Hashset is what will take care of the duplicates, minding the serial number possibility you mentioned.  Thanks for the explanation and the solution, good information.


How to hide individual staff lines in lilypond?

Question: How can individual staff lines be hidden in lilypond?
E.g. in
<code>\new DrumStaff \with {
  \override StaffSymbol.line-count = #3
}
<<
  \drummode {
    <<
      {
        r4 hh
      } \\
      {
        bd4 bd8 bd8
      }
    >>
  }
>>
</code>

I'd like to hide the staff line in the middle.
And e.g. in
<code>\new DrumStaff \with {
  \override StaffSymbol.line-count = #2
}
<<
  \drummode {
    <<
      {
        r4 hh
      } \\
      {
        bd4 bd8 bd8
      }
    >>
  }
>>
</code>

I'd like to hide the staff line at the very top (only visible when there is a note at the top) and the staff line at the very bottom (only visible when there is a note at the bottom)
I took a look at the documentation, but could only find how to hide all of the staff lines, but not individual ones.
Answer: I don't fully understand what you're looking for in the bottom example. Feel free to clarify, or perhaps this answer will move you in the right direction.
This solution specifies the number of staff lines while also specifying their positions.
<code>\version "2.18.2"

\relative c' {
  \new DrumStaff
    <<
      \drummode {
        \override Staff.StaffSymbol.line-count = #2
        \override Staff.StaffSymbol.line-positions = #'(-2 2)
        <<
          {
            r4 hh
          }
          \\
          {
            bd4 bd8 bd8
          }
        >>
      }
    >>
}
</code>
Comment: I could be wrong, but I'm pretty sure OP just wants to hide the *ledger lines* at the end of the question, which could be accomplished with a command like \override NoteHead.no-ledgers = ##t.
Comment: Thanks! Yes, that does the trick @Athanasius I wasn't aware that these are called ledger lines


Contour integration with infinite poles

Question: I am trying to find the integral of the following expression:-
$$\int_{-\infty}^{\infty} \frac{x^2}{e^{k}+e^{x^2}}dx$$
I think this can be solved using contour integration. The poles will be the points with $z^2 = k+i(2n+1)\pi$ according to me. But this results in infinite poles if you choose a contour covering the entire real axis. Does anybody have any insights to solve this integral?
Comment: It is not a problem of infinitely poles. You can't use contour integration because the function doesn't $\to 0$ for $|x|$ large on an half-plane.
Comment: You never really choose the contour to be infinite. You always choose a finite contour (say a semi circle of radius $R$), then apply the residue theorem and take the limit of $R$ going to infinity in the end. And for any finite value of the radius $R$ there will only be a finite number of poles inside the contour. Thus an infinite number of poles in the upper half plane is not an issue as it only appears in the limit.
Comment: @reuns That doesn't necessarily mean that it *can't* be solved using contour integration. It may require a nastier contour than the standard large semicircle, but, for example, $e^{-x^2}$ can be done using a parallelogram, combined with some modification to give the integrand poles in useful places.
Comment: @reuns See, e.g. https://math.stackexchange.com/q/1266856/221811
Comment: @Chappers I don't see what you mean, we need to close the contour with some curve where it $\to 0$, here there is not
Comment: @Chappers I'm quite sure if you allow such undirect method to compute $\int_{-\infty}^\infty e^{-\pi t^2}dt$ then every theorem in mathematics can be proven "using contour integrals"
Answer: Let's assume, for the moment, that $k\leq 0$. Then we can rewrite our integral in the following way:
$$\int_{-\infty}^\infty \frac{x^2}{e^k + e^{x^2}}dx = e^{-k}\int_{-\infty}^\infty \frac{x^2e^ke^{-x^2}}{e^ke^{-x^2}+1}dx = e^{-k}\sum_{n=1}^\infty (-1)^{n+1}e^{nk}\int_{-\infty}^\infty x^2e^{-nx^2}dx$$
Then, by Feynman's trick
$$= e^{-k}\sum_{n=1}^\infty (-1)^{n+1} e^{nk}\Biggr(-\frac{d}{dn}\int_{-\infty}^\infty e^{-nx^2}dx\Biggr) = e^{-k}\sum_{n=1}^\infty (-1)^{n+1} e^{nk} \left(-\frac{d}{dn}\sqrt{\frac{\pi}{n}}\right)$$
$$ = -\frac{\sqrt{\pi}}{2}e^{-k} \sum_{n=1}^\infty \frac{(-e^k)^n}{n^{\frac{3}{2}}} \equiv -\frac{\sqrt{\pi}}{2}e^{-k} \text{Li}_{\frac{3}{2}}(-e^k)$$
While these specific steps don't apply when $k>0$, we can use analytic continuation to extend the polylogarithm (and taking the antilimit).
Comment: Nice use of Feynman's trick. $\to +1$
Comment: Alternatively I think you could use the identity $$\frac{\Gamma(s/2)}{n^s\pi^{s/2}}=\int_0^\infty x^{s/2-1}e^{-n^2\pi x}dx,$$ instead of Feynman's trick since your integral is symmetric about $x=0$. You'd need to apply a change of variable and substitute a value for $s$ first.
Answer: Using a CAS, I did not find any antiderivative. However, for the integral
$$\int_{-\infty}^{\infty} \frac{x^2}{K+e^{x^2}}\,dx=-\frac{\sqrt{\pi } }{2 K} \text{Li}_{\frac{3}{2}}(-K)$$ where appears  the polylogarithm function.
$$\int_{-\infty}^{\infty} \frac{x^2}{e^{k}+e^{x^2}}\,dx=-\frac{\sqrt{\pi }}{2}  e^{-k} \,\text{Li}_{\frac{3}{2}}\left(-e^k\right)$$
Comment: Hmm, interesting. Originally, I came across the above integral while manipulating a function related to fermi-Dirac statistics. I think if we do go along the road of expanding the above function in terms of the infinite poles, we may end up in the polylogarithmic function only.
Answer: I would like to add a different approach, directly connecting the integral to the field of polylogarithms (and I don't know why it wasn't mentioned within the two excellent answers already given).
Clearly, the integrand is an even function of $x$ and thus we only need to be concerned about the interval $[0,\infty]$. Enforcing the substitution $x^2\mapsto x$ reveals the integral representation of the Polylogarithm Function as
\begin{align*}
\int_{-\infty}^\infty \frac{x^2}{e^{x^2}+e^k}\mathrm dx&=2\int_0^\infty \frac{x^2}{e^{x^2}+e^k}\mathrm dx\\
&=\int_0^\infty\frac{x^\frac12}{e^x+e^k}\mathrm dx\\
&=-e^{-k}\int_0^\infty\frac{x^{\frac32-1}}{e^x/(-e^k)-1}\mathrm dx\\
&=-e^{-k}\left[\Gamma\left(\frac32\right)\operatorname{Li}_\frac32\left(-e^k\right)\right]
\end{align*}

$$\therefore~\int_{-\infty}^\infty \frac{x^2}{e^{x^2}+e^k}\mathrm dx~=~-\frac{\sqrt\pi }2e^{-k}\operatorname{Li}_\frac32\left(-e^k\right)$$

The last step follows by basic properties of the Gamma Function. Anyway, note that the conditions - under which this representation holds - are met and at the same time the final expression matches the ones given by the other answers. Integral representation, as the one used here, are quite helpful when dealing with integrals of the "Mellin type" as they are sometimes called (due to their relation to the Mellin Transform).
Comment: Nice and "simple" solution, indeed ! $\to +1$
Comment: @ClaudeLeibovici Thank you kindly!

Contour integration with infinite poles