Creating nodes with Views Bulk Operations

Question: This seems like it would be a common application but not sure if it is doable.  I have a view (d7, views3) that is displaying fields in views bulk operation format from a content type (call it general).  For each row the user selects, I want to create a node of a separate content type (call it userspecific) made up of the user id and some of the fields from the general content type.  Is this something that is possible using VBO ??
Answer: This can be done using views bulk operations. But you may have to implement hook_actions_info in a custom module to create an action and the use that action in the views bulk operation.
Following code illustrates the process.
<code>function custom_test_action_info(){
  return array(
    'custom_test_create_new_node' => array(
      'type' => 'node',
      'label' => t('Create New Page'),
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
    );
}

function custom_test_create_new_node($node, $context = array()){
  global $user;
  $page_node = new stdClass();
  $page_node->type = 'page';
  $page_node->status = 1;
  $page_node->title = $node->title;
  $page_node->field_body[LANGUAGE_NONE][0]['value'] = $node->field_body[LANGUAGE_NONE][0]['value'];
  $page_node->uid = $user->uid;
  node_save($page_node);
}
</code>
After saving this code flush the drupal cache and the views bulk operations form will have the action available.

After saving the view you will get the operation available in the views bulk operation page.

select a node and then execute the operation and you will have a new basic page created.
i am attaching an export of the view which i created you can import this view in your system and give a try to understand the workflow.
Export code of the view:
<code>$view = new view();
$view->name = 'test_vbo_node_creation';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Test VBO node creation';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Test VBO node creation';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_operations'] = array(
  'action::node_assign_owner_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::custom_test_create_new_node' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_revision' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 1,
    'label' => 'Create a new node',
  ),
  'action::node_make_sticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_unsticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_modify_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'show_all_tokens' => 1,
      'display_values' => array(
        '_all_' => '_all_',
      ),
    ),
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::node_promote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_publish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpromote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_save_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_send_email_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_by_keyword_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test-vbo-node-creation';
</code>
Comment: Super stuff !  I created the custom code and was able to create the action, then see it in VBO and select it.  I brought up the page, selected one of the rows, and pressed the button.  It created a new node with the title and user id but the problem I am having is with my other fields getting values in them.  All but one are text fields and I did them like you did the body field.  It seems to be a problem on the $page_node side because I tried just putting literal values in there but they didn't show up.  Any thoughts ??
Comment: Now fields are being created but does anyone know how to query the rows to determine which ones have the checkbox checked ??  It looks like the field is called views_bulk_operations but when I display it, the value is NULL on all rows even though I checked the first one.
Comment: Hi @ronnienorwood,  you don't have to query the rows to determine which ones have the checkbox checked. In your action callback you will get only those nodes that have been selected in the views bulk operation. If your use case is something different please let me know more details.
Comment: Probably is a little bit different use case in that I used a date field with the repeat option and had to tell the view to create a row for each date by unchecking 'display all values in the same row' on the date field.  So then I ended up creating a foreach loop in the custom code to handle the individual rows.
    foreach ($rows as $row=>$value) {
      $page_node->field_date_class['und'][0]['value'] = $node->field_date_class['und'][$row]['value'];
      node_save($page_node);
    }
This created nodes for all rows so that's why I was trying to figure out which rows had been selected.


Is making objects of two classes member of each other a bad practice?

Question: Here's a bare minimum pseodo-code of what I use:
class A{
    //other variables
    B b;

    void delayedPartnerInit(B b){
        this.b=b;
    }
}

class B{
    //some other variables

    A a;

    void delayedPartnerInit(A a){
        this.a=a;
    }
}

I could make it into a single class but certain members(not shown here) of A are needed to exist before data about B. In other words, objects of A and B are instanced at different times but need reference of each other's variables once both set of variables are available.
The question is there a better way to do this? Am I missing some basic concept of programming?
Though I am currently working on C#, I have had this thought many times before when working with other languages too.
Update: I am using this in Unity game engine where B is Unity C# script. Since Unity doesn't allow us create scripts without adding it to something I need 2 classes. I get certain data(A's data) earliar which needs processing.
Didn't mention this earlier because I asked it as a generic question.
Note before closing as duplicate: I checked similar questions but found only specific questions that caused issues to authors who tried to do what I am doing. My question is whether it is a bad practice.
Comment: Typically try to avoid tightly coupled classes such as this.
Comment: `Since Unity doesn't allow us create scripts without adding it to something I need 2 classes.` This is a very vague claim. Ofcourse you can create instances of classes without attaching them to a certain `GameObject` if this is what you mean .. it applies only to classes of type `Component`. Any `static` class e.g. would simply exist for the entire session. Also within a MonoBehaviour you can use `new` to create an instance of a "normal" class at any time. One could even be a subclass of the other ... so maybe you should try to describe your exact usecase and add your actual code ...
Answer: Tightly coupled classes are generally bad practice:

Changes in one class lead to changes in another.
You cannot test one of classes without creating (or mocking) another one. Which in your case creates circular dependency.
Both classes depend on each other's implementations, not abstractions.
Harder for other persons (or yourself half a year later) to understand and reason about first class logic without inspecting second class as well.

Since Unity doesn't allow us create scripts without adding it to something I need 2 classes. I get certain data(A's data) earliar which needs processing

MVC pattern for Unity provides useful trick for decoupling monobehaviours:
interface ISomeObjectView {
    event Action OnUpdate;
    event Action Destroyed;
    event Action TriggerEntered;
    void SetTransform(Vector3 position, Quaternion rotation);
    void AddForce(Vector3 force);
    // Other methods or events you need to expose:
    // MouseOver, OnFixedUpdate, Move() or SetScale(), ...
}

MonoBehaviour itself does not contain any logic, it simply invokes events and uses incoming values:
public void SetTransform(Vector3 position, Quaternion rotation)
{
    // Params validation
    transform.rotation = rotation;
    transform.position = position;
}

private void Update()
    => OnUpdate?.Invoke();

MonoBehaviour logic must be moved to your data class or new controller class. Now your data class simply links itself to provided interface events and methods without circular dependencies. Monobehaviour does not require any references to other classes, it simply provides methods to manipulate itself and events to catch input.
This trick helps in several ways:

MonoBehaviour doesn't depend on anything and doesn't require any references to other classes.
Your data/logic classes doesn't require ant special knowledge about monobehaviours, only provided interface.
You can have several implementations for interface, switching different views depending on situation.
Easy to test, easy to mock.
You can move all the "Unity stuff" inside MonoBehaviour and write all related classes on pure C#. If you want to.

Please note that using event Action is not conventional way to deal with events! I think it's very convenient, but I'd suggest to use conventional EventHandler (UnityEvents is another option that might suit your needs).

Update: an example of simple MVC.
Consider the following Player controller:
[Serializable]
public class PlayerInfo {

    // Values configurable via inspector
    [SerializeField] private float speed = 1.5f;
    [SerializeField] private float jumpHeight = 5;
    [SerializeField] private float damage = 15;
    [SerializeField] private Player playerPrefab;

    public float Speed => speed;
    public float JumpHeight => jumpHeight ;
    public float Damage => damage;

    private Player playerInstance;

    public void InitializePlayer() {
        playerInstance = Instantiate(playerPrefab);
        playerInstance.Info = this;
    }

    public void TeleportTo(Vector3 newPosition) {
        playerInstance.transform.position = newPosition;
    }
}

public class Player : MonoBehaviour {
    public PlayerInfo Info { get; set; }
    private Rigidbody rb;

    private void Awake() {
        rb = GetComponent<Rigidbody>();
    }

    private void Update() {
        if (Input.GetButtonDown("Jump")
            rb.AddForce(Vector3.up * info.JumpHeight);
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        rb.AddForce(movement * info.Speed);
    }

    private void OnTriggerEnter(Collider other) {
        var enemy = other.GetComponent<Enemy>();
        if (enemy != null)
            enemy.TakeHit(info.Damage);
    }
}

There you go. PlayerInfo is created before Player. PlayerInfo references Player and Player references PlayerInfo. Player is used to move gameobject and attack enemies, PlayerInfo contains required info. What can we do here?
First, Rewrite MonoBehaviour without any logic:
public class PlayerView : MonoBehaviour {

    private Rigidbody rb;

    // Events for future subscription.
    public event Action OnUpdate;
    public event TriggerEntered<Collider>;

    // Simple initialization of required components.
    private void Awake() {
        rb = GetComponent<Rigidbody>();
    }

    // Unity methods doing nothing but invoking events.
    private void Update() {
        OnUpdate?.Invoke();
    }

    private void OnTriggerEnter(Collider other) {
        TriggerEntered?.Invoke(other);
    }

    // We still need a method to move our player, right?
    public void Move(Vector3 direction) {
        rb.AddForce(direction);
    }

    public void SetPosition(Vector3 position) {
        transform.position = position;
    }
}

Now you need class containing data about player:
[Serializable]
public class PlayerModel {

    [SerializeField] private float speed = 1.5f;
    [SerializeField] private float jumpHeight = 5;
    [SerializeField] private float damage = 15;

    public float Speed => speed;
    public float JumpHeight => jumpHeight ;
    public float Damage => damage;
}

Now we need a way to tie those two together:
public class PlayerController {

    private readonly PlayerModel model;
    private readonly PlayerView view;

    public PlayerController(PlayerModel model, PlayerView view) {
        // Validate values here.

        this.model = model;
        this.view = view;

        // Linking logic to events.
        view.OnUpdate += Move;
        view.TriggerEntered += Attack;
    }

    // Actual logic moved here.
    private void Move() {
        Vector3 movement = Vector3.zero;
        if (Input.GetButtonDown("Jump")
            movement += Vector3.up * model.JumpHeight;
        movement += new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) * model.Speed;
        view.Move(movement);
    }

    private void Attack(Collider other) {
        var enemy = other.GetComponent<Enemy>();
        if (enemy != null)
            enemy.TakeHit(model.Damage);
    }

    // Method from PlayerInfo to set player position without actual movements.
    public void MoveTo(Vector3 position) {
        view.SetPosition(position);
    }
}

Now you have 3 classes instead of 2, but model and view classes are very simple and do not require any dependencies. All the work is done by Controller class, which receives other two pieces and ties them together.
It becomes even better when interfaces are introduced in addition to classes: IPlayerModel, IPlayerView, IPlayerController.
You might think that it would be easier to create single class instead of three linked classes, but in the long run you will thank yourself for using this pattern: view and model are extremely simple, easy to read, easy to check for errors, easy to expand with new functionality. Single class, on the other hand, will quickly grow to hundreds of lines and become a nightmare to test and expand.
I strongly recommend this article with more complicated examples of MVC.
Comment: But don't we need to write the logic for all Unity related methods/events ourself(`MonoBehaviour logic must be moved to your data class or new controller class.`)? I wanted to keep my data in an class that's independent of Unity. Guess it's not possible.
`Now your data class simply links itself to provided interface events and methods without circular dependencies.`
How exactly do I do this?
Comment: @Anutrix like I showed in example, MonoBehaviour class has `OnUpdate` event, which invoked each `Update()`. You can attach any logic you need to that event: `view.OnUpdate += MyUpdateMethod()`. As long as method is attached to event it will be invoked each frame. Basically you move all methods outside of MonoBehaviour and then link them via events.
Comment: So you want me to make an interface that inherits MonoBehaviour and calls the each of respective functions in the data class?
Comment: Please advice. I really need this to work. Also, won't doing what I just said have negative affect on performance since there will be calls to update() every frame?
Comment: @Anutrix `there will be calls to update() every frame?` Well, yeah. But keep in mind that if you don't need to forward Update events to other scripts - then just don't use `void Update()` and `event Action OnUpdate`. Think of it this way: if your monobehaviour has `Update()` with logic inside it, then move logic outside and provide `public event` for subscription. If you do not have `Update` logic - then do nothing. Same goes for other unity functions - use events like `OnAwake`, `MouseOver`, `TriggerEntered` only if you have logic inside those methods. (Also I updated my post with examples)


Converting values in a dictionary to individual lists

Question: How do i convert the values in a dictionary to individual lists?
For example:
dictionary = {'a':[1,2,3], 'b':[4,5,6],'c':[8,9,10]}

outcome:
a = [1,2,3]
b = [4,5,6]
c = [8,9,10]

So far i could only think of creating individual lists and putting it into the list.
Is there any looping or better ways to do this?
Comment: Why would you need to do this? Instead of ```a```, you can use ```dict["a"]``` to access the same list
Comment: Thats redundant what you are trying to do , you already have the required values , instead of using it as a list notation use it via a dict notation dict['key']
Comment: That's what i'm currently doing, but as i have many data (lets say 500), i'm wondering if there's any better way to do this as i have to create an individual list for all of them.
Answer: a dictionary has keys and values, you can create a list out of keys and values by using d.keys() and d.values() respectively. if you want to only have value for one key say a you can use d["a"], and it gives you [1,2,3].
d = {'a':[1,2,3], 'b':[4,5,6],'c':[8,9,10]}
a = d["a"]
b = d["b"]
c = d["c"]
print(a)
print(b)
print(c)
print(d.keys())
print(d.values())

Comment: Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
Answer: import __main__

d = {'a':[1,2,3], 'b':[4,5,6],'c':[8,9,10]}

for k in d.keys():
    __main__.__dict__[str(k)] = d[k]

print(a, b, c)

Output:
[1, 2, 3] [4, 5, 6] [8, 9, 10]

Answer: d = {'a':[1,2,3], 'b':[4,5,6],'c':[8,9,10]}

for s in d.keys():
    vars()[s] = d[s]

print(a)
print(b)
print(c)

Result
[1, 2, 3]
[4, 5, 6]
[8, 9, 10]

Update According to OP's comment to another answer he wants "exact output" as in the question. This is also easy. Changing the second loop to
for s in d.keys():
    print(s + ' = ', end='')
    print(vars()[s])

we get the output
a = [1, 2, 3]
b = [4, 5, 6]
c = [8, 9, 10]


$\sum_{n=1}^\infty \frac{a_1+a_2+\cdots+a_n}{n}$ converges/divereges?

Question: Let $a_n\geq 0$. $\sum_{n=1}^\infty \frac{a_1+a_2+\cdots+a_n}{n}$ converges/divereges?
Take $a_n=1/n$ for example, then the proposed series looks like $\sum\frac{\ln n}{n}$, which is divergent. What about the general case?
Comment: If $a_1 > 0$ then the sum is at least $\sum_{n = 1}^{\infty}\tfrac{a_1}{n}$ which diverges. Similarly if any of the $a_n$'s are positive, the sum diverges.
Comment: it cud also converge obviously; e.g. $a_n = 0$ for each $n$
Comment: Or even worse: $\frac{1+2+3+\cdots+n}{n}$ clearly diverges. You need an extra condition such as $\lim_{n \to \infty} a_n = 0$ or that $a_n$ is decreasing.
Comment: looks like cauchy's first theorem on limit. see here https://math.stackexchange.com/questions/1930373/limits-and-cauchys-first-theorem
Answer: Convergence holds only when  $a_n=0$ for all $n$. $\sum\limits_{n=1}^{\infty} \frac 1 n \sum\limits_{i=1}^{n} a_i=\sum\limits_{i=1}^{\infty}a_i \sum\limits_{n=i}^{\infty} \frac 1 n=\infty$ unless $a_i=0$ for all $i$.
Comment: [ I have used the fact that $\sum\limits_{n=i}^{\infty} \frac 1 n = \infty$ for every $i$].
Comment: Note that the interchange in order of summation is justified by Tonelli's theorem.


Form API adds word "edit" in ID of every Form element

Question: FORM API adds word "edit" before the id of any form element. When I have to use the element in JS  I have to add "edit" before element id.
Example if I have element $form['curdate'] then in drupal_add_js('#edit-curdate');
Why so
Answer: Drupal adds edit to denote that the element is an input element. It helps to identify form elements through CSS, and reduces the possibility of ID clashes with other elements on the page.
In case you're interested, this is done in the form_builder() function...and there's no easy way to override it system-wide.
You can easily override it for individual form elements though if it's bothering you:
$form['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Some title',
  // ...
  '#id' => drupal_html_id('my-new-id')
);

Comment: Thanks....I am trying to use Jquery_ui datepicker but its not working in Drupal 7. so I thought the error might be due to JS using datapicker
Comment: The UI datepicker works great for me in Drupal 7, are you trying to include it in a custom form? If so what's your code?
Comment: Yes I am trying to use it custom form module. jquery_ui_add(array('ui.datepicker'));
  drupal_add_js('$(document).ready(function(){$("input#edit-curdate").datepicker({dateFormat: "yy-mm-dd"});});','inline');
  drupal_add_css(drupal_get_path('module', 'jquery_ui') . "/ui.datepicker.css", 'module');                                                   $form['curdate']=array( '#type'=>'textfield','#title'=>'Date*);
Comment: Try: `$form['element'] = array('#type' => 'date_popup', '#title' => 'Date', '#date_format' => 'd/m/Y');`. That works perfectly for me. The date module has that `date_popup` widget built in so you don't need to add any CSS/JS yourself, Drupal will do it all for you
Comment: I have installed Date module with all features.but following errors are displaying...     Notice: Undefined index: #id in theme_date_popup() (line 663 of D:\wamp\www\drupal\sites\all\modules\date\date_popup\date_popup.module).
    Warning: Missing argument 1 for myform_data_entry_form() in myform_data_entry_form() (line 28 of D:\wamp\www\drupal\sites\all\modules\myform\myform.module).
    Warning: Missing argument 2 for myform_data_entry_form() in myform_data_entry_form() (line 28 of D:\wamp\www\drupal\sites\all\modules\myform\myform.module).
Comment: @Dharmender Please keep the comments about the currently asked question. Using a date popup is a different question.


SSL connection hangs as client hello (curl, openssl client, apt-get, wget, everything)

Question: I've run into a problem on my Debian VPS (a xen domU) regarding SSL. Namely almost all SSL connections hangs at client hello. For example:
# curl -vI https://graph.facebook.com

About to connect() to graph.facebook.com port 443 (#0)
Trying 220.127.116.11... connected
Connected to graph.facebook.com (22.214.171.124) port 443 (#0)
successfully set certificate verify locations:
CAfile: none
CApath: /etc/ssl/certs
SSLv3, TLS handshake, Client hello (1):

It's the same when using the openssl client. However, some of the SSL traffic works (for example https://www.nordea.se).
Server
#uname -a
Linux server.com 2.6.26-1-xen-amd64 #1 SMP Fri Mar 13 21:39:38 UTC 2009 x86_64 GNU/Linux
It does however work on my Dom 0 (the main xen host).
Apt-get
I can't even run apt-get update with the debian security sources (hangs on reading headers)
Open SSL
At the begining I thought I had an old openssl client (0.9.8o-4) since I appeared to have a newer on the Dom 0 (0.9.8g-15+lenny8) but doing a manuanl update on the openssl deb didn't help.
Open SSL Client
This is the full output of when the openssl client hangs: http://pastebin.com/PAjwMap9
Closing thoughts
I've Googled the crap out of this, and I'm not getting any further. I've seen problems with curl, apt-get etc. but they are all specific relating to the very application - not general for the system. Any thoughts?
Comment: As a follow up, I'm starting to thinks it's a Xen issue (all domU have the same issue). DomU are img based + (network-script network-bridge). They are also one another IP chain then the Dom0 via net.ipv4.ip_forward
Answer: After some discussions back and forth with my hostingprovider it turned out that they had a MTU problem with the IP Chains that my DomU was using (but not the Dom0). I wanted to thank everyone who helped me out in the process, your help was invaluable :)
Comment: We just resolved the same type of problem today with the same solution - lowering MTU from 1500 to 1495 fixed it. Also running on Xen, we Curl over SSL was failing at the same point (after client hello).
Comment: just make me remember to include MTU in my default checklist next time
Comment: Had a similar problem. Some SSL sites would hang after the client hello. For me, I had to reduce the mss value on an old Cisco switch.
Answer: This is old and already answered, but we suffered the same exact issue and the cause was related, but different.
The key was to sniff traffic on our edge router, where we saw ICMP messages to the server (GitHub.com) asking for fragmentation. This was messing the connection, with retransmissions, duplicated ACKs and so.

The ICMP packet had a field, MTU of next hop with a weird value, 1450. The usual value is 1500.

We checked our router and one of the interfaces (an Ethernet tunnel) had this value as MTU, so the router was taking the minumun MTU of all interfaces as next hop. As soon as we removed this interface (it was unused), the SSH handshake started to work again.
Comment: You the man! My MTU was 1300 due to some VPN issues we had. As soon as I put it back to 1500 it started working. Tks man.
Answer: Try:
 $sudo apt-get --reinstall install openssl libssl0.9.8

Comment: I had to do a apt-get -f install first (it was complaining on (libssl-dev: Depends: libssl0.9.8 (= 0.9.8o-3) but 0.9.8o-4 is to be installed). Still the same problem though :( - now running openssl 0.9.8o-4 and libssl0.9.8 0.9.8o-4
Comment: I also did a apt-get upgrade, but no luck.
Answer: Sounds like a problem with the guest's /dev/urandom or /dev/random .. or maybe another device.  Run your hanging process under strace, and see if it is hanging trying to read.
Comment: I tried a random file, and also strace. It does hang trying to read, but still does so using a random file. Here is the full strace output: http://pastebin.com/AKnHJjGC
Comment: Not sure if this is vital, but I did a "dd if=/dev/random of=/tmp/x bs=1 count=1024" and it stalls on both DomU and Dom0. However, /dev/urandom works fine. "dd if=/dev/urandom of=/tmp/x bs=1 count=1024
1024+0 records in
1024+0 records out
1024 bytes (1.0 kB) copied, 0.00653607 s, 157 kB/s"
Comment: That said, using urandom doesn't help: "openssl s_client -state -connect graph.facebook.com:443 -rand /dev/urandom" still hangs
Comment: The strace suggests that the client hangs waiting for the server to respond to the client hello.  Would you be willing to send along `strace -s0 openssl s_client -state -connect graph.facebook.com:443 -rand /dev/urandom`, the contents of your fb_ca_chain_bundle.crt, and the contents of /usr/lib/ssl/openssl.cnf?
Comment: Of course I can! I just grabbed the fb_ca_chain_bundle.crt at random. Anway, strace: http://pastebin.com/AHK3ik99 fb_ca_chain_bundle.crt: http://pastebin.com/wYz7iG5W and openssl.cnf: http://pastebin.com/YUQckxcc I've also sent a mail to my hosting provider to ask if he has seen similar results before (firewall, routing issues, etc. etc.). Feels unlikely since dom0 is fine, but it never hurts to check.
Comment: Do you get the same results if you force ssl3 with `openssl s_client -ssl3 -state -connect graph.facebook.com:443`?  This server doesn't do sslv2.

This problem is not related to your /dev/u?random... something else is going on here.  The software should be waiting for 5 bytes on the socket before continuing.  Send along the debug with `openssl s_client -debug -state -connect graph.facebook.com:443`.
Answer: I would try using openssl s_client and giving it a random file ("any" file) just to check if the problem is related to /dev/random|urandom as Ben said:
openssl s_client -state -connect graph.facebook.com:443 -rand anyfile
Be aware that using a file this way is very dangerous cryptography-wise so be sure to find another solution before pushing that in production.
Comment: Unfortunately it still hangs at the same point, going to try strace straight away


Como faço para gerar números aleatórios e sem repeti-los em um intervalo de tempo?

Question: Estou criando um 'jogo' no qual é necessário que o usuário escolha um intervalo, e neste intervalo, ele escolha quantos números aleatórios ele deseja gerar. Entretanto, nos números aleatórios gerados, não podem haver repetições, por exemplo:
Intervalo 1 a 10, mostrar 10 números aleatórios neste intervalo.
Não podem haver dois números 8 etc, porém não sei como pôr para não repeti-los. Segue o código:
printf("GERADOR DE N NÚMEROS ALEATÓRIOS\n");
printf("Digite o número máximo do intervalo: ");
scanf("%d", &intervalo); //Lê o intervalo máximo proposto pelo usuário.

printf("Intervalo proposto: [1 a %d]\n\n", intervalo); //Mostra na tela o intervalo proposto pelo usuário.

printf("Digite quantos números aleatórios e diferentes deseja gerar: ");
srand(time(NULL)); //Complementa o comando rand. Toda vez que executar o programa, os números gerados não estejam na mesma sequência que anteriormente.
scanf("%d", &n); //Lê a quantidade de números que serão mostrados na tela

for(i=1; i<=n; i++) // Coemça o intervalo em i, e mostra a quantidade de números até chegar em "n" que representa o intervalo proposto pelo usuário.
    printf("%dº número: %d\n",i, 1+(rand()%intervalo)); //Aqui é onde é imprimido na tela o número aleatório gerado, entretanto, ele precisa ser diferente do número anterior gerado.

system("PAUSE");
return 0;

}
Comment: Não sei se entendi bem, mas você poderia armazenar estes números em um array e depois verificar se o número já existe no array. Caso exista, gere outro...
Comment: Felipe, o seu problema está resolvido? Você não chegou a aceitar a resposta ou dar algum feedback.
Answer: Uma maneira de fazer isso é usar um array, std:set ou std::unordered_set (C++11 ou superior) para armazenar os valores intermediários. Os sets são especialmente interessantes umas vez que eles não permitem repetições:
std::unordered_set<int> numbers;
for(int i=1; i<=n; i++) {
    int number = 1 + (rand() % intervalo);
    bool inseriu = numbers.insert(number).second;
    if (inseriu) {
        printf("%dº número: %d\n",i, number);
    } else {
        printf("\t*%d é um número repetido, tentando novamente\n", number);
        i--;
    }
}

Veja que unordered_set::insert retorna um pair<iterator,bool>. O iterator aponta para o elemento recém inserido (ou o elemento com o mesmo valor), enquanto o bool indicada se o elemento foi inserido ou não.
A diferença entre o  set e o unordered_set é que o primeiro usa uma árvore ordenada (e.g., Árvore rubro-negra) com tempo de inserção / busca O(log(n)). Já o segundo usa uma tabela de dispersão, sacrificando a ordem por tempos de inserção amortizados O(1). No seu caso unordered_set parece fazer mais sentido.

Se o intervalo for suficientemente pequeno, uma solução alternativa é construir um vector contendo todo o intervalo, embaralhar e escolher os n primeiros elementos.
std::vector<int> numbers2(intervalo);
std::iota(numbers2.begin(), numbers2.end(), 1);
std::random_shuffle(numbers2.begin(), numbers2.end());
for (int i=0; i<n; i++) {
    printf("%dº número: %d\n",i+1, numbers2[i]);
}

Nesse exemplo a função iota inicializa o vector com os números do intervalo e a função random_shuffle embaralha esses valores. Esse algoritmo é interessante, por exemplo, para simular uma jogador embaralhando cartas.
Exemplo funcional no Ideone
Answer: Em C, a maneira usual de resolver o problema de aleatoriedade sem repetição é meter todos os valores possíveis num array, baralhar o array e escolher os primeiros N elementos.
int limite_inferior, limite_superior, quantidade;
// obter valores, eg
limite_inferior = 1;
limite_superior = 100;
quantidade = 30;

if (limite_superior < limite_inferior) /* erro */;
int alcance = limite_superior - limite_inferior + 1;
if (quantidade > alcance) /* erro */;

int *array = malloc(alcance * sizeof *array);
for (int k = 0; k < alcance; k++) array[k] = k + limite_inferior;

shuffle(array, alcance);
for (int k = 0; k < alcance; k++) printf("%d ", array[k]);

Para a função shuffle() ver, por exemplo, o artigo na Wikipedia sobre Knuth Shuffle.


Redirect & mask URL to Azure subdomain

Question: I have an ASP.NET MVC web app running on Azure as generic-site.co. It's a white-label site that supports a number of subdomains: acme.generic-site.co, globex.generic-site.co, initech.generic-site.co, etc. Browsing to each of them changes branding on the pages, but the underlying functionality is exactly the same.
Meanwhile I have an external domain name acme-site.com hosted by GoDaddy. I want to redirect this specifically to the acme.generic-site.co subdomain, but I also want to maintain acme-site.com as the root URL for any further browsing on that site, allowing users to have a pure acme experience without any indication of the underlying generic-site-ness.
I've tried to do this using GoDaddy's Domain Forwarding with masking, but I ran into CSRF issues almost immediately.
Is there any way I can achieve this? I suspect IIS URL rewriting might be helpful, but I'm at a loss as to how to proceed.
Answer: It is probably easier to use IIS Url Rewrite module as you mentioned in your question. There are several examples on how to do this. Please start with this post by Scott Forsyth: https://weblogs.asp.net/owscott/iis-url-rewrite-redirect-multiple-domain-names-to-one
Answer: Don't use Domain Forwarding with masking.
Just add custom domain acme-site.com to Azure Web App.
And you may need to do one of the following:

Add a middleware or something that change Host in HTTP request header from
acme.generic-site.co to acme-site.com.
Adjust the application to
load correct branding when using domain acme-site.com.

Redirect & mask URL to Azure subdomain


Most DNS queries for TLDs do not pass through dnsmasq

Question: Most DNS queries for top-level domains from my LAN behind a router with dnsmasq 2.55 on OpenWRT 10.03.1 return negative results, e.g.:
$ dig com. ANY

; <<>> DiG 9.7.3 <<>> com. ANY
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 36108
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;com.               IN  ANY

;; Query time: 3 msec
;; SERVER: 192.168.1.1#53(192.168.1.1)
;; WHEN: Tue Feb 12 22:37:30 2013
;; MSG SIZE  rcvd: 21

When using some external recursive server (e.g. dig com. ANY @220.127.116.11), the query result is successful.
I thought that the problem migh be that dnsmasq considers the query for .com as a query for unqualified name com (terminal . seems to be always stripped). But even when dnsmasq is configured to forward queries for com comains and undistinguished names:
server=/com/220.127.116.11,server=//220.127.116.11

results are the same.
However, some types of queries actually DO pass, like NS or SOA. Some other, which DO NOT pass and return NOXDOMAIN, besides ANY, are e.g. DNSKEY or RRSIG.
Corresponding lines from the dnsmasq log are:
Feb 12 21:41:13 myrouter daemon.info dnsmasq[11569]: using nameserver 184.108.40.206#53 for unqualified names
...
Feb 12 21:42:52 myrouter daemon.debug dnsmasq[11569]: query[DNSKEY] com from 192.168.1.5
Feb 12 21:42:52 myrouter daemon.debug dnsmasq[11569]: config com is NXDOMAIN
...
Feb 12 21:43:06 myrouter daemon.debug dnsmasq[11569]: query[NS] com from 192.168.1.5
Feb 12 21:43:06 myrouter daemon.debug dnsmasq[11569]: forwarded com to 126.96.36.199

I wonder if, and how, can be dnsmasq configured to return expected results fot those queries. (queries for "normal" hostnames work properly)
Answer: You probably have the domain-needed option enabled:

  -D, --domain-needed

Tells dnsmasq to never forward  A  or  AAAA  queries  for  plain names,
  without dots or domain parts, to upstream nameservers. If the name is not
  known from /etc/hosts or DHCP then a "not found" answer is returned.

Find where this is set (either /etc/dnsmasq.conf or the command line parameters) and remove it.
Comment: this dnsmasq really has `-D` option (though not defined in `/etc/dnsmasq.conf`, but in `/etc/init.d/dnsmasq`) and disabling it fixes the problem, however it is a good idea to use it to prevent some information leakage, so i wonder if the problem can be solved without disabling the `-D` param (to work for real TLDs, not for random names) .. interesting is that it is also blocking some other queries than `A` or `AAAA`..
Comment: http://i.stack.imgur.com/1CoCt.png
Comment: Michael, i insist that `com.` IS a DNS name :)
Answer: I guess the problem is with the domain regex. This worked for me.
Just remove the regex over the domain:
server=18.104.22.168#53


unable to add certificates to alpine linux container

Question: I have a small python app inside an alpine linux container, here is the dockerfile:
FROM alpine

# basic flask environment
RUN apk add --no-cache bash git nginx uwsgi uwsgi-python py2-pip \
    && pip2 install --upgrade pip \
    && pip2 install flask

# application folder
ENV APP_DIR /app
ENV FLASK_APP app.py

# app dir
RUN mkdir ${APP_DIR} \
    && chown -R nginx:nginx ${APP_DIR} \
    && chmod 777 /run/ -R \
    && chmod 777 /root/ -R
VOLUME [${APP_DIR}]
WORKDIR ${APP_DIR}

# copy config files into filesystem
COPY nginx.conf /etc/nginx/nginx.conf
COPY app.ini /app.ini
COPY entrypoint.sh /entrypoint.sh

RUN apk update && apk add ca-certificates && rm -rf /var/cache/apk/*
COPY ./cert.pem /usr/local/share/ca-certificates/mycert.pem
COPY ./key.pem /usr/local/share/ca-certificates/mykey.pem
COPY ./ssl_password_file.pass /etc/keys/global.pass
RUN update-ca-certificates

COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPOSE 5000
ENTRYPOINT ["/entrypoint.sh"]

This worked fine 2 weeks ago, but when i tried to rebuild it recently i got this error:
WARNING: ca-certificates.crt does not contain exactly one certificate or CRL: skipping
WARNING: ca-cert-mykey.pem.pem does not contain exactly one certificate or CRL: skipping

so I checked those files, and found that for some reason, now the file ca-certificates.crt now has a chain of certificates.
I found this on stack overflow:

/etc/ssl/certs/ca-certificates.crt is actually appending each
  individual cert from /usr/local/share/ca-certificates.

but what changed? why is this now a problem?
So i tried reverting to an older version of alpine linux - same problem.
I tried recreating the certificates, I tried removing a whole bunch of certificates from the container, I checked the pem files before the update to make sure they are only a single certificate, and apparently directly after running
RUN update-ca-certificates

many certificates appear.
help ?
Answer: I think below worked for me (I was adding a root certificate on blackfire/blackfire image which extends from alpine):
RUN apk update && apk add ca-certificates && rm -rf /var/cache/apk/* \
  mkdir /usr/local/share/ca-certificates/extra
COPY .docker/other/cert_Intertrials-CA.crt /usr/local/share/ca-certificates/extra
RUN update-ca-certificates

I then logged into that VM and see it has added it to the merged cert file, /etc/ssl/certs/ca-certificates.crt (I believe i heard it takes each cert file from inside /usr/local/share/ca-certificates and merges into the /etc/ssl/certs/ca-certificates.crt file).
Now you will get that 'does not contain exactly one certificate or CRL: skipping' error probably, but i heard that is fine.
https://github.com/gliderlabs/docker-alpine/issues/30
mentions: "that this is just a warning and shouldn't affect anything."
https://github.com/gliderlabs/docker-alpine/issues/52
mentions:
"The WARNING: ca-certificates.crt does not contain exactly one certificate or CRL: skipping is just what it says it is, a warning. It is saying that ca-certificates.crt doesn't contain only one certificate (because it is the concatenation of all the certificates), therefore it is skipped and not included in ca-certificates.crt (since it cannot include itself)."
"The warning shown is normal."
Comment: This does *not work* in alpine linux according to my experience. As stated [here](https://github.com/gliderlabs/docker-alpine/issues/260#issuecomment-351128828), you *must not* put your custom cert files in a sub-directory of `/usr/local/share/ca-certificates`.
Comment: it's not just a warning for Alpine 3.13, this doesn't work
Comment: I can confirm (for me) that, on current alpine, certificate have to be added to `/usr/local/share/ca-certificates` not to `/usr/local/share/ca-certificates/extra` directory.
Comment: Not sure, worked for me and got 12 upvotes so far. Maybe people are just slightly modifying my COPY step (by removing extra/) to:
COPY .docker/other/YOURCERT.crt /usr/local/share/ca-certificates/
Comment: It seems it depends on the version of your distribution. Using
 doptopenjdk/openjdk11:alpine-jre now, its mandatory. I´ve used anapsix/alpine-java:8u192b12_server-jre before and it was enough to copy the cert to /usr/local/share/ca-certificates/
Comment: @vladkras It works in alpine 3.11, but broke in 3.12.
Answer:
WARNING: ca-certificates.crt does not contain exactly one certificate or CRL: skipping
WARNING: ca-cert-mykey.pem.pem does not contain exactly one certificate or CRL: skipping

OP mentioned two warnings, which includes the pem file to be added. Only the first warning can be ignored. The second warning is caused by the pem file containing more than one certificate, which is entirely valid but handled poorly by update-ca-certificates.
Instead, you can append the cert file's contents directly:
cat ca-cert-mykey.pem.pem >> /etc/ssl/certs/ca-certificates.crt

Another use case for CI config:
echo "$ADDITIONAL_CA_CERT_BUNDLE" >> /etc/ssl/certs/ca-certificates.crt

Answer: In my case, I had to execute the update-ca-certificates before add any package. But it fails if the /etc/ssl/certs/ doesn't exists.
So, I add RUN mkdir -p /etc/ssl/certs/ && update-ca-certificates on my Dockerfile before the RUN apk add ....
Answer: A little off topic because OP asked help for alpine, and I was using node:16 as base image in my dockerfile, but I would like to share my case just as a precedent. I was installing my RootCA properly, but beyond the "normal" warning my container was not taking the new certificate even when it was indexed in /etc/ssl/certs/ca-certificates.crt.
I was struggling since 3 hours ago with this no-sense bug; so, I just moved to node:18-bullseye (or greater) and then the certificate installed properly.
Answer: That's how it works for me
ADD .docker/cert/root2022.cer /usr/local/share/ca-certificates/root2022.cer
RUN openssl x509 -inform PEM -in /usr/local/share/ca-certificates/root2022.cer -out /usr/local/share/ca-certificates/certificate.crt
RUN chmod 644 /usr/local/share/ca-certificates/certificate.crt && update-ca-certificates

Answer: Even after adding the self-signed certs to /etc/ssl/certs/ca-certificates.crt, the @azure/openai library still refused to use them.
I had to add: ENV NODE_EXTRA_CA_CERTS=/usr/src/certs/cacert.pem to my Dockerfile to create the NODE_EXTRA_CA_CERTS env var.


Picker sincronizado React Native

Question: Tenho um Json com todos os estados e cidades. Quero fazer ao selecionar o Estado ele me mostre somente as cidades referente ao estado do select já selecionado.
Meu código imprime as as cidades. com o console.war, porém o retorno é undefined.
Segue as informações.
JSON:
{
  "estados": [
    {
      "sigla": "AC",
      "nome": "Acre",
      "cidades": [
        "Acrelândia",
        "Assis Brasil",
        "Brasiléia",
        "Bujari",
      ]
    },
    {
      "sigla": "AL",
      "nome": "Alagoas",
      "cidades": [
        "Água Branca",
        "Anadia",
        "Arapiraca",
        "Atalaia",
      ]
    }
  ]
}

Código:
    _getItem = (val) => {

        JSONCidades.estados.map(element => {
            if (val == element.sigla) {
                console.warn(element.cidades)
                return  element.cidades
            }
        })

    }

    _onChageValue = (value) => {
        this.setState({ uf: value })
    }

    _onChageValue2 = (value) => {
         console.warn(value)
    }

                            <Picker
                                selectedValue={this.state.uf}
                                style={{ height: 50, width: 120 }}
                                onValueChange={this._onChageValue.bind(this)}
                            >
                                {
                                    JSONCidades.estados.map((element, index) => {
                                        return <Picker.Item label={element.sigla} value={element.sigla} />
                                    })
}

<Picker
    selectedValue={this.state.cidade}
    style={{ height: 50, width: 120 }}
    onValueChange={this._onChageValue2.bind(this)}
>
    {
        this._getItem(this.state.uf.toString())
    }

</Picker>

Comment: Amigo sua função está correta, ele dá o warn com as cidades e depois printa undefined, se você trocar pelo console.log() talvez clareie mais a resposta.
Mas sua função está ok. Depois que ele printa os valores ele sempre printa um undefined.
Answer: Segue a solução que implementei.
Separei o Picker de Estados e Cidades. Cada um em componentes diferentes.
CIDADES
import React from 'react';
import { View, Picker, StyleSheet } from 'react-native';

export default props => (
    <View  >
        {
            props.data ?
                <Picker
                    selectedValue={props.selectedValue}
                    onValueChange={props.onValueChange}
                >
                    {
                        props.data.cidades.map(cidade => <Picker.Item key={cidade} label={cidade} value={cidade} />)
                    }
                </Picker>
                :
                <Picker
                    selectedValue={props.selectedValue}
                    onValueChange={props.onValueChange}
                >
                    <Picker.Item  label={'Selecione'} />
                </Picker>
        }
    </View>
)

ESTADOS
import React, { Component } from 'react'
import {View, Picker } from 'react-native'

export default  props => (
    <View >
        {
            props.data ?
                <Picker
                    selectedValue={props.selectedValue}
                    onValueChange={props.onValueChange}
                >
                    {
                        props.data.map(estado =>
                            <Picker.Item key={estado} label={estado.sigla} value={estado} />)
                    }
                </Picker>
                :
                null
        }
    </View>
)

Depois eu chamei eles na minha tela desta forma.
import React, { Component } from "react";
import { Picker, View, TextInput, Text, Button } from "react-native";
import { estados } from './cidades-estados/cidades-estados.json'
import SelectEstados from './components/SelectEstados'
import SelectCidades from './components/SelectCidades'

export default class Teste extends Component {

      state = { uf: null, selectedValueEstado: null, selectedValueCidade: null }

      componentDidMount() {
        this.setState({
          uf: estados,
          selectedValueEstado: '',
          selectedValueCidade: ''
        })
      }

      renderValueChangeEstado = (value) => {
        console.warn(value.sigla)
        this.setState({
          selectedValueEstado: value
        })
      }

      renderValueChangeCidade = (value) => {
        console.warn(value)
        this.setState({
          selectedValueCidade: value
        })
      }

      render() {
        const { selectedValueCidade, selectedValueEstado, uf } = this.state;
        return (
          <View>
            <View >
              <SelectEstados
                selectedValue={selectedValueEstado}
                data={uf}
                onValueChange={this.renderValueChangeEstado} />
            </View>
            <View>
              <SelectCidades selectedValue={selectedValueCidade}
                data={selectedValueEstado}
                onValueChange={this.renderValueChangeCidade} />
            </View>
          </View>
        );
      }
    }

Picker sincronizado React Native


How to make menu link show for certain roles?

Question: I want to add "Login" and "Logout" to the same menu but only for the right role. In previous versions of Drupal, you would just add /user/login and /user/logout to a menu and it would only render one or the other based on if they actually were logged in or not.
However in D8, it looks like the Logout link shows regardless... is there a way to replicate this without creating multiple menus?
Comment: How does one log out if you hide the Log Out link? How does one login if you hide the Log In link?
Comment: Reverse your comment. You see Log out if you are logged in, and vice versa.
Answer: In D8 this is a menu link class, which you can add to a menu in *.links.menu.yml:
mymodule.links.menu.yml
<code>mymodule.logout:
  weight: 10
  menu_name: mymenu
  class: Drupal\user\Plugin\Menu\LoginLogoutMenuLink
</code>
This class shows Log in or Log out for user roles authenticated or not:
<code>  public function getTitle() {
    if ($this->currentUser->isAuthenticated()) {
      return $this->t('Log out');
    }
    else {
      return $this->t('Log in');
    }
  }
</code>
and links it to the corresponding route:
<code>  public function getRouteName() {
    if ($this->currentUser->isAuthenticated()) {
      return 'user.logout';
    }
    else {
      return 'user.login';
    }
  }
</code>
Comment: Hmm, so this is not handled automatically anymore?
Comment: You can add menu links in UI for /user/login and /user/logout, and it will show only one of them, because they have defined requirements for the user roles. You can't test this as admin though, because admin has access rights for both.


Simulating from a skew normal distribution

Question: I am analyzing a data set in R, the histogram gives an impression of a normal distribution, but the qqplot suggests a slightly skewed normal distribution, so I want to try this out as well.  I fitted the model like so:
library(sn)# Azzalini skewnormal package
m1  <-  selm(log(dataset) ~ 1,data=Data)

Is this the right way to do it? I also want to simulate data from this model for control, how do I do this?  The "simulate" command does not work here.
Answer: The code you show is from the Azzalini skew normal (sn) package. To simulate data from the estimated model you can get estimated predicted values from the model, and then simulate from the distribution of the residuals, and add that. Since you didn't post your data I simulate some:
set.seed(7*11*13)
test  <-  rsn(1000, 0, 1, alpha=1)
hist(test)
mod  <-  selm(test ~ 1)
mod
Object class: selm
Call: selm(formula = test ~ 1)
Number of observations: 1000
Number of covariates: 1 (includes constant term)
Number of parameters: 3
Family: SN
Estimation method: MLE
Log-likelihood: -1196.029
summary(mod)
Call: selm(formula = test ~ 1)
Number of observations: 1000
Family: SN
Estimation method: MLE
Log-likelihood: -1196.029
Parameter type: CP

CP residuals:
     Min       1Q   Median       3Q      Max
-2.66726 -0.56187 -0.07027  0.51962  2.68867

Regression coefficients
     estimate  std.err  z-ratio Pr{>|z|}
mean  0.58863  0.02545 23.13155        0

Parameters of the SEC random component
       estimate std.err
s.d.     0.8050   0.019
gamma1   0.2746   0.080

Now you can get fitted values from this model by:
mod.fit  <-  fitted(mod)
str(mod.fit)
 Named num [1:1000] 0.589 0.589 0.589 0.589 0.589 ...
 - attr(*, "names")= chr [1:1000] "1" "2" "3" "4" ...

you can see all of them is equal to the fitted mean.  Now you could continue, simulate new residuals from the fitted skew normal error distribution, and simulate from that.  For the details you would have to look up Azzalini' book.
Answer:
There is a distribution known as the skew normal distribution,
  with density
  $$f(x|\alpha,\omega,\xi)=\frac{2}{\omega}\,\varphi(\{x-\xi\}/\omega)\,\Phi(\alpha\{x-\xi\}/\omega)\qquad
> x,\xi,\alpha\in\mathbb{R}\quad\omega\in\mathbb{R}^*_+$$ which
  generalises the Normal $\mathcal{N}(\xi,\omega)$ distribution when
  $\alpha\ne 0$.

You may try to fit this distribution to your dataset and test whether or not $\alpha=0$.
Comment: I don't think this answers the question ...


Compute without calculator, $ \frac{1}{\cos^{2}(10)} + \frac{1}{\sin^{2}(20)} + \frac{1}{\sin^{2}(40)} - \frac{1}{\cos^{2}(45)} $

Question: Compute without calculator,
$$ \frac{1}{\cos^{2}(10^{\circ})} +  \frac{1}{\sin^{2}(20^{\circ})} +   \frac{1}{\sin^{2}(40^{\circ})} -   \frac{1}{\cos^{2}(45^{\circ})} $$

Attempt:
Let $A = \cos(10) \sin(20) \sin(40)$, then
$$ \frac{1}{\cos^{2}(10)} +  \frac{1}{\sin^{2}(20)} +   \frac{1}{\sin^{2}(40)} = \frac{\sin^{2}(20) \sin^{2}(40) + \cos^{2}(10) \sin^{2}(40) + \cos^{2}(10) \sin^{2}(20)}{A^{2}} $$
notice also
$$2A \sin(10) \sin(40) =  \sin^{2}(20) \sin^{2}(40) $$
$$2A \cos(20) \cos(10) =  \cos^{2}(10) \sin^{2}(40) $$
so we have
$$\frac{2A \sin(10) \sin(40) + 2A \cos(20) \cos(10)+ \cos^{2}(10) \sin^{2}(20)}{A^{2}} $$
$$ = \frac{2A \left[2 \sin(10) \sin(20) \cos(20) + \frac{\sqrt{3}}{2} + \sin(10)\sin(20) \right]+ \cos^{2}(10) \sin^{2}(20)}{A^{2}} $$
$$ = \frac{2A \left[\sin(10) \sin(20) (1+ \cos(20) + \cos(20)) + \frac{\sqrt{3}}{2}   \right]+ \cos^{2}(10) \sin^{2}(20)}{A^{2}} $$
$$ = \frac{2A \left[\sin(10) \sin(20) (3\cos^{2}(10) - \sin^{2}(10)) + \frac{\sqrt{3}}{2}   \right]+ \cos^{2}(10) \sin^{2}(20)}{A^{2}} $$
How to continue then?
Comment: See also : https://math.stackexchange.com/questions/3234514/finding-the-value-of-sin-4-frac-pi16-sin-4-frac3-pi16-sin/3234783#3234783   and https://math.stackexchange.com/questions/3226619/evaluate-sum-k-17-tan2-frack-pi16-tan2-frac4-pi16/3227419#3227419   and https://math.stackexchange.com/questions/951522/trig-sum-tan-21-circ-tan-22-circ-tan2-89-circ  and https://math.stackexchange.com/questions/175736/evaluate-tan220-circ-tan240-circ-tan280-circ
Answer: \begin{align*}
&\;\frac{1}{\cos^{2}10^{\circ}} +  \frac{1}{\sin^{2}20^{\circ}} +   \frac{1}{\sin^{2}40^{\circ}} -   \frac{1}{\cos^{2}45^{\circ}} \\
=&\;\frac {16\sin^210^\circ\cos^220^\circ}{16\sin^210^\circ\cos^210^\circ\cos^220^\circ}+\frac{4\cos^220^\circ}{4\sin^220^\circ\cos^220^\circ}+   \frac{1}{\sin^{2}40^{\circ}} -2\\
=&\;\frac{4(1-\cos20^\circ)(1+\cos40^\circ)+2(1+\cos40^\circ)+1}{\sin^240^\circ}-2\\
=&\;\frac{7-4\cos20^\circ+6\cos40^\circ-4\cos20^\circ\cos40^\circ}{\sin^240^\circ}-2\\
=&\;\frac{7-4\cos20^\circ+6\cos40^\circ-2\cos60^\circ-2\cos20^\circ}{\sin^240^\circ}-2\\
=&\;\frac{6-6\cos20^\circ+6\cos40^\circ}{\sin^240^\circ}-2\\
=&\;\frac{6-12\sin30^\circ\sin 10^\circ}{\sin^240^\circ}-2\\
=&\;\frac{6-6\cos 80^\circ}{\frac12(1-\cos80^\circ)}-2\\
=&\;10
\end{align*}
Comment: @SoumalyaPramanik You are [wrong](https://www.wolframalpha.com/input/?i=sec%5E2(pi%2F18)+%2B+csc%5E2(pi%2F9)+%2B+csc%5E2(2*pi%2F9)+-+sec%5E2(pi%2F4)).
Comment: $\cos A\cos B=\frac{1}{2}(\cos(A+B)+\cos(A-B))$. It is $-4\cos40^\circ\cos20^\circ=-2\cos60^\circ-2\cos20^\circ$.
Comment: The double angle formula $\sin 2\theta=2\sin\theta\cos\theta$ and the facts that $40=2\times 20$ and $20=2\times 10$. These are big hints to me.
Comment: https://www.wolframalpha.com/input/?i=sec%5E2(pi%2F36)+%2B+csc%5E2(pi%2F18)+%2B+csc%5E2(pi%2F9)+-+sec%5E2(pi%2F4)
Comment: @SoumalyaPramanik Your angles in the first three terms are incorrect.
Comment: Oh god I assumed $\pi$ radians = $360$ degrees.. That is a blunder
Comment: How do you get $4 \cos(40) \cos(20) = 2 \cos(60) - 2 \cos(20)$?
Comment: how about $ 2\sin(30) \sin(10) = \cos(80)$?
Comment: $2\sin30^\circ\sin10^\circ=2(\frac{1}{2})\cos(90^\circ-10^\circ)$.
Comment: how do you come up with the initial approach..?
Comment: thanks @CYAries
Answer: I believe this is how the problem came into being.
Observe that
$\dfrac1{\cos^210^\circ}=1+\tan^210^\circ$
$\dfrac1{\sin^220^\circ}=\dfrac1{\cos^270^\circ}=1+\tan^270^\circ$
$\dfrac1{\sin^240^\circ}=\dfrac1{\cos^250^\circ}=1+\tan^2(-50^\circ)$
Observe that the angles differ by $60^\circ$
Now if $\tan3x=\tan3A,3x=180^\circ n+3A$ where $n$ is any integer
$x=60^\circ n+A$ where $n=-1,0,1$ or more generally $n\equiv-1,0,1\pmod3$
Again, $\tan3A=\tan3x=\dfrac{3t-t^3}{1-3t^2}$
$\implies t^3-(3\tan3A)t^2-3t+\tan3A=0$ where $t=\tan x$
whose roots are $t_r=\tan(60^\circ r+A)$ where $r=-1,0,1$
$\displaystyle\implies S(A)$
$\displaystyle=\sum_{r=-1}^1t_r^2 =\left(\sum_{r=-1}^1t_r\right)^2-2(t_{-1}t_0+t_0t_1+t_1t_{-1}) =\left(\dfrac{3\tan3A}1\right)^2-2\left(\dfrac{-3}1\right)=6+9\tan^23A$
Here $3A=30^\circ\equiv-150^\circ\equiv210^\circ\pmod{180^\circ}$
So, $\tan3A=\tan30^\circ=\dfrac1{\sqrt3}$
$\implies S(10^\circ)=6+9\left(\dfrac1{\sqrt3}\right)^2=?$


Cálculo de frete Correios + PHP

Question: Como é calculado os valores dos fretes no caso do usuário selecionar mais de um produto em uma loja virtual? Na hora de cadastrar um produto, estamos dando a opção do cliente colocar o comprimento, altura, largura, diâmetro e o peso por produto. No PHP pego dessa forma antes de calcular o frete:
<code>$parametros['nVlComprimento'] = '35';
$parametros['nVlAltura'] = '21';
$parametros['nVlLargura'] = '13';
$parametros['nVlDiametro'] = '0';
</code>
Minha única dúvida é como isso é calculado? No momento estou calculando a quantidade de produtos * o valor do frete que é gerado pela API que estou usando, mas eu não teria que calcular também os valores acima no caso do cliente escolher mais um produto?
Comment: Já trabalhei com Loja Virtual, eu usava a API dos Correios para calcular, enviava os dados como peso etc e o correio retornava o valor. Pq depende do tamanho, peso do produto, local, etc. Por exemplo: https://github.com/newerton/api-correios/blob/master/Correios.php
Answer: Eu calculo de maneira separada o frete para cada produto. Como se fosse ter uma embalagem para cada. Depois, somo todos os resultados.
Como o frete dos correios é baseado por volume e peso, não tem como ter certeza do valor exato em caso de mais de um produto, já que não temos como saber o tamanho da caixa final onde vai ser colocado tudo (caso coloque tudo em uma caixa apenas).
Comment: Obrigado a todos.

Cálculo de frete Correios + PHP


Worklight download image through adapter

Question: My scenario
I will get logged into to SSO through Adapters and fetch some data and then need to get the image and show in the app.
To access the Image you need to login and then you can access.
I had already logged in this SSO for fetching other data through adapters
So My Question is

Do I need download the image through adapter only.
or Can I directly use  tag and give the URL as src.
Answer: What does the display of an image has to do with SSO? These are two distinct and different things.
Additionally, your scenario is very scarce of details... you need to edit the question and elaborate to get a more complete answer.
Anyway...
You can do either one of the options you've mentioned: get an image file & display it and using a URL to an image.

If you intend on using an image file, you will have to first make sure the image you will fetch is base64 encoded and then get the resulting string in the adapter response. To display it, you will then need to base64 decode it and display it.
More on base64 encode/decode
post image using worklight http adapter proper format
If you intend on using a URL to an image, you will have to simply place the URL (which is the adapter response) in the img tag.
You could also use the Cordova File Transfer API to fetch images, store them locally and display them.


I get 404 when uploading private *image* files in D7

Question: I have this Drupal 7.15 site (it needs an upgrade, I know).
I have some public and private files in there (all according to my settings). I have a public file field and a private file field.
So, using my private field, I can upload some files that are set to private (I've set the allowed extensions as: .zip, .pdf, .jpg, .png, .gif, and some more). I'm the only user allowed to use the private field.
When I upload an image file (png, jpg or gif), it does get uploaded ok, but when trying to click on the link I get a "404 error". When there's any other file type uploaded, everything works just fine.
The private files field is inside a content type that is set as a "group content type".
All files get uploaded ok and they do appear at the list of uploaded files in the normal way.
Some configuration information

My Apache file handler is mode_php (aka DSO).
Permissions and file owner of all files (images or not) are the very same: rw-rw-r-- (664)
Group and owner are the same too (images or not): nobody and nobody
All files are being uploaded to the same folder: ../files/private/filename.ext
All files get the same symlink: ../system/files/filename.ext

But only the pdf file is accessible to users (with perms to view the node). Even as an admin I get the 404 error when trying to access the image files.
What's wrong?
Comment: Have you check the upload setting on your module? Like IMCE, they have permission setting per role.
Answer: First, have you already checked the status report (/admin/reports/status)?
If that's all green then do you can dig around the content type field settings and also the content type view fields settings to see if you're using any image styles on the images. If you are you need to make sure the folder sites/default/files/styles has proper access perms.


Construct partition such that sum of chromatic numbers is greater than chromatic number of graph

Question: I'm asked to prove the following:

Show that for any undirected non-complete graph $G$ there is a partition $V(G)=V_1\sqcup V_2$ such that $\chi(G[V_1])+\chi(G[V_2])>\chi(G)$

I managed to show that we can assume that every vertex $x$ with non-full degree has degree atleast $\chi(G)-1$ (otherwise, we may take $V_1=\{x\}$ and consider its neighbors), but then I get stuck. I also considered doing induction by taking the "almost-complete" non-complete graph (i.e. a complete graph with one edge removed) and removing edges, but I'm not sure what to do in the induction step. Any help would be appreciated.
Comment: Isn't this false for the complete graph?
Comment: @MishaLavrov Yes sorry, I forgot that. Edited the question
Comment: @DavidScholz I wish I did... but no, we have to prove inequality
Comment: Do you mean $\geq$ instead of $>$?
Answer: Let $v$ be a vertex with non-full degree. Take $V_1 = \{v\} \cup N(v)$ and $V_2 = V(G) \setminus V_1$. Now notice that if we can color $V_1$ with $k_1$ colors and $V_2$ with $k_2$ colors then we can color $G$ with $k_1+k_2-1$ colors by coloring $v$ with one of the colors of $V_2$ (this comes from the fact that $v$ cannot have the same color with any of the other vertices in $V_1$). This gives us that
$\chi(G) \leq \chi(G[V_1]) + \chi(G[V_2]) - 1$ and we are done.


Transforming a sum of products in a product of sums

Question: I am studying the proof for the formula of $\sigma (n)$, the divisor function.
At a certain point there is this equivalence but I can't see how it works:
$$\sum_{b_i \in \{0,1,\dotsc a_i\}}{p_1^{b_1} \cdot p_2^{b_2} \dotsm p_k^{b_k}} = \prod_{i=1}^{k}{(1+p_i+p_i^{2}+ \dotsc+p_i^{a_i})}.$$
How is it possible to transform a sum like this in a product of sums?
Perhaps there is some combinatorics behind this but I don't see it.
Thanks for your help.
Comment: Try expanding out the product $(1+x+x^2)(1+y)(1+z+z^2+z^3)$ by hand to get some intuition.
Answer: The sum in the product, is the sum of divisors of $p_i$ the product of these sums contain every product without repetition, of their divisors not exceeding the original number.
Comment: why does the product of the sums not exceed the original number?
Comment: Neither say they don't go larger than the orignal number used as input. One simply does the termwise product of values of divisors first, then sums them. The second  sums the divisors of a given power in the original number, then multiplies all the individual sums together.


$\mathcal{D}$-classes

Question: Let $$\alpha = \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
1&3&3
\end{array}\right) \in \mathcal{T}_3\text{.}$$
(a) Show that the $\mathcal{D}$-class of $\alpha$ contains all those elements of $\mathcal{T}_3$ which have the same rank (cardinality of their image) as $\alpha$.
(b) Show that the $\mathcal{D}$-class of $\alpha$ contains 3 $\mathcal{R}$-classes and 3 $\mathcal{L}$-classes and that it has 2 element $\mathcal{H}$-classes.
How to do (b)?
From (a) we have that $D_{\alpha} = \{ \beta \in \mathcal{T}_3 : | \text{Im}( \beta )| = 2 \}$.
Explicitly then:
$$D_{\alpha} = \left\{ \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
1&1&2
\end{array}\right), \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
1&2&1
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
2&1&1
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
2&2&1
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
2&1&2
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
1&2&2
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
3&3&1
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
3&1&3
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
1&3&3
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
1&1&3
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
1&3&1
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
3&1&1
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
2&2&3
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
2&3&2
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
3&2&2
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
3&3&2
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
3&2&3
\end{array}\right) , \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
2&3&3
\end{array}\right) \right\}$$
Comment: It would help if you told us what $\mathcal T_3$ is and what $\mathcal{D, R, L, H}$-classes are.
Comment: $\mathcal{T}_3$ is the full transformation semigroup (set of all maps from a set $X$ to itself). $\mathcal{D}$, $\mathcal{R}$, $\mathcal{L}$, $\mathcal{H}$ are Green's relations:$$a\;\mathcal{L}\; b \iff S^1a = S^1b \;\;\;\;\forall \;\;a,b\in S\text{.}$$ $$a\;\mathcal{R}\; b \iff aS^1 = bS^1 \;\;\;\;\forall \;\;a,b\in S\text{.}$$ $\mathcal{H} = \mathcal{L} \cap \mathcal{R}$.$$a\; \mathcal{D}\;b \iff \exists \; c\in S\;\text{st}\;a\;\mathcal{R}\;c\;\mathcal{L}\;b$$ $R_{\alpha}$ is the $\mathcal{R}$-class of $\alpha\in S,\;D_{\alpha}$ is the $\mathcal{D}$-class of $\alpha$, etc.
Comment: Sorry: $\mathcal{T}_3$ is the set of all maps $\alpha : \{ 1,2,3\} \to \{ 1,2,3 \}$
Comment: I hope you don't mind that I removed the group-theory and inverse semigroups tags.  Since the ${\cal T_3}$ is neither a group nor an inverse semigroup, they didn't seem appropriate.
Comment: @Jim:  People likely to help with this question would know those definitions, so I don't think it's necessary to provide them.
Comment: @TaraB: I didn't expect him to write out the definition if it's standard; just giving the name "Green's relations" would be enough.  Semigroups are not so complicated that we should expect it to be impossible to answer a question on them after looking at the definition of the relations.
Comment: @Jim:  Fair enough.  Well, I wouldn't agree with 'semigroups are not so complicated', but certainly basic semigroup theory isn't.
Comment: Wow... all those arrays. Why not use `\begin{pmatrix}` and save all that trouble?
Answer: So you're fine with a)?  By the way, this is a special case of a more general fact: the ${\cal D}$-classes in a full transformation semigroup are always the sets of all transformations with a given rank.
For b), try playing around with the elements of the ${\cal D}$-class to find out when they are ${\cal R}$- or ${\cal L}$-related.  Hint:  it has something to do with images and kernels.
In response to your question below:  Okay, so you already knew the thing I was hinting at.  An ${\cal R}$-class is just an equivalence class under the relation ${\cal R}$.  So you need to show that there are are three different possible kernels and three different possible images for elements of ${\cal D}_\alpha$.
Comment: I'm fine with (a). Two elements of $\mathcal{T}_3$ are $\mathcal{R}$ related if and only if they have the same kernel and they're \mathcal{L} related if and only if they have the same image. I think I can find the elements of $R_{\alpha}$, $L_{\alpha}$ and $H_{\alpha}$ using that. What does it mean by saying show that $D_{\alpha}$ contains 3 $\mathcal{R}$-classes etc?
Comment: I edited my answer in response to your comment.  Does that help?
Answer: I've had to change accounts as I can't access my email account so I can't reply to any posts because I'm not using the account I originally asked the question from!
So:
$\beta \in R_{\alpha} \iff \text{Ker}(\beta)$ has classes $\{1\},\{2,3\}$ and $\beta \in L_{\alpha} \iff \text{Im}(\beta) = \{1,3\}$
$$R_{\alpha} = \left\{ \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
1&2&2
\end{array}\right), \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
2&1&1
\end{array}\right), \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
1&3&3
\end{array}\right), \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
3&1&1
\end{array}\right), \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
2&3&3
\end{array}\right), \left(\begin{array}{@{\,}c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\;\; }c@{\,}}
1&2&3\\
3&2&2
\end{array}\right) \right\}$$
Comment: This is correct.  Now what are the other ${\cal R}$- and ${\cal L}$-classes in ${\cal D}_\alpha$, and what are the ${\cal H}$-classes?
Comment: I've just posted what I think the elements of $R_{\alpha}$ are above (I had to post as an answer due to the character limit). How do you know how to separate these into 3 $\mathcal{R}$-classes?
Comment: It's ${\cal D}_\alpha$ that you want to separate into three ${\cal R}$-classes.  So $R_\alpha$ is one of them.  What are the other two?  You know that ${\cal R}$-classes are determined by the kernel of the transformations, so what are the other possible kernels for elements in ${\cal D}_\alpha$?
Comment: What is the definition of the kernel? What is the kernel of the elements of $R_{\alpha}$?
Comment: For a transformation $\alpha: X\to Y$, $\ker(\alpha)$ is the equivalence relation on $X$ given by $x\sim y$ iff $x\alpha = y\alpha$.  So the kernel of the elements of $R_\alpha$ is $\ker(\alpha)$, which is { {1}, {2,3}}, as you pretty much said in your answer.
Comment: So the other possible kernels of elements of $D_{\alpha}$ are $\{\{1,2\},\{3\}\}$ and $\{\{1,3\},\{2\}\}$
Comment: That's right.  So that lets you conclude there are three ${\cal R}$-classes.  Now do the same thing with images for the ${\cal L}$-classes.  Hmm, it's asking me to move this to chat now, but you can't chat because you need 20 rep or something.
Comment: The 3 possible images of elements of $D_{\alpha}$ are $\{1,2\}$, $\{2,3\}$ and $\{1,3\}$ so $D_\alpha$ contains 3 $\mathcal{L}$-classes. Now the $\mathcal{H}$-classes are the intersections of the $\mathcal{R}$-classes and the $\mathcal{L}$-classes. The 3 $\mathcal{R}$-classes each contain 6 elements and the 3 $\mathcal{L}$-classes each contain 6 elements. There are then 9 $\mathcal{H}$-classes each containing 2 elements.
Comment: You should probably state that you are using the fact that all the ${\cal H}$-classes in a ${\cal D}$-class have the same size.  Right, all sorted then!  You could put this all into your answer and accept it.

$\mathcal{D}$-classes


Using proftpd how do I disable regular ftp but leave sftp running

Question: We have a Debian Linux box with proftpd, we have both FTP and SFTP running, but we would like to disable regular FTP and just leave the SFTP running
Is there some way to do this?
Comment: Actually you can have FTP and SFTP provided both by ProFTPd, depending on the configuration.
Comment: It's funny, I am just looking for a solution to disable SFTP but leave FTP :)
Answer: I haven't used ProFTPd my self in quite some time, but remembered it having FTPS support.
So do you really mean SFTP or did you mean FTPS? The earlier being the SSH implementation of a protocol with similar capabilities as FTP and the later being FTP secured by SSL/TLS.
on a quick search I found the following document on FTPS in ProFTPd
http://www.proftpd.org/docs/howto/TLS.html
Answer: It's been a while since this was first asked, but ProFTPD does support FTP, FTPS (via mod_tls), and SFTP (via mod_sftp) now.
And to answer the question, you can configure ProFTPD to:

simultaneously allow both FTP and SFTP,
or just SFTP only.

The same rich, configurable logging that ProFTPD does for FTP transfers is done for SFTP transfers.
Answer: I recommend using SSH as well. Most FTP clients will support it.  Also, if you add /usr/libexec/sftp-server (or whatever the path is on your system) to /etc/shells. You can grant SFTP access without giving full shell access.
VS-FTP is nicer than openssh's built in SFTP
One thing I do not like about openssh's SFTP protocol is, by default, it does not log transfers.  If you need to log transfers, then you may want to check into VS-FTP.  I am pretty sure VS-FTP supports FTP over SSL and SFTP as well as transfer logging.  VS-FTP is default on Red Hat 5, I think.


Transforms Europe PMC RESTful "search" responses to source/external-id lists

Question: I would like to use Europe PMC RESTful API to transforms "search" responses to source/external-id lists, with one-line per record text.
Any suggestions / examples (in JavaScript)?
Answer: You can use XSLT to transform the response you get from the Europe PMC RESTful API.
You can find an example written in Vue.js on JSBin, where you can find the example XSL file, and how to transform the XML response to an ID list in JavaScript as below:
Example XSL
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

   <xsl:output method="text" encoding="UTF-8" />
   <xsl:param name="idMode" select="1" />

   <xsl:variable name="newline" select="'
'" />
   <xsl:template match="/">
      <xsl:for-each select="/responseWrapper/resultList/result">
         <xsl:choose>
            <xsl:when test="$idMode=1 and source/text()='MED'">
               <xsl:text>PMID</xsl:text>
            </xsl:when>
            <xsl:when test="$idMode=1 and (source/text()='PMC')">
               <xsl:text>PMCID</xsl:text>
            </xsl:when>
            <xsl:otherwise>
               <xsl:value-of select="source/text()" />
            </xsl:otherwise>
         </xsl:choose>
         <xsl:choose>
            <xsl:when test="$idMode=1">
               <xsl:text>:</xsl:text>
            </xsl:when>
            <xsl:otherwise>
               <xsl:text />
            </xsl:otherwise>
         </xsl:choose>
         <xsl:value-of select="id/text()" />

         <xsl:choose>
            <xsl:when test="$idMode=1 and source/text()='MED'">
               <xsl:if test="pmcid != ''">
                  <xsl:text>,PMCID:</xsl:text>
                  <xsl:value-of select="pmcid/text()" />
               </xsl:if>
            </xsl:when>
            <xsl:otherwise />
         </xsl:choose>

         <xsl:value-of select="$newline" />
      </xsl:for-each>
   </xsl:template>
</xsl:stylesheet>

HTML
<!DOCTYPE html>

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">

      <title>JS Bin</title>

         <input type="text" size="70" v-model="url">
         <fieldset>
            <legend>Output</legend>
            <textarea id="output" cols="56" rows="10" v-model="output"></textarea>
         </fieldset>
         <button @click="downloadData">Download</button>

Vue.js
var app = new Vue({
    el: '#app',
    data() {
        return {
            url: "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=cancer",
            xhttp: {},
            output: ''
        };
    },
    watch: {
        url: function() {
            this.output = this.transform();
        }
    },
    created() {
        if (window.ActiveXObject) {
            this.xhttp = new window.ActiveXObject("Msxml2.XMLHTTP");
        } else {
            this.xhttp = new XMLHttpRequest();
        }
    },
    methods: {
        loadXMLDoc: function(filename) {
            this.xhttp.open("GET", filename, false);
            try {
                this.xhttp.responseType = "msxml-document";
            } catch (err) {}
            this.xhttp.send("");
            return this.xhttp.responseXML;
        },
        download: function(filename, text) {
            let element = document.createElement('a');
            element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
            element.setAttribute('download', filename);
            element.style.display = 'none';
            document.body.appendChild(element);
            element.click();
            document.body.removeChild(element);
        },
        downloadData: function() {
            this.download('idlist.txt', this.output);
        },
        transform: function() {
            let xml = this.loadXMLDoc(this.url);
            let xsl = this.loadXMLDoc("https://yucigou.github.io/staticfs/xsl/rest2ids.xsl");
            if (window.ActiveXObject || this.xhttp.responseType === "msxml-document") {
                return xml.transformNode(xsl);
            } else if (document.implementation && document.implementation.createDocument) {
                // code for Chrome, Firefox, Opera, etc.
                let xsltProcessor = new XSLTProcessor();
                xsltProcessor.importStylesheet(xsl);
                let resultDocument = xsltProcessor.transformToFragment(xml, document);
                return resultDocument.textContent;
            }
        }
    },
    mounted () {
        this.output = this.transform();
    }
});

When you run this example in a browser, you will see the output:

You can change the query to see the output being updated, and you can also download it to a file as shown above.


FancyBox functionality

Question: I've implemented the futures of the FancyBox on our website which I'm designing in Asp.Net, everything was fine until the point where I've noticed that after I've opened the page using code below and make some entry's and then closing by parent.$.fancybox.close();.
The next time I use the same functionality to open the page the inputs on the same screen become not accessible even the rest of functionality like grid or something else is working without the issues. As soon as I'm doing full page refresh I may do again 1 time entry. Also I've noticed if I'm not using the parent.$.fancybox.close(); to close the FancyBox and using x mark to close, everything works fine no matter how many times I open the pages and close with X mark.
$.fancybox(
            {
                'width': '85%',
                'height': '80%',
                'autoScale': true,
                'transitionIn': 'fade',
                'transitionOut': 'fade',
                'href': Href,
                'type': 'iframe',
                'afterClose': function () {
                    __doPostBack(control, "");
                 }
              }
          );
 return false;

Also, when I use the following line:  $(".Diagnosis")[0].focus(); to set the focus of the input type=text I'm getting the error : can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus.
Answer: Alex, I've had my share of headaches with fancybox as well, don't worry, I think this happens to everyone.
instead of using parent.$.fancybox.close();
see what happens if you code a function in the parent window to close the fancybox, like this:
function closeFancyBox(){
   $.fancybox.close();
}

and then call that function from the child window like this:
window.parent.closeFancyBox();

tell me what happens after that.
Also; is it safe to share the link to the page whereon the link is happenning?

FancyBox functionality


Angular project specify multiple host names under same project

Question: I have a multi-store site which needs to be setup in a angular project, i changed the default localhost:4200 to my custom domain and i have all my domains listed in my hosts file under the same ip.
Currently when i run yarn start it loads my angular project on my domain rather than localhost:4200 which works great.
In angular.json i have set the following
    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "browserTarget": "spartacus:build",
        "disableHostCheck": true,
        "host": "my-store-de.local",
        "port": 4200
      },

How can i alter this hosts property to allow for multiple domains so if i went to my-store-ch.local for example it would load the project on that domain too. I have had a look at similar cases but all of them seem to be in firebase which i am not using this is just for local development for now any help or someone who could point me in the right direction would be greatly appreciated!
Answer: ng serve is aimed for development purposes only so it doesn't support what you need.
You can start your project on a 127.0.0.1 IP address (instead of domain localhost)  if you bind custom domains to 127.0.0.1 then everything should work.
Another solution is to start the app on localhost:4200 but additionally setup nginx web server locally (or Apache it's up to you) setup there few local domains + use it in proxy mode, something like this
server {
  server_name my-store-de.local;
  listen 80;

  location / {
     index index.html;
     proxy_pass http://localhost:4200;
  }
}


Laravel Muito pra Muitos?

Question: Eu tenho este model
public function exercicio()
{
    return $this->belongsToMany(Exercicio::class);
}

e
public function treino()
{
    return $this->belongsToMany(Treino::class);
}

Meu Controller
public function salvarTreino(Request $request)
{

}

Como eu faço para salvar uma lista de exercicio em treino?
no momento está assim
public function salvarTreino(Request $request)
{
    $treino = new Treino();
    $treino->nome = $request->nome;
    $treino->save();
    $treino->exercicio()->attach([1]);
    return response()->json("", 201);

}

porém eu estou passando manualmente o id do exercicio, quero q o usuario possa escolher
Comment: A sua pergunta é facil responder mas, eu precisa ver o layout das tabelas, o model na sua totalidade e sua view para dar uma resposta confiável e fiel ao que você tem! Só lembrando que aqui é StackOverflow em Portuguès!
Comment: Não vi na hora que postei :/ então eu não terei o view, esse controlador retornará um json.
Comment: Tem uma cópia do `Json` e nela vem o código do treino?
Comment: Na função salvarTreino quero que o usuario de um nome ao treino e escolha um exercicio q ja foi cadastrado anteriormente
Comment: Entendi, você está enviando esses dados de qual maneira? ou é essa a sua duvida?
Answer: Você deverá usar checkbox.
Assim, você poderia montar seu formulário de maneira similar a essa:
<form method="POST">
      @foreach($exercicios as $exercicio)

               <input type="checkbox" name="exercicios[]" value="{{ $exercicio->id }}" />

      @endforeach
</form>

Após enviar o submit, você pode capturar os dados no controller dessa forma:
public function salvarTreino(Request $request)
{
    // Valida para saber se os dados estão corretos
    $this->validate($request, [
        'exercicios' => 'required|array'
    ]);

    $treino = new Treino();

    $treino->nome = $request->nome;

    $treino->save();

    // Pega os exercícios selecionados e adiciona-o ao Treino
    $treino->exercicio()->attach($request->exercicios);

    return response()->json("", 201);

}

Se não quiser usar o checkbox, você também poderia usar um select com a opção multiple.

Laravel Muito pra Muitos?


In views formatted as table, columns with taxonomy term fields are sorted according to term ID, not label

Question: In Drupal 8 I have View formatted as table, where user can click to any column header to sort displayed records according to the given field. This works well for numbers (ascending/descending), as well as for plain text (ascending/descending for title or any other text values), records are then sorted correctly alphabetically. But this does not work for taxonomy terms - they are sorted according to taxonomy term ID and not alphabetically according to label.
I.e. I wish to display in the table column with a taxonomy term (only one value is allowed per node) and be able to sort the table alphabetically.
In my use case I have records about plant specimens containing plenty of fields, including e.g. species or life form. These are taxonomy terms. I'm displaying the specimen records in table filterable according to various criteria, e.g. various traits. The table is also sortable according to any column, e.g. species, but in this particular case, it is sorted according to taxonomy term ID and not naturally by label.
I found several answers to similar problems, but nothing exactly fitting my problem. Views Natural Sort module might also help, but its development status is not very promising.
Answer: That's because the stored value of the field is the term ID, the label of it is just how it is displayed.
To sort on the name, you need to instead add a relationship using that field to terms, and then add the name field of that relationship. Then you should be able to sort it as well based on that.
Comment: Thank you. I followed https://www.drupal.org/docs/8/core/modules/views/add-a-relationship-to-a-view, but I wasn't successful. I can add relatioship to e.g. `Taxonomy term referenced from field_life_form`, but it doesn't add anything new when adding new Field, neither to respective options (Field `Content: Life form (Life form)`). So that the result is unchanged. Am I missing some critical point?
Comment: There should be a "Name" field for example in the new "Taxonomy term" or maybe just "Term" group.
Comment: Ah, thank you. This wasn't very obvious, I overlooked that.
Comment: Funny enough this relationship then has to be added to all displays, see [#2921276](https://www.drupal.org/project/drupal/issues/2921276#comment-13202300).


what is the difference between owl:Class and owl:Thing?

Question: I know that owl:Class is a subclass of rdfs:class and that all OWL classes are members of owl:Class. I also know that owl:Thing is at the top of the class hierarchy. So what's the difference between owl:Class and owl:Thing? Isn't owl:Class at the top of the class hierarchy?
Comment: http://answers.semanticweb.com/questions/1974/rdfsclass-vs-owlthing
Answer:
The most basic concepts in a domain should correspond to classes that are the roots of various taxonomic trees. Every individual in the OWL world is a member of the class owl:Thing. Thus each user-defined class is implicitly a subclass of owl:Thing. Domain specific root classes are defined by simply declaring a named class. OWL also defines the empty class, owl:Nothing.

Every class or object is a 'Thing', if you know java, it's like to say every thing is an object, even java.lang.Class inherit from it
Answer: In practice: owl:Class is the URI used to identify the concept of a class in OWL. It's kind of meta information, it's one of the entity type you can use to create your ontology and represent the domain knowledge (there are also owl:ObjectProperty or owl:NamedIndividual types for instance).
owl:Thing is about what your are trying to represent and model. It's the concept that seats in the top of all other concepts and it has to be present on the top by definition.


Calendar - Adding relationship to contextual date filter

Question: I would like to create an Calendar view of some interships for a certain student. But when I change the Contextual (Date) filter to use an relationship no results are shown in the calendar.
When I construct a similar view page in a list instead of an calendar view mode, with identical filters, the results get returned.
Below an image of my attempt to get the relationship in a contextual date filter.
Comment: i'm pretty sure you have to add a date field to the fields and then select it in the calendar settings.
Answer: As J. Reynolds suggested some settings in the Calender Entities must be set. Changing the relationship fixed my problem.


Variables in a regression which could be zero or intentionally missing

Question: I have a very specific regression problem involving a data set with a general pattern of missing data. The data set has several variables and corresponding binary variables determining whether those variables are expected to have a value or not.
Basically if the binary variable has a value of 1, there would be a value (could potentially be zero, positive or negative) for the respective variable. If the binary variable has a value of 0, the corresponding variable would have no value. i.e. NULL or .
The structure of the data set corresponds to the real world scenario where some companies offer certain services while others do not.
<code>An example dataset

Dependent variable - Company Value                  (y1)
Independent variable 1 - Total sales of product A   (x1)
Binary variable 1 - Does the company sell Product A (b1)
Independent variable 2 - Total sales of product B   (x2)
Binary variable 2 - Does the company sell Product B (b2)

y1  x1  b1  x2  b2

30  46  1   .   0
50  0   1   82  1
20  18  1   .   0
40  .   0   0   1
</code>
My actual data set consists of c.1000 records and there are 5 independent variables with their associated binary variables
Is it appropriate to incorporate all of the variables and binary variables into a single regression model and if so, do I add them in as separate terms or as interaction terms? There are potentially 32 combinations of product/service offerings in my data set so I don't see how I could easily split this into multiple models.
Answer: No, it will not work. In linear regression cases with missing are omitted. So all your cases with x1 and x2 omitted will be dropped, resulting in b1 and b2 containing only 1s. Independent variables that are a constant will not stay in the regression. At the end it is just the same as if you only put x1 and x2 in the model.
I think the technique was perhaps misunderstood. Usually, some people will just model b1 and b2 first to see of presence of data or not predicts the dependent variable. Then, another model with x1 and x2 will be done and its interpretation carried out with the first regression's results in mind.
Yet, this is generally considered a biased approach as well. One of such related work is Indicator and Stratification Methods for Missing Explanatory Variables in Multiple Linear Regression by Michael P. Jones. Other work such as directed acyclic graph has also shown that this is a biasing technique.
Perhaps multivariate missing imputation would be useful?
Answer: You should not include both the binary variables and the sales values in your regression model as there is a direct relationship between your binary variables and the sales of the respective products. This violates the independence assumption of the model.
You need to first understand the reason for missing values in the variables x1 and x2. If they are missing because they was no sales or if they are missing because of some data issues.
If they are missing because there was no sales recorded, that means you can impute the missing values by 0. But if they are missing because of some data handling issues, consider building your model on x1,x2 and treat the missing values with some missing imputation techniques before training your model.