Custom plugin definition not loading

Question: I'm trying to create my own plugin type in Drupal 9 but it's not finding my test definition and I can't figure out why.
Here's my services.yaml:
services:
  plugin.manager.reaction:
    class: Drupal\nm_events\ReactionManager
    parent: default_plugin_manager

Here's ReactionManager.php:
<?php

namespace Drupal\nm_events;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;

/**
 * Defines the reaction plugin manager.
 */
class ReactionManager extends DefaultPluginManager {

  /**
   * Constructs a ReactionManager object.
   *
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_h
andler) {
    parent::__construct('Plugin/Reaction', $namespaces, $module_handler, 'Drupal\nm_events\ReactionInterface', 'Drupal\nm_even
ts\ReactionAnnotation');
    $this->setCacheBackend($cache_backend, 'reaction_plugins');
    $this->alterInfo('reaction_info');
  }

}

Here's my Annotation class:
<?php

namespace Drupal\nm_events;

use Drupal\Component\Annotation\Plugin;

/**
 * Declare a class for event reactions.
 *
 * Plugin Namespace: Plugin\Reaction.
 *
 * @see plugin_api
 *
 * @Annotation
 */
class ReactionAnnotation extends Plugin {
  /**
   * The plugin ID.
   *
   * @var string
   */
  public $id;

  /**
   * The human-readable title of the plugin.
   *
   * @var \Drupal\Core\Annotation\Translation
   *
   * @ingroup plugin_translatable
   */
  public $title;

}

And here's my Test plugin (in src/Plugin/Reaction/Test.php
<?php

namespace Drupal\nm_events\Plugin\Reaction;

use Drupal\nm_events\ReactionInterface;

/**
 * Test reaction.
 *
 * @Reaction(
 *   id = "test",
 *   title = @Translation("Reaction for testing reactions")
 * )
 */
class Test implements ReactionInterface {
  public function processEvent($event, $entity) {
    var_export($event->title->value);
  }
}

But when I try to get the definitions:
$ drush cr
 [success] Cache rebuild complete.
$ drush php
Psy Shell v0.11.17 (PHP 8.0.15 — cli) by Justin Hileman
New/Mode base (Drupal 9.5.8)

> $p = $container->get('plugin.manager.reaction')
= Drupal\nm_events\ReactionManager {#2893}

> $p->getDefinitions();
= []

Edit: Here's the interface definition:
<?php

namespace Drupal\nm_events;

use Drupal\Component\Plugin\PluginInspectionInterface;

/**
 * Defines an interface for a Reaction plugin.
 *
 * @see plugin_api
 */
interface ReactionInterface extends PluginInspectionInterface {
  public function processEvent($event, $entity);
}

Answer: I have played a little bit and changed the structure slightly, but finally made it work. Here's my example:
Final structure:
├── pm_test.info.yml
├── pm_test.services.yml
└── src
    ├── Annotation
    │   └── ReactionAnnotation.php
    └── Plugin
        ├── Reaction
        │   └── Test.php
        ├── ReactionInterface.php
        └── ReactionManager.php

services.yml looks like this:
services:
  plugin.manager.reaction:
    class: Drupal\pm_test\Plugin\ReactionManager
    parent: default_plugin_manager

Annotation class(src/Annotation/ReactionAnnotation.php)
<?php

namespace Drupal\pm_test\Annotation;

use Drupal\Component\Annotation\Plugin;

/**
 * Declare a class for event reactions.
 *
 * Plugin Namespace: Plugin\Reaction.
 *
 * @see plugin_api
 *
 * @Annotation
 */
class ReactionAnnotation extends Plugin {

  /**
   * The plugin ID.
   *
   * @var string
   */
  public $id;

  /**
   * The human-readable label of the plugin.
   *
   * @var \Drupal\Core\Annotation\Translation
   *
   * @ingroup plugin_translatable
   */
  public $label;

}

The ReactionInterface (src/Plugin/ReactionInterface.php)
<?php

namespace Drupal\pm_test\Plugin;

use Drupal\Component\Plugin\PluginInspectionInterface;

/**
 * Defines an interface for a Reaction plugin.
 *
 * @see plugin_api
 */
interface ReactionInterface extends PluginInspectionInterface {

  public function processEvent($event, $entity);

}

The ReactionManager(src/Plugin/ReactionManager.php)
<?php

namespace Drupal\pm_test\Plugin;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;

/**
 * Defines the reaction plugin manager.
 */
class ReactionManager extends DefaultPluginManager {

  /**
   * Constructs a ReactionManager object.
   *
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   */
  public function __construct(
    \Traversable $namespaces,
    CacheBackendInterface $cache_backend,
    ModuleHandlerInterface $module_handler,
  ) {
    parent::__construct(
      'Plugin/Reaction',
      $namespaces,
      $module_handler,
      '\Drupal\pm_test\Plugin\ReactionInterface',
      '\Drupal\pm_test\Annotation\ReactionAnnotation'
    );

    $this->alterInfo('reaction_info');
    $this->setCacheBackend($cache_backend, 'reaction_info_plugins');
  }

}

And finally the Test(/src/Plugin/Reaction/Test.php):
<?php

namespace Drupal\pm_test\Plugin\Reaction;

use Drupal\Component\Plugin\PluginBase;
use Drupal\pm_test\Annotation\ReactionAnnotation;
use Drupal\pm_test\Plugin\ReactionInterface;

/**
 * Test reaction.
 *
 * @ReactionAnnotation(
 *   id = "test",
 *   title = @Translation("Reaction for testing reactions")
 * )
 */
class Test extends PluginBase implements ReactionInterface {
  public function processEvent($event, $entity) {
    var_export($event->title->value);
  }

}

At the end, I checked the same way with drush and here's the result:
Psy Shell v0.11.18 (PHP 8.0.24 — cli) by Justin Hileman
Drush Site-Install (Drupal 9.5.9)
> $p = $container->get('plugin.manager.reaction');
= Drupal\pm_test\Plugin\ReactionManager {#7435}

> $p->getDefinitions();
= [
    "test" => [
      "id" => "test",
      "title" => Drupal\Core\StringTranslation\TranslatableMarkup {#7452},
      "class" => "Drupal\pm_test\Plugin\Reaction\Test",
      "provider" => "pm_test",
    ],
  ]

In my opinion the biggest issue with your code was the Annotation. Instead of using
 * @Reaction(
 *   id = "test",
 *   title = @Translation("Reaction for testing reactions")
 * )

it should have been
 * @ReactionAnnotation(
 *   id = "test",
 *   title = @Translation("Reaction for testing reactions")
 * )

after the name of the annotation class. I hope this helps
Comment: Heh) Almost in same time)). Funny, what is a chance of such event could happen.
Comment: Thanks to you both, I switched @Reaction to ReactionAnnotation and it worked, but I'll probably apply the other refactoring too. I'm not sure who to give the bounty to now!
Comment: You may see the entire refactored structure here, including the Test class extension of the PluginBase, so it's fully functional
Comment: @VladMoyseenko - indeed, funny case :D
Answer: You have two options:

A. Adjust Test class with correct annotation id
B. Rewrite your code
to follow common approaches with plugin definition.

A. The Test.php reaction plugin uses wrong annotation name. Instead of @Reaction there sholud be @ReactionAnnotation.
B. Code Refactor.
There are couple of issues with your code:

Rename and move ReactionAnnotation.php from nm_events/src/ReactionAnnotation.php into nm_events/src/Annotation/Reaction.php and adjust namespace to Drupal\nm_events\Annotation and class name to Reaction
Change annotation name in ReactionManager.php from Drupal\nm_events\ReactionAnnotation to Drupal\nm_events\Annotation\Reaction
Change annotation id within Test.php from @ReactionAnnotation to @Reaction

After this adjustments $p = $container->get('plugin.manager.reaction')->getDifitions() should show your test plugin.
However.
When you try to create plugin instance: $test = $container->get('plugin.manager.reaction')->createInstance('test', [])
You will get fatal error Test contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods. To fix it you need extend it with Drupal\Core\Plugin\PluginBase class.
Now instance could be created.
Note.
I would recommend to take a look how other core modules deal with plugins, there are lot's of useful classes out of the box in Drupal.
Here is example: ImageEffectManager.php.
And maybe you also need plugin collection similar to: ImageEffectPluginCollection
To save time you can use drush generate plugin:manager command and create all stuff (including service, annotation, interface, manager, test plugin, plugin interface) using provided wizard.

Custom plugin definition not loading


BACnet devices vs BACnet objects

Question: As a beginner in the world of BACnet I am looking into clarification on BACnet devices.  If I have a system that I want to be compatible with BACnet I am assuming that the system is considered to be an object such as an analog input and that the actual device is a controller or similar that has multiple objects that plug into it.  The ASHREA standard 135-2016 states that there is supposed to be exactly one device object type in each device.  Is each system on a BACnet(ie HVAC, sensors, lighting, doors, or anything else) considered a device or an object? Thanks for any help!
Answer: A system (such as an air handler), is normally controlled via 1 or more devices. Within each device, each real-world piece of data (such as the measured air temperature, or the control signal sent to a motor) would be a input, an output or a value object.
The control logic for a complex system, like an air handler, would be contained within the collection of devices as either fixed firmware, programmable control modules, or through the configuration of some of the complex standard BACnet object types.
For example, control of a damper within an air handler might be handled by a BACnet Loop object (PID loop) tied to an Analog Output object; detection of adverse conditions with the damper might be monitored by a Event Enrollment object; and a log of the damper's performance might be generated by a Trend Log object. And the overall control logic for the air handler might be handled by a collection of Program objects.
Stepping back and looking at a larger part of the HVAC system, cooperation between the air handler, and the VAV boxes which distribute the conditioned air, might be handled by the Program objects in the air handler devices reading and writing input, output, and value objects in the collection of devices which control the VAV boxes.
Answer:
Is each system on a BACnet(ie HVAC, sensors, lighting, doors, or
anything else) considered a device or an object?

Anything within a BACnet network with an "instance number" (device address) is considered a DEVICE.
Despite the fact that each device must have an internal object (of type 8=device) wich represents itself. In other words, the "device object" is just a way to represent the properties of it's device, but it is NOT the device itself, nor the device is an object.
I hope I have clarified your doubt.
Cheers!
Answer: I'll try to narrow the focus a little more to your question; it's kinda slightly incestual in terms of the self-referential (/almost recursive) nature of the model - at least for the one case of a 'device'.
Here's my stab at a simple summary:-
In terms of a explicit/concrete model, BACnet models the essential/high-level pieces (/players or actors within the model) as either an 'object', or a 'property' hanging-off an (/a parent) object (- most likely just one of a related set of properties that happen to belong to the parent object that's referencing it).
Each object belongs to a class/grouping of objects, or rather more correctly, an object-type (- each object is stamped with one of the standard types - in order to identify it's core/base capabilities).
You have physical devices (- "Woo-hoo!  I can touch it!!"  ;D).
And then you have BACnet's logical rendition of a device - it's (effectively) not a standalone item within the BACnet model - at least not as much/like an 'object' or 'property' is - it's more so only of interest in terms of 'how I get there'/location of the objects treasure chest - to side-step the device & jump straight into showing interest in it's contained 'objects' (- "stuff my wonderful [object] children, what about me [the parent device]!?"  ;P); a 'device' in the BACnet world is represented as a specific one of the object-types - a 'DEVICE'-type object (or rather an object whose 'object-type' property is set to 'DEVICE').
So, not only is it more so a gateway to accessing the real items of interest within our OOP (Object Orientated Programming)-like model - the 'objects' & their associated (/child) 'properties'.
But - and here's where it's a little self-referential/egg-&-chicken; it's also represented as an object itself (above & beyond the more typical case if it just been the location where the set of device objects reside upon the BACnet InterNetwork) - that happens to be the keeper of the list of all the objects that relate to that physical device (- at least as portrayed/exposed by the vendor thru the interpretive dance of BACnet & with a slightly vendor proprietary/open rendition of how the values are conveyed), of which, the 'object-list' property of the (logical device/) 'device' object also contains a reference to the 'device' object/itself.  =S
If you read this a few times, it should make some sense; and if it does, then it might at first glance seem a little like nonsense/not immediately intuitive (at least not without seeing it in front of your own eyes).  ;P

BACnet devices vs BACnet objects


How to get the body tag attributes for a specific element

Question: I have to check if a specific element is present under the body tag I have stored at the beginning of execution.
I used below code and stored the attribute value in a String.
Body_class= driver.find_element_by_tag_name('body'). get_attribute('class')

Now I have to check if the 2nd element is present under the same Body_class.

1st element

2nd element

Comment: _I have to check if a specific element is present under the body tag I have stored at the beginning of execution._ for me this sentence is not very much clear, can you please explain a little bit about it?
Comment: Could you provide a complete minimal code
Comment: `.get_attribute('class')` could you explain this
Answer: Does this answer your question? (it's not very clear)
any(
    [
        "2nd element" in element.text
        for element in driver.find_element_by_tag_name("body").find_elements_by_css_selector("div")
    ]
)

This is the HTML file I used
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

1st element

2nd element

Answer: It is not really clear what you are asking, but in case you wanna grab all class attribute value, under body tag then the below code can be used :
Body_class= driver.find_element_by_tag_name('body')
all_tags_with_class = Body_class.find_elements(By.XPATH, "//*[@class]")
for tag in all_tags_with_class:
  print(tag.get_attribute('class'))


how to get nid of a node when user is not on a node page

Question: I had made a custom form and want a field in it that would work as a node reference field. Currently iam not on the node page but i want the nid of nodes of a content type to be the options of the select field which is my node reference field. here is the code for the select field that should work as node reference field.

function formModule_form($form, &$form_state) {

    $form['selectbox'] = array(
    '#type' => 'select',
    '#title' => t('What is your Qualification?'),
    '#required' => TRUE,
    '#options' => array(
      '1' => 'UnderGraduate',
      '2' => 'Graduate',
      '3' => 'Post Graduate',
         ),
    '#description' => t('Choose an option.'),
  );

return $form
}

the #option in the above code should have the nid of nodes.
Comment: if you aren't node viewing, then where are you and how you want determine parent node nid?
Answer: You'll want to Query the database for the nodes you need and then use the results of that query to populate the #options property. Something like this:
<?php
    $result = db_select('node', 'n')
    ->fields('n')
    ->condition('type', 'node_type_name','=')
    ->condition('status', 0,'>')
    ->execute()
    ->fetchAssoc();
?>

You can then use the results of that query easily since it comes back as an associative array. You'll want to specify exactly which fields you want (in your case, probably just title and node. See http://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7 for how to do a proper select.
Answer: You could call a simple query and create the option list something like this
    $result = db_query("SELECT n.nid, n.title FROM {node} n
                         WHERE n.type = 'content type name'");

    $options = array();
   foreach($result as $row) {
      $options[$row->nid] = $row->title;
    }

Now you can assign '#options' => $options
Comment: this code is giving an error:Fatal error: Call to undefined function db_fetch_object() in D:\xampp\htdocs\olinestore\store\sites\all\modules\formModule\formModule.module on line 56
Comment: Sorry that was for drupal 6. for 7 you can use the for loop. have edited the code.
Comment: by the way you dont need the node_load function just directly assign it to $row->title as we are getting it from query. have updated the answer
Comment: you can use the forloop since the result implements the  Iterator interface http://php.net/manual/en/class.iterator.php
Answer: If you're in Drupal 7, I'm a big fan of Entity Field Queries. To get a list NIDs of all nodes of type article, that are published, and have a value in field_foo of "bar":
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_foo', 'value', 'bar', '=')
$result = $query->execute;

EFQs enable you to write queries without knowing the details of the table and column names, and you can also run them with the permissions of a specific user. They return an array of entity IDs so they're ideal for just finding the NID of a node.


Exact meaning of compactly supported smooth function - support can be any measurable compact set?

Question: Let $C_c^\infty(\mathbb{R}^n)$ be the space of compactly supported smooth function on $\mathbb{R}^n$.
Here, I am now a bit curious about the precise meaning of support and smooth.
For example, any measurable $B \subset \mathbb{R}^n$ of finite measure can be approximated by compact subsets.
Let's say $K_m \subset B$ is compact and $\mu(B-K_m) < \frac{1}{m}$ for each $m \in \mathbb{N}$, where $\mu$ is the $n$-dimensional Lebesgue measure.
Then, I remember vaguely that there exists a smooth function $\phi_m : \mathbb{R}^n \to \mathbb{R}$ supported on $K_m$ for each $m \in \mathbb{N}$.
However, $K_m$ can be quite arbitrary and even discrete. In all such cases, how does one define smoothness?
Could anyone please clarify for me?
Comment: A compactly supported function is defined on all of $\mathbb{R}^n$, so we just use the usual notion of smoothness. "Compactly supported" just means that it is zero outside of a compact set (a bit more precisely, the closure of $\{x:f(x)\not=0\}$ is compact).
Comment: But this is all living in $\mathbb{R}^n$ with the usual topology. That's what the notation "$C_c^\infty(\mathbb{R}^n)$" indicates.
Comment: To tell whether $f:\mathbb{R}^n\rightarrow\mathbb{R}$ is in $C_c^\infty(\mathbb{R}^n)$, we do two things: (1) check whether $f$ is smooth in the usual $\mathbb{R}^n$-sense and then (2) check whether $cl(\{x:f(x)\not=0\})$ is compact (again in the usual $\mathbb{R}^n$ sense). Neither of these steps is ambiguous. Note that step (1), where we check smoothness, **does not refer to the support at all**.
Comment: I am particularly concerned about the cses where the support is discrete.
Comment: Also, I would like to make sure that for any compact measurable set $K$, there indeed exists a smooth function supported on $K$. Is this true?
Comment: The claim you're asking about is not true: in order for there to be a smooth function whose support is $K$, $K$ must be appropriately nice. In particular, since smooth implies continuous, $K$ can't be discrete (and so your particular concern doesn't arise).
Comment: That is where I am confused. Because on discrete sets, you can impose the discrete topology to define continuity and so on..
Comment: Yes, as the subspace topology of $\mathbb{R}^n$, a discrete subset has the discrete topology..
Comment: Maybe a  example could help: $$f(x)=\begin{cases}1,\quad x=0;\\ 0,\quad |x|\geq 0;\\\frac{1}{1+\exp\left(\frac{1-2|x|}{x^2-|x|}\right)},\ \text{otherwise}\end{cases}$$
Answer: Based on the comments above, it seems you're misparsing "smooth function with compact support" as "function with compact support which is smooth on its support." This is not what it means: the requirements for $f:\mathbb{R}^n\rightarrow\mathbb{R}$ to be in $C_c^\infty(\mathbb{R}^n)$ are precisely that

$f$ be smooth in the usual $\mathbb{R}^n$-sense, and

$cl(\{x:f(x)\not=0\})$ be compact (also in the usual $\mathbb{R}^n$-sense).

In particular, the support of such an $f$ can never be discrete since for any smooth (or even continuous) $f:\mathbb{R}^n\rightarrow\mathbb{R}$ the set $\{x: f(x)\not=0\}$ will be open. In order to be the support of a continuous (let alone smooth) function, a compact set $K$ must satisfy $$K=cl(int(K)).$$ It's a good exercise to check whether this necessary condition is also sufficient.


Change screen animation when back button is pressed

Question: When you go press '<' to pop back on your navigation controller previous screen, the screen animates by sliding to the right.
I'd like to change the back behavior so instead of it sliding to the right, it slides to the left instead.
Any ideas how I could achieve this?
Comment: You write a _custom transition animation_. Google it...
Comment: https://stackoverflow.com/questions/10553264/popviewcontrolleranimated-custom-transition-animation
Answer: You need a custom back button. On your destination view controller create a custom UIButtonItem, set it as your leftBarButtonItem and perform an animation on button's action.
<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "back", style: .plain, target: self, action: #selector(self.back))
}

@objc func back(){
    //Create and set up the animation
    let transition = CATransition()
    transition.duration = 0.4
    transition.type = kCATransitionMoveIn
    transition.subtype = kCATransitionFromRight//animates from right to left
    self.navigationController?.view.layer.add(transition, forKey: nil)//adds the animation
    self.navigationController?.popViewController(animated: true)
}
</code>
Comment: thanks so much! I ended up using kCATransitionPush instead but this is great, ty!!!


log 0xffff base 0xff is not 2

Question: I tested on wolfram alpha and rust language and the log(0xff, 0xffff), is not 2 but 0xff power 2 equals 0xffff. The result is 2.00141... Why does this happen?
I have a 4 byte number and I want to get the amount of bytes that it needs (e.g. lower than 0xff needs 1 byte, lower than 0xffff needs two bytes, etc.). I thought logarithm was the right way to solve this.
Comment: Do not confuse 0xff which is $255 = 2^8-1$ with $2^8$ and 0xffff which is $2^{16}-1$ with $2^{16}$.  Note that $2^8$ when squared results in $2^{16}$ but $(2^8-1)^2$ results in $2^{16}-2^9+1$, not $2^{16}-1$
Answer: If $\log_{2^8-1}(2^{16}-1)$ was $2$, it would mean that $(2^8-1)^2=2^{16}-1$ which is obviously not the case. ($255^2\not= 65535$)
Why not just initialise a counter to $0$, and then shift your value by 8 bits (up to $4$ times), increasing the counter every time you get a nonzero result?
If you insist on logarithms (even though they are probably too slow for what you need), take the base 0x100 = $256$. Then take the integer part and add $1$ - this will give you the number of bytes needed. In other words, the formula is, for $x\ne 0$: $d=\lfloor\log_{256}(x)\rfloor+1$.
Example: $\lfloor\log_{256}(\text{0x72A943})\rfloor+1=\lfloor2.855\ldots\rfloor+1=2+1=3$.
Comment: Too much computers make me miss that last digit :P Thank you. And you're probably right that it might be faster to do a for loop or 3 if statements instead of a logarithm

log 0xffff base 0xff is not 2


Disabling authoring information in Omega 3.x does not work from content type; how can I disable it?

Question: I see no way of successfully disabling, through the user interface, the author information, wheb using an Omega 3.x sub-theme. The standard method of disabling it from the content type settings is not functional.
So is my only option to use a theme suggestion?
Comment: If this was a bug, I believe it is now fixed, because I am able to turn off the display of author information using the checkbox in the content type settings.
Answer: Don't know how exactly it looks in your Omega theme, but in Zen you just remove/change the following snippet in templates/node.tpl.php (or templates/node--content_type.tpl.php):
<?php if ($display_submitted): ?>

    <?php print $submitted; ?>

<?php endif; ?>

In Bartik it's equivalent would be:
<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php print $submitted; ?>

<?php endif; ?>

Comment: Thanks Maciej,
But what im trying to find is a way to make it work without needing the "theme suggest".  I am aware of this method, but because i am trying to build a replicatable template, i need this setting stored in the dB somewhere.  I believe this is an issue with the Omega theme not having conditional logic for the $submitted value.  While all other themes seem to have this.  I will take it up with the dev, to make this an option in the Omega settings or to use the Content Type configuration.
Answer: Well in omega you can still disable author and date in your content-type settings, but what if you only want to disable one portion of it? for example just the author name? go ahead and copy node.tpl.php from omega > templates folder into your subtheme folder then find this part:
      <?php if ($display_submitted): ?>
       <?php print $date; ?> -- <?php print $name; ?>
      <?php endif; ?>

as you can see in omega unlike other themes it renders as two different variables: $date and $name . so you can delete <?php print $name; ?> or <?php print $date; ?>
make sure after copying node.tpl.php empty your cache.


Extract email from text usin notepad++ and regexp

Question: I have a lot of text simmilar to this
Джамал Выбрать...АссистентБухгалтерВедущий специалистВладелецДокторДиректорЗаведующийЗам.директораГл.редакторГл.продавецГл.бухгалтерГен.директорГл.специалстИнженерКадровикПомощникПродавецПоварМенеджерНачальник отделаУправляющийУчредитель 923 230 24 54 922 009 72 00 firstname.lastname@example.com

I only need the email from this line, so firstname.lastname@example.com
How do i do this with notepad and regex?
I found this \b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
But its not excatly wha tim looking for
Comment: Use case-insensitive checkbox. It should work.
Comment: `[A-Z]{2,4}`  is very poor to match TLDs, see official list: https://data.iana.org/TLD/tlds-alpha-by-domain.txt
Answer: You need to add lowercase alphabets range inside the character class or turn on the case insensitive i modifier to match both upper and lowercase alphabets.
\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b

OR
(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

DEMO
Comment: That regex, finds all the emails, but how do i separate the selected emails from all the junk?
Comment: This works half way, i also need to extract it somehow, so i only see the emails
Comment: use a capturing group like `(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b)` , now `$1` contains all the email addressses.
Answer: \S+?@\S+?\.\S+

Try this.This will get the email.See demo.
http://regex101.com/r/iM2wF9/18


Cannot "find" Repeater inside a nested Accordian

Question: I have an Accordion nested inside an Accordion.  I wasn't sure you could even do that, but you can!  It works. However...
In the inner Accordion, I have a repeater. When I try to set the RepeaterName.DataSource, I am getting a null reference exception.  I tried to force the issue by using this.FindControl, but still no joy.  The code behind just isn't seeing the Repeater inside the nested Accordion.
I'm frustrated, but not surprised.
I really don't want to "un-nest" these.  What I have is an Accordion of Authors, and then inside each Author Pane I have another Accordion of their works.
So, we have
Author1

Article 1
Article 2

Author2

Article 1
Article 2
Article 3

etc.
EDIT: Adding markup and code behind
                        <AjaxToolkit:AccordionPane runat="server" ID="JohnBunyanPane">
                             John Bunyan
                        <Content>
                        <AjaxToolkit:Accordion ID="JohnBunyanInternalAccordion" runat="server"
                            SelectedIndex="-1"
                            CssClass="accordion"
                            HeaderCssClass="accordionHeader"
                            HeaderSelectedCssClass="accordionHeaderSelected"
                            ContentCssClass="accordionContent"
                            AutoSize="None"
                            FadeTransitions="true"
                            TransitionDuration="250"
                            FramesPerSecond="40"
                            RequireOpenedPane="false"
                            SuppressHeaderPostbacks="true">
                            <Panes>
                                <AjaxToolkit:AccordionPane runat="server" ID="GraceAboundingPane">
                                         Grace Abounding
                                    <Content>

                                        <asp:UpdatePanel ID="GraceAboundingUpdatePanel" runat="server">
                                            <ContentTemplate>
                                                <asp:Repeater ID="GraceAboundingRepeater" runat="server">
                                                    <ItemTemplate>

                                                        <asp:Label ID="GraceAboundingBody" runat="server" Width="100%"  Text='<%# Eval("Body")%>'></asp:Label>

                                                        <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/separator.jpg" />

                                                    </ItemTemplate>
                                                </asp:Repeater>
                                            </ContentTemplate>
                                        </asp:UpdatePanel>

                                    </Content>
                                </AjaxToolkit:AccordionPane>
                            </Panes>
                        </AjaxToolkit:Accordion>
                        </Content>
                    </AjaxToolkit:AccordionPane>

Here is the call to populate it:
            try
        {
            myDataAdapter.Fill(myDataSet);
            DataTable myDataTable = myDataSet.Tables[0];

            var childAccordionPane = (AccordionPane)this.FindControl("JohnBunyanPane");
            var repeater = (Repeater)childAccordionPane.FindControl("GraceAboundingRepeater");
            //Repeater myRepeater = (Repeater)childAccordionPane.FindControl("GraceAboundingRepeater");
            //GraceAboundingRepeater.DataSource = myDataTable;
            //GraceAboundingRepeater.DataBind();

            repeater.DataSource = myDataTable;
            repeater.DataBind();
        }

Comment: Can you provide a little more code?
Comment: Can you access inner accordion?
Answer: Your FindControl probably can't see into the AccordionPane.  You'll need to traverse down through the top-level (parent) AccordionPane.
Something like this:
var childAccordionPane = (AccordionPane)parentAccordionPane.FindControl("childAccordionPaneId");

var repeater = (Repeater)childAccordionPane.FindControl("repeaterId");

We can make it compile and work if given your markup to verify the strings representing each of the control IDs is correct.
Comment: Garrison,  sorry for the delay.  I've been unavailable for a few days here.  Conceptually I see what you're saying.  When I try to implement it, "(AccordianPane)" is not being recognized in the code behind.  Says it's not a recognized namespace.  Do I need a using statement to grab the library?
Comment: Okay... I got the reference, so it builds.  Still getting a null reference exception, but I'm liking this solution, and will continue to work with it till I get it to go.
Comment: If you give me your ASPX markup, I should be able to help you find it exactly.


The interior of a connected set in $\mathbb R^k$

Question: Is the interior of a connected set in $\mathbb R^k$ connected?
Comment: No, as answers below suggest. But, however you may want to prove that closure of connected sets are connected. (and that, interior of connected sets in $\Bbb{R}$ are connected.)
Answer: No. If $X\subset\mathbb R^2$ is the union of two closed disks of radius $1$, one with center at $(1;0)$ and another with center at $(-1;0)$, then $X$ is connected but its interior is not.
Comment: @user43901: Both closed and open in what space? The interior of $X$ is trivially closed and open in itself, and it is not closed in $X$.  Neither of those facts have bearing on why the interior is disconnected.  It is a union of $2$ disjoint nonempty open subsets.
Comment: how do you show that the interior is both closed and open? It is eas to see by visualization, but is there a formal way to see this?
Answer: No.
Let
$A_1=\{(x,y)|x\leq0,y\leq0\}$ (The third quadrant and the positive x-axis) and
$A_2=\{(x,y)|x\geq0,y\geq0\}$.(The first quadrant and the positive x-axis).
$A_1\cup A_2$ is connected. Their interior is the first and third quadrants.
Proof by visualization.
Answer: Nope... Pick two tangent balls...
Comment: BTW: probably a better example is two non-touching disks connected by a segment of line.


Using a bind variable in an INSERT statement

Question: I need to ask the user for a variable, use that variable in a SELECT statement, and then use that same variable in an INSERT statement. Right now I am just trying to get using the variable for an INSERT to work:
var num NUMBER(10)
exec num := &ExpNum
INSERT INTO ExpDet
VALUES(num, &LineNum, &Descrip, &Amt, &HCode, &SubCode)

When I run this, I get an error saying

Bind variable 'num' is not declared.

Do I have the right idea here, or do I need to use some other method entirely?
Answer: A working example:
SQL> create table expdet
  2    (num number,
  3     linenum number,
  4     descrip varchar2(20),
  5     amt number,
  6     hcode number,
  7     subcode number);

Table created.

SQL> var num number
SQL> exec :num := &expnum
Enter value for expnum: 100

PL/SQL procedure successfully completed.

SQL> insert into expdet values
  2    (:num, &linenum, &descrip, &amt, &hcode, &subcode);
Enter value for linenum: 1
Enter value for descrip: 'a'
Enter value for amt: 1
Enter value for hcode: 1
Enter value for subcode: 1
old   2:   (:num, &linenum, &descrip, &amt, &hcode, &subcode)
new   2:   (:num, 1, 'a', 1, 1, 1)

1 row created.

SQL>


Matrix exponentials, computing the product of $\exp(-iBt)$ and $\exp(-iB^{-1}t)$.

Question: Suppose I have some matrix exponential $U(t)=\exp(-iAt)$ where $t$ is some real valued number, $A$ is a hermitian matrix (so $U(t)$ is unitary) where $A=B+B^{-1}$ and $B$ is unitary. Because $B$ and $B^{-1}$ commute we have
$$ U(t)=\exp(-iBt).\exp(-iB^{-1}t)$$ Can this expression for $U(t)$ then be simplified any further without diagonalising $B$ and $B^{-1}$?
Comment: Even in 1-d, I see no good way of simplifying $e^{-ibt}e^{-it/b}$...
Comment: Since $B$ is unitary, $B^{-1} = B^\dagger$. This means that $\exp(-iB^{-1}t) = \exp(iBt)^\dagger$. Writing $U(t) = \exp(-i B t)\exp(iBt)^\dagger$ at least makes it clear that $U$ is unitary.
Comment: @amitsett Yes. And since $\Lambda$ is diagonal, $\Lambda + \Lambda^\dagger = 2\mathrm{Re}[\Lambda]$. Not sure how much this helps, but it's neat.
Comment: @eyeballfrog true. So lets say I diagonalised $B=V\Lambda V^\dagger$ then I should get
\begin{align}
U(t)&=V \exp(-i \Lambda t) V^\dagger (V \exp(i \Lambda t) V ^\dagger)^\dagger\\
&=V \exp(-i \Lambda t) V^\dagger V \exp(-i \Lambda^\dagger t) V^\dagger\\
&= V \exp(-i (\Lambda + \Lambda^\dagger)t)V^\dagger

\end{align}
Since $B$ is unitary its eigenvalues have modulus 1 and hence $\Lambda$ is unitary as well.
Answer: One obvious simplification is
\begin{align}
U(t)
&=\exp(-itB)\exp(-itB^{-1})\\
&=\exp(-it(B+B^{-1}))\ \text{ (because $B$ commutes with $B^{-1}$)}\\
&=\exp(-it(B+B^\ast))
\end{align}
but you probably already know this.
Comment: Yep. I guess to be more clear I'm trying to break it up into exponentials of matrices that are easier to exponentiate. I could diagonalise $B$ such that $B=V\Lambda V^\dagger$ then

$$\exp(-itB)=V\exp(-it \Lambda)V^\dagger$$

However I want to check if there's any further tricks I could use before finding eigenvectors and eigenvalues.


Where should one go for Magento Support?

Question: After migrating from stackoverflow.com/tags/magento and the old community forum at magento.com, it seems that we are now left with two separate and capable forums for Magento support:
https://magento.stackexchange.com/
and
http://community.magento.com/t5/Programming-Questions/bd-p/devqa
My questions are:
Which forum should be in primary use?
Is there any advantage of one forum over the other?
Are certain types of questions better suited on either forum?
Is there a different visitor persona on either forum or are they similar?
How about engagement levels?
Also if anyone could compile a list of awesome Magento support resources delineated by user experience and role that could be super helpful.

Magento community forums are also very focused on technical issues. See list of forum categories:
Comment: It's more for these kinds of 'soft' questions, ones that are related to forum policy etc. On the main forum we focus on technical questions
Answer: For a list of resources check out https://github.com/aleron75/mageres by Alessandro Ronchi.
This forums primary focus is technical questions. All others are better off on the community.magento.com forum
Comment: It seems that the community.magento.com forums share a very similar focus on technical issues. See added screenshot.
Comment: Thanks for that list.


Como mostrar próximo campo quando usuário clicar no botão verde

Question: Tenho vários campos que estão escondidos e só devem aparecer quando o usuário clicar no botão ver ao lado do primeiro campo.
A minha ideia inicial seria quando a pessoa clicar no botão verde (after do .newField) ele adicionasse a classe newField ao próximo campo.
(não tem problema se o botão verde ficar duplicado, é claro que se conseguirem deixar só no último é melhor.)

.c-form .hide {
  display: none;
}

.newField {
  display: block!important;
  position: relative;
}

.c-form .newField:after {
  font-family: "Font Awesome 5 Free";
  font-weight: 900;
  content: "\f138";
  font-size: 35px;
  cursor: pointer;
  color: #1fa050
}

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">

  <form id="formsugestoes" method="post" enctype="multipart/form-data">

Fale conosco

    <input type="hidden" name="setor" value="">

    <input type="hidden" name="assunto" value="formsugestoes">

    Nome: *<input class="text" type="text" name="nome" value="" required>

    E-mail: *<input class="text" type="email" name="email" value="" required>

    Cidade: *<input class="text" type="text" name="cidade" value="" required>

    Telefone:<input class="text mask-tel" type="text" name="telefone" value="" required>

    Mensagem:<textarea class="text" name="mensagem" value=""> </textarea>

<input type="submit" name="enviar" value="Enviar" class="btnEnviar hide lado" />

  </form>

Comment: No click basta validar as condições pra identificar os campos que não ser exibidos e remover deles a classe "hide", e setar o focus no "próximo" campo
Answer: Você está criando um pseudo-elemento no label, assim não tem como detectar via JavaScript o clique exato no botão, o clique vai ficar ativo no label por inteiro, o que tira a intenção do clique no botão. Até porque se clicar no botão vai focar o campo do nome, o que não faz sentido.
Sugiro que crie o botão em um span fora do label para que fique independente, desta forma você pode capturar o clique apenas no botão sem focar o campo. E também ir clonando o botão e adicionando após o próximo label até chegar no botão Enviar.
Ficaria assim:

$(document).on("click", "span.newField", function(){
   var clone = $(this).clone();
   var next = $(this).next();

   $(this)
   .prev()
   .removeClass("newField hide");

   if(next[0].tagName != "DIV"){
      $(this)
      .next()
      .addClass("newField")
      .removeClass("hide")
      .after(clone);
   }else{
      $(this)
      .next()
      .find("input")
      .removeClass("hide");
   }

   $(this).remove();
});
.c-form .hide {
  display: none;
}

.newField {
  display: inline-block!important;
  position: relative;
}

.c-form span.newField:after {
  font-family: "Font Awesome 5 Free";
  font-weight: 900;
  content: "\f138";
  font-size: 35px;
  cursor: pointer;
  color: #1fa050;
  display: inline-block;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">

  <form id="formsugestoes" method="post" enctype="multipart/form-data">

Fale conosco

    <input type="hidden" name="setor" value="">

    <input type="hidden" name="assunto" value="formsugestoes">

    Nome: *<input class="text" type="text" name="nome" value="" required>

    E-mail: *<input class="text" type="email" name="email" value="" required>

    Cidade: *<input class="text" type="text" name="cidade" value="" required>

    Telefone:<input class="text mask-tel" type="text" name="telefone" value="" required>

    Mensagem:<textarea class="text" name="mensagem" value=""> </textarea>

<input type="submit" name="enviar" value="Enviar" class="btnEnviar hide lado" />

  </form>

Answer: Você faz um listener do botão, e via javascript remove a class ".hide".

Essa função é genérica, dentro do seu código não consegui identificar qual botão você vai clicar para mostrar os inputs, mas para ter uma base, isso deve lhe ajudar.
Comment: O btn na verdade é um pseudo-elemento ::after na label... é um elemento construido no CSS ele só aparece depois que a página renderiza pois ele não está no html
Comment: Exatamente, e por este motivo não consegui fazer funcionar.


How can I use the QUERY() function to create subtotals for each group based on a specific column within the QUERY() function's results?

Question: I am pulling the table in the screenshot below with the following query:
=QUERY(SIPARISLER; "select C, D, E, F where G = 'KESİN' order by C DESC"; 1)
Query Result
But I want to get a subtotal based on the ORDER NO value as follows. How can I do that?
What I want to do!
INPUT (obtained from query):

+
A
B
C
D

1
FIRMA
ORNER NO
BCE NO
QTY

2
SLP
231561
30-129
50

3
SLP
231561
30-302
30

4
SLP
231784
30-116
100

5
OFM
312
30-123
3

6
DELTA
233391
60-120
6

EXPECTED OUTPUT:

+
A
B
C
D

1
FIRMA
ORDER NO
BCE NO
QTY

2
SLP
231561
30-129
50

3
SLP
231561
30-302
30

4
SUBTOTAL

80

5
SLP
231784
30-116
100

6
SUBTOTAL

100

7
OFM
312
30-123
3

8
SUBTOTAL

3

9
DELTA
233391
60-120
6

10
SUBTOTAL

6
Comment: [duplicate of this post here](https://www.reddit.com/r/googlesheets/comments/1bbzd5d/how_do_i_make_a_subtotal_with_the_query_function/)
Answer:
Here's one approach you may test out:
<code>=let(Σ;query(SIPARISLER; "select C, D, E, F where G = 'KESİN' order by C DESC";0); Λ;index(Σ;;2);
    reduce(tocol(;1);unique(Λ);lambda(a;c;vstack(a;filter(Σ;Λ=c);hstack("SUBTOTAL";;;sum(ifna(filter(index(Σ;;4);Λ=c))))))))
</code>


Tough Analysis Question Involving Dense Subset of $R$ and Convergence of Measurable Functions

Question: It's a bulky four part question, most of which I've already worked through, but towards the end it begs for the construction of sets based on triangle functions and rectangular functions, which has so far strained my abilities. Here is the question:

Let $\{r_n\}$ be a dense subset of $\Bbb R$. Let $g_n:\Bbb R \rightarrow [0,1]$ be continuous $\forall n\in\Bbb N$. Assume $g_n(r_n)=1$  $\forall n$. Assume $\sum_{n\in\Bbb N} m(\{g_n>0\})<\infty$. Let $g=\sum_{n\in \Bbb N}g_n$.

Show that $g$ is defined and finite almost everywhere.
Show that $g$ is not bounded on any open interval (non-trivial)
Let $g_n$ be a triangle function with height 1 and base $\frac 1 {2^n}$. Explicitly construct a set $F \subset [0,1]$ such that $m([0,1]\setminus F)<\frac 1 8$ and that $g_n \rightarrow 0$ on $F$ almost everywhere.
Let $g_n$ be a rectangular function with height 1 and base $\frac 1 {2^n}$. Explicitly construct a set $F \subset \Bbb R$ such that $m(\Bbb R \setminus F)<\frac 1 8$ and a continuous function $f$ on $\Bbb R$ where $g=f$ on $F$.

So yes it's a long one. My work so far towards 1 and 2 are posted below. Being checked over would be great!
3 and 4 have stumped me pretty good, I am having trouble relating a triangle/rectangle function to the given conditions.

My Solutions in an answer
Answer: My Solutions
1 and 2. First off, assumptions:

Let $\{r_n\}$ be a dense subset of $\Bbb R$.
Let $g_n:\Bbb R \rightarrow [0,1]$ be continuous $\forall n\in\Bbb N$.
Assume $g_n(r_n)=1$  $\forall n$.
Assume $\sum_{n\in\Bbb N} m(\{g_n>0\})<\infty$.
Let $g=\sum_{n\in \Bbb N}g_n$.

Defined: Since $g_n$ maps to $[0,1]$, $g$ must be greater than or equal to zero since it is the sum of a bunch of positive/zero values. It will either converge to some number or diverge (to infinity). In either case it is defined since there is no alternating behavior. $\Box$
Finite AE: Since $\sum_{n\in\Bbb N} m(\{g_n>0\})< \infty$, there must be some point in the sequence for which the tail becomes arbitrarily small, for some $N \in \Bbb N$. I.e. when $k \ge N$ $\Rightarrow \sum_{n=k}^\infty m(\{g_n> 0\}) < \epsilon$.
Now notice $m(\bigcup_{n=N}^\infty\{g_n>0\}) \le \sum_{n=N}^\infty m(\{g_n>0\})
< \epsilon$. Now that we observe that $\bigcup_{n=N}^\infty\{g_n> 0\}$ is less than epsilon we can remove this from our consideration. So examining our function on the set $\Bbb R \setminus \bigcup_{N}^\infty\{g_n> 0\}$ we have that $g= \sum_{n=1}^\infty g_n= \sum_{n= 1}^{n— 1} g_n$.
So $g$ is finite almost everywhere. (does this make sense?)
$\Box$
Show not bounded on open interval: Consider some arbitrary open interval $I=(a,b)$. Inside $I$ exists some elements of $\{r_n\}$, say $r_i$ and $r_j$, where $a<r_i<r_j<b$ WLOG. Since $\{r_n\}$ is dense you can always find another $r_k$ in between, i.e. $a<r_i<r_k<r_j<b$ etc etc etc. You can continue to repeat this process to see that there are infinite number of $r_n$'s within $(a,b)$.
This implies that $\sum_{n=1}^\infty g_n$ is not bounded since $g_n(r_n)=1$ at each $r_n \in (a,b)$ and there are an infinite number of $r_n$'s within $(a,b)$ due to density illustrated above. (does this make sense?)
$\Box$
Answer: Hint for (3) and (4): you can in fact make all but finitely many $g_n$ equal to $0$ on $F$.
Comment: Sorry, I did mean $F$.  $g_n$ is a triangle function in (3), but the set where is is nonzero is disjoint from $F$.  The fact that $r_n$ is dense is no problem, because $F$ is not an open set.
Comment: By $E$ do you mean $F$? Also, I'm not quite sure what you mean, I was under the impression that $g_n$ had to be a triangle function defined for all the $r_n$ in the dense subset.


Downsampling from 1 month to multiple months in Pandas

Question: I have a dataset that spans 36 months. I want to downsample for periods of 3 months. I use:
df = df.resample('3M').sum()

However, when I look at the output, it does not seem to separate the period of months correctly. For example, here's 36 months of data:
1901-01-01    266.0
1901-02-01    145.9
1901-03-01    183.1
1901-04-01    119.3
1901-05-01    180.3
1901-06-01    168.5
1901-07-01    231.8
1901-08-01    224.5
1901-09-01    192.8
1901-10-01    122.9
1901-11-01    336.5
1901-12-01    185.9
1902-01-01    194.3
1902-02-01    149.5
1902-03-01    210.1
1902-04-01    273.3
1902-05-01    191.4
1902-06-01    287.0
1902-07-01    226.0
1902-08-01    303.6
1902-09-01    289.9
1902-10-01    421.6
1902-11-01    264.5
1902-12-01    342.3
1903-01-01    339.7
1903-02-01    440.4
1903-03-01    315.9
1903-04-01    439.3
1903-05-01    401.3
1903-06-01    437.4
1903-07-01    575.5
1903-08-01    407.6
1903-09-01    682.0
1903-10-01    475.3
1903-11-01    581.3
1903-12-01    646.9

If I resample this in periods of 3 months, I get the following:
1901-01-31     266.0
1901-04-30     448.3
1901-07-31     580.6
1901-10-31     540.2
1902-01-31     716.7
1902-04-30     632.9
1902-07-31     704.4
1902-10-31    1015.1
1903-01-31     946.5
1903-04-30    1195.6
1903-07-31    1414.2
1903-10-31    1564.9
1904-01-31    1228.2

If we look at the first element, instead of summing the first 3 months, it outputs only the first month. After that, it takes the following three months and starts summing them and repeats this until it reaches the end of the dataset. The final point in the output only sums the last two points in the dataset. Not to mention the dates are all messed up. I'm expecting:
1901-03-31
1901-06-30
1901-09-31

and not
1901-01-31
1901-04-30
1901-07-31
1901-10-31

Answer: You need parameter closed='left' it looks for the latest possible start, because default parameter closed='rigth' looks for the earliest possible start.
Docs of resample:

closed : {'right', 'left'}
Which side of bin interval is closed. The default is 'left' for all frequency offsets except for 'M', 'A', 'Q', 'BM', 'BA', 'BQ', and 'W' which all have a default of 'right'.

df = df.resample('3M',closed='left').sum()
print (df)
               col
1901-03-31   595.0
1901-06-30   468.1
1901-09-30   649.1
1901-12-31   645.3
1902-03-31   553.9
1902-06-30   751.7
1902-09-30   819.5
1902-12-31  1028.4
1903-03-31  1096.0
1903-06-30  1278.0
1903-09-30  1665.1
1903-12-31  1703.5

df = df.resample('3M').sum()
#df = df.resample('3M',closed='right').sum()
print (df)
               col
1901-01-31   266.0
1901-04-30   448.3
1901-07-31   580.6
1901-10-31   540.2
1902-01-31   716.7
1902-04-30   632.9
1902-07-31   704.4
1902-10-31  1015.1
1903-01-31   946.5
1903-04-30  1195.6
1903-07-31  1414.2
1903-10-31  1564.9
1904-01-31  1228.2


Renaming geometry column in GeoDataFrame with more than one geometry

Question: I have this issue with dataframes with more than one column of type geometry. My dataframe looks like this:
New_zone_short_edges =

       id  vertex_id                    point1  \
1   A1                2  POINT (119.79008 28.35047)
3   A1                4  POINT (122.85067 44.85106)
5   A2                1  POINT (138.79141 26.48802)
7   A2                3  POINT (141.73386 44.89716)
13   A3               5   POINT (68.47770 44.07370)
11   A3               3   POINT (46.63571 51.16575)

                      point2    length                    midpoint
1   POINT (122.85067 28.08433)    3.072140  POINT (121.32038 28.21740)
3   POINT (119.92314 44.71798)    2.930553  POINT (121.38690 44.78452)
5   POINT (141.92247 26.26168)    3.139230  POINT (140.35694 26.37485)
7   POINT (138.79141 44.89716)    2.942450  POINT (140.26263 44.89716)
13   POINT (65.42208 48.14785)    5.092692   POINT (66.94989 46.11078)
11   POINT (46.59798 47.65744)    3.508504   POINT (46.61685 49.41159)

with the following info:
<class 'geopandas.geodataframe.GeoDataFrame'>
Int64Index: 206 entries, 1 to 425
Data columns (total 6 columns):
 #   Column      Non-Null Count  Dtype
---  ------      --------------  -----
 0   id          206 non-null    object
 1   vertex_id   206 non-null    int64
 2     point1    206 non-null    geometry
 3     point2    206 non-null    geometry
 4     length    206 non-null    float64
 5   midpoint    206 non-null    geometry
dtypes: float64(1), geometry(3), int64(1), object(1)
memory usage: 11.3+ KB
None

Now, if my dataframe were a pandas dataframe, I could rename an individual column using for instance:
New_zone_short_edges = New_zone_short_edges.rename(columns ={'point1':'new_point'})

But since I wish to rename a geometry, I need to do something like this:
New_zone_short_edges.rename_geometry('<the new name>', inplace=True)

This is problematic since I cannot choose which geometry to rename. Is there something similar to do as with pandas?
Splitting my dataframe in three, changing the geometry name and then merging with the other seems like a tedious thing to do if it can be avoided. I have looked everywhere for an alternative without any luck. I have read somewhere that it is bad practice to have several geometries in a single dataset, but for my purposes it is, at least for calculations, imperative to have it this way.
Any idea is welcome. Thanks!
Answer: Renaming works fine as your first try:
>>> df.rename(columns ={'point1':'new_point'})
    id  vertex_id                   new_point                      point2    length                    midpoint
1   A1          2  POINT (119.79008 28.35047)  POINT (122.85067 28.08433)  3.072140  POINT (121.32038 28.21740)
3   A1          4  POINT (122.85067 44.85106)  POINT (119.92314 44.71798)  2.930553  POINT (121.38690 44.78452)
5   A2          1  POINT (138.79141 26.48802)  POINT (141.92247 26.26168)  3.139230  POINT (140.35694 26.37485)
7   A2          3  POINT (141.73386 44.89716)  POINT (138.79141 44.89716)  2.942450  POINT (140.26263 44.89716)
13  A3          5   POINT (68.47770 44.07370)   POINT (65.42208 48.14785)  5.092692   POINT (66.94989 46.11078)
11  A3          3   POINT (46.63571 51.16575)   POINT (46.59798 47.65744)  3.508504   POINT (46.61685 49.41159)
>>> df.rename(columns ={'point1':'new_point'}).info()
<class 'geopandas.geodataframe.GeoDataFrame'>
Int64Index: 6 entries, 1 to 11
Data columns (total 6 columns):
 #   Column     Non-Null Count  Dtype
---  ------     --------------  -----
 0   id         6 non-null      object
 1   vertex_id  6 non-null      int64
 2   new_point  6 non-null      geometry
 3   point2     6 non-null      geometry
 4   length     6 non-null      float64
 5   midpoint   6 non-null      geometry
dtypes: float64(1), geometry(3), int64(1), object(1)
memory usage: 508.0+ bytes

It seems you might be confused by the fact that rename_geometry does not require you to specify which geometry column to rename − that's because it sets the  active geometry column.

A GeoDataFrame may also contain other columns with geometrical (shapely) objects, but only one column can be the active geometry at a time. To change which column is the active geometry column, use the GeoDataFrame.set_geometry() method.

It's basically the column that is returned by the df.geometry accessor, and the column you passed as geometry= argument to the GeoDataFrame constructor.
For example setting the point1 column that way:
>>> df.set_geometry('point1').rename_geometry('new point').info()
<class 'geopandas.geodataframe.GeoDataFrame'>
Int64Index: 6 entries, 1 to 11
Data columns (total 6 columns):
 #   Column     Non-Null Count  Dtype
---  ------     --------------  -----
 0   id         6 non-null      object
 1   vertex_id  6 non-null      int64
 2   new point  6 non-null      geometry
 3   point2     6 non-null      geometry
 4   length     6 non-null      float64
 5   midpoint   6 non-null      geometry
dtypes: float64(1), geometry(3), int64(1), object(1)
memory usage: 508.0+ bytes

This is useful for plotting with GeoDataFrame.plot for example. The arguments you specify decide the plotting color, and the shape(s) are decided by the geometry column.
The issue you run into if you rename without rename_geometry is that your GeoDataFrame then loses track of its active geometry column:
>>> df.set_geometry('point1').rename(columns={'point1': 'new point'}).plot()
[...]
AttributeError: No geometry data set yet (expected in column 'point1'.)

So you need to either

rename your active geometry column with .rename_geometry() and other columns with .rename()
rename all columns with .rename() and then set the active geometry again with .set_geometry(new_column_name)
Comment: Thank you! As you said, I got confused there.


Wrapper classes and generic clarifications in Java

Question: In the below code, the line System.out.println(sumInteger(bigs) == sumInteger(bigs)); displays as false. But when again we compare the another Integer wrapper classes System.out.println(bc == ab);, it returns true. Why is the comparison of wrapper classes false in the first case and true in the second case?
import java.util.Arrays;
import java.util.List;

public class Arrays {

    public void array1() {

        List<Integer> bigs = Arrays.asList(100,200,300);
        System.out.println(sumInteger(bigs) == sum(bigs)); // 1. Output: true
        System.out.println(sumInteger(bigs) == sumInteger(bigs)); //2. Output: false

        Integer ab = 10;
        System.out.println(ab == 10); //3. Output: true
        Integer bc = 10;
        System.out.println(bc == ab); //4. Output: true
    }

    public static int sum (List<Integer> ints) {
        int s = 0;
        for (int n : ints) { s += n; }
        return s;
    }

    public static Integer sumInteger(List<Integer> ints) {
        Integer s = 0;
        for (Integer n : ints) { s += n; }
        return s;
    }

    public static void main(String[] args) {
        Array tm = new Array();
        tm.array1();
    }
}

Comment: The first one does and `int` to `int` comparison (after unboxing the first operand). The second one does `Object` comparison (with `==`).
Answer:    System.out.println(sumInteger(bigs) == sum(bigs)); // 1. ***Output: true
   System.out.println(sumInteger(bigs) == sumInteger(bigs)); //2. ***Output: false

sumInteger() returns an Integer and sum() returns an int, so you are testing the the equality of an Integer with an int, which causes the Integer to be auto-unboxed, so you end up comparing an int with an int. Both ints now have the same value, hence 'true'.
sumInteger() returns an Integer, calling sumInteger() again returns an Integer. These two Integers are separately created objects, yet both hold the same internal value. When you use '=='' compare them it compares the references and seeing as how each object was created independently the references are not equal, hence 'false'. Had you wanted to test the value for equality you would have needed to use the .equals() method.
Comment: It might be worth pointing out that `sumInteger(bigs) == sumInteger(bigs)` is not *guaranteed* to yield false - that depends on the value returned from the method. `Integer`s up to a certain value are cached, and in that range the reference comparison would be `true`.
Comment: (which is the reason for `bc == ab` being `true`)


Push não vai para remoto e não acusa erro

Question: Tou fazendo git push -f origin "nome do branch" e não vai de forma alguma para o repositório remoto. Sendo que não aparece erro nenhum, também alterei alguns configs de buffers, o que faço para resolver?
Counting objects: 267, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (192/192), done.
Writing objects: 100% (267/267), 14.28 MiB | 0 bytes/s, done.
Total 267 (delta 62), reused 195 (delta 31)

Comment: Estranho não ter relatado nenhum erro.Tenta clona o repositório novamente e substitui seus arquivos alterados, comita e depois faz o push.
Answer: Primeiro, você está tentando fazer um push -f, verifique se possui autorização para isso.
Segundo, seus commits totalizam 14MB, verifique se possui arquivos grandes e se seu repositório remoto suporta arquivos com esses tamanhos.
Verifique se seus repositórios remotos estão configurados corretamente: git remote -v deve exibir algo do tipo:
origin  email@example.com:gabrsar/dotfiles (fetch)
origin  email@example.com:gabrsar/dotfiles (push)

Verifique se os endereços estão corretos.
Caso tudo isso esteja correto, tente o seguinte:
Tente fazer o mesmo processo sem o -f, e verifique se apresenta algum erro.
O parâmetro -v fará um push verboso, mostrando todas as mensagens de erro. Verifique se é exibido algum erro ou aviso (warning).
Se possível cole o resultado do git push origin nome_do_branch -fv. para que possamos ajudar melhor.


Given a Flow Network and an Edge e, Describe an Algorithm that Determines Whether e Crosses Some Minimum Cut

Question: Given a flow network G = (V,E) with a source s, a sink t and and edge e = (u,v), describe an algorithm that determines whether the edge e crosses some minimum cut (S,T).
My first idea was to calculate a maximum flow f and then decrease the capacity of e by some a > 0. Then we check if the residual graph has a path from s to t (it means that we can increase the flow f even more).
Now, if there is no path from s to t, we can be sure that e doesn't cross any minimum cut.
The problem is with the other direction. If there is a path from s to t, it might be because we have created a new minimum cut that e crosses by not being careful when choosing a > 0.
So how do I pick a small enough a > 0 ?
Answer: Its a cool question.
"
My first idea was to calculate a maximum flow f and then decrease the capacity of e by some a...
"
Did you mean increase? because the flow cant grow if you decrease the capacity..
Any way:
Run algo to find max flow and suppose flow is F.
Check if the flow flowing on e equals to its capacity,if not,then we return false.
Does it mean that if it is equals,e must cross some min cut?
Suppose e=(u,v):Because of the edges rule,the flow enters u must leave completely,
it means that for every cut you will take,will have some ecrooses it and e=(x,y),
we will have some path from u->v....->x  or y->....u->v.
if we will delete this edge(e),and the flow will be decreased,it means that we cant,in any-way
 return the flow that came to x(or flow that left y cant find a way to the sink now) as it were before. it means e was in some min cut.
if the flow doesnt change,it only means that we found another way to return the flow that we "lost",so that means that  e doesnt belong to any min cut because its not affects any Min cut capacity whitch equals to the max flow.
Your intuition to the problem is good,but see that it wont work because the increase/decrease of e can lead to no way,because there is a simple example where you change capacity of e and there is still no path from s to t in the residual network,but e still belong to some min cut.


Execute a set of lines from another R file

Question: I'm not sure if this is even possible, but I'm looking for something similar to defining regions in R script. I would like to execute a pre-specified set of lines from another R script. I know I can run the entire file using source(filename) but instead of running the entire file, I would like to only run a few lines in the file.
Is it possible for me to define regions or anything similar in the file and then execute it from another file?
Any help would be much appreciated.
Comment: Seems you should be writing R functions and building packages.
Answer: If you're worried about the region of interest will be shifted once you add new lines upstream, then an alternative (or slightly modified) version of MrFlick's answer would be read as:
sourcePartial <- function(fn,startTag='#from here',endTag='#to here') {
  lines <- scan(fn, what=character(), sep="\n", quiet=TRUE)
  st<-grep(startTag,lines)
  en<-grep(endTag,lines)
  tc <- textConnection(lines[(st+1):(en-1)])
  source(tc)
  close(tc)
}

Now you need to put a small, unique hash tag just above and below of the region of interest. Such as "#from here" and "#to here"
Answer: This doesn't sound like a super-safe idea given how easily line numbers can change during edits. Seems like it would be safest to split up your larger sourced file into smaller parts that are safer to include and run. But you could do something like this
sourcePartial <- function(fn, skip=0, n=-1) {
    lines <- scan(fn, what=character(), sep="\n", skip=skip, n=n, quiet=TRUE)
    tc <- textConnection(lines)
    source(tc)
    close(tc)
}

here we use scan() to read lines from a file. See the documentation for skip= and n= at ?scan to see how to skip a certain number of lines and stop reading after a certain number. So
sourcePartial("test.R", 4, 11)

would run lines 5-15 from "test.R"
Comment: I suppose you could write something a bit more general if the poster were willing to break the source file up into sections with a common (commented) header label, say `#header: Region_4`, You could read with one pass to find the lines with headers and then pick out the target section based on name or sequence number.
Comment: thanks for your answer, I think the generalized version is even better.
Comment: Well, if that's what you wanted it would have been better to describe that in the original question. The other version makes even more assumptions about file contents.


Executar comandos do Prompt do Windows e guardar a saída num arquivo de texto

Question: Tenho um programa que faz lançar um comando do Prompt do Windows.
Eu quero copiar a saída deste comando e guardar num arquivo de texto.
Exemplo: O comando é ipconfig e eu quero que a saída seja copiado para um arquivo.
Comment: Veja como [aqui](https://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx)
Answer: Usa > para redireccionar o output.
ipconfig > file.txt

Comment: Perfeito @dcastro! "ipconfig > "Ambiente de Trabalho"\ip.txt" assim fica gravado no meu Ambiente de Trabalho, mas se o Windows tiver em Inglês, não ficará gravado. Como poderei colocar para todos?
Comment: @DonVitoCorleone, você pode usar `%userprofile%\Desktop` que será direcionado para a área de trabalho, independente de idioma. Note que `%userprofile%` é uma variável do Windows.
Comment: @DonVitoCorleone Ja fizeste essa mesma pergunta anteriormente: http://pt.stackoverflow.com/questions/65376/obter-caminho-do-desktop
Comment: Não amigo @dcastro... Anteriormente era para colocar no código do C#, agora é para escrever na Linha de Comandos...
Comment: Já está a funcionar, consegui arranjar outra forma! Obrigado a todos!
Comment: Amigo @dcastro, isto está a copiar tudo em linha, não é possível fazer os parágrafos?
Answer: Você pode fazer isso usando a classe Process:
public static string ExecutarCMD(string comando)
{
    using (Process processo = new Process())
    {
        processo.StartInfo.FileName = Environment.GetEnvironmentVariable("comspec");

        // Formata a string para passar como argumento para o cmd.exe
        processo.StartInfo.Arguments = string.Format("/c {0}", comando);

        processo.StartInfo.RedirectStandardOutput = true;
        processo.StartInfo.UseShellExecute = false;
        processo.StartInfo.CreateNoWindow = true;

        processo.Start();
        processo.WaitForExit();

        string saida = processo.StandardOutput.ReadToEnd();
        return saida;
        }
    }

Nota: Declare os namespaces System.Diagnostics e System.IO.
Use assim:
string saida = ExecutarCMD("ipconfig");
File.WriteAllText("NomeArquivo.txt", saida);


Drupal 6 term based view not translating vocabulary terms

Question: I have a dilly of a pickle here. Please do help if you can.
I have a site that uses internationalization translation to translate content.
Some of the content is not translating.
Specifically a "view" that is of type "term".  All my other views are translating correctly.
Here is the configuration page of my vocabulary

Here is an example of the term translations.

Here is the view for the taxonomy term countries.
The view here seems to not have the correct  filters available. For node based views, you can add a filter called "node translation-language" and set it to filter on the current language.  But with views based on taxonomies there is no equivalent "term translation-language".  How are we supposed to filter out the extra taxonomy terms from the view.

This is an example of a view based on nodes that has the filter "term translation-language"
My term based view is missing this filter

Here is the Countries view in action...notice that Haiti shows up for every language in it's non translated form (note that those are 3 different Haiti's)

Can someone please explain what I need to do to get a term based view translating and not showing extra terms?
Thanks,
David
Answer: I think what you are trying to do is something along these lines:

Which here gives me:

And when I change the language, eg:

it then gives me:

I've set my vocabulary here up like so:

with translations (quickly done just for this so pardon the potential sloppiness)

and nodes translated like this (pardon the silly titles):

so if you are getting different results, check to make sure all of the various places you can set a language are similar.


Probability of 1x six from seven dice?

Question: Could someone help me with how the following is calculated:
What is the probability of rolling a die seven times and getting at least one six?
My instinct told me it would be $1/6+\cdots + 1/6$ but this ends up being $7/6$.
Comment: I've posted an answer that not only gives a correct method, but explains why the method proposed in the question is incorrect even when one throws the die only twice, so that the number purporting to be the probability is not more than $1$.
Comment: And, as Chris Cutler's answer points out, the _average_ number of $1$s that you get when you throw a die seven times is indeed $7/6$.
Answer: Consider a slightly different question:
With two fair coins what's the probability of at least one head.
By your reasoning the probability would be $\frac{1}{2} + \frac{1}{2} = \frac{2}{2} = 1$.
That means it's certain to happen: bet your house against a penny.  You can't lose! right?
However, for this example we can simply list all the possibilities:
HH, HT, TH, TT
All these outcomes are equally likely so the real probability is $\frac{3}{4}$
I can calculate this by noting that I win every time except TT and the probability of TT is:
$$\frac{1}{2} \times \frac{1}{2} = \frac{1}{4}$$
So the probability of at least one head is:
$$1 - \frac{1}{4} = \frac{3}{4}$$
As we got by listing all possibilities.
Now to return to the original question the probability of getting at lest one 6 from 7 dice is:
One minus the probability of getting no 6.
$$Answer = 1 - {\left( \frac{5}{6} \right)}^7 = \frac{6^7 - 5^7}{6^7} = \frac{279936 - 78125}{279936} = \frac{201811}{279936} \approx 0.7209$$
If instead you wanted the probability of exactly one six from seven dice then consider the specific case first dice is a six and in the next 6 rolls there is no six.
The probability of this would be:
$$\frac{1}{6} \times {\left( \frac{5}{6} \right)}^6$$
And since we don't care about the order of these rolls the six could be on any of the seven rolls.  Giving a probability of:
$$7 \times \frac{1}{6} \times {\left( \frac{5}{6} \right)}^6 \approx 0.3907$$
Hope that helps clear up any misunderstanding.
Answer: HINT:
The probability of getting no six $p=\left(\frac56\right)^7$
The probability of getting at least one six $=1-p$
Comment: What I don't get is, the probability of getting at least one six across all the dice is independent per dice- so why is it not 1/6 + 1/6.... etc (besides the fact that sum is greater than 1)
Comment: @user997112, what is the probability of exactly one six or exactly two sixes?
Answer: The quickest way to obtain this probability is as follows:
Subtract from $1$ the probability of getting NO rolls of a $6$: The probability of getting at least one six is equal to $$1 - \left(\frac 56\right)^7$$
Comment: What I don't get is, the probability of getting at least one six across all the dice is independent per dice- so why is it not 1/6 + 1/6.... etc (besides the fact that sum is greater than 1)
Comment: Think about it for the case of two dice, instead of being $\frac{2}{6} = \frac{12}{36}$, the probability is only $\frac{11}{36}$.  That's because we don't want to count the case where both dice are sixes twice.
Comment: Think about a similar problem with coins...or using fewer dice.
Comment: If you want to add probabilities, you need to add "getting exactly one six with 7 dice" + "getting exactly two sixes using 7 dice" + ... + "getting exactly seven sixes when rolling 7 dice". This will not total nor exceed a probability of $1$, but requires *a lot* more work than if you simply compute the probability of obtaining zero 6's when rolling seven dice, and subtracting that total from one.
Comment: Thanks, @Amzoti! Hope your work day has ended!?
Comment: @amWhy: just got home and ate dinner! Thanks! However, mentally, work never really ends. :-)
Comment: @amWhy:  $\ddot\smile$
Answer: Your instinctual answer, $\frac16+\cdots+\frac16=\frac76$, is the expected number of sixes rolled. The reason why we can add up all the fractions to calculate the expectation is called the linearity of expectation. In fact, linearity doesn't even require that the events are independent!
What you've proved is that the expected number of times an event happens is different from the probability that it happens at least once.
Answer: Is the probability of getting at least one "$1$" when the die is thrown twice equal to $1/6+1/6$?
There the answer is no.
One time in six you get a $1$ the first time you throw the die.
One time in six you get a $1$ the second time you throw the die.
But sometime you get a $1$ both times, and that must be taken into account.
You get 36 possible outcomes:
$$
\begin{array}{c|cccc}
11 & 12 & 13 & \cdots & 16 \\
\hline
21 & 22 & 23 & \cdots & 26 \\
31 & 32 & 33 & \cdots & 36 \\
\vdots & \vdots & \vdots & & \vdots \\
61 & 62 & 63 & \cdots & 66
\end{array}
$$
The first horizontal row contains the six cases where the first trial gives you a "$1$".  There are six of those.
The first vertical column contains the six cases where the second trial gives you a "$1$".  There are six of those.
There's one case in which both trials give you a $1$.
If you just say the number of trials where you get a $1$ is $6+6$, that one gets counted twice.  So it's $6+6-1$.  The probability of getting at least one "$1$" is therefore
$$
\frac{6+6-1}{36} = 0.305555\ldots
$$
The rule that $\Pr(A\text{ or }B)=\Pr(A)+\Pr(B)$ is valid only if the events $A$ and $B$ are mutually exclusive, i.e. they cannot both happen.  But the event of getting a $1$ on the first trial and the event of getting a $1$ on the second trial are not mutually exclusive: they can both happen.
Now do it by a different method:
The probability of getting no $1$ the first time is $5/6$.
The probability of getting no $1$ the second time is $5/6$.
The probability of getting no $1$s in the sequence of two trials is therefore $$\frac56\cdot\frac56 = 0.69444444\ldots$$
The probability of getting at least one $1$ in those two trials is therefore
$$
1-\left(\frac56\cdot\frac56\right) = 1-\frac{25}{36} = \frac{11}{36} = 0.30555555\ldots
$$
When you write
$$
\frac16+\frac16+\frac16+\frac16+\frac16+\frac16+\frac16,
$$
you neglect the possibility of getting a $1$ more than once.  Therefore this method will give you a wrong answer.
When you write
$$
1-\left(\frac56\cdot\frac56\cdot\frac56\cdot\frac56\cdot\frac56\cdot\frac56\cdot\frac56\right),
$$
you don't neglect anything and you get a right answer.

Probability of 1x six from seven dice?


Proving the equivalence of a pdf with a log-normal distribution

Question: I have the following function normalised to 1 on $(0, \infty)$:
$$
g(x) = \frac{e^{-\left(\mu + \frac{\sigma^2}{2}\right)} e^{-\frac{(\mu -\text{Log}[x])^2}{2 \sigma ^2}}}{\sigma  \sqrt{2 \pi }}
$$
which, after multiplying by $\frac{1}{x}e^{\left(\mu + \frac{\sigma^2}{2}\right)}$ gives a log-normal distribution.
The n-th moment of g is $e^{n \mu + \frac{n^2\sigma ^2}{2} + n \sigma^2}$, which again is the same as for the log-normal to the factor $e^{n \sigma^2}$.
It seems like I might be missing some theory here but how can I show that $g(x)$ and the log-normal distribution are essentially the same? I can make them overlap in the plot...
(EDIT)
The reason I think $g(x)$ and the log-normal distribution must be somehow related is the following. Suppose I set the first two moments, $m_1$ and $m_2$, of these distributions to same values. For $g(x)$ I obtain the following scale and shape parameters:
$$
\mu_g = \log{\frac{m_1^4}{m_2^{3/2}}}\\
\sigma_g = \sqrt{\log{\frac{m_2}{m_1^2}}}
$$
For the log-normal distribution I get the following:
$$
\mu_{LN} = \log{\frac{m_1^2}{m_2^{1/2}}}\\
\sigma_{LN} = \sigma_g
$$
After substituting the above parameters to their respective distributions I calculate the ratio:
$$
\frac{g(x)}{f_{LN}(x)} = x \frac{m_2}{m_1^3} \left( \frac{m_1^2}{m_2} \right)^{\log{ \left( \frac{m_2}{m_1^3} x \right)} / \log{ \left( \frac{m_2}{m_1^2} \right)}} = 1
$$
which I find quite surprising especially because the two distribution differ by a factor that is not a constant but depends on $x$. I wonder whether this is a case of a more general rule?
Comment: what do you mean they are essentially the same? they are clearly not? you are multiplying by something which is not a constant.
Comment: i dunno how data has anything to do with this?

you gave me 2 different density functions and tried to convince me they are the same function. I dunno what you mean by they exactly overlap. they may be very close, but your equations say they are not the same?
Comment: @Lost1 I can plot them such that they exactly overlap. Shape parameters are equal and only $\mu$ of g and log-normal differ. Additionally, when I fit the two distributions to the same set of data, the best fit is such that they both exactly overlap. Also the parameter such as Bayesian information criterion for both fits is exactly the same. This made me wonder whether there's something that makes these two distributions connected. Rescaling parameters for instance?
Comment: @Lost1 well, it seems they are. See my EDIT in the above question.
Answer: For every $a\gt0$ and every $b$, consider the function $h_{a,b}$ defined on $x\gt0$ by
$$
h_{a,b}(x)=\exp(-a(\log x)^2+(b-1)\log x).
$$
Let $h:x\mapsto g(x)/x$ where $g$ is the function in the first displayed formula of the question. Then:

The function $h$ a multiple of $h_{1/2\sigma^2,\mu/\sigma^2}$.
For every $c$, $x^ch_{a,b}(x)=h_{a,b+c}(x)$.

Thus, the function $g$ is a multiple of the function
$$h_{1/2\sigma^2,1+\mu/\sigma^2}.
$$
In other words, $h$ being the lognormal density with parameters $(\mu,\sigma^2)$ implies that $g$ is proportional to the lognormal density with parameters $(\mu+\sigma^2,\sigma^2)$.


Cmake: use add_custom_command to copy binary to specific location failed when location doesn't exist

Question: I'm trying to copy all the binaries generated by cmake to a specific directory. I don't want to use EXECUTABLE_OUTPUT_PATH, keeping them in the building tree make development easier.
So I use add_custom_command to add a post build copy
<code># set the final binary dir
set(PROJECT_BINARY_DIR ${PROJECT_SOURCE_DIR}/bin)

# get name and location of binary, namecan change with os (cf. ".exe" suffix on windows)
GET_TARGET_PROPERTY(EXAMPLE_BIN_NAME example LOCATION)
# copy bin to binary folder
ADD_CUSTOM_COMMAND(TARGET example
          POST_BUILD
          COMMAND ${CMAKE_COMMAND} -E copy ${EXAMPLE_BIN_NAME} ${PROJECT_BINARY_DIR}/.
)
</code>
The problem is that at the first build the "bin" folder doesn't exist (the copy fail), but the "bin" folder is created just after. So at the second build the copy works.
Is there a way to make the custom command create the bin folder and then copy the binary ?
Or is it possible to have two EXECUTABLE_OUTPUT_PATH with cmake ?
Thanks !
Comment: See https://stackoverflow.com/questions/6594796/how-do-i-make-cmake-output-into-a-bin-dir
Answer: Just make sure that the target location "bin" exists before invoking the copy command, i.e.:
<code>ADD_CUSTOM_COMMAND(TARGET example
          POST_BUILD
          COMMAND ${CMAKE_COMMAND} -E make_directory ${PROJECT_BINARY_DIR}
          COMMAND ${CMAKE_COMMAND} -E copy ${EXAMPLE_BIN_NAME} ${PROJECT_BINARY_DIR}/.
)
</code>
Comment: Yes, that was my workaround, but I was hoping for a better solution. Thank you anyway for your answer !


Heroku Push rejected: fails when building dependencies if Grunt is one of them - "(node) warning: Recursive process.nextTick detected..."

Question: I'm quite puzzled since I pushed to Heroku with no problem twice today before it started rejecting any git push attempt. (I added comments to the log below.)
//Everything is smooth and then...
remote: -----> Building dependencies
remote:        Installing node modules (package.json + package-lock)
remote:        (node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
remote:        (node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
remote:        (node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
remote:        (node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
//hundreds of that line above again and again...
// Then this line below ONCE
remote:        npm(node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
//Then hundreds of that other line again...
remote:        (node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
remote:        (node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
//And eventually...
remote:
remote:        util.js:35
remote:        var str = String(f).replace(formatRegExp, function(x) {
remote:        ^
remote:        RangeError: Maximum call stack size exceeded
remote:
remote: -----> Build failed
remote:
remote:        We're sorry this build is failing! You can troubleshoot common issues here:
remote:        https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote:        If you're stuck, please submit a ticket so we can help:
remote:        https://help.heroku.com/
remote:
remote:        Love,
remote:        Heroku
remote:
remote:  !     Push rejected, failed to compile Node.js app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to nameOfProject.
remote:
To https://git.heroku.com/nameOfProject.git
 ! [remote rejected]     master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/nameOfProject.git'

Locally, I can npm rebuild with no problem and run the app too.
None of my util.js file has var str = String(f).replace(formatRegExp, funct... anywhere, in fact, I can't find that line of code.
From what I read in other questions, the "(node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral." could be related to Grunt, but I didn't touch my Gruntfile.js for days if not weeks so I doubt that would be the issue.
EDIT
Turns out that Grunt IS causing the problem. If we take every Grunt related dependency out of our package.json file, we can push to Heroku.
So my guess is that Grunt updated something, that thing is out of our control and it somehow doesn't work wit Heroku.
For now, our solution is to not push Grunt to heroku since we don't need it there anyway. But it would be great to understand what's going on. If you experience the same issue or have a better understanding please share!
Here is our package.json:
{
  "name": "ourName",
  "version": "0.0.1",
  "dependencies": {
    "@google/maps": "^0.3.1",
    "angular-i18n": "1.6.6",
    "angular-touch": "1.6.6",
    "async": "0.2.8",
    "bluebird": "^3.5.1",
    "bwip": "~0.6.3",
    "cloudinary": "1.0.1",
    "connect-flash": "0.1.0",
    "connect-mongodb": "1.1.4",
    "cookie": "^0.3.1",
    "cron": "1.0.1",
    "ejs": "0.8.4",
    "express": "3.2.5",
    "express-subdomain": "1.0.5",
    "feed-read": "0.0.1",
    "file-system": "^2.2.2",
    "google-auth-library": "^0.10.0",
    "googleapis": "^17.1.0",
    "http-auth": "1.2.2",
    "ipware": "^1.0.0",
    "jade": "~0.27.4",
    "js2xml": "0.0.6",
    "jsonify": "0.0.0",
    "lame": "1.2.1",
    "mailchecker": "3.0.27",
    "mailchimp": "*",
    "mailchimp-api-v3": "1.7.0",
    "moment": "2.1.0",
    "mongodb": "1.3.10",
    "mongoose": "3.6.13",
    "netmask": "^1.0.6",
    "newrelic": "~1.3.1",
    "node-schedule": "1.2.3",
    "nodemailer": "2.4.2",
    "nodetime": ">=0.8.4",
    "object-assign": "^4.1.1",
    "octobat-npm": "^2.0.1",
    "optimist": "0.3.4",
    "password-generator": "2.1.0",
    "pdfkit": "~0.2.7",
    "request": "2.81.0",
    "rollbar": "2.0.0",
    "stripe": "4.24.0",
    "temp": "~0.6.0",
    "time": "0.8.0",
    "timekit": "*",
    "touch": "^3.1.0",
    "twilio": "^2.11.1",
    "uglify-js": "1.3.3",
    "underscore": "^1.8.3",
    "v8tools": "*",
    "wav": "0.1.2",
    "when": "1.7.1",
    "xml2js": "0.4.17"
  },
  "devDependencies": {
    "angular-momentjs": "^0.2.2",
    "autoprefixer": "^7.1.2",
    "chai": "*",
    "cssnano": "^3.10.0",
    "database-cleaner": "0.7.0",
    "expect.js": "*",
    "factory-lady": "0.1.0",
    "grunt": ">=0.4.1",                 //REMOVED AND THEN IT WORKS
    "grunt-contrib-concat": "^1.0.1",   //REMOVED AND THEN IT WORKS
    "grunt-contrib-imagemin": "^1.0.1", //REMOVED AND THEN IT WORKS
    "grunt-contrib-jshint": "^1.1.0",   //REMOVED AND THEN IT WORKS
    "grunt-contrib-uglify": "^3.0.1",   //REMOVED AND THEN IT WORKS
    "grunt-hash": "^0.5.0",             //REMOVED AND THEN IT WORKS
    "grunt-postcss": "^0.8.0",          //REMOVED AND THEN IT WORKS
    "lodash": "1.2.x",
    "mocha": "1.10.0",
    "moment": "^2.1.0",
    "pixrem": "^3.0.2",
    "vows": ">=0.6.4",
    "zombie": "2.0.x"
  },
  "engines": {
    "node": "0.10.x",
    "npm": "3.9.2"
  },
  "scripts": {
    "test": "NODE_ENV=test vows test/api/*.js test/web/*.js --spec",
    "start": ""
  }
}

Comment: can you update your question and post your `package.json` too
Comment: Thanks @antzshrek, I updated the question as we now know that Grunt clearly is the dependency causing problem. (Which is a step forward, yay!)
Comment: Do you have any `util.js` in your project?
Answer: I see your problem might be coming from this very lines I comment at the ending of your package.json
  "engines": {
    "node": "0.10.x", //here
    "npm": "3.9.2"
  },
  "scripts": {
    "test": "NODE_ENV=test vows test/api/*.js test/web/*.js --spec",
    "start": "" //here
  }
}

On the engines your version of node can result to that error, so I suggest you change your engines to this below:
"engines": {
  "node": "*", //this should make your app run on the most recent version of node
  "npm": "*" //this should make your app run on the most recent version of npm

Then is your scripts, you still didn't specify your entry point from your start. Your scripts should be something like this:
  "scripts": {
    "test": "NODE_ENV=test vows test/api/*.js test/web/*.js --spec",
    "start": "node index.js" //this is where you should place your entry point.
  }

Note: It is not a most to use index.js, you can write your entry point to the app with the name you called it, maybe app.js or server.js or whatever your called it.
And I also notice you didn't have a "main": "" in your package.json.
Implement these corrections to your package.json and your problem should be fixed


Get next node in nodequeue

Question: I have a nodequeue named work_order.
If I am in a page which belongs to this queue, is there a way I can get the next node that will be there in the nodequeue?
I looked at most of their API functions, but I did not find one that does this.
I am using drupal 7
Comment: Are you talking about the module named Nodequeue or the queue for cron jobs?
Comment: @Paul module named nodequeue
Answer: Should be something like getting the nid of the current node and then being $nid the node id of the current node and $sqid the queue id:
$pos = nodequeue_queue_position('work_order', $nid);
$nodes = nodequeue_load_nodes($sqid, FALSE, $pos+1, 1, TRUE);

It's untested so maybe you need to tweak the position and so.
Comment: sorry, but what is `$sqid` here?
Comment: It should be the id of your nodequeue, "work_order"
Comment: I have a valid `$nid`. In the nodequeue admin section my queue's machine name is `work_order`. However when I pass both to `node_queue_position`, I get `$pos` empty...
Answer: My solution is bit different from pcambra's. Actually I implement looking for previous and next node like this:
$pos = (int)nodequeue_get_subqueue_position($sqid, $node->nid);
$node_prev = nodequeue_load_nodes($sqid, FALSE, $pos - 2, 1);
$node_next = nodequeue_load_nodes($sqid, FALSE, $pos, 1);

Note: The previous is $pos-2, not $pos-1. The reason is that the returned position of nodequeue_get_subqueue_position is starting from 1, and the argument of position in nodequeue_load_nodes is from 0! The same reason for the next node.
Finally, the node you got is stored in the returned array. For example you can retrieve its nid like this:
$next_node_nid = $node_next[0]->nid;

Answer: I got it working using custom_pagers module.
https://www.drupal.org/project/custom_pagers
It actually quite simple once you apply the needed patches as the module is not well maintained.
https://www.drupal.org/node/262854
apply these patches -
https://www.drupal.org/node/1288368#comment-6429832
https://www.drupal.org/node/1346194#comment-5881226
Now, just enable the module, create a new custom pager
pager position : sideblock
pager node list : view >> nodequeue_#
to get the correct nodequeue - admin/structure/nodequeue
just hover over the edit link to get the machine id

Get next node in nodequeue


show images for taxonomy terms in referenced node

Question: D7 question. I need to have a "clients" taxonomy with an image extra field on each term (the client's logo). Then I have a "project" content type. Projects belong to specific clients, ie the project content type has a term reference field to the client taxonomy.
When I click on a "project", I want to see the clients logo and not (only) the term name. This seems possible by following these instructions http://drupal.org/node/1224916, but this article is misleading: it suggests having an entity-reference field on the project content type instead of a term-reference. The problem with that approach is that when you connect a term and content by an entitity field, these two are not connected as far as taxonomy is concerned. So you lose all taxonomy functionality.
Answer: I beleive you can achieve this with the normal "Term reference" field, and a custom template file: field--field_my_custom_field.tpl.php in your theme folder which renders the image. You can access the value of your custom field through $items[$key]['#options']['entity']->field_my_custom_field where $key is the array index (if you have more than 1 value for this field, first item is index 0, second is 1 etc, usually you should just loop through the $items like foreach($items as $item) and then you can do $item['#options']['entity']->field_my_custom_field)
You may need to have a field.tpl.php (copy from root/modules/field/theme then duplicate it and rename the duplicate into field--field_my_custom_field.tpl.php) in your theme folder in order for it to work (or templates folder inside your theme folder, basically same folder as your custom field--field_my_custom_field.tpl.php) (Not 100% sure, but this was the case in Drupal 6)
API documentation for field.tpl.php
This may also come in handy: taxonomy-term.tpl.php
Sorry for unsure answer with a lot of unknowns, just trying to help :)