How to debug EntityMalformedException?

Question: I've got fatal error EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7700 of .\includes\common.inc) when trying to access user/xyz.
I tried to retrieve info about the malformed node at line 7700, where the error message is built, thinks like :
if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
 dpm($info);// or dpm($entity);
 throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
}

dpm($entity) returns an unexpected user object, and $info a huge qty of things.
Could somebody put me on the right way ?
I already read whatever I could find about Missing bundle property errors, but none helped solving.
dpm($entity) returns
uid (String, 2 characters ) 70
name (String, 9 characters ) John
pass (String, 55 characters ) $S$DUwPuOuDPiDL4nRTYXqc7a5uOfMKey7pyhOFUEKka1XM...
mail (String, 30 characters ) firstname.lastname@example.com
theme (String, 0 characters )
signature (String, 0 characters )
signature_format (String, 13 characters ) filtered_html
created (String, 10 characters ) 1396286331
access (String, 10 characters ) 1397146661
login (String, 10 characters ) 1396513460
status (String, 1 characters ) 1
timezone (NULL)
language (String, 2 characters ) fr
picture (NULL)
init (String, 30 characters ) email@example.com
data (Array, 5 elements)
roles (Array, 1 element)
og_user_node (Array, 0 elements)
message_subscribe_email (Array, 1 element)
field_bio (Array, 0 elements)
field_name_first (Array, 1 element)
field_name_last (Array, 1 element)
field_facebook_url (Array, 0 elements)
field_linkedin_url (Array, 0 elements)
field_twitter_url (Array, 0 elements)
user_trusted_contacts (Array, 1 element)
group_group (Array, 1 element)
group_access (Array, 1 element)
metatags (Array, 0 elements)
rdf_mapping (Array, 3 elements)
realname (String, 13 characters ) John Doe
content (Array, 13 elements)
entity_view_prepared (Boolean) TRUE
privatemsg_disabled (Boolean) FALSE

Comment: @Kojo The cause is actually a really simple one...something is calling `entity_extract_ids('node', $var);`, but instead of a node object for `$var`, it's passing a user object. If you have any custom or dev version contrib modules, try disabling them one by one to see it you can find the culprit
Comment: Yikes. `dpm(debug_print_backtrace());` will be invaluable here. You can see what module started it all off by following the functions back to the beginning of the request
Comment: I meant the it is basically checking if the bundle information exist before throwing the exception.
If you could post the output of dpm($entity) (with the sensitive information blurred of course), that will help others to see what's wrong.
Comment: No worries, if you can get xdebug installed and configured with `xdebug.collect_params = 4` that will also make your life a lot easier
Comment: This is usually a pretty low level one that you can find out just by dpm()'ing the $entity. Make sure you are passing the entity itself -- and not a set of entities that entity load functions return.
Comment: tks Ayesh ! sorry not sure I understood? As I dmp() exactly at the test point, and it returns only one entity, it should be the one who causes error ? maybe all my users are malformed ? on the other hand it says of type node, not user.. what do you mean by pretty low level please ?
Comment: Tks. If I only knew which is the sensitive info... :( About the check, this is where I placed the dpm I believe.
Comment: Tks Clive ! wow I'll try to find, but this is like looking for a needle in a hay stack... because this is an advanced project based on commons + commerce + several custom modules :(
Comment: BTW I prefer the French version of that saying ;)
Comment: haha  "chercher une aiguille dans une botte de foin !" ;) I'll learn how to use dpm(debug_print_backtrace()) and turn back let's say in a weeeeek. Many thanks for your help
Comment: @Clive : I found the needle, thanks again for advices !!!
Answer: The error:

EntityMalformedException: Missing bundle property on entity of type node.

happens, because your bundle property is malformed either on load or save, so Drupal can't find what type of bundle is it.
The logic of that Exception is:
// Explicitly fail for malformed entities missing the bundle property.
if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
  // var_dump(debug_backtrace()); exit; // You may want this line to debug.
  throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
}

So basically value of $info['entity keys']['bundle'] (for node it's: type) can't be found in $entity object ($node->type for the node), therefore Drupal doesn't know with what kind of entity it's dealing with. So most likely your entity is invalid (e.g. you're loading something else instead) or it is just empty ($entity is NULL).

If you haven't modified any Drupal code, this potentially can be caused by variety of things (most likely by specific Drupal module bug), such as:

saving invalid entity such as:

missing type from the node object (e.g. wrongly generated by Devel Generate?);

orphaned nodes in node table;
invalid rows in field_data_field_xxx table;
having orphaned nodes, caused by:

search view having indexed nodes which aren't in the system;
other modules (like Feeds) removing nodes from Drupal improperly;

nodes having invalid/non-existing references; for term data this can be checked by:
drush sqlq "SELECT nid, title from node WHERE nid IN (select entity_id from  field_data_field_some_ref WHERE field_some_ref_tid not IN (select tid from taxonomy_term_data));"

Where field_data_field_some_ref is data field of field_some_ref which is type of 'Term reference'.
See: DB records not deleted for Term Reference Fields after Term is Deleted
having orphaned taxonomy terms (so you may use Taxonomy Orphanage);
entity caching issue;
when using Rules Link module;
invalid custom code (human error) such as:

badly implemented Entity API,
badly implemented CTools/Form API,
!empty() test on the entity variable before calling field_get_items(),
rendering field by invalid calls,
triggering functions which shouldn't be triggered on certain pages (e.g. field_view_field()),

Here is the responsible code which is thrown by Drupal core (file: common.inc):
 if (!empty($info['entity keys']['bundle'])) {
    // Explicitly fail for malformed entities missing the bundle property.
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
    }
    $bundle = $entity->{$info['entity keys']['bundle']};
  }

Debugging
If you don't recognise anything above, the easiest thing to debug that kind of error is by placing var_dump(debug_backtrace()); or dd(debug_backtrace()); (when Devel is on) before the actual throw new EntityMalformedException on the affected line in common.inc.
Note: Using dd() function from Devel will generate the debugging info to the file in your Drupal temp folder (temporary://drupal_debug.txt) with backtrace dump, otherwise could be too big and difficult to read when dumping on the screen. When using var_dump(), it's easier to call die(); after the call and check the dump in the view-source mode of the page.
If this is happening on node save, check this EntityMalformedException post at SO for more detailed instructions.

See also the following Drupal issue: #1778572 for more ideas.
Comment: kudos for a such detailed answer! I solved my issue a long time ago, but not doubt this will be helpful for a lot of people, me included.
Comment: This is a fantastic answer! Deserves more upvotes.
Comment: Found it: the command created a file called `drupal_debug.txt` inside `/tmp/drupal_theme/` where "drupal_theme" is the name of the drupal theme. Thanks for your excellent debugging help!
Comment: I added `dd(debug_backtrace());` to the affected line in front of `throw new EntityMalformedException`, made sure Devel is enabled and ran the drush command in cron that is throwing this error and am not getting any debugging output. What did I do wrong? Thanks!
Answer: Thanks to Clive comments, I solved the issue as following.
Added ddebug_backtrace() where error occured (entity_extract_ids(), line 7700 of .\includes\common.inc ) to print the function call stack.
Then looking for anything unexpected in output, I found that a pane visibility rule might be the problem.
19: ctools_entity_field_value_ctools_access_check() (Array, 2 elements)
  file (String, 81 characters ) profiles\commons\modules\contrib\ctools\plugins...
  $...['19: ctools_entity_field_value_ctools_access_check()']['file']
    profiles\commons\modules\contrib\ctools\plugins\access\entity_field_value.inc:213
  args (Array, 3 elements)
    0 (Array, 2 elements)
      field_theme (Array, 1 element)
      //...

I had applied a patch on entity_field_value.inc a few days ago just to solve a visibility rule notice... and created a test visibility rule with a field_theme condition.
Now reverting patch or removing any pane visibility rule solved current EntityMalformedException bug... Powerful ddebug_backtrace() !
Comment: I tried this method and i got 1000's of line of code on front end. How do you see where the error is?
Comment: @Sam have a look at Kenorb answer, it might help you
Answer: This issue comes up when there are orphaned nodes, simply get rid of them and cron will run without any error. Search indexing will finally get to 100%.
Backup your database before proceeding.
Assuming you have access to phpMyAdmin, run this SQL code to identify the nodes then delete them. Replace my question content type machine name with your specific content type machine name one after the other till you get no result, that's after deleting.
SELECT n.nid, n.title, n.vid, nr.vid FROM drcm_node n LEFT JOIN drcm_node_revision nr ON nr.nid = n.nid WHERE n.type = 'question' AND nr.vid IS NULL ORDER BY n.nid ASC

You can delete the orphaned nodes by using the SQL code below. Replace the numbers in the bracket with your specific node IDs
DELETE from node where nid IN (12779,12780,12781,12782)

How to debug EntityMalformedException?


Three.ImageLoader - Object [object Object] has no method 'addEventListener'

Question: I'm working on a simple model previewer using three.js, where the user can dynamically upload and change the textures for the model's materials, among other things.
For the life of me I can't get past this error, and I've run across this problem for other loaders in three.js that are supposed to have the addEventListener method. So what am I doing wrong? I'm using r59
function loadTex(tex)
{
    var texture = new THREE.Texture();

    var imgloader = new THREE.ImageLoader( manager );

    imgloader.addEventListener('load', function(event) {
        // Event stuff
    });

    imgloader.load( tex );
}

This function gets called after an image successfully uploads to the server. All I'm trying to do is change the texture for a material that already exists.
Comment: Did you maybe recently update Three.js and it was working before? For OBJLoader and other external loaders, you also need to update those files.
For ImageLoader i am not quite sure but you could also just use Three.ImageUtils.loadTexture();
Comment: @GuyGood, thanks for responding. I didn't use ImageLoader before, so can't say if it worked for previous versions. I switched to ImageUtils.loadTexture() instead and it worked fine. Thanks!
Comment: By the way, I'm still wondering why the original code didn't work. I may need the .addEventListener method in the future, so I'll probably run into this problem again with various three.js functions. A clear answer would no doubt help other entry-level users.
Answer: I had the same issue when I upgraded to r59 from r58. It looks like addEventListener method is not available in r59 (https://github.com/mrdoob/three.js/blob/master/src/extras/ImageUtils.js)
You can use loadTexture method and listen to onLoad and onError events
function onLoad(event) {
// do something
}

function onError(event) {
// do something
}

texture = THREE.ImageUtils.loadTexture(url,mapping,onLoad,onError)

You can pass {} for mapping or use any of the values defined here
http://threejs.org/docs/59/#Reference/Textures/Texture
Comment: There must be a better way. I had the same issue with the OBJloader and just ended up using the older library.
Answer: var imgloader = new THREE.ImageLoader( manager );
imgloader.load(tex, function(event) {
    // Event stuff
});

Comment: Please explain what is wrong with OP's code and how that solves the problem *by editing your answer*.


Is there a more elegant way to write generic static variables in Rust?

Question: Assume we have this struct:
struct A<T> {
    name: &'static str,
    call: &'static (dyn Fn(T) -> T + Sync),
    // and some other fields
}

And I would like to define a static object of A with different type parameters, like:
use num::Float;

static expf32: A<f32> = A { name: "exp", call: &|x| f32::exp(x), /* some other fields */ };
static expf64: A<f64> = A { name: "exp", call: &|x| f64::exp(x), /* some other fields */ };
static exp_big: A<BigDecimal> = A { name: "exp", call: &|x| BigDecimal::exp(x), /* some other fields */ };

etc.
Is there a shorthand for these definitions? For example, something that looks like this:
static exp<T>: A<T> = A { name: "exp", call: &|x| T::exp(x), /* some other fields */ }; //?

My Ideas: The closest method I came up with is to define a generic struct and put all the static members in its implementation:
use Num::Float;

struct Functions<T>;
impl<T: Float> Functions<T> {
    static exp: A<T> = A { name: "exp", call: &|x| T::exp(x), /* some other fields */ }
}

But the compiler will report an error:
error: associated `static` items are not allowed
  --> src/terms/funcbase.rs:12:5
   |
12 | /     pub static exp: SingleArgFuncBase<T> = SingleArgFuncBase {
13 | |         name: "exp",
14 | |         call: &|x| T::exp(x),
15 | |     };
   | |______^

Answer: Generic statics are not allowed, because they are problematic to implement. But you can use a macro:
macro_rules! define_exp {
    {
        $( static $name:ident<$type:ty>; )+
    } => {
        $( static $name: A<$type> = A { name: "exp", call: &|x| <$type>::exp(x), /* some other fields */ }; )+
    };
}

define_exp! {
    static expf32<f32>;
    static expf64<f64>;
    static exp_big<BigDecimal>;
}


Show $X$ and $Y$ are independent if we assume that $E[XY] = E[X] E[Y] $

Question: Assume that $$E[XY] = E[X]E[Y]$$ Let $X$ and $Y$ be random variables taking two different values $a,b \in \mathbb{R}$. Show that X and Y are independent.

Note: I've spent a long time on this problem. I tried to use all the info given and arrived at a tautology. For that reason, I think there is no use in posting my attempt.
Comment: This is not true. What leads you to believe that it is?
Comment: I like how this gets downvoted, but some wally being like 'why do we give sin and cos names' - 42 upvotes.
Comment: @Omnomnomnom I believe it is true in this case
Comment: @Omnomnomnom its a practice problem
Comment: @Omnomnomnom This is true for Bernoulli variables - and X Y basically are
Comment: Oh, I misinterpreted the part about two values; the question makes sense. My mistake!
Answer: Hint: Show it first for $a=0$, $b=1$ (Bernoulli variables).
In this case, $E(XY)= P(X=1,Y=1)=p_{11}$ and $E(X)=P(X=1)=p_{10} + p_{11}$
 $E(Y)=p_{01} + p_{11}$
So $E(X)E(Y)=E(XY)$ implies that $ P(X=1,Y=1) = P(X=1) P(Y=1)$. Show that this also is valid for the other joint probabilities - and hence $X,Y$ are independent.
Next, for general $a,b$ consider $U=(X-a)/(b-a)$ and $V=(Y-a)/(b-a)$. Show then that $X,Y$ uncorrelated implies $U,V$ uncorrelated. And $U,V$ independent implies $X,Y$ independent.
Comment: Why must we introduce U and V here? Is it necessary to use correlation here? I have not learned that yet.
Comment: Two variables are uncorrelated if and only if the expectation of their product equals the product of their expectation.
Comment: @Ryan I introduced UV to solve the problem as a generalization from a more specialized one (Bernoulli variables) which is itself important and well known (for jointly distributed Bernoulli -as well as for Gaussian- rv s, uncorrelation implies independence). You don't need to go that way. If you prefer, you can directly express the equality of expectations in terms of the joint probabilities (four values) and deduce that X Y are independent.


Rearranging elements in a table only with CSS

Question: I need to center 3 spans in a list in a table.
Right now it looks like this: spans not properly centered
But I want it to look like this: span properly centered

ul {
  text-align: center;
  list-style-position: inside;
  list-style-type: none
}
li {
  display: grid;
  grid-template-columns: 1fr 2.5fr 1fr;
  gap: NaNpx 2%;
  grid-template-areas:
    "subject teacher room";
  justify-content: center;
  align-content: center;
  justify-items: center;
  align-items: center;
}
body {
  text-align: center;
}
.ttps-span-center {
  font-weight: normal;
  grid-area: teacher;
}
.ttps-span-right {
  font-weight: bold;
  grid-area: room;
}
.ttps-span-left {
  font-weight: bold;
  grid-area: subject;
}
<link href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" rel="stylesheet"/>

<colgroup><col style="width:(100/6)%" /><col style="width:(100/6)%" /><col style="width:(100/6)%" /><col style="width:(100/6)%" /><col style="width:(100/6)%" /><col style="width:(100/6)%" /></colgroup>
	Monday 25.10.2021	Tuesday 26.10.2021	Wednesday 27.10.2021	Thursday 28.10.2021	Friday 29.10.2021

07:45-08:30

EJdB202

FCEJdB206

FCa,PtB207

EJdB211

MRBsA510

08:40-09:25

EJdB202

WROeB303

FCa,PtB207

DWhB208

KlBsA510

09:45-10:30

BGMiA513

WROeB303

MBsA510

FCa,PtB211

DWhB202

10:40-11:25

BGMiA513

GgWsB312

DWhB211

FCEJdB211

DWhB202

11:35-12:20

ICTBs,ScB335

GgWsB312

MBsA414

12:30-13:15

WROeB309

SKLdBU201

SMKfA120

13:25-14:10

GDe,EnB316

WROeB309

CWb,Sf,Nf,Hl,Li,Ve,KgB414

CWb,Sf,Nf,Hl,Li,Ve,KgB410

CWb,Sf,Nf,Hl,Li,Ve,KgB418

CWb,Sf,Nf,Hl,Li,Ve,KgB405

CWb,Sf,Nf,Hl,Li,Ve,KgB415

CWb,Sf,Nf,Hl,Li,Ve,KgB408

NaTechWb,Sf,Nf,Hl,Li,Ve,KgA410

MBsA312

14:20-15:05

DIGrB208

GDe,EnB316

SKLdBU201

SMKfA120

CWb,Sf,Nf,Hl,Li,Ve,KgB414

CWb,Sf,Nf,Hl,Li,Ve,KgB410

CWb,Sf,Nf,Hl,Li,Ve,KgB418

CWb,Sf,Nf,Hl,Li,Ve,KgB405

CWb,Sf,Nf,Hl,Li,Ve,KgB415

CWb,Sf,Nf,Hl,Li,Ve,KgB408

NaTechWb,Sf,Nf,Hl,Li,Ve,KgA410

MBsA312

15:15-16:00

DIGrB208

SKLdBU201

SMKfA120

CWb,Sf,Nf,Hl,Li,Ve,KgB414

CWb,Sf,Nf,Hl,Li,Ve,KgB410

CWb,Sf,Nf,Hl,Li,Ve,KgB418

CWb,Sf,Nf,Hl,Li,Ve,KgB405

CWb,Sf,Nf,Hl,Li,Ve,KgB415

CWb,Sf,Nf,Hl,Li,Ve,KgB408

NaTechWb,Sf,Nf,Hl,Li,Ve,KgA410

FCa,PtB211

16:10-16:55

CWb,Sf,Nf,Hl,Li,Ve,KgB414

CWb,Sf,Nf,Hl,Li,Ve,KgB410

CWb,Sf,Nf,Hl,Li,Ve,KgB418

CWb,Sf,Nf,Hl,Li,Ve,KgB405

CWb,Sf,Nf,Hl,Li,Ve,KgB415

CWb,Sf,Nf,Hl,Li,Ve,KgB408

NaTechWb,Sf,Nf,Hl,Li,Ve,KgA410

17:05-17:50

Also, here is my codepen:
https://codepen.io/momonunu-the-encoder/pen/dyzvoJg
Thank you.
Answer: You just need to remove padding-left from your ul inside the ttps-lesson class and then everything will be just great.
This is a bootstrap style. (padding-left: 2rem)
Or just add padding-left:0; into ul styles.
Comment: Please also read [why an image of your code is not acceptable](https://idownvotedbecau.se/imageofcode).
Comment: tysm, works perfectly fine.
Comment: You should use a [repro] instead of an image with code and output!
Comment: Ok, sure but I thought that this would help very quickly and just in a glance. I represented the minimal style as you can see but I provide the image to ensure @momonunu that it will work fine.
Comment: Just use the copy button for the code from the OP. there, everybody can run the snippet and see the outcome themself just fine. A task that takes 5 seconds to do while your description has enough info of what you did.
Comment: I do not see what is the problem with providing images, but as it is the best practise I will avoid it in the future.


How to justify this differential manipulation while integrating?

Question: Some time ago I had a physics test where I had the following integral: $\int y'' \  \mathrm{d}y$. The idea is that I had a differential equation, and I had acceleration (that is, $y''$) given as a function of position ($y$). The integral was actually equal to something else, but that's not the point. I needed to somehow solve that. I can't integrate acceleration with respect to position, so here's what I did:
$$
\int y'' \ \mathrm{d}y =
\int \frac{\mathrm{d}y'}{\mathrm{d}t} \ \mathrm{d}y =
\int \mathrm{d}y' \frac{\mathrm{d}y}{\mathrm{d}t} =
\int y' \ \mathrm{d}y' = \frac1{2}y'^2 + C
$$
My professor said this was correct and it makes sense, but doing weird stuff with differentials and such never completely satisfies me. Is there a substitution that justifies this procedure?
Comment: $$\int y''dy=\int y''(t)[y'(t)dt]=\int\frac{1}{2}\left[\frac{d}{dt}(y')^2\right]dt=\frac{(y')^2}{2}+C\;\;?$$
Comment: $\int y'' dy$ stands for, as anon shows, $\int y''(t) y'(t) dt$. When the differential $df$ appears on its own, where $f$ is a function, it stands for $f'(t) dt$.
Comment: $\int y{}^\prime{}^\prime dy$ does not make any sense to me.
Comment: @AlexE: I don't really remember why I did that, but I know that I did. The exercise was to find an expression for velocity in terms of position for an object thrown up from the Earth, taking into account that fact that gravity changes with height: the equation was $y'' = G \frac{m_E}{(y+R_E)^2}$, where $m_E$ is Earth's mass and $R_E$ is its radius.
Comment: Since this came up on a physics test, it may be helpful to lay out the physical interpretation. If $y(t)$ gives the motion of an object, then $y''$ is its acceleration, and the work done on the object is $W=\int F dy$, which by Newton's second law equals $m\int y'' dy$. Throwing in the factor of $m$, the result $(1/2)my'^2$ is the kinetic energy. The constant of integration $C$ is the object's initial energy. What is being proved is known as the work-kinetic energy theorem, that the work done by the net force acting on the object equals the change in the object's kinetic energy.
Answer: When dealing with differentials, we generally have a "manipulate first, ask questions later" attitude. Differentials have a way of giving out correct results when manipulated formally but it's a mistake to think that something meaningful is going on. Okay, this is not totally true: there are non-traditional approaches to calculus where some of these manipulations can be rigorously justified, but I couldn't tell you much about them. The most popular of these approaches is due to H.J. Keisler. More info here.
Comment: Yes. The basic idea is that in Leibniz notation, $dy$ stands for an infinitesimal change in $y$, and $\int$ means a sum with infinitely many terms. This is what Leibniz meant by these notations, and this is what great mathematicians like Gauss and Euler understood them to mean. If you understand them that way, then it becomes obvious that the OP's manipulations are valid. Non-standard analysis (as presented nicely in the Keisler book) clears up concerns about logical problems with infinitesimals -- basically it shows that the concerns were unfounded.
Answer: I'm doubtfull about what $y''$ and $dy$ stand for in your problem. If you have $y = y(x)$ then clearly $$\int y'' dx = y'+C$$ But you're integrating with respect to $dy = d\{y(x)\} = y'(x) dx$ assuming $y(x)$ has a continuous derivative. So you finally have.
$$\int y''(x) y'(x) dx = \int   y'(x) d(y'(x)) = \frac{y'^2}{2}+C $$
I'd recommend you read about the Riemann Stieltjes integral, which would formally clarify this issues.


Linking error references

Question: I was trying to update a framework that we used before, since they had completely renewed it, there wasn't just a simple way of updating the files.
In my project I just removed the current framework and added the newer one.
After some testing I wanted to go back to the old version, so I removed the new framework and added the old one again. So basically nothing changed in the code or in the files.
But still, when I try to build my files now, I'm getting this linking error, again, no changes to the code were made.

ld: duplicate symbol _OBJC_IVAR_$_DocumentViewController.thumbPage in /Users/wouter/Library/Developer/Xcode/DerivedData/WiC-dubdfuwbsdrffuatbuonqmpzuvcz/Build/Intermediates/WiC.build/Debug-iphonesimulator/WiC.build/Objects-normal/i386/DocumentViewController-B98A1B42C236E973.o and /Users/wouter/Library/Developer/Xcode/DerivedData/WiC-dubdfuwbsdrffuatbuonqmpzuvcz/Build/Intermediates/WiC.build/Debug-iphonesimulator/WiC.build/Objects-normal/i386/DocumentViewController-B98A1B42C236E973.o for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Why would it give me this error if everything is the same as before?
My guess is that Xcode keeps some references (even though I asked to delete them) to deleted files.
Any ideas on how to get rid of this?
Answer: Are you sure you're at the same revision? Can you back out to that version with git?
So you're project is finding at least 2 copies of ivar DocumentViewController.thumbPage ... Did you:

Do a Clean All
Delete the build directory

If that doesn't work, I would search the project or the project.pbxproj file (just using a text editor) and seeing if you can find the object or 2 frameworks that would be added to your target that contains this.
If that doesn't work, blow away the .xcodeproj directory and just created a new one and add all your files to it ... but this is as last resort.
Comment: The Clean en Clean build folder sure helped me.
Answer: I'll bet that you accidentally #imported a .m file instead of a .h file.  Check to make sure that your #import reads
<code>#import DocumentViewController.h
</code>
Do a clean and run again.
Comment: It says DocumentViewController.h, everything worked perfectly before, until trying out the other framework.
Comment: Press shift+cmd+f and search for'.m"' (without the single quotes, but include that last double quote)
Comment: what about checking your 'Compile Sources' list.  Does it contain two versions of the DocumentViewController.m file?
Comment: It did contain only one reference there, I tried deleting it but for some reason it didn't let me, after pressing delete a couple of times, I did a Clean and Clean Build Folder and everything worked again ...
Comment: Well then, if that is the answer, post it and accept your own answer so this doesnt wind up in the 'Not Answered" tab.
Comment: Thanks for all the suggestions!
Answer: Turns out that my "Compile Sources" was keeping a references to the same file previously deleted, trying to delete it didn't help.
After doing a Clean and Clean build folder the problem was magically fixed.

Linking error references


Which hand for which in guitar? (a complication)

Question: I'm going to start learning guitar in the next coming weeks, and I'm wondering which hand I should use for fretting and which to use for strumming. I am left hand dominant, and have tendonitis in my right wrest, as well as much more tension in my right fingers and a slight tremor as well. I am in physical therapy looking to resolve the issue, and wear a brace on my right wrist fairly frequently. That being said, I am pretty determined to learn guitar. I dont plan on doing anything super complicated, and I have a decent knowledge of basic musicianship from a year of piano lessons. I plan on using Justin Guitar.
TLDR: I have tendonitis and wrist/finger tension in my right hand. My left hand, which is my dominant hand, is pretty much fine. Which hand should I use for fretting and which for strumming? Thank you.
Comment: have you tried playing either way? what was the result?
Comment: Not for a very very long time. Before I even developed tendonitis. If it helps, I don't think Ill have too much trouble strumming with a pick. I would like to be able to play simple Bon Iver songs that involve picking with individual fingers though. Similar to piano, I dont have trouble playing chords with my right hand - I only have trouble with really complex or repetitive and fast melodies-fly by Einaudi killed my right hand, gymnopedie no.1 is a breeze. I'm learning The Girl with the Flaxen hair right now, and what bothers me the most are chords where I have to either stretch wide or bend
Answer: You should play right-handed. At least give it a solid try. Mainly for two reasons :

Not endangering more your wrist : From my experience, the fretting hand is the one that requires the more strength and put the more pressure on your forearm and fingers. Given that you have tendinitis, you should use your right hand to strum, as it requires less strength from that arm.
Convenience : As a left-hander that plays the guitar right-handed (right hand strums), I can only advise you to try to play right-handed yourself. It's much more convenient :

you will be able to play on basically any guitar you find. A friend brought a guitar at a party ? Fine, you can play on it, since the strings will most likely be set up for a right-handed guitarist.
if you ever have a teacher (or a friend or a relative teaching you guitar) it'll make life easier for your teacher, given that he plays the guitar right-handed like most of guitarists. Same goes if you are the teacher (maybe in a few years, or even sooner !).

It's really no problem at all to play right-handed guitar as a left-hander. Back to when I started playing the guitar, I actually started left-handed as it felt more natural to me. For a few weeks, I learned guitar that way. But then when I started my lesson, my teacher immediatly told me to try right-handed play. I was okay with it when trying it and then she told me that I should play right-handed guitar from now on. I never regretted that I had followed her advice !
On the other hand, how big this brace is on your right hand ? If it's too big it might interfere with your strumming and that may be a problem. But most likely it's not that big I guess.
Good luck and have fun playing the guitar !
Comment: Hi there. Thanks for the response. It really isn't too big. It covers more of my wrist than my hand, and besides a piece of the brace that wraps between my index and thumb, my hand/fingers are totally free - I just can't bend the wrist much or angle it too weirdly, though I have no problem moving it up and down or being precise with my fingers, which is another reason I think I should play right-handed.
Answer: I gave this question a shot in a slightly different context a few years ago, and it's only slightly changed.
There are many left-handed players who play right-handed, availability of new instruments will be much greater if you play right-handed. There are benefits. That your right hand has issues only adds to these benefits.
But if your hands will not go that way, like mine the few times I tried to play left-handed, then they won't and you shouldn't force it.
Playing a guitar is awkward until you know what you're doing, but if your hands really want to hold it the other way, you will know.
I'll say this: playing guitar should not hurt, and if what you're doing hurts, stop right now. Fretting and even bending doesn't take much hand strength, and if you put too much in, you're hurting your fingers, making transitions harder and bending your notes sharp. There's no musical benefit to a heavy touch or a tight squeeze, and much to recommend a light touch for guitar.
I've been playing for over 30 years, and I've been fortunate enough that, with handedness and health, most guitar gear is built to just work for me without problem. I hope you figure out what's best for you and that music continues to bring you joy.
Answer: Traditionally the left hand is used for fretting and the right for plucking/strumming.  If your right hand is already injured fret with the left.  Like others have stated, there are many great left handed (opposite of traditional) guitarists but if you don't have a prejudice to which hand to use for fretting you won't know the difference.  It always feels strange at first.  A side note: Many guitar teachers encourage their students to try flipping the guitar and play simple one string melodies.  This helps you remember what it was like to be a beginner when you get frustrated, and who knows you could become the next Mike Batio or Stanley Jordan.  I would watch that right hand and make sure your guitar playing is not making it worse (whatever it is).  I've played guitar for 40+ years and now have carpel tunnel syndrome in the right hand due to working at a computer for hours a day.  The guitar playing doesn't make it worse and in fact is therapeutic w/r to this issue.  If things get worse tell your physical therapist.  And I'd recommend taking lessons from an experienced instructor.
Answer: Any time we do something repetitive (play an instrument, type, etc.) we run the risk of setting up a tension pattern in the body, especially if the action is non-symmetrical such as playing the guitar. Playing the guitar places your body in a repetitive position doing repetitive movements that are not balanced right and left.
The guitar places mechanical stress on hands and fingers but also the entire body.  The guitar requires you to set up a twist that involves the entire spine - hips, back and shoulders, neck. You can develop tensions that aggravate existing conditions or set you up for new tensions.
If you side sit on a bed or a couch, this can be stressful if done over time. Place the music in front of you. Face forward.
To stay healthy we have to create a routine which counteracts the repetitive movements and the repetitive positioning that we must maintain to practice and play our instruments.
Some suggestions are: Take breaks, breathe, find stretches that counteract the repetitive positioning. Relax when playing - drop your shoulders, keep breathing, soften your grip, press only when necessary on the strings, relax between chord changes. Let your energy flow.
Enjoy this gorgeous, resonant instrument as it vibrates through your body.
Answer: I guess this is pure opinion/anecdote, but...
There are sooo many great left-handed guitarists who play right-handed guitar, it would feel a shame not to try it that way first... which would also fit your right hand tendonitis/brace better, imho.
Comment: Thanks for the feedback. I think I will try right-handed at first. It appears the bending and contorting of fingers when fretting would probably stress the heck out of my right wrist, and I likely wouldnt have trouble just strumming simple chords with my brace on. Again, considering piano is my prime area of interest, I want to just be able to play a few guitar songs that I'm interested in, and if my wrist begins to heal over time, I probably would have less trouble doing more complex strumming with my right fingers. Thank you.


What outlier score is used here?

Question: I have come across a score function in a program, but I don't exactly understand what it does. This score is a measure of how probable a sampled/created value is. I will describe the procedure for computing the score function as accurately as I can.
Let $Y$ be a normally distributed random variable (I think this assumption is necessary, as evident in the following).
Furthermore, we are given a sample $\{y_n\}$ of $Y$ and compute the midrange of this sample, called $y_{\text{midr}}$. Then some statistic, in the code called $y_{\text{std}}$ is computed by
$ y_\text{std} = \frac{y_{\text{max}} - y_{\text{midr}}}{3}$
where $y_{\text{max}}$ is the largest value of the sample.
Finally, the score is computed for the value $y_{\text{true}}$:
$\text{score} = 2 \Phi(\frac{y_{\text{true}} - y_{\text{midr}}}{y_\text{std}}) - 1$
This just seems to be the scattering range of $y_{\text{true}}$ for the cdf of the standard normal distribution.
I then discovered some statement that checkes if the $\text{score}$ value is smaller than a certain threshold, but I have not found what this threshold is.
Is this a known outlier test, or some frequently used statistical test? Why is the midrange and this strange deviation used?
Answer: Well, $y_{std} = (y_{max} - y_{midr})/3$ is inspired by the fact that 99.7% of data will fall within 3 standard deviations of the mean. This is sometimes called the range rule and is sometimes recommended as a way you can mentally calculate a rough standard deviation in your head.
The range rule is not a great way to estimate a standard deviation and in particular it is anti-robust and extremely sensitive to outliers. There are robust ways to estimate the standard deviation such as $s = IQR / 1.34896$. (Here, "robust" means insensitive to rare outliers.)
The score part is simply the usual two-sided p-value for the one sample z-test.
I have never seen this used in a program (where there is always a library function which can calculate the usual unbiased estimate of variance). It makes little sense to use the range rule (which is really just a rule-of-thumb) if you have access to the full sample. The range rule estimate is particularly ill-suited to outlier testing, because it is guaranteed to overestimate variance if even one outlier is present in the sample.
Comment: Excellent answer! The program is a variational autoencoder: https://github.com/regel/loudml/blob/master/loudml/loudml/donut.py#L1145 and the function where the score is computed is called compute_bucket_scores. The sample is obtained by MC sampling (search for '# MC integration') to obtain reconstruction probabilities. It has its roots deep in Bayesian Stats, but I am no stat myself, so I can only guess why the author proceeded like this. If you have any idea if this could be related to MC sampling and reconstruction in the VAE, please let me know.

What outlier score is used here?


regex for cos/sin/tan with inner brackets inside

Question: Cant't find an appropriate pattern for this kind of math expression:   2*-5+ sin(1.5*4)+(28- 3^4-(cos(3+(19*3)+1+(6/2))/2+tan(1+cos(1+9))-6/3+2.3*3.3345)+1)+1)-(4/2) where there is (or not) inner brackets inside cos.
desirable result is:
 1. cos(3+(19*3)+1+(6/2))
 2. cos(1+9)

i tried cos\(.+?\) , but i get only cos(3 + (19*3). If i'm trying a greedy quantifier i get the whole string till the last )
thank you in advance!
Comment: Well, the [current duplicate](http://stackoverflow.com/questions/5475804/regular-expression-for-math-operations-with-parentheses) question deals with any `[...]` unit in an expression, while this question asks how to only get units like `cos(...)`.
Comment: Algebraic expressions are not a regular language. Use a proper parser.
Comment: http://stackoverflow.com/a/5475880/5812121
Answer: I would suggest a method accepting the string to parse, a string before the starting balanced symbol, the character delimiters and a flag to include or exclude the delimiters (markers).
See the Java IDEONE demo:
public static List<String> getBalancedStr(String s, String strBefore, Character markStart,
                                 Character markEnd, Boolean includeMarkers) {
    Matcher m = Pattern.compile("(?=(\\b\\Q" + strBefore + markStart.toString() + "\\E.*))").matcher(s);
    List<String> subTreeList = new ArrayList<String>();
    while (m.find()) {
        int level = 0;
        int lastOpenBracket = -1;
        for (int i = 0; i < m.group(1).length(); i++) {
            char c = m.group(1).charAt(i);
            if (c == markStart) {
                level++;
                if (level == 1) {
                    lastOpenBracket = (includeMarkers ? i : i + 1);
                }
            }
            else if (c == markEnd) {
                if (level == 1) {
                    if (includeMarkers) {
                        subTreeList.add(strBefore + m.group(1).substring(lastOpenBracket, i + 1));
                    } else {
                        subTreeList.add(m.group(1).substring(lastOpenBracket, i));
                    }
                    break;
                }
                level--;
            }
        }
    }
    return subTreeList;
}

Sample usage:
String s = "2*-5+ sin(1.5*4)+(28- 3^4-(cos(3+(19*3)+1+(6/2))/2+tan(1+cos(1+9))-6/3+2.3*3.3345)+1)+1)-(4/2)";
System.out.println("cos: " + getBalancedStr(s, "cos", '(', ')', true));
// cos: [cos(3+(19*3)+1+(6/2)), cos(1+9)]
System.out.println("sin: " + getBalancedStr(s, "sin", '(', ')', true));
// sin: [sin(1.5*4)]
System.out.println("tan: " + getBalancedStr(s, "tan", '(', ')', true));
// tan: [tan(1+cos(1+9))]

Note that the method compiles a regex - "(?=(\\b\\Q" + strBefore + markStart.toString() + "\\E.*))" - that will match cos or sin only as a whole word (since \b is a word boundary) and the .* will match up to the end of the line. If you want to support multiple line input, use (?s) in front: "(?s)\\b\\Q" + strBefore + markStart.toString() + "\\E.*". Since the pattern is in a capturing group inside an unanchored positive lookahead, we collect all overlapping matches, and will only get 1 balanced substring at each match (since after we have found a corresponding matching closing delimiter, we break out of the for loop.


Get domain name of website where my remote js is included

Question: I have a script which I can include in any page on a same domain or on a different domain.
from that script, I am making ajax calls to my server.
What I want is to get the domain name of the page where the script is included.
This is my code:
My script on a page say www.abc.com/index.html

My ajax call will go to a .ashx handler say

http://demo.xyz.com/web/myHandler.ashx.

Inside that handler, if a access,
HttpContext.Current.Request.Url.Host

I get

"demo.xyz.com" instead "www.abc.com"

I want to retrieve "www.abc.com" on server side.
I don't want to include/or send this domain name to server side via js.
Comment: Possibly [HttpContext.Current.Request.UrlReferrer](http://msdn.microsoft.com/en-us/library/system.web.httprequest.urlreferrer(v=vs.110).aspx). Not sure if it works with AJAX requests, but it's worth testing. Otherwise, you might have to pass the info back from the JavaScript itself with the [location object](http://www.w3schools.com/jsref/obj_location.asp)
Comment: yes `HttpContext.Current.Request.UrlReferrer` is working.
Answer: The HeaderReferer value of the HttpWorkerRequest class can help, like this:
Inside of your HTTP Handler code:
public void ProcessRequest(HttpContext context)
{
    var theProvider = (IServiceProvider)context;
    var theWorker = (HttpWorkerRequest)theProvider.GetService(typeof(HttpWorkerRequest));
    string theReferer = theWorker.GetKnownRequestHeader(HttpWorkerRequest.HeaderReferer);

    // Do something with referer here

}


Convert a float literal to int representation in x86 assembly?

Question: The following C code:
int main()
{
    float f;
    f = 3.0;
}

Is converted to the following assembly instructions:
main:
  pushl %ebp
  movl %esp, %ebp
  subl $16, %esp
  flds .LC0
  fstps -4(%ebp)
  movl $0, %eax
  leave
  ret
.LC0:
  .long 1077936128

What is the correct way to calculate the .long/int representation of the float literal?
e.g. 1077936128 generated from 3.0 for the example shown above

For this example gcc is used with the -m32 -S -O0 -fno-stack-protector -fno-asynchronous-unwind-tables flags using intel settings to generate the assembly output.

References:
Compiler Explorer Link  with compilation flags and other settings
Answer: x86 FPU hardware uses IEEE754 binary32 / binary64 representations for float / double.
Determining the IEEE 754 representation of a floating point number is not trivial for humans.  In handwritten assembly code, it's usually a good idea to use the .float or .double directives instead:
.float 3.0    # generates 3.0 as a 32 bit float
.double 3.0   # generates 3.0 as a 64 bit float

If you really want to compute this manually, refer to the explanations on Wikipedia.  It might be interesting to do so as an exercise, but for actual programming it's tedious and mostly useless.
Compilers do the conversion (with rounding to the nearest representable FP value) internally, because FP values often don't come directly from a literal in the source; they can come from constant folding.  e.g. 1.23 * 4.56 is evaluated at compile time, so the compiler already ends up with FP values in float or double binary representation.  Printing them back to decimal for the assembler to parse and re-convert to binary would be slower and might require a lot of decimal places.

To compute the representation of a 32 bit float as a 32 bit integer, you can use an online IEEE754 converter, or a program like this:
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main(int argc, char *argv[])
{
    union { uint32_t u32; float f32; } intfloat;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s some-number\n", argv[0]);
        return EXIT_FAILURE;
    }

    intfloat.f32 = atof(argv[1]);

    printf("0x%08" PRIx32 "\n", intfloat.u32);

    return EXIT_SUCCESS;
}

Comment: @janniks I have added a program that does this.   If you ever write assembly code, please never encode floating point literals as integers.  That's just terrible for the next person to read your code.
Comment: Here's a great online tool for `IEEE 754` conversions: [FloatConverter](https://www.h-schmidt.net/FloatConverter/IEEE754.html)
Comment: `unsigned long` may vary from C implementation to C implementation.It would be better to use `uint32_t`. Then the `printf` needs to use `"0x%08" PRIx32 "\n"`. `float` may vary too (although four bytes is overwhelmingly common), so testing its size would not be a bad idea. (Also, there is no need for parentheses on `return` statements, and `u32` is a more common and clear name for an unsigned 32-bit integer than `i32`.)
Comment: @EricPostpischil Since there are only two assemblers the recognizes this syntax (Solaris as and GNU as) and both have high quality floating point parsing routines, there is little to worry about.
Comment: Do you know of C source code for this functionality?
Comment: Thanks! I will try to use `.float` for floats in most cases - maybe use the conversion for some proof-of-concept optimizations...
Comment: Using `.float` or `.double` in assembly runs the risk that a poor assembler will round improperly when converting. I expect the compiler generates `.long` to avoid that. Programmers using `.float` or `.double` should check the quality of their assembler in this regard.
Comment: @EricPostpischil Feel free to edit the code.  Parentheses around return statements follow KNF, the remaining things are design decisions made to remove clutter from the code.
Comment: @EricPostpischil: good call, compiled for x86-64 SysV (where `unsigned long` is 64 bit), we happen to get lucky that gcc decides to assume the upper half of the 64-bit `i32` union member is zero, and uses `movd esi, xmm0` for type punning.  But without optimization the upper 4 bytes come from uninitialized stack space.  https://godbolt.org/g/CjxzQ8


Distance between line and point

Question: Using 2D cartesian co-ordinates:
$Point = (x, y)$
$Line = (x_1,y_1),(x_2,y_2)$
Here we are taking $(x_1,y_1)$ and $(x_2, y_2)$ as line segment ends, not points on the infinitely extended line between those points.
How can we calculate, if the point is perpendicular to the line, the distance between the two?
Comment: There is actually a distance formula you can look up.  Alternatively find the vector perpendicular to your line.  Then travel from the point to the line along this vector, and find the length of the.  Alternative 2: find a vector between a point on your line and your point off the line.  The project this vector onto your line.  And subtract this projection from the original vector.
Comment: one of the axioms is that given a line and a point not on the line, it's always possible to draw a perpendicular thru that point
Comment: Are we considering $(x_1 , y_1)$ and  $(x_2 , y_2)$ as line segment ends or just points along an infinite tine  passes through those points?
Comment: @WarrenHill, they are line segment ends.
Comment: @Edward updated your question to clarify intent. Question details should be in the question body.
Comment: @WarrenHill, thank you. Do you have a solution to the problem?
Comment: Not yet but I am working on it
Comment: @WarrenHill, thank you. :)
Comment: How can a point be perpendicular to a line?
Comment: @amd, I mean perpendicular to the line (between x1,y1 and x2,y2).
Comment: @Edward If you are ok, you can set as solved. Thanks!
Answer: CASE 1 - "INFINITE" LINE
Suppose we are given a infinite line through two points: $P_1(x_1,y_1)$ and $P_2(x_2,y_2)$; the aim is to determine the the distance between a point $Q(x_0,y_0)$ and the infinite line $\vec{P_1P_2}$.
The equation of the line through $P_1(x_1,y_1)$ and $P_2(x_2,y_2)$ in the general implicit form
$$Ax + By + C = 0$$
can be easlily found expanding the following:
$$\frac{y-y_1}{y_2-y_1}=\frac{x-x_1}{x_2-x_1}\iff (y-y_1)(x_2-x_1)-(x-x_1)(y_2-y_1)=0$$
Finally the distance between the point $(x_0,y_0)$ and the line $Ax + By + C = 0$ is given by:
$$\text{Distance QP} = \frac{\left | Ax_{0} + By_{0} + C\right |}{\sqrt{A^2 + B^2} }$$
NOTE
It is meaningless define a "point perpendicular to a line".
What is true is that the minimum distance between the point Q and a point P on the line is attained at $P$ such that the line $\vec{QP}$ is perpendicular to the line $\vec{P_1P_2}$.
CASE 2 - "FINITE" LINE
Suppose we are given a finite line between two points: $P_1(x_1,y_1)$ and $P_2(x_2,y_2)$ and the aim is to determine the the distance between a point $Q(x_0,y_0)$ and the line $\vec{P_1P_2}$.
In the simple case of 2D cartesian coordinates you can proceed firstly to draw a graph of the line $\vec{P_1P_2}$ and the point $Q(x_0,y_0)$ in order to verify whether or not the pependicular line from $Q$ to $\vec{P_1P_2}$ lies internally to $\vec{P_1P_2}$.
If the pependicular line from $Q$ to $\vec{P_1P_2}$ lies internally to $\vec{P_1P_2}$ you can determine the distance $QP$ as for the CASE 1.
If the pependicular line from $Q$ to $\vec{P_1P_2}$ lies externally to $\vec{P_1P_2}$ you can determine the distance $QP$ as:
$$QP=Minimum(QP_1,QP_2)$$
where (by Phytagorean Theorem):
$$QP_1= \sqrt{(x_1-x_0)^2+(y_1-y_0)^2}$$
$$QP_2= \sqrt{(x_2-x_0)^2+(y_2-y_0)^2}$$
NOTE
It would be possible solve the problem without any graphing in a pure algebric way but for this simple case it is not necessary.
Comment: Does this account for the fact that the line is of a fixed length? where would you plug in x2 and y2?
Comment: No the given formula do not take into account the finite length os the line (i.e. segment). Im going to update the aswer to take into account this possibility.
Comment: An example: line between {5,10} and {12,15}, and point {2,5}
Comment: If you could update your answer using my example, I'll select your question.
Comment: I've just update a full answer.
Comment: In your example you are in Case 2 withIf the pependicular line that lies externally  thus $QP=Minimum(QP_1,QP_2)$.
Comment: Could you demonstrate using my values? I need distance = ....
Comment: $QP_1=\sqrt{(5-2)^2+(10-5)^2)}=\sqrt{9+25}=\sqrt{34}$.$QP_2=\sqrt{(12-2)^2+(15-5)^2)}=\sqrt{100+100}=\sqrt{200}$. Thus $QP=\sqrt{34}$.
Comment: Should the operator to be `minus` instead of `plus` in the middle of the second formula?
Comment: @jayatubi Yes, good catch! I fix it. Thanks
Answer: the slope of your line lets say $l$ is given by $$m_1=\frac{y_2-y_1}{x_2-x_1}$$
and then we have
$$y=\frac{y_2-y_1}{x_2-x_1}x+n$$ with $$P(x_1,y_1)$$ we get $n$; the line perpendicular to the given line has the slope $$m_2=-\frac{1}{m_1}$$
Can you proceed?

Distance between line and point


Tomcat support on WebStorm

Question: I am JavaScript developer, and currently working on project where Tomcat server is used.
I am familiar with IntelliJ idea but recently read about another JetBrains product specially for web-development - WebStorm. I've found some cool features in WebStorm(especially related to AngularJS autocompletion) but it seems that there is no Tomcat server support and I have to build server side of project into *.war-file and run it manually through terminal each time.
So is there any Tomcat/Java support in WebStorm?
(Or I should continue to use IntelliJ idea and forget about WebStorm and its cool functionality =) )
Comment: I can't answer the "does WebStorm support Tomcat" portion of your question since I do not use it... but I'm curious as to what "cool functionality" in WebStorm you would lose by changing to IntelliJ IDEA. WebStorm is a subset of IntelliJ IDEA **Ultimate**. (You do not mention if you've used ultimate or community.) Anything in WebStorm is also in IDEA. (The main difference is in project setup.) While it is not bundled into IDEA by default, the exact same AngularJS plug-in that WebStorm uses is available to IDEA _Ultimate_. Just install it from the JetBrains plug-in repository in Settings.
Comment: **Simply speaking:** WebStorm is targeted for JavaScript/HTML/CSS (and similar languages/technologies, e.g. SASS/LESS/Dart/NodeJS etc) -- it does NOT support any of the Java-specific stuff. Need Java and related technologies -- keep using IntelliJ -- any "missing" functionality (available in WebStorm but not in IntelliJ IDEA **Ultimate**) can be installed via plugin manually (as mentioned above).
Comment: Ok, I've got it.
Thanks for response!
Answer: You can do one thing.

First start your apache tomcat server with startup.bat/startup.sh. (Suppose your project directory name is "AngularJSTest" in WebStorm.)
Right click on that > Refactor > Move .
Give the path to webapps directory of Apache tomcat.

So from now on whatever changes you make in the project from WebStorm,  it will get reflected in the webapps directory. You can access it from the link http://localhost:8080/AngularJSTest/yourHtml.html.
Comment: This is horrible advice. Throwing the baby out with the bath water.

You likely want to keep your web project within your git repo/project folder and not directly in the tomcat webapp folder. You also don't want a cleaned tomcat to wipe your project directory from webapps.

Tomcat support on WebStorm


configuring mod_proxy_html properly?

Question: I have an apache2 web server that handles reverse proxy for Rails3 app running on another machine.
The setup works except URLs generated within the webapp aren't getting rewritten by my configuration for mod_proxy_html.
The "Reverse Proxy Scenario" is exactly what I'm trying to do, so I've followed the tutorial as completely as I know how.
I've applied or tried answers supplied here on stackoverflow, to no effect.
According to the "Reverse Proxy Scenario" you want a number of modules loaded.  All those instructions are in my httpd.conf file and when I examine the output from
apactectl -t -D DUMP_MODULES

all the expected modules show in amongst the listing.
My external web server doing the reverse proxy is at www.ourdomain.org and the Rails app is internally available at apphost.local (the server is Mac OS X Server 10.6, the rails app server is Mac OS X 10.6).
What's working right now is access to the webapp via the reverse proxy as:
http://www.ourdomain.org/apphost/railsappname/controllername/action

But none of the javascript files, css files or other assets get loaded, and links internal to the web app come out missing the apphost portion of the URL, as if my rewrite rule is configured incorrectly (so of course I've focused on that and can't seem to get anything to be added or deleted in the process of passing the html in from the apphost and out through the Apache server).
For instance, hovering over an action link in the html returned by the web app you'll get:
http://www.ourdomain.org/railsappname/controllername/action

Here's what my Apache directives look like:
LoadModule proxy_html_module /usr/libexec/apache2/mod_proxy_html.so
LoadModule xml2enc_module /usr/libexec/apache2/mod_xml2enc.so
    ProxyHTMLLogVerbose On
    LogLevel Debug
    ProxyPass /apphost/  http://apphost.local/
    <Location /apphost/>
            SetOutputFilter INFLATE;proxy-html;DEFLATE
            ProxyPassReverse /
            ProxyHTMLExtended On
            ProxyHTMLURLMap railsappname/ apphost/railsappname/
            RequestHeader unset Accept-Encoding
    </Location>

After every change I make to httpd.conf I religiously check apachectl -t just to be sane.
I'm definitely not an Apache expert, but all the directives that follow mine seem to not overrule what I'm doing here.  But then nothing that I try seems to alter the URLs I see in my browser after hitting the Apache server with a request for my web app.
Even if you can't tell what I've done incorrectly, I'd welcome ideas on how to get Apache to help see what it's working on and doing to the html coming from my web app.  That's what I understood the ProxyHTMLLogVerbose On and LogLevel Debug to be setting up, but I'm not seeing anything in the log files.
Comment: What path are the resources loading from in the application's HTML?  Can you alter those paths to be relative so that they'll function regardless of the apparent path?
Comment: Looked into that already, and they are relative.  When you access the web app at the web app host (like on a client within the org network) it all loads fine, and it's all relative.  But relative to the reverse proxy URL will not work since there's nothing there to tell the reverse proxy to add the apphost back into the URL.
Comment: That means it's not relative, then - you have a leading slash in your resource URLs.  The client constructs the request, not the proxy - the proxy is not capable of "adding back" to the URL in any way; mod_proxy_html is a workaround to transform the HTML response. The client needs to request `/apphost/path/to/resource.css` instead of `/path/to/resource.css`, which means that instead of `` you should have `href="path/to/resource.css"` relative to the location of the page that's loading the CSS.
Comment: Thanks, Shane. So I used curl to see what HTML was coming back from the app server to the web server.  The links are starting with a slash, "/app/controller/action" -- I'll read more on mod_proxy_html, but it sure reads as though it can pick up on the presence of /app/ in returned HTML and rewrite it as /apphost/app/
Comment: Yes, it's capable of doing that, but a more reliable and portable solution would be to have the application not care what directory it's in.  For instance, if CSS or javascript are involved in populating resource URLs, mod_proxy_html isn't capable of helping.
Comment: Hmm. From http://www.apachetutor.org/admin/reverseproxies "mod_proxy_html doesn't parse Javascript or CSS, so dealing with URLs in them requires text-based search-and-replace. This is enabled by the directive ProxyHTMLExtended On."  I read that to mean that if you need  to get rewritten as "/apphost/webapp/..." that extended mode would help there.
Comment: Shane, it turns out that mod_proxy_html needs to be told explicitly which attributes you want it to work on (not sure when that started but definitely true in my version, 3.1.2).  And it can be told to look inside javascripts to rewrite URLs -- see the SVN link brain99 provided.  Good stuff!
Answer: Maybe a bit of a simplistic answer, but most (if not all) ProxyHTMLURLMap directives I've seen so far have a / at the beginning of the match/replace pattern. Have you tried this variant of your configuration?
ProxyHTMLURLMap /railsappname/ /apphost/railsappname/

If that does not help, what version of apache are you running? And if applicable, which version of the module? It only comes bundled with apache since apache 2.4, so for older versions of apache you must have installed (some version of) this module yourself.
As an alternative you can also switch to mod_substitute, although that requires more configuration than mod_proxy_html.
At some point, they removed some built-in configuration, which requires you to add it yourself. See http://apache.webthing.com/svn/apache/filters/proxy_html/proxy_html.conf, the ProxyHTMLLinks and ProxyHTMLEvents directives are the ones you need to add to your config.
Comment: I'm up for any simplistic answers!  I was not preceding the paths with a slash, so at your suggestion, I just tried.  It didn't change anything.  It really feels like mod_proxy_html isn't activated. Apache 2.2.21 -- I downloaded mod_proxy_html just about a week ago when I started all this, so I believe it's the current version.  Thanks for your response!
Comment: All right, up to some other things to check then. Are you sure that your `` block is being used? How about placing something trivial to check (using firebug or similar) in there, like adding an extra HTTP response header? `Header add Server foo`
This will also allow you to make 100% sure that your responses are not being cached somewhere, which could also explain why they are not being processed properly.
Also, you say you're not seeing anything in the log files, but with LogLevel Debug, your error.log should have loads of entries. Are you checking the correct log?
Comment: I'm not sure any of it is working ;-) However, after a graceful restart, Apache does report "[Mon Aug 27 12:16:31 2012] [notice] Apache/2.2.21 (Unix) mod_ssl/2.2.21 OpenSSL/0.9.8r PHP/5.3.8 proxy_html/3.1.2 configured -- resuming normal operations" so I believe proxy_html to be configured...  I added your header suggestion *outside* of the location block to see if I could get *something* showing up.  In Firebug there is a Server annotation, but it's what I expect from the apphost anyway.
Comment: I just moved my additions to httpd.conf to the very end to ensure that nothing else was unsetting my directives.  I am now getting [debug] messages in error_log, so that's an apparent improvement.  They don't seem related to what I'm working on though, as they are notes about /server-status and caching of store_headers...
Comment: (trimmed date/time to fit) proxy_util.c(1818): proxy: grabbed scoreboard slot 34 in child 54100 for worker http://apphost.ourdomain.org/
proxy_util.c(1837): proxy: worker http://apphost.ourdomain.org/ already initialized
proxy_util.c(1934): proxy: initialized single connection worker 34 in child 54100 for (apphost.ourdomain.org)
proxy_util.c(1818): proxy: grabbed scoreboard slot 35 in child 54100 for worker proxy:reverse
proxy_util.c(1837): proxy: worker proxy:reverse already initialized
proxy_util.c(1934): proxy: initialized single connection worker 35 in child 54100 for (*)
Comment: Also, according to Firebug, the GET tasks has a status of 304 Not Modified.  I added, inside the  block, a Header add Warning="testing underway" directive since a) there was already a Server entry in the headers, and b) there was no Warning entry in the headers.  Does this sound like a valid test? No warning entry is present in the headers after a graceful restart of my Apache server and a request to the proxiedapp host.
Comment: A status of 304 Not Modified means the response was cached. Did you try to force a full refresh with ctrl+f5? Also, from your comment ("I am now getting [debug] messages") it seems that your first additions were not being loaded at all. In which file did you put them at first?
Comment: Okay, I figured out a way to get Firefox (Mac OS X) to refresh, such that I got a 200 OK status, but that hasn't changed any of the response headers to include my "Header add Server foo" or 'Header add Warning="testing underway"' directives.
Comment: The exact location of my block in httpd.conf was immediately following the MaxRequestsPerChild directive and before the Dynamic Shared Object (DSO) Support section (which precedes the LoadModule entries).  I have now removed my work from httpd.conf and added an Include directive at the end of httpd.conf to pull in a new include file containing just my directives.
Comment: I simplified things trying to get to the smallest case I could verify and ensure I understood. Header add X-Test Testing works as expected: only requests that include /apphost/ get the test header.
Comment: What's still not working is any sort of reverse html adjusting.  So here's a basic question: Should the ProxyHTMlURLMap be a part of the Apache configuration on the public web server or on the internal app server?  I set ProxyHTMLExtended On and then I ask for ProxyHTMLURLMap  /appname/ /apphost/appname/ -- but nothing ever happens.  And no log entries.  Frustrating!
Comment: Did you compile the module yourself, or did you download a binary? If you simply downloaded a binary, it may be that not all dependencies for the module are met. Is there any kind of error logged upon (re)starting apache?
Comment: Compiled from source.  No errors or warnings in error_log after an apachectl graceful
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/4669/discussion-between-brain99-and-tobinjim)
Comment: For folks who come along afterwards, the key was that in my version of mod_proxy_html, 3.1.2: "All knowledge of HTML links has been removed from the mod_proxy_html
# code itself, and is instead read from httpd.conf (or included file)
# at server startup.  So you MUST declare it.  This will normally be
# at top level, but can also be used in a ."  So the first step in having anything be altered by mod_proxy_html was to add "ProxyHTMLLinks a href" as a directive inside my   Many thanks to brain99 for seeing that.
Comment: Please add this as an answer ! I missed this comment the first time I came here :(

configuring mod_proxy_html properly?


Disable snmpd log in BSD?

Question: I can disable SNMP log using snmpd.options in RHEL or CentOS, but I can't find any solution in BSDs. Does anyone knows how to disable it or change the log location? The SNMP message is fillng up my /var directory always, and it's annoying.
Answer: You can configure the options to pass to daemons, but how you can configure it is depends on BSDs (much like it differ between Linux distributions). So, you better refer to documentation.
For FreeBSD 9.x + net-snmp installed via ports, you can configure such in /usr/local/etc/rc.conf as variable snmpd_flags. Check /usr/local/etc/rc.d/snmpd how it is used.

Disable snmpd log in BSD?


PyMC3 Beta-Binomial fails to converge on actual parameter values

Question: Something is not performing as expected with PyMC. I'm trying a simple Beta-Binomial conjugate prior model, trying to recover known parameters.
Control data
from scipy.stats import beta
import numpy as np
import seaborn as sns
def find_ab(x, search=range(2, 22)):
    avg, score, best_a, best_b = 1000, 1000, 1, 1
    for i in search:
        for j in search:
            samples = beta.rvs(i, j, size=1000)
            new_avg = np.mean(samples)
            new_score = abs(new_avg - x)
            if new_score < score:
                best_a, best_b = i,j
                avg = new_avg
                score = new_score
    return best_a, best_b, avg

ctrl = 0.61
a_ctrl, b_ctrl ,avg_ctrl = find_ab(ctrl)
print(f"a={a_ctrl}, b={b_ctrl}, avg={avg_ctrl}")
samples_ctrl = beta.rvs(a_ctrl, b_ctrl, size=10_000)
sns.kdeplot(samples_ctrl)

Test data
test = ctrl + 0.12
a_test, b_test ,avg_test = find_ab(test)
print(f"a={a_test}, b={b_test}, avg={avg_test}")
samples_test = beta.rvs(a_test, b_test, size=10_000)
sns.kdeplot(samples_test)

As you can see, control is centered on 0.61 and test on 0.73. I'll generate samples using Numpy, effectively 10,000 independent Bernoulli trials, each, with 0.61 and 0.73 as inputs, respectively for p.
ris_ctrl = np.random.binomial(n=1,p=avg_ctrl,size=10_000)
ris_test = np.random.binomial(n=1,p=avg_test,size=8_000)

And the modeling in PyMC3
import pymc as pm
with pm.Model() as model_ctrl:
    theta_ctrl = pm.Beta('theta', a_ctrl, b_ctrl)
    lik_ctrl = pm.Binomial('likelihood',p=theta_ctrl, n=len(ris_ctrl), observed=ris_ctrl)
    trace_ctrl = pm.sample(chains=4, draws=4000)
posterior_ctrl = trace_ctrl.posterior['theta'].stack(sample=("chain", "draw")).values
pm.plot_trace(trace_ctrl, compact=False)

with pm.Model() as model_test:
    theta_test = pm.Beta('theta', a_test, b_test)
    lik_test = pm.Binomial('likelihood',p=theta_test, n=len(ris_test), observed=ris_test)
    trace_test = pm.sample(chains=4, draws=4000)
posterior_test = trace_test.posterior['theta'].stack(sample=("chain", "draw")).values
pm.plot_trace(trace_test, compact=False)

But when I look at the traces plots, the ctrl and test have centered on 0.00061 and 0.00091, respectively. I have no idea why the means are magnitudes lower than the parameters that they should recover.
What is going on here? Is this an issue with how I've defined prior and likelihood or an issue with PyMC3?
I know that Beta-Binomial is a conjugate prior so this is unnecessary; but this is effectively why I chose this prior-likelihood as a test use case.
Answer: You specify the number of trials parameter, $n$, inconsistently.
First you simulate Bernoulli random variables with np.random.binomial(n=1, p=p, size=size). Then in the likelihood you have pm.Binomial("likelihood", p=theta, n=len(sample), observed=sample).
Replace n=len(sample) with n=1 to get the expected result.
You can do a back-of-the-envelope calculation to understand why you got the estimates that you report: 0.00061 ≈ 0.61 / 10_000 and 0.00091 ≈ 0.73 / 8_000.


How can we update UWP application run on raspberry pi 3 remotely from Azure Iot hub?

Question: I have created UWP c# application that run on Raspberry pi 3 with windows 10 Iot core OS.It has program that read sensor data and send data to Azure.We want to make sure that once it deploy to customer location we would be able to manage and update application remotely.We have build our iot solution using Azure Iot central.
We have checked below options for automatic device management article from Microsoft MSDN site but those are put us in confusion and do not have any real time sample and suggest lengthy  process of registering and certified solution  application package on store and provide update to device
https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-automatic-device-management
https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-device-management-get-started
We want simple,clear and professional approach to update remote device achieve this so in the future we can support multiple tenant and do not to go for Microsoft store registration approach
Comment: Not sure what you mean. You cannot deploy a new assembly to your device or install new software on it once it is in the field afaik. What you can do is ]manage its configuratuion](https://learn.microsoft.com/en-us/azure/iot-central/howto-manage-devices#change-a-device-setting). If you need to auto update the software I think you need to program that into your application.
Comment: Thank you for reply.I do not need auto update I want to push it to device group when it would require from Azure.I tried to install IOT edge run time but it is not compatible with raspberry pi3.Now i m not sure which way i will follow from suggested in this link.https://learn.microsoft.com/en-us/windows-hardware/service/iot/updating-iot-core-apps#using-oma-dm
Answer: You can use Windows Azure DM Client to update your UWP app. Azure IoT Device Management allows you to update software remotely without the need to have local, physical access to the device. Firstly, you need to upload the new version application into a blob storage, the device client needs to connect the Azure IoT Hub, and then you can use a portal or an application to remote upgrade the application.
Comment: Above one is good example but It has some c++ code.I am not familiar with c++ .it would be very difficult to trouble shoot issue in the production for us
Comment: Sorry,i  can only find this sample which is provided by Microsoft.  Which language did you want? You can post a feedback in the repo.


equal *population* variances in paired t test

Question: I I want to perform a paired t-test to check if there's some effect, I have the distribution of "before" and the distribution of "after" the manipulation. Do I need to assume the population variances of the two distribution are equal ?
Comment: The paired t-test is a t-test applied to the differences, so the distribution of the differences is what matters.
Answer: Any assumptions you make in a paired test would have to do with the paired differences. After all, a paired test is a one-sample test in disguise.
Therefore, NO, you do not need to assume equal variances of the two groups for a paired t-test.
Comment: The paired $t$-test considers whether the mean has changed: it cannot spot whether or not the variance has changed.


How to prove that a map is a Hurewicz fibration?

Question: A Hurewicz fibration is a continuous map $p:E\to B$ having the homotopy lifting property with respect to each space.
Let X be a topological space. I want to prove that for all $n\geq 2$ the map $p_{n}:X^{I}\to X^{n}$ defined by $$p_{n}(\alpha)=(\alpha(0),\alpha(\dfrac{1}{n-1}),..., \alpha(\dfrac{n-2}{n-1}),\alpha(1))$$ is a hurewicz fibration. I tried to do it by induction on n (we know that $p_{2}$ is a Hurewicz fibration) but I failed. How to do it?
Answer: On page 50 of May's "A Concise Course in Algebraic Topology" he states in a lemma that if $A \rightarrow Y$ is a cofibration then the restriction map $B^Y \rightarrow B^A$ is a fibration.
In your case if we set $A = \{k/(n-1) \in I \mid\ 0 \leq k \leq n-1 \}$ and consider the inclusion map $A \rightarrow I$ it suffices to prove that this map is a cofibration (which is simple enough) to show that $X^I \rightarrow X^n$ is a fibration. This is because $X^A \approx X^n$ in a way that commutes with all the necessary maps proving that $X^I \rightarrow X^n$ is indeed a fibration.
By fibration and cofibration I mean Hurewicz fibration and cofibration.


Trigger a function after saving content type

Question: I've created my own search engine with a custom module and some XML.
I would like to add content to the XML file with a custom function in my module.
The content that needs to be added will be coming from some content types. Is there a way to trigger a function after a content type is saved (node saved)?
I know the Rules module can do this, but I need to do it from my custom module (i.e. I need to write a function to achieve this).
Is this even possible?
Answer: There are some hooks you can use to do this, but they are all fired before the data is recorded in the database.
Have a look at hook_node_insert(), hook_node_update() and hook_node_presave(). The two first ones are fired only on insert or update, the last one every time.
After, another way to do so, is to add your own submit method on node_form, using the hook_form_FORM_ID_alter() (hook_form_node_form_alter()), which will be fired after the node is properly saved in the database.
If I were you, I would use a setting page for my module to set the content types to use.


Squid, configured for SSL, chokes on some sites

Question: I have a Squid 3.5.23 running on Debian Stretch, recompiled from the deb source and configured as a transparent proxy. I changed the configuration in order to allow SSL proxying and it seems to be running OK when I install the generated Squid certificate as a trusted root authority. Facebook, Google, Kernel.org and most other HTTPS sites pass through OK, and the browser correctly thinks those sites' certificate authority is the proxy's. Now, SOME sites give me a certificate warning and then an error if I accept it as an exception.
https://elpais.com ->
<code>The following error was encountered while trying to retrieve the URL: https://126.96.36.199/*

    Failed to establish a secure connection to 184.108.40.206

The system returned:

    (71) Protocol error (TLS code: SQUID_ERR_SSL_HANDSHAKE)

    Handshake with SSL server failed: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure

This proxy and the remote host failed to negotiate a mutually acceptable security settings for handling your request. It is possible that the remote host does not support secure connections, or the proxy is not satisfied with the host security credentials.
</code>
https://wiki.squid-cache.org/ (Now that is ironic) ->
    The following error was encountered while trying to retrieve the URL: https://master.squid-cache.org/*
<code>    Failed to establish a secure connection to 22.214.171.124

The system returned:

    (71) Protocol error (TLS code: X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY)

    SSL Certficate error: certificate issuer (CA) not known: /C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3

This proxy and the remote host failed to negotiate a mutually acceptable security settings for handling your request. It is possible that the remote host does not support secure connections, or the proxy is not satisfied with the host security credentials.
</code>
I generated the certificate with the following commands:
openssl req -new -newkey rsa:4096 -days 3650 -nodes -x509 \
-keyout mycompany.pem -out mycompany.pem
openssl x509 -in mycompany.pem -outform DER -out mycompany.der
/usr/lib/squid/ssl_crtd -c -s /etc/squid/certs/ssl_db -M 4MB
chown -R proxy.proxy ssl_db
Clues?
Comment: Not sure what is the reason for failing ssl handshake ( I do not have any troubles with the site you mentioned with explicit proxy ); but the reason for being unable to get issuer locally is a site mis-configuration - the admin of the site did not include whole chain of SSL certificates into initial SSL handshake - see more explanations at https://docs.diladele.com/faq/squid/fix_unable_to_get_issuer_cert_locally.html
Answer: In the end, I solved the problem by installing Squid 4.0.21 (still a beta at this moment) which has code to handle these missing certificate cases like browsers do. More details at this page in Squid's wiki.


Tough situation - "does an extension which does XYZ exist?" questions

Question: Meta ref: Is it appropriate to ask about experiences with specific extensions and help customizing?
Question ref: https://magento.stackexchange.com/questions/9945/what-is-your-experiences-with-using-and-or-modifying-multi-warehouse-by-innoexts
This user has gone out of his way to ensure he's asking his question as true as possible to acceptable "just the facts" limits. The most recent edit poses several criteria which are more likely to result in clear "yes/no" answers than the previous wording. I am seeking advice from my fellow moderators on this - while this question is pushing the boundaries of potentially receiving "opinion-based" answers, it seems to be just inside the limit in my mind. I'd like to reopen & let it stand, but I want to check that feeling with others.
Edit - Related meta discussion here: Commercial Extension Recommendation
Answer: My response is generic, but I am gonna voice out my concern anyway.
Should be allowed
IMO not everyone is going to build custom extensions from scratch. Lets say, I am trying to tie up my store with Braintree and their extension on MagentoCommerce is crap. So I want to pick that up and fix things that are not working rather than building from scratch. I might need some help on that road. And what about if I don't have magento mojo? May be I am just a general PHP developer? I am gonna need some help. Don't see any point why that should be discouraged.
Commerical extensions
Why treat them differently? I know a customer has paid for their support (or may be their support expired), or may be they are not getting helpful responses. Why should the customer (Magento user, lover?) be deprived of seeking help here?
If you are pissed at premium extension builders because they sorta offload their work here, you are not obliged to help every single of them. Lets not forget what brings us together as a community here.
And Stack Exchange network already has means to control quality. What's good enough will be upvoted eventually and something that's terrible will be downvoted, so lets just keep it to that.

TLDR: If the question is asked in a way how it should be, regardless of whether its about asking about opinion or code level help for free / premium extension, it should be allowed, IMO.
Comment: Thanks for the well thought out answer. It brought out some points I hadn't thought.  Really what is the difference if I paid for an extensions or not? I am the one who paid the price, so my customer got a lot of functionality for a whole lot less money than custom even after the customizing I need done.
Comment: Mostly it was the Magento mojo comment.
Answer: I'm voting for allowed. There is no other forum to really help someone choose an extension that would fit the needs or ask questions. For me it should be disallowed to put links/pricing/any obvious spam. But discussing issues with an extension - how that is an advertisement?
Maybe adding something in the post like "WE DO NOT ENDORSE ANY SPECIFIC EXTENSION" would help?
Answer: I think extension existence/recommendations are ok, but I don't see any value to the community for commercial extension bug questions because there are a lot of commercial extensions with bugs and this will just create clutter for the 99.9% of users who don't even have access to the code for those exensions. Self-promotion could be a problem and I think answers with links to commercial extensions by the creators without an accompanying detailed explanation should not be acceptable.
I see this as only slightly different than the EE issue since EE has enough overlap with CE that most questions will apply equally. EE questions that can't be effectively asked due to licensing terms should just not be asked at all, IMO.
Comment: What seems to be happening thus far with extension bug questions is that OP is asked whether they have engaged vendor support, and I believe that some/many end up being closed as "Too Localized"
Comment: It really depends on who you think stack exchange is for -  specialised questions like this don't have much value to power users looking for points, but they're more useful to the general public who are trying to get things done and are searching for answers.
Answer: You know my opinion Ben. Call me paranoid but this particular question is spam.
I have nothing against questions like "does such an extension exists" as long as no links to commercial extensions are listed in neither question, nor answers.
Comment: So to your way of thinking would the post be allowable if OP had said "InnoExts Multi-Warehouse extension"? I noticed that OP seemed to deliberately leave out a direct link to the extension page?
Comment: *"If you think I'm harming a website"* - not at all, Tim. I think that the mods and the community all have equal right to establish an identity and culture for this community. We will naturally have different interpretations of content and related boundaries. My main interest is that when there are differences, we discuss them in public so that the community can be informed. Let's both post to social media to get some more input? I see & understand your point, and I want to get some consensus.
Comment: I don't see a link to an extension?
Comment: Innoexts.com in the title?
Comment: I know that I'm playing a "bad" inspector here but someone have to do this. I'm guarding this website to be used in a proper way and of course some times I'm going a bit far. However I believe it's better to be over then under cautious here. If you think I'm harming a website acting like this please let me know and I will retire. No offence.
Comment: I think that unless you are willing to do some research, you should not call something spam. I'm the OP in question and I did research in the meta before I asked. At what point does someone get _known_ enough to post there own extensions like fooman just did? I am nowhere near the level of fooman and perhaps never will be but I still have valid questions. I don't even sell extensions.
Answer: I think this kind of question (are there extensions that do X Y Z and that are compatible with extension W) is totally fine, but editing out all the first half as irrelevant would be fine.
Comment: *"editing out all the first half as irrelevant"* <-- ?
Comment: In this case, nothing in the background section is really relevant to the actual question, and all of the things that (I suspect) are setting off Tim's shill-radar are in that part of the question.
Comment: Relevant because I wanted to make clear what I didn't want as well as what I did want. How would you ask the question?


Building same directory structure of git server and bitbucket

Question: I have two environments, one BitBucket and the second a regular git server used with git-shell.
Problem is - I want to use one link for all ENVs
In order to use the same URL and I manipulate the host via /etc/hosts.
Example
# /etc/hosts
# ENV X
my-git-repo.com <bitbucket.com>

# ENV Y
my-git-repo.com <personal server.com>

And it works fine when I use the domain in all ENVs:
git clone ssh://my-git-repo.com/.... .git

My problem remains - is the structure between the two providers
# Structure of BitBucket
ssh://my-git-repo.com/projectKey/needed_repo.git
                         ^^^

# Structure of git server has no "projectKey"
ssh://my-git-repo.com/needed_repo.git

The fact that the URL is different still making me juggling with ENV variables and all kinds of hacks to understand in which ENV i am and then change the address.
Yet, I want a single URL for all.
Question: how i adjust git server directory structure to be the same as BitBucket ?
this way the link is identical ?
Or any other idea will be appreciated
Answer:
a regular git server used with git-shell.

It depends on the actual nature of your git server, but a straightforward approach would be to said local Git server to serve your repository from the projectKey subfolder.
Meaning, you would move your existing needed_repo.git from the root folder server by your Git server, to a new projectKey subfolder.

But in a "configuration level" it just not working ... something between the combination of authorized_keys and .git project and the way the interact: just keeps failing.

Adjusting the server's directory structure is one thing, but making sure SSH and the Git services respect and function with the new structure is another challenge.
First, make sure you have the proper configuration in the ~/.ssh/authorized_keys file.
If you are using something like git-shell, then your authorized_keys might look like:
command="git-shell -c \"$SSH_ORIGINAL_COMMAND\"",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3N...

The git-shell ensures that only Git commands can be executed over the SSH connection.
Second, double-check the directories (including the new projectKey ones) and the repositories inside them have the correct permissions.   Typically, they should be owned by the git user (or whatever user your Git service runs as).
chown -R git:git /path/to/repositories

Those checks allow you to test SSH directly:
ssh firstname.lastname@example.com git-receive-pack 'projectKey/needed_repo.git'

(check the logs at /var/log/auth.log or /var/log/secure)
If there is an issue with the SSH setup, that ssh command should help you pinpoint it.

If nothing works, consider using gitolite instead
Gitolite allows you to define repositories in its configuration with a namespace structure. For instance, you can easily set up repositories under different "projectKeys" just like BitBucket.
In your Gitolite config, you would have entries like:
repo projectKey1/needed_repo
RW+ = @all

repo projectKey2/another_repo
RW+ = @all

The above would correspond to directories like projectKey1/needed_repo.git in the Gitolite home directory.
With Gitolite in place, when you point my-git-repo.com to your personal Git server, your clone URL would look the same as BitBucket's:
ssh://email@example.com/projectKey1/needed_repo.git

While Gitolite does not directly make your BitBucket and personal server URLs identical, it provides the tools and configurations to set up your personal server in such a way that its URL structure matches BitBucket's, making it easier for you to use the same URLs by manipulating /etc/hosts as you initially intended.
Comment: @RickyLevi OK. The Gitolite approach might be safer then.
Comment: Yes that was my thought, but in a "configuration level" it just not working ... something between the combination of authorized_keys and .git project and the way the interact ... just keeps failing
Comment: I highly appreciate it @VonC we are actually using gitolite, I had no idea about `repo projectKey1/needed_repo` !! I'll try it out ! just wanted to mention that I actually tried the first snippet that you wrote, but running `git clone ssh://domain.com/...` the slash caused it to search in the `/` root folder, meaning only `git clone ssh://domain.com/home/$user/repos/needed_repo.git` - but i'll try the gitolite thing !
Comment: @RickyLevi `/` root folder? That would happen with SSH (no Gitolite or forced command), using a key registered in `/root/.ssh/authorized_keys`. Surely, you are not using the remote `root` user with your SSH queries?
Comment: no no, it just go to the root and say no permissions ... it's like it doesn't start from the root folder of the home user - it starts from the root folder of the machine itself, maybe the `command=` doesn't work correctly in my case
Comment: Tested gitolite conf as you said - and it worked. many thanks !


Find the limit of $\lim_{ x\to 14} \frac{x^2-14x}{x^2-196}$

Question: Find the following limit when  $$\lim_{ x\to 14} \frac{x^2-14x}{x^2-196}$$ I have find that subbing in 14 gives a null answer. But am having trouble factorizing this equation
Comment: @Kevin it's too overboard.
Comment: Try L'Hôpital's rule
Answer: $$\dfrac{x^2-14x}{x^2-196}=\dfrac{x(x-14)}{(x-14)(x+14)}$$
Answer: $$\frac{x^2-14x}{x^2-196}=\frac{x(x-14)}{(x+14)(x-14)}={x\over x+14}$$ Then you will find the limit$={14\over28}={1\over2}$.
Answer: $$x^2-14x=x(x-14)\text{ and } x^2-196=x^2-14^2=(x-14)(x+14)$$
Answer: Since x tends to 14 and when you replace x with 14 you get 0/0 condition. Apply L'hospital rule i.e. differentiate both numerator and denominator w.r.t. x. Apply the limit and you have your answer.
Answer: Hint: when $x \neq 14$ we have
$$
\frac{x^2-14x}{x^2-196} = \frac{x(x-14)}{(x+14)(x-14)} = \frac{x}{x+14}.
$$


Alocação de memoria de um serviço

Question: Estou com um problema, preciso verificar a quantidade de memória que um serviço especifico está alocando.
Existe algo em C# que faça isso? Alguma classe ou método?
Pois todas que vi, trazem a informação geral de consumo do PC.
Comment: É possível mas depende de como está isso, você não deu nenhum detalhe. Certamente não há algo mágico que você coloque e ele adivinhe a quantidade de memória usada de algo não especificado. Se você não sabe o que você quer descobrir, você vai descobrir nada. Então fale pra gente o que você quer saber. Talvez você não precise disto de fato.
Comment: Deixa eu detalhar então. Meu sistema tem um serviço CacheService.exe, ele vai alocando memória conforme vai sendo utilizado eu gostaria de criar um JOB em c# para ir verificando  a quantidade de memória que ele está consumindo.
Answer: Para saber informações sobre um serviço basta pegar o processo associado a esse serviço e avaliar suas propriedades:
<code>// Pega todos os serviços ativos com o nome NomedoServiço.exe e faz uma inspeção superficial em suas propriedades
foreach(var Processo  in  Process.GetProcessesByName("NomedoServiço.exe")){

    Console.WriteLine($"{Processo}-{Processo.Id}");
    Console.WriteLine("-------------------------------------");

    Console.WriteLine($"  Uso de memória física  : {Processo.WorkingSet64}");
    Console.WriteLine($"  Tempo de uso da CPU    : {Processo.TotalProcessorTime}");
    Console.WriteLine($"  Memória paginada       : {Processo.PagedMemorySize64}");
}
</code>
Answer: @Felipe Rosa
Você está querendo saber quanto de memória a sua aplicação utiliza, é isto que entendi.
Bom, encontrei algumas publicações que poderão auxiliá-lo, porém tem que pesquisar sobre sistemas operacionais, isso o ajudará, vamos lá, então:
O que encontrei e que está como entendi da sua questão é Monitorando o consumo de memória e tempo de execução

Read more: http://www.linhadecodigo.com.br/artigo/3077/monitorando-o-consumo-de-memoria-e-tempo-de-execucao.aspx

Este segundo está em inglês é mais abrangente mas acredito estar ligado ao que você precisa
http://www.codeproject.com/Articles/18727/Customized-Task-Manager-in-NET-using-C-and-Windows
Acredito que com estes dois modelos você conseguirá atingir o seu objetivo.

att

LMV

Alocação de memoria de um serviço


Como fazer uma function, substituir o valor de uma varível em JS?

Question: Olá! Estou desenvolvendo um joguinho em Java Script, mas estou com uma dificuldade na hora que o jogador o compra um bonús de moedas, ela irá substituir um valor em uma outra funcion, para quando ela for ativada, o jogador ao inves de ganhar 1 ponto, irá ganhar 2 pontos. Mas inflizmente, não consigo fazer a váriavel ${money}, valer 2 pontos, ao inves de 1, e isso vale tambem para os outros dois bonús que tem no jogo! Qualquer ajuda ou auxílio, é de grande valor! Segue o código:

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clique para ganhar!</title>

Clique, Ganhe, Vença!

        <form>

            <input type="button" id="clqg"  value="Ganhar!" onclick="button()">

                Bonús: 75$
                <input type="button" class="btnbuy"  value="Comprar" onclick="buyone()">

                Híper bonús: 125$
                <input type="button" class="btnbuy" value="Comprar" onclick="buytwo()">

                Ultimate final: 1000$
                <input type="button" class="btnbuy" value="Comprar" onclick="buythree()">

        </form>

```

Answer: Você pode atribuir declarar uma variável somador e usar ela para modificar o valor de money. daí é só modificar o valor de somador que inicialmente é igual a 1, para o valor que desejar.
Exemplo:

var txt = document.getElementById('money') // div onde vai o valor da moeda //
var money = Number(0); // valor da moeda inicial = 0 //
var somador = 1;

function button() {
  money += somador
  txt.innerHTML = `Seu saldo é igual a <strong>${money}$</strong>`
}

function buyone() {
  var btn1 = document.getElementById("btnone")
  if (money >= 75) {
    money -= 75;
    btn1.innerHTML = `Comprado!`
    somador = 2;
  } else {
    window.alert('Seu saldo é insuficiente!')
  }
}

function buytwo() {
  var btn2 = document.getElementById('btntwo')
  if (money >= 125) {
    money -= 125;
    somador = 4;
    btn2.innerHTML = `Comprado!`
  } else {
    window.alert("Seu saldo é insuficiente!")
  } // opção de dobrar os pontos //
}

function buythree() {
  var btn3 = document.getElementById('titleex')
  if (money >= 1000) {
    money = 0;
    btn3.innerHTML = `Parabens, você ganhou!`
  }
} // aqui se zera o game //
body {
  background-color: rgb(12, 12, 136);
  margin: 25px;
}

h1 {
  text-align: center;
  font-family: 'Lexend Mega', sans-serif;
}

form {
  background-color: white;
}

div {
  text-align: center;
}

#clqg {
  margin: 10px;
  padding: 15px 15px;
  font-family: 'Happy Monkey', cursive;
  font-size: large;
}

.buyling {
  padding: 10px 0px 0px;
}

.title {
  font-size: xx-large;
  font-family: 'Lexend Mega', sans-serif;
}

.btnbuy {
  margin: 15px;
}

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Clique para ganhar!</title>

Clique, Ganhe, Vença!

    <form>

      <input type="button" id="clqg" value="Ganhar!" onclick="button()">

        Bonús: 75$
        <input type="button" class="btnbuy" value="Comprar" onclick="buyone()">

        Híper bonús: 125$
        <input type="button" class="btnbuy" value="Comprar" onclick="buytwo()">

        Ultimate final: 1000$
        <input type="button" class="btnbuy" value="Comprar" onclick="buythree()">

    </form>

Comment: Muito obrigado rapaz!!


How to compute the pullback of $(2xy+x^{2}+1)dx+(x^{2}-y)dy$ along $f(u,v,w)=(u-v,v^{2}-w)$?

Question: I'm trying to do my first pull-back of a differential form.
I know that $\omega=(2xy+x^{2}+1)dx+(x^{2}-y)dy$ is a differential form on $\mathbb{R}^{2}$.
I have $f : \mathbb{R}^{3} \to \mathbb{R}^{2}$ which is
$$f(u,v,w)=(u-v,v^{2}-w)$$
and I have to calculate the pullback. I was told that by definition
$$(f^{*}\omega)(X) = \omega(f_{*}(X)),$$
and so I calculated
$$f_{*}=\begin{pmatrix}
1 & -1 & 0\\
0 & 2v & 1
\end{pmatrix}$$
But then I don't really know how to proceed. Should I take a general vector and calculate the form, should I substitute $x,y$ with $u,v,w$? Do you have a general recipe to proceed?
Comment: Refer to this http://math.stackexchange.com/questions/576638/how-to-calculate-the-pullback-of-a-k-form-explicitly
Answer: $\newcommand{\Blank}{\underline{\qquad}}$(Good-natured note: This isn't the first pullback you've computed. You've been computing pullbacks since you learned the chain rule and  method of substitution.)
It's easiest to start by turning the clock back to 1850 or so. You have
\begin{align*}
x &= u - v, \\
y &= v^{2} - w,
\end{align*}
so the chain rule gives
\begin{align*}
dx &= \Blank\, du + \Blank\, dv + \Blank\, dw, \\
dy &= \Blank\, du + \Blank\, dv + \Blank\, dw.
\end{align*}
Now, to express this in modern terms, replace the $1$-forms on the left by pullbacks: $dx \to f^{*}dx$, etc.
Answer: The nice thing about forms is that you are intuitively doing the right thing, which is: just plug in $x=u-v$ etc. as Andrew already wrote.
To see the connection with the formal definitions, note that the exterior derivative and pullbacks commute and hence $f^*dx=d(f^*x)=d(x\circ f)=d(u-v)$. Furthermore, pullbacks respect wedge products, so e.g.
$$f^*(x^2dx)=f^*(x^2 \wedge dx)=(f^*x^2) \wedge (f^*dx)=(u-v)^2d(u-v)$$


How do I enable scroll arrows for large number of items in UISegmentedControl?

Question: I want to use a UISegmentedControl to present several options for interacting with the screen. However I have a larger number of items than the width of the screen on an iPhone device. How do I enable scroll arrows on the UISegmentedControl to scroll through the items as seen is some apps?
Answer: There is no built-in support for arrows and scrolling in UISegmentedControl.  You need to put in arrow segments yourself and change the segments when the arrow segments are clicked.