Backslashes interpreted as control character in JavaScript

Question: I've got LaTex code from server and have no control over it. I would like to print the LaTex code as it is using JavaScript, but it interprets as control characters on assigning to variable.
var str = '\[\frac{{{d^2}y}}{{d{x^2}}} - \,3\,\left( {\frac{{dy}}{{dx}}} \right)\, + \,2y\, = \,0\]';

This interprets as follows
[rac{{{d^2}y}}{{d{x^2}}} - ,3,left( {rac{{dy}}{{dx}}} ight), + ,2y, = ,0]

And I want as follows:
\[\frac{{{d^2}y}}{{d{x^2}}} - \,3\,\left( {\frac{{dy}}{{dx}}} \right)\, + \,2y\, = \,0\]

I tried varies RegExps, and result of
var index = str.indexOf("\\")

is -1
JavaScript removes control characters like \f, \r and so on and there are thousands of backslash notations in TeX.
Comment: How are you getting the code from the server? What is the server response type? If the server does not output the right escaped string, then you have to fix it on the server... If you have no control over it, I think you're screwed...
Comment: I've already said that its beyond my control that how I should get the LaTeX code, my role is to render it to graphics using JavaScript, and I stuck in this situation.
Comment: That's not what you were asked. In which way you get (without control) the LaTex code. How is loaded in str var?
Comment: It's a text/plain response from server, I get it from from Ajax request and assign it to the var. BTW its not important how I get it to assigned to a var. Please focus on the problem. That's why I'm on SOF!
Comment: This is only a representative presentation. I also get response in json format, still the string gets interpreted with escape characters and they simply been removed.
Comment: Ok, you got an answer now.
Answer: How is loaded in str var?
Anyway, there is a work around (working here):
var c=',[]flr';
for(var i=0;i<c.length;i++)
 eval("str=str.replace(/\\"+c.charAt(i)+"/g,'\\\\"+c.charAt(i)+"');");

What we do is for any char in c evaluate the following code (replacing X with the char):
str=str.replace(/\X/g,'\\X');

Anyway, there is a work around (working here):
var c=',[]flr';
for(var i=0;i<c.length;i++)
 eval("str=str.replace(/\\"+c.charAt(i)+"/g,'\\\\"+c.charAt(i)+"');");

What we do is for any char in c evaluate the following code (replacing X with the char):
str=str.replace(/\X/g,'\\X');

Ok, that's an odd (and maybe dangerous) bug at the site which delivers the JSON. If it does not turns the \' to \', maybe it does not turns the ' to \'. So, anything after a ' or a " (depending on how the string is quoted) will be executed on any site that includes that (i.e. your site). Maybe as JSON is a little more secure.
Comment: How many characters should I assign to c? Here we know these are ,[]flr. Or we require to assign whole set of characters from ascii (7-bit); but these characters are unpredicted as there are lots of TeX escape sequences coming from TeX server. However the solution is quite acceptable and thanks for the solution, you saved my time!
Comment: Is there any other way to tell JS not to execute escape sequences quoted in single or double. Like in Perl, it doesn't execute the string when quoted in single. But we have not choice for JS!
Comment: You're wellcome. As far as I know there's no way to avoid execution of escape sequences. You could use a for(var i=32;i<127;i++) eval(...).


overlay does not work after enabling my custom module

Question: I am using latest Drupal 7.
I just noticed my admin overlay is not working.
First I thought its due to Jquery Update contrib module installation however that not it.
 Its apparently due to my custom module, overlay works if I uninstall my module.
My module consists of few basic hooks like hook_menu, hook_form, etc and a simple js file with delete confirm popup code in it.
Also in Home » Administration » Structure » Content types » Basic page, in manage fields tab, 'select a widget' select list (dropdown) shows all options. It is suppose to show options according to field type selected.
<code>$(function() {
 $(document).ready(function () {

  $(".del-link").click(function () {
   var answer = confirm("This action will delete this record?")
    if (answer){ // if yes is clicked on the confirm box.
     var del_record_id = this.id; // get record id that needs to be deleted.
      window.location = "/delete_url/" + del_record_id; // go to url which trigs the delete function and the record is deleted.
    }
  });

  $("#edit-my-form-field").click(function () {
    $("#edit-my-form-field").is(":checked") ? $("#show-hide-div").hide() : $("#show-hide-div").show();
  }); // end of click function.

 }); // end of  $(document).ready(function ().
}); // end of $(function().
</code>
Has anyone come across similar issue?
Comment: Sounds very much like you've introduced javascript errors in your simple js file that are stopping the rest of the JS on the page from loading. Are there errors in the browser console?
Comment: Yes, you are right, apparently there seems to be an error in js. Browser Console shows >>> Error: ReferenceError: jQuery is not defined Source File: egl_dcs/misc/drupal.js?mgz5hk
Line: 5.
Line 5 is >> // Allow other JavaScript libraries to use $. jQuery.noConflict(); Pls help! :-/
Comment: Can we see your JS code? How do you load it in Drupal?
Comment: I hav added js code in my question. :)
Comment: It seems like jquery is not loaded or something like that. As @ermannob asked, how do you call this JS file in your module?
Comment: I am using drupal_add_js, my custom js works fine. But built in drupal ajax like overlay, form ajax, etc stopped working. So right now my situation is, its either my custom js or drupal ajax I want both to work. :-/
Answer: I figured (googled) it out. :)
I added my custom js in my custom module's info file instead of using drupal_add_js in my module directly.

scripts[] = my_module.js

and added drupal behaviors in my js file as well, so now my custom js looks like below

(function ($) {
Drupal.behaviors.my_module = {
attach: function (context) {

// my js code

 }
};
})(jQuery);

I spent many hours figuring this out but it was as simple as could be be.
Hope this helps someone! :)
Answer: did you wrap your code in a closure? if it is Drupal 7 you should wrap everything like nya:
<code>(function($) {
  // Your custom code here.
})(jQuery);
</code>
Just throwing the $ around like that in the global scope is cray.


Troubleshoot empty Cartopy streamplot

Question: I'm trying to plot streamlines of vector data using Cartopy (0.17.0), but the resulting figures are empty.  Using straight matplotlib (3.1.1) works.  The array and paths properties for the arrow PatchCollection and lines LineCollection are empty.
I've tried different projections, explicitly creating x, y, v, and u from cartopy.vector_transform.vector_scalar_to_grid(), removing/changing extents, removing nans from velocity fields.
Simple reproducible example:
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

x = np.array([233., 236.83146159, 240.66292318, 244.49438477])
y = np.array([28., 31.645003, 35.290006, 38.935009])
u = np.array(
      [[ 0.03955199, -0.22247993, -0.25873835,  0.04202399],
       [-0.23483805,  0.09814767, -0.10702853,  np.nan],
       [ 0.21835904,  0.06390616, np.nan,       np.nan],
       [ 0.19803461,  np.nan,     np.nan,       np.nan]]
)
v = np.array(
    [[-0.0986053 ,  0.05887021, -0.25543633, -0.20215461],
     [ 0.11536164, -0.11004942, -0.01419378, np.nan],
     [-0.06482275, -0.35679315, np.nan,      np.nan],
     [ 0.16507462, np.nan,      np.nan,      np.nan]]
)
ax = plt.subplot(projection=ccrs.PlateCarree())
ax.streamplot(
    x,
    y,
    u,
    v,
)

This works:
ax = plt.subplot()
plt.streamplot(
    x,
    y,
    u,
    v
)

Comment: This seems like a bug in CartoPy. I would open an issue at https://github.com/SciTools/cartopy/issues/new
Answer: To answer my own question, I found the following workaround:
    from cartopy.vector_transform import vector_scalar_to_grid
    from matplotlib.axes import Axes

    ax = plt.subplot(projection=ccrs.PlateCarree())
    new_x, new_y, new_u, new_v, = vector_scalar_to_grid(
        ccrs.PlateCarree(),
        ccrs.PlateCarree(),
        5,
        x,
        y,
        u,
        v
    )

    Axes.streamplot(
        ax,
        new_x,
        new_y,
        new_u,
        new_v,
        transform=ccrs.PlateCarree()
    )

Troubleshoot empty Cartopy streamplot


Is there an opposite to Clustering or "Anti-"Clustering?

Question: In Clustering we want to find optimal Clusters - data points that are close together (measure by a defined distance measure). Is there any "Anti-"Clustering? We have a set of data points and want to find "Anti-"Clusters - subsets with data points that are as far apart as possible (measure by a defined distance measure, for example euclidean distance).
In a concrete application I have a set of people and want to divide these people into n groups as diverse as possible measure with a few predefined criteria (diverse means: as less as possible of the same values of each criteria in each group).
The first time I thought about this it seemed pretty intuitive but I couldn't find any method to create these subsets, maybe I'm to focused on regular Clustering methods. Sorry, if this question is too trivial, but any help would be appreciated!
Comment: A naive but often serviceable starter definition of a cluster is that its points are like each other **_and unlike points in other groups_**. So, it's still clustering.
Comment: Here's an interesting paper on hipsters - the observations that want to maximize their differences with the population end up looking the same. https://arxiv.org/abs/1410.8001
Comment: Suppose you have 4 numbers: $x_i\in (1,2,8, 9)$. Your distance is the $d(i,j)=|x_i-x_j|$. How do you want your two anti-clusters look? (1,8) and (2,9)?
Comment: My post is admittedly rather imprecise. if we have the four numbers and the distance measure given by you, both {(1,8),(2,9)} and {(1,9),(2,8)} would have the same average distance within the clusters. However, {(1,8),(2,9)} would be the better split since there are no differences in the distances within the clusters.
Comment: Referring to the definition by @NickCox:
The definition of clustering is: points are like each other and unlike points in other groups. And the definition of anti-clustering (which I only chose as a name since I don't know any better) should be, that points are unlike within a group and like points in other groups - which in terms expresses that the distances within the clusters should be rather similar to each other. I hope that makes sense.
Comment: Try using the negative distance metric, d'(x, y) = -d(x, y) or use d'(x, y) = max_d - d(x, y).
Comment: I think what you are asking has been referred to in this paper. They use a inverted clustering approach to sample data points. A Maximal Heterogeneity Based Clustering Approach for Obtaining Samples. https://arxiv.org/abs/1709.01423
Answer: Based on the poster's response in one of the answers, I will rephrase the problem statement because it can be solved using an R package that I wrote:
The task is to partition a set of elements into K groups such that the distances between clusters is minimized and the distance within clusters is maximized. This is mathematically the opposite of clustering and has indeed been called anticlustering; there are some rarely-cited papers on this approach (Späth 1986; Valev 1998). Generally, anticlustering leads to clusters that are similar to each other.
If you are using R, you can use my package anticlust to tackle the anticlustering problem. For example, use the following code to create three similar sets of plants in the classical iris data set:
library(anticlust)
data(iris)

## Maximize the k-means criterion
anticlusters <- anticlustering(
  iris[, -5],
  K = 3,
  objective = "variance"
)

## Compare feature means by anticluster
by(iris[, -5], anticlusters, function(x) round(colMeans(x), 2))
#> anticlusters: 1
#> Sepal.Length  Sepal.Width Petal.Length  Petal.Width
#>         5.84         3.06         3.76         1.20
#> ---------------------------------------------------------------------------------------
#> anticlusters: 2
#> Sepal.Length  Sepal.Width Petal.Length  Petal.Width
#>         5.84         3.06         3.76         1.20
#> ---------------------------------------------------------------------------------------
#> anticlusters: 3
#> Sepal.Length  Sepal.Width Petal.Length  Petal.Width
#>         5.84         3.06         3.76         1.20

My package can maximize two clustering objectives: (a) the classical k-means objective, leading to similar feature means; (b) the cluster editing objective, which is the sum of the pairwise distances within clusters. In the package, you can vary the parameter objective between "variance" (k-means) or "distance" (cluster editing).
The Github page and the package docs contains some more information on the methods and algorithms used in the package.

Späth, H. (1986). Anticlustering: Maximizing the variance criterion. Control and Cybernetics, 15(2), 213–218.
Valev, V. (1998). Set partition principles revisited. In Joint IAPR international workshops on statistical techniques in pattern recognition (SPR) and structural and syntactic pattern recognition (SSPR) (pp. 875–
881).
Answer: There are several related domains:

Outlier detection: find unusual points, rather than typical representatives as in clustering.
Stratified sampling. Choose a random sample such that the samples correspond to different classes. For larger sets, so that the class distribution matches.
Archetypal analysis. Summarize data not by 'average' cluster representatives, but rather by extreme observations that "bound" the clusters.

But you'll certainly need to become more explicit about the formal requirements that you have, some vague intuition is not enough.
Maybe you still want clustering - kmeans tries to minimize the within-cluster variance, which implies that it maximizes the between cluster sum of squares. So in a good kmeans clustering, the typical squared deviation of two objects not in the same cluster is maximized; the clustering does divide the data into partitions that are "as dissimilar as possible".
Comment: Thanks for your answer. I thought about using k-means to help in my problem. My understand is, that k-means minimizes the distance within a cluster and maximizes the distance between the clusters. For my problem I would need to do the opposite. That is to maximize the distance within a cluster and minimize the distances between the clusters (so that the distances within the clusters are rather similar). That why I tried to describe it as "anti-clustering". But it sounds like stratified sampling could be another approach to the problem - I will have to look into this further.
Answer: It's still clustering that you want, because you're trying to split the data into subsets, which is clustering.
If you clustering algorithm is based on a distance measure, then simple negative of that measure or inverse should accomplish subsetting you request. Some algorithms rely on the distance measure being positive, in this case the inverse should work. You could soften the inverse with a fractional power function, of course.
Comment: The correctness and utility of this answer are doubtful, because the parallel with clustering is imperfect. In clustering, data are partitioned into subsets whose values are *mutually close* within each subset but otherwise values in different subsets are *far apart*.  In the present case it appears to be necessary for values within subsets to be *mutually far* (so far, so good) but *no criteria are applied to distances between points in different subsets.* Furthermore, nonlinear transformations of distances ought to produce very different solutions and therefore require careful consideration.
Comment: Right: that's why this seems fundamentally to be a different kind of problem.
Comment: You're right that negative difference would lead to observations within subset far from each other, but the subsets to be close to other. However, I think that it's inevitable.
Answer: Building on the useful comments & answers by Nick Cox and others here:
DBSCAN is a clustering algorithm that also identifies points that do not belong well to any particular cluster, and treats them as 'noise'. This might be one way to achieve what you are after, since it identifies points that are distant enough from clusters to make grouping them together questionable.
Answer: We have been working on unclusters (and anti-clusters and noclusters) and we have a few definitions that we have been exploring.

the holes between clusters that illustrate where points can not exist.
the density of points on the periphery of a cluster.
the density of clusters (as compared to the density of points in the clusters)
the specificity of the centroid in any given cluster... how much can you move the centroid yet still keep the cluster reasonably intact.
the potential overlap between clusters (coclusters) - we even thought there should be a complex cluster with a real and imaginary components to handle overlapping densities.

k-means is certainly a useful approach, but there seems to be some underlying meaning to these "unclusters"... and we have started to try to model these unclusters so that we can learn optimal numbers of clusters and start with 'better' centroid estimates.
It sounds like you are exploring the density aspect to help with cluster separation and overlap. Certainly a very interesting topic and one that warrants more thought.


changing lastactivity mysql table from myisam to memory a good idea?

Question: I am trying to reduce the writes to disk and in my social site I have a lastactivity table which is updated with the time() a user last used the site. It is currently MyIsam:
id          int(7)  PRI auto_increment
lastactivity    int(10) unsigned
username    varchar(25)
it has about 100,000 records currently. If mysql is restarted I can just populate it again from the last logins in the main user table. The machine has a lot of spare memory, but this table is frequently locked I imagine because of all the updates performed on it which would be better if it was MEMORY table type?
Comment: for anyone curious, I decided to benchmark it with a natural mix of selects and updates. The selects were a little faster (even though it uses a range despite HASH index) but the updates were much faster. I will stick to memory but yes perhaps this data doesn't need to be in the DB at all and I could use something like APC to keep track of it.
Answer: Running from memory is always faster than disk with the only draw-back that you'll lose your data in a power-out. However, you claim that you can regenerate your data if such a situation occurs. So, I agree that you should use your memory since you have gobs of it.
That said, I recall something that Knuth once said about data. Something about not having to do any computation at all, if you structure your data correctly. Smart data is better than a smart algorithm.
So, it might be prudent for you to look at how you may re-structure your database and/or application to reduce the amount of locking required?
Take a step back?
Answer: Be sure to know the restrictions applying to in memory tables like the default index type which is HASH and not BTREE. It might be a good idea to review the queries using this table especially if some of them work with range queries. In the later case force constructing the indexes using BTREE rather than the default HASH.


How to redirect before page processing along with all the sent data?

Question: I have a link on my Drupal page. This link points to the page "\node\23423". When user clicks on this link, the user should get redirect to another path "\node\45644".
But this should happen before Drupal starts processing the original path. Also any POST data that is being sent to the original page should be passed to the next redirect page.
Is there a possible way to do this?
Comment: _But this should happen before Drupal starts processing the original path_...that would make this un-related to Drupal, wouldn't it?
Comment: I would suppose, that the OP needs clarification about the approach to what he wants. For me it's not at all clear what he wants though. Best guess would be to change the link in the first place
Comment: Would say no, because node/45644 is supposedly still a drupal path?!
Comment: Well no...how exactly are you going to use Drupal to solve this if the solution has to happen before Drupal gets involved with the request? It's a contradiction in terms, can't happen
Comment: Agree @berliner, some clarification would be good
Comment: @Clive: What I meant by that was that Drupal should be able to do all the bootstrapping but should not process the original page (should not create the page array for the original page) but should pass all the data passed to that page as-it-is to the new page.
Comment: Ah ok, you're just looking for a redirect then. If you want to forward `POST` vars you'll need to tackle it at the web server level with a rewrite rule
Answer: My suggestion (experimental) is something like this (but NOT RECOMMENDED):
<code>function MY_THEME_preprocess_page(&$variables) {
  if(arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    if($nid == '23423') {
      drupal_goto('node\45644');
    }
  }
}

function MY_THEME_node_view($node, $view_mode, $langcode) {
  if($node->nid == 45644) {
    $old_node = node_load(23423);
    $old_node_view = node_view($old_node);

    $node->content['body'] = $old_node_view['body'];
  }
}
</code>
Comment: _But this should happen before Drupal starts processing the original path_...the path has very much been processed at both of those points in the request
Comment: @Clive `But this should happen before Drupal starts processing the original path` - Yes, you're right.. My answer is just a suggestion.. I don't why he needs to redirect BEFORE Drupal processes the original path. May be my answer will help him If he decides to just redirect and show another content..
Comment: Problem is, he specifically needs `POST` vars to be sent along, which can't be done with this method
Comment: @Clive then I would use own path (which's been registered by hook_menu) instead of another node path.. And specify my own implementation of generating content..


Dojo and unregistering widgets

Question: I am new to the Dojo Toolkit. I'm getting the error
Tried to register widget with id=myButton but that id is already registered

whenever I try to load dojo content twice (meaning I load HTML content through jQuery.Load into a container div). Is there a way of unregistering already registered widgets in dojo? I've seen some examples, but I don't really get them working.
My button:
<button dojoType="dijit.form.Button" id="myButton">button</button>

Answer: If you're looking to unregister specific widgets, you can use their destroy()  or destroyRecursive() methods. The second one destroys any widgets inside the one you are destroying (i.e. calling destroyRecursive on a form widget will also destroy all the form components).
In your case, it sounds like your best bet would be to do this before jQuery.load -
var widgets = dijit.findWidgets(<containerDiv>);
dojo.forEach(widgets, function(w) {
    w.destroyRecursive(true);
});

The above code will unregister all widgets in <containerDiv>, and preserve their associated DOM Nodes. To destroy the DOM nodes, pass false to destroyRecursive instead.
Reference:
http://dojotoolkit.org/api/1.3/dijit/_Widget/destroyRecursive
Comment: Others looking for a solution : See also answer below for non-recursive solution.
Comment: Exactly what I was looking for. Thanks a bunch!
Answer: Based on http://bugs.dojotoolkit.org/ticket/5438, I found a sufficient way of destroying dojo-widgets:
dijit.registry.forEach(function(w){
                  w.destroy();
          });

Answer: This worked for me:
dijit.byId( 'myButton' ).destroy( true );

Answer: I think you would be better off removing the id from your button and accessing it using an attach point. You would basically do <button dojoType="dijit.form.Button" data-dojo-attach-point="myButton">button</button>
then in your code you would access it like this.myButton.... however im not sure which version of dojo you are using. This will fix any id issues since dojo will assign a unique id to it automatically.

Dojo and unregistering widgets


How can i add a custom delegate method to my singleton

Question: I am developing a digital magazine reader app and it requires to download magazines first.
While downloading them i want to pass download progress data between viewcontrollers.
That's why i am using singleton design pattern.
I also use NSNotification to update progressBar percentage while its downloading. But i do not think it is quite efficient to send notificiation in every milisecond. So i decided to use delegate design pattern but i don't know to implement a custom delagete method. Any help on custom delegate? And is it the best way to use delegate?
// Header

@interface ZXCSingleton : NSObject

+ (id)sharedInstance;

- (BOOL)isDownloadingProduct:(NSString *)productID;
- (void)addToDownloadListWithProductID:(NSString *)productID;
- (void)removeFromDownloadListWithProductID:(NSString *)productID;
- (NSArray *)getDownloadList;

- (void)setDownloadProgress:(float)progress
              withProductID:(NSString *)productID;
- (float)getDownloadProgressWithProductID:(NSString *)productID;

@end

// M

#import "ZXCSingleton.h"

@implementation ZXCSingleton{
    NSMutableArray *downloadList;
    NSMutableDictionary *downloadProgress;
}

+ (id)sharedInstance
{
    static ZXCSingleton *sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        sharedInstance = [[ZXCSingleton alloc] init];
    });
    return sharedInstance;
}

- (id)init
{
    self = [super init];
    if (self) {
        downloadList        = [[NSMutableArray alloc] init];
        downloadProgress    = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (BOOL)isDownloadingProduct:(NSString *)productID
{
    for (int i = 0; i < downloadList.count; i++) {
        if ([[downloadList objectAtIndex:i] isEqualToString:productID]) return YES;
    }
    return NO;
}

- (void)addToDownloadListWithProductID:(NSString *)productID
{
    [downloadList addObject:productID];
}

- (void)removeFromDownloadListWithProductID:(NSString *)productID
{
    [downloadList removeObject:productID];
}

- (NSArray *)getDownloadList
{
    return downloadList;
}

- (void)setDownloadProgress:(float)progress
              withProductID:(NSString *)productID
{
    if (progress != [[downloadProgress objectForKey:productID] floatValue]) [[NSNotificationCenter defaultCenter] postNotificationName:@"downloading" object:nil];
    [downloadProgress setObject:[NSString stringWithFormat:@"%0.2f", progress] forKey:productID];
}

- (float)getDownloadProgressWithProductID:(NSString *)productID
{
    return [[downloadProgress objectForKey:productID] floatValue];
}

Answer: Define a delegate by creating a protocol first for defining the interface required by the delegate :
@protocol ZXCSingletonProtocol

   - (void)downloadProgessUpdates:(float)progress;

@end

Create a property for the delegate in your singleton :
@property (nonatomic, weak) id<ZXCSingletonProtocol> delegate;

Let your view controller conform to that protocol :
@interface MyViewController : UIViewController <ZXCSingletonProtocol>

and implement the downloadProgessUpdates in the view controller as required (e.g. update the UI element with the given progress number). REMEMBER to set the delegate when you initialize the view controller (viewDidLoad will do):
[ZXCSingleton sharedInstance].delegate = self; // self is the view controller instance

In your singleton update the setDownloadProgress method to update the delegate as well :
[_delegate downloadProgessUpdates:progress];


Character Controller for Horizontal Shooter in Unity 3D

Question: I am creating a horizontal side-scrolling shooter which I plan to release on mobile devices. How can I set up the ship so that:

It can be moved up/down/left/right freely (with varying horizontal/vertical speeds)
Collide and stop against obstacles (i.e. IF collision with obstacle STOP)
Diagonal movement against horizontal plane (down + right input) should move right pressed against floor

The ship must not be able to pass through obstacles.
I created a custom character controller which simply adjust position based on velocity. I cannot figure out how to detect collision and avoid moving through obstacles. There must be an easier way to achieve this simple requirement.
Note: To clarify, the camera follows the ship, it does not automatically scroll. The player can stop the ship by releasing input button.
Answer: To start with, try making sure you've added a collider component to your obstacles and to your character controller.  That should be enough to stop your ship passing through the obstacles.
Comment: The ship object has a spherical collider. I am unsure as to how to make that collider work. My custom controller script simply uses velocity to translate the object. I do not know how to detect collision and cancel movement.
Comment: Take care to not enable Collider's IsTrigger checkbox.
Comment: @Kay The `IsTrigger` checkbox is not ticked. My main problem (I think) is that I have no collision detection logic in my character controller. I am not sure how this would be implemented.
Comment: @Kay I have added "Ridged Body" and now it appears to be colliding. But upon hitting ground the ship begins to rise upwards and it doesn't stop. I have Mass:1,Drag:0,Angular Drag:0.2,Gravity:No,Kinematic:No,Interpolate:None,Collision Detection: Discrete, Lock X/Z Rotation
Comment: I've found the solution now, see below. Thanks for your help, you have helped me to improve my understanding of how this works.
Answer: I was storing my own velocity vector which I was then applying using transform.Translate. This obviously was ignoring any collision detection and would have required a custom collision detection implementation.
Instead I found that the Rigidbody component contains its own velocity variable. That velocity value can be easily altered and the object will automatically translate and collide with obstacles. Here is an example:
using UnityEngine;
using System.Collections;

public class CharacterController : MonoBehaviour {

    public Vector2 maximumSpeed = new Vector2(1.0f, 1.0f);

    void Start() {

    }

    void Update() {
        Rigidbody rigidbody = GetComponent<Rigidbody>();

        Vector2 velocity = new Vector2();

        velocity.x = Input.GetAxis("Horizontal") * maximumSpeed.x;
        velocity.y = Input.GetAxis("Vertical") * maximumSpeed.y;

        rigidbody.velocity = velocity;
    }

}

This appears to work quite well. Comments would be appreciated :-)
Comment: The other solution that is perhaps more suitable for a player-controlled entity is to use the `CharacterController` component, which provides similar function but with some "loosened" logic to allow for the fact that the entity is player-controlled (as opposed to being a pure physics entity).  With your velocity/inertia though, it may be that you're best with the solution you have.
Comment: @Dan Cheers I will experiment with that. Is it likely that `CharacterController` would perform better?


How to update python-sqlite on mac osx

Question: Python 2.7.3 on Mac OS X Snow Leopard (downloaded from python.org), tells me it is using sqlite 3.6.12 (sqlite3.sqlite_version).
However, to use foreign keys, I need at least sqlite 3.6.19.
How can I update sqlite alone?
I already tried pip install pysqlite (from this question/answer: Updating the SQLite3 build on my python install), but the sqlite_version did not change. pip search sqlite shows pysqlite 2.6.3 is installed, but I still have, both from commands python and python2.7
>>> import sqlite3
>>> sqlite3.sqlite_version  #3.6.12
>>> sqlite3.version         #2.6.0 (yeah, no 2.6.3)

Answer: You'll first need to install SQLite, then build and install pysqlite, making sure that it's building against your newly installed version of sqlite and not the system's version of sqlite. Alternately, if pysqlite is dynamically linked, you might be able to fiddle with LD_LIBRARY_PATH to make your existing pysqlite load the newer version of the library.
For more, see: https://groups.google.com/group/python-sqlite/browse_thread/thread/9fb6694c803431eb
Comment: "making sure that it's building against your newly installed version of sqlite and not the system's version of sqlite" this is exactly what I need to do (I have sqlite from homebrew I want to link against), can you please explain how to or point to some docs?
Comment: Thanks, I see that there's no other way than that. It's actually much simpler to manually enforce the foreign keys by code, so I guess that's what I'll do.
Comment: Via your Google Groups link I found http://trac.edgewall.org/wiki/PySqlite , which recommends against Macs doing a static build ("Users of Mac OS X please take care; the Apple-supplied SQLite contains additional code to support..."). But install-source.txt mentions nowhere the standard sqlite3 module, just pysqlite2. Ick! Question: How do I use the LD_LIBRARY_PATH trick?

How to update python-sqlite on mac osx


confusion about solving and graphing a simple rational function

Question: given the function:

$\frac{x+1}{5} - 2 = -\frac{4}{x}$

I could multiply through by $5x$ yielding the quadratic with solutions $(5,4)$:

$x^2 - 9x + 20 = 0$

or.... I could create a common denominator of $5x$ and add fractions yielding:
$\displaystyle\frac{x(x+1)}{5x} - \frac{10x}{5x} + \frac{20}{5x}$

$\frac{x^2 - 9x + 20}{5x} = 0$

All three seem to have different graphs - 2 is a parabola, 3 is a hyperbola
They have different domain restrictions as well
Which is correct?  In fact, using algebra rules, I could arbitrarily divide a function by anything on both sides of the equation, changing the graph and the domain, right?  I assume that the original function (1) is what we are after but I'm confused about legitimate algebra operations changing everything.  What is the philosophy here?  Thank You!
Chris
Answer: If $x_0$ is a solution to the equation $$f(x) = 0$$ then $x_0$ is also a solution to the equation $$f(x)g(x) = 0$$ However, the reverse is not true - if $x_0$ is a solution to $g(x) = 0$ but not to $f(x) = 0$ then it will be a solution to $f(x)g(x) = 0$. However, if there are only finitely many solutions to  $f(x)g(x) = 0$ then it is easy to check each of them individually to see whether they satisfy $f(x) = 0$ - the ones that do are all the solutions.
An important philosophical consideration here is that the equation $f(x) = 0$ and the function $f(x)$ are very different things. The former only talks about the roots of $f$ - i.e. the points where the graph crosses the x-axis.
Answer: we have to solve
$\frac{x+1}{5}-2=\frac{-4}{x}$
and it must be $x\ne 0$ then our equation is equivalent to
$$x(x+1)-10x=-20$$
$$x^2-9x+20=0$$
the solutions are
$$\{\{x\to 4\},\{x\to 5\}\}$$


D8 render a contact form from theme preprocess

Question: I want to render a form in a node view. I made an entity reference to a contact form, then in the preprocess_node I'm trying to get the render array of the contact form.
<code>function mysupertheme_preprocess_node(&$variables) {
  $node = $variables['node'];

  if ($node->getType() == 'mynodetype') {
    if (!empty($node->field_mynodetype_form->referencedEntities())) {
      $contact_form = $node->field_mynodetype_form->referencedEntities()[0];
      $message = \Drupal::entityManager()
      ->getStorage('contact_message')
      ->create(array(
        'contact_form' => $contact_form->id(),
      ));

      //$form = \Drupal::entityFormBuilder()->getForm($message);
    };
  }
}
</code>
I don't know how to call entityFormBuilder in preprocess. Is this the right way to do this ? How can I display a choosen contact form in a node ?
Thanks
Answer: Your code will work when this patch is implemented:
Add a view builder for contact_form
Comment: Right direction, but what you actually want to write is "Your code will no longer be needed because it will just work with that patch :)"
Comment: @nicholas.alipaz, it is now planned for 8.2, in the meantime it is in https://www.drupal.org/project/contact_storage (and see Berdir's comment, you probably don't need any code)
Comment: I believe that patch should've gotten into 8.1.0, but it doesn't "just work" from what I can tell. I have the field set to "Rendered View" since that is the only formatter that is available aside from Label and Entity ID. That gives an error of `Notice: Trying to get property of non-object in Drupal\views\Element\View::preRenderViewElement() (line 49 of ..../core/modules/views/src/Element/View.php).`
Comment: +1 for contact_storage as the stop-gap solution before drupal core fixes it. I do like the other features of contact_storage too. A new display formatter is available for a contact form entity reference called rendered entity after the module is enabled. Thanks!


C How to Pass an Array of Arrays of Structs to a function?

Question: #include <stdio.h>
#include <string.h>

typedef struct Person {
    char name[100];
    int age;
    char secondName[100];
} Person;

int printA(Person **arrayA) {
    printf("here\n\n");
    int i;
    int j;
    for(i=0; i<2; i++) {
        for(j=0; j<3; j++) {
            printf("%s\n", (*((arrayA+j) + i))->name);
        }
        printf("DONE Array\n\n");
    }
}

int main()
{
    Person person1;
    Person person2;
    Person person3;
    Person person4;
    Person person5;
    Person person6;

    strcpy(person1.name, "John");
    strcpy(person2.name, "Will");
    strcpy(person3.name, "Bill");
    strcpy(person4.name, "Tim");
    strcpy(person5.name, "Andrew");
    strcpy(person6.name, "Sarah");

    strcpy(person1.secondName, "Smith");
    strcpy(person2.secondName, "Johnson");
    strcpy(person3.secondName, "Brown");
    strcpy(person4.secondName, "Williams");
    strcpy(person5.secondName, "Jones");
    strcpy(person6.secondName, "Garcia");

    person1.age = 20;
    person2.age = 25;
    person3.age = 30;
    person4.age = 35;
    person5.age = 40;
    person6.age = 45;

    Person array1[3];
    Person array2[3];

    array1[0] = person1;
    array1[1] = person2;
    array1[2] = person3;

    array2[0] = person4;
    array2[1] = person5;
    array2[2] = person6;

    Person *arrayMain[2];

    arrayMain[0] = array1;
    arrayMain[1] = array2;

    printA(arrayMain);
}

Above is the best I have managed to make, but I can't get it to work properly. What I am trying to achieve is passing an array of arrays of structs to a function and allowing the function to view the struct values.
This outputs a few values although in the wrong order ("John", then "Tim") and then seg-faults.
Comment: Whenever I see "parallel" definitions (e.g. `Person p1,p2,p3,p4,p5,p6;`), I want to convert those to an _array_ (e.g. `Person persons[6];`). Because of this, you need an extra/indirect pointer array (`arrayMain`). But, if this is cleaned up, we don't need to pass an _indirect_ pointer array to `printA`. (i.e.) We can eliminate `arrayMain` and, in `main`, we can just do: `printA(persons);` and change to: `int printA(Person *arrayA)`
Comment: Usually it is more scalable to have a [dynamic array](https://en.wikipedia.org/wiki/Dynamic_array) of people. `struct person_array { size_t size, capacity; struct Person *data; }` then `void printA(struct person_array *)`.
Answer: You have two problems, both of which are here:
printf("%s\n", (*((arrayA+j) + i))->name);

First, you've got your array indices mixed up.  Second, you've got the dereference in the wrong place.  The above is the same as:
printf("%s\n", (*(arrayA + j + i))->name);

Which doesn't make sense.  You need to move the dereference operator inside one set of parenthesis and swap the indices:
printf("%s\n", ((*(arrayA+i) + j))->name);

Or better yet, use array index notation:
printf("%s\n", arrayA[i][j].name);

Answer: Alright, here we have a few mistakes.
The one is that you are trying to get the name value from the variable declared as a stack, not a heap. When a variable is declared as a stack (with [n]), we use simple . to get access to its value. When a variable is declared as a heap (with *) and is known as a pointer, we use * and -> (if a variable in a struct) to get access to its value.
The other is that you messed up with iterators. You have to look at the array in reverse order of the declaration, as you declared arrayMain with [2] items that had been declared with [3] each previously. So, here is how arrayMain looks:
arrayMain => [array1[3], array2[3]];
arrayMain[0] => [person1, person2, person3];
arrayMain[0][0] => parson1;

Therefore, the right way to get access to name from stack arrays would be:
arrayA[i][j].name


How can I disable a button after it has been clicked in Vue Native?

Question: I have a button in my template that does something on click. However, I want it to be disabled after the user has clicked it once.
Comment: Have you tried setting disabled=true on the button in the onclick?
Answer: v-bind:disabled="newName === ''"
try this
Comment: Could you please give a clear example with context where it can be used?


NotServingRegionException: Region hbase:meta

Question: We have HBase service installed through Cloudera Manager (5.4), but for some reason we decided to delete the service & redeploy HBase service again. But after redeployment HBase master fails to start with following
2015-05-13 14:17:56,242 INFO org.apache.hadoop.hbase.master.ServerManager: Waiting for region servers count to settle; currently checked in 0, slept for 73755 ms, expecting minimum of 1, maximum of 2147483647, timeout of 4500 ms, interval of 1500 ms.
2015-05-13 14:17:56,809 INFO org.apache.hadoop.hbase.master.ServerManager: Registering server=hdp015.abc.com,60020,1431541075296
2015-05-13 14:17:56,815 INFO org.apache.hadoop.conf.Configuration.deprecation: fs.default.name is deprecated. Instead, use fs.defaultFS
2015-05-13 14:17:56,844 INFO org.apache.hadoop.hbase.master.ServerManager: Waiting for region servers count to settle; currently checked in 1, slept for 74358 ms, expecting minimum of 1, maximum of 2147483647, timeout of 4500 ms, interval of 1500 ms.
2015-05-13 14:17:58,349 INFO org.apache.hadoop.hbase.master.ServerManager: Finished waiting for region servers count to settle; checked in 1, slept for 75863 ms, expecting minimum of 1, maximum of 2147483647, master is running.
2015-05-13 14:17:58,355 INFO org.apache.hadoop.hbase.master.MasterFileSystem: Log folder hdfs://magnetic-hadoop/hbase/WALs/hdp015.abc.com,60020,1431541075296 belongs to an existing region server
2015-05-13 14:17:58,462 INFO org.apache.hadoop.hbase.catalog.CatalogTracker: Failed verification of hbase:meta,,1 at address=hdp015.abc.com,60020,1431540681831, exception=org.apache.hadoop.hbase.NotServingRegionException: org.apache.hadoop.hbase.NotServingRegionException: Region hbase:meta,,1 is not online on hdp015.abc.com,60020,1431541075296
at org.apache.hadoop.hbase.regionserver.HRegionServer.getRegionByEncodedName(HRegionServer.java:2761)
at org.apache.hadoop.hbase.regionserver.HRegionServer.getRegion(HRegionServer.java:4256)
at org.apache.hadoop.hbase.regionserver.HRegionServer.getRegionInfo(HRegionServer.java:3623)
at org.apache.hadoop.hbase.protobuf.generated.AdminProtos$AdminService$2.callBlockingMethod(AdminProtos.java:20158)
at org.apache.hadoop.hbase.ipc.RpcServer.call(RpcServer.java:2031)
at org.apache.hadoop.hbase.ipc.CallRunner.run(CallRunner.java:108)
at org.apache.hadoop.hbase.ipc.RpcExecutor.consumerLoop(RpcExecutor.java:116)
at org.apache.hadoop.hbase.ipc.RpcExecutor$1.run(RpcExecutor.java:96)
at java.lang.Thread.run(Thread.java:745)

2015-05-13 14:17:58,467 INFO org.apache.hadoop.hbase.master.MasterFileSystem: Log dir for server hdp015.abc.com,60020,1431540681831 does not exist
2015-05-13 14:17:58,467 INFO org.apache.hadoop.hbase.master.SplitLogManager: dead splitlog workers [hdp015.abc.com,60020,1431540681831]
2015-05-13 14:17:58,468 INFO org.apache.hadoop.hbase.master.SplitLogManager: started splitting 0 logs in []
2015-05-13 14:17:58,468 INFO org.apache.hadoop.hbase.master.SplitLogManager: finished splitting (more than or equal to) 0 bytes in 0 log files in [] in 0ms
2015-05-13 14:17:58,469 INFO org.apache.hadoop.hbase.zookeeper.ZooKeeperNodeTracker: Unsetting hbase:meta region location in ZooKeeper
2015-05-13 14:17:58,531 INFO org.apache.hadoop.hbase.master.AssignmentManager: Assigning hbase:meta,,1.1588230740 to hdp015.abc.com,60020,1431541075296
2015-05-13 14:17:58,532 INFO org.apache.hadoop.hbase.master.RegionStates: Transitioned {1588230740 state=OFFLINE, ts=1431541078483, server=null} to {1588230740 state=PENDING_OPEN, ts=1431541078532, server=hdp015.abc.com,60020,1431541075296}
2015-05-13 14:17:58,571 INFO org.apache.hadoop.hbase.master.ServerManager: AssignmentManager hasn't finished failover cleanup; waiting
2015-05-13 14:17:58,588 INFO org.apache.hadoop.hbase.master.RegionStates: Transitioned {1588230740 state=PENDING_OPEN, ts=1431541078532, server=hdp015.abc.com,60020,1431541075296} to {1588230740 state=OPENING, ts=1431541078588, server=hdp015.abc.com,60020,1431541075296}
2015-05-13 14:17:58,865 INFO org.apache.hadoop.hbase.master.RegionStates: Transitioned {1588230740 state=OPENING, ts=1431541078588, server=hdp015.abc.com,60020,1431541075296} to {1588230740 state=OPEN, ts=1431541078865, server=hdp015.abc.com,60020,1431541075296}
2015-05-13 14:17:58,868 INFO org.apache.hadoop.hbase.master.handler.OpenedRegionHandler: Handling OPENED of 1588230740 from hdp015.abc.com,60020,1431541075296; deleting unassigned node
2015-05-13 14:17:58,882 INFO org.apache.hadoop.hbase.master.RegionStates: Onlined 1588230740 on hdp015.abc.com,60020,1431541075296
2015-05-13 14:17:58,884 INFO org.apache.hadoop.hbase.master.HMaster: hbase:meta assigned=1, rit=false, location=hdp015.abc.com,60020,1431541075296
2015-05-13 14:17:58,970 INFO org.apache.hadoop.hbase.catalog.MetaMigrationConvertingToPB: hbase:meta doesn't have any entries to update.
2015-05-13 14:17:58,970 INFO org.apache.hadoop.hbase.catalog.MetaMigrationConvertingToPB: META already up-to date with PB serialization
2015-05-13 14:17:58,987 INFO org.apache.hadoop.hbase.master.AssignmentManager: Clean cluster startup. Assigning userregions
2015-05-13 14:17:58,996 INFO org.apache.hadoop.hbase.master.SnapshotOfRegionAssignmentFromMeta: Start to scan the hbase:meta for the current region assignment snappshot
2015-05-13 14:17:59,004 INFO org.apache.hadoop.hbase.master.SnapshotOfRegionAssignmentFromMeta: Finished to scan the hbase:meta for the current region assignmentsnapshot
2015-05-13 14:17:59,023 INFO org.apache.hadoop.hbase.master.TableNamespaceManager: Namespace table not found. Creating...
2015-05-13 14:17:59,063 FATAL org.apache.hadoop.hbase.master.HMaster: Master server abort: loaded coprocessors are: []
2015-05-13 14:17:59,064 FATAL org.apache.hadoop.hbase.master.HMaster: Unhandled exception. Starting shutdown.org.apache.hadoop.hbase.TableExistsException: hbase:namespace
at org.apache.hadoop.hbase.master.handler.CreateTableHandler.prepare(CreateTableHandler.java:133)
at org.apache.hadoop.hbase.master.TableNamespaceManager.createNamespaceTable(TableNamespaceManager.java:232)
at org.apache.hadoop.hbase.master.TableNamespaceManager.start(TableNamespaceManager.java:86)
at org.apache.hadoop.hbase.master.HMaster.initNamespace(HMaster.java:1069)
at org.apache.hadoop.hbase.master.HMaster.finishInitialization(HMaster.java:942)
at org.apache.hadoop.hbase.master.HMaster.run(HMaster.java:613)
at java.lang.Thread.run(Thread.java:745)
2015-05-13 14:17:59,076 INFO org.apache.hadoop.hbase.master.HMaster: Aborting
2015-05-13 14:17:59,077 INFO org.apache.hadoop.ipc.RpcServer: Stopping server on 60000
2015-05-13 14:17:59,077 INFO org.apache.hadoop.hbase.master.CatalogJanitor: CatalogJanitor-hnn002:60000 exiting
2015-05-13 14:17:59,077 INFO org.apache.hadoop.ipc.RpcServer: RpcServer.listener,port=60000: stopping
2015-05-13 14:17:59,078 INFO org.apache.hadoop.ipc.RpcServer: RpcServer.responder: stopped
2015-05-13 14:17:59,078 INFO org.apache.hadoop.ipc.RpcServer: RpcServer.responder: stopping
2015-05-13 14:17:59,077 INFO org.apache.hadoop.hbase.master.balancer.ClusterStatusChore: hnn002.abc.com,60000,1431540999332-ClusterStatusChore exiting
2015-05-13 14:17:59,077 INFO org.apache.hadoop.hbase.master.balancer.BalancerChore: hnn002.abc.com,60000,1431540999332-BalancerChore exiting
2015-05-13 14:17:59,079 INFO org.apache.hadoop.hbase.master.HMaster: Stopping infoServer
2015-05-13 14:17:59,079 INFO org.apache.hadoop.hbase.master.cleaner.HFileCleaner: master:hnn002:60000.archivedHFileCleaner exiting
2015-05-13 14:17:59,079 INFO org.apache.hadoop.hbase.master.cleaner.LogCleaner: master:hnn002:60000.oldLogCleaner exiting
2015-05-13 14:17:59,081 INFO org.apache.hadoop.hbase.replication.master.ReplicationLogCleaner: Stopping replicationLogCleaner-0x44d20db9b2a4642, quorum=hdp015.abc.com:2181,hdp005.abc.com:2181,hdp010.abc.com:2181, baseZNode=/hbase
2015-05-13 14:17:59,083 INFO org.mortbay.log: Stopped firstname.lastname@example.com:60010
2015-05-13 14:17:59,088 INFO org.apache.zookeeper.ZooKeeper: Session: 0x44d20db9b2a4642 closed
2015-05-13 14:17:59,088 INFO org.apache.zookeeper.ClientCnxn: EventThread shut down
2015-05-13 14:17:59,189 INFO org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation: Closing zookeeper sessionid=0x14d20db9a0f470c
2015-05-13 14:17:59,197 INFO org.apache.zookeeper.ZooKeeper: Session: 0x14d20db9a0f470c closed
2015-05-13 14:17:59,197 INFO org.apache.zookeeper.ClientCnxn: EventThread shut down
2015-05-13 14:17:59,248 INFO org.apache.hadoop.hbase.master.SplitLogManager$TimeoutMonitor: hnn002.abc.com,60000,1431540999332.splitLogManagerTimeoutMonitor exiting
2015-05-13 14:17:59,305 INFO org.apache.zookeeper.ZooKeeper: Session: 0x14d20db9a0f470b closed
2015-05-13 14:17:59,305 INFO org.apache.zookeeper.ClientCnxn: EventThread shut down
2015-05-13 14:17:59,305 INFO org.apache.hadoop.hbase.master.HMaster: HMaster main thread exiting
2015-05-13 14:17:59,306 ERROR org.apache.hadoop.hbase.master.HMasterCommandLine: Master exiting java.lang.RuntimeException: HMaster Aborted at org.apache.hadoop.hbase.master.HMasterCommandLine.startMaster(HMasterCommandLine.java:194)
at org.apache.hadoop.hbase.master.HMasterCommandLine.run(HMasterCommandLine.java:135)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
at org.apache.hadoop.hbase.util.ServerCommandLine.doMain(ServerCommandLine.java:126)
at org.apache.hadoop.hbase.master.HMaster.main(HMaster.java:2822)

Answer: Try to delete /hbase in zookeeper, while doing the same make sure HBase Cluster is down:
echo "rmr /hbase" | zookeeper-client

Then try to start HBase.


Facet API : How to change some behaviors like having input radio instead of checkbox

Question: I need to change some default behavior from the facet API.
I am searching for documentation about the hook from the Facet API module, but I have not found anything for now, except a very good tutorial about Apache Solr and Facet API.
I downloaded the Facet API bonus module because I thought it would help me.
There are some very good features like Rewrite facet items via callback function, but it seems it only works for the markup; I can't change the input.
function custom_facet_facet_items_alter(&$build, &$settings) {
  dsm($build);
  dsm($settings);
  if ($settings->facet == "field_produit_dev_durable") {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);
    }
  }
}

I tried to use the Devel modutle o see the content of the variables build, and setting, but there is nothing interesting for me.

So I need two things

Understand how to change the checkbox input
Understand how to remove the count number aside the Yes or No

I made my module and use this, but weirdly it doesn't remove the number.
$build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);

I used the fist tutorial I linked at the beginning of my post, but I found a problem I don't understand.
When I used my code on two different facets I got an error:

An illegal choice has been detected. Please contact the site administrator.

My code is the same code shown in this article, but I replace the select field with a radio field. I think there is a conflict between the two form, when I validate.
Answer: What you're doing to change the markup should just work, here's a working example I have from a project that does just that:
function foo_facet_items_alter(&$build, &$settings) {
  if ($settings->facet === 'my_facet') {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = drupal_ucfirst($item["#markup"]);
    }
  }
}

I can confirm that it works as expected.
As far as switching the select for a radio, the error you get is pretty common and you're probably not removing/adding extra Form API options that aren't allowed for one of the types.
Radio buttons behave a bit different than selects, you might not be able to just switch the #type and have it work, if this is still relevant, please post the code you're using to alter that form... thanks!
Answer: On this page you find a paragraph about creating a custom facet api widget:
http://www.trellon.com/content/blog/apachesolr-and-facetapi
Comment: This article was linked in the OP.


incorrect work HTML5 Sortable lists, ajax post and disabled item

Question: I'm using a neat sort plugin for jQuery, HTML5 Sortable http://farhadi.ir/projects/html5sortable/ and would like to disable some items.
I add class="disabled" to
-tag and add items: ':not(.disabled)' to javasript, but it does't work...
By the way if remove $('.sortable').sortable().bind() function from javasript, then everything works correctly...
Does anyone know what I'm doing wrong?

One

Two

Three

Four

Five

Answer: Christina, try to modify your code like this:
$(function() {
    $('.sortable').sortable({
        items: ':not(.disabled)'
    }).bind('sortupdate', function() {
    var dataIDList = $('.sortable li').map(function(){  return $(this).data("id"); }).get().join(",");
    $.ajax({ type: "POST",  url: "post.php?dataIDList="+dataIDList });
    });
});

Answer: The reason is you're calling the sortable at the start:
$('.sortable').sortable().bind('sortupdate...
You need to change it to read:
$('.sortable').bind('sortupdate...


Complex integral of product of two polynomial powers

Question:
Compute $$\int_{|z|=1}z^n\left(z-\dfrac{1}{2}\right)^mdz$$ where $m,n$ are integers.

If $m,n\geq 0$, the function is entire, and so the integral is $0$.
If $n<0$ and $m\geq 0$, the function becomes $\dfrac{\left(z-\dfrac12\right)^m}{z^{|n|}}$. This can be handled by the Cauchy formula. Let $f(z)=\left(z-\dfrac12\right)^m$. Then the integral is $\dfrac{2\pi i}{|n-1|!}\cdot f^{(|n-1|)}(0)$.
If $m<0$ and $n\geq 0$, it should be similar.
But what if $m,n<0$? Now there are two values for which the denominator vanish. How can we use Cauchy's theorem or otherwise?
Edit: Since this exercise appears in Ahlfors many sections before the Residue theorem, I would like to see a solution that doesn't use Residue theorem.
Answer: Residue theorem.  The residue of $z^{-j} (z - 1/2)^{-k}$ at $z=0$, for example,
is the coefficient of $z^{j-1}$ in the Maclaurin series of $(z-1/2)^{-k}$, which you can find using the binomial series.
Comment: That's interesting.. this exercise appears in Ahlfors before Residue Theorem (in fact, many sections before it!) Is there a way to do without Residue Theorem?
Answer:
$\displaystyle{%
\int_{\left\vert\, z\,\right\vert\ =\ 1}
z^{n}\left(z- {1 \over2}\right)^{m}\,{\rm d}z:\ {\large ?}\\[5mm]
}$

In general, we have two expansion of the integrand:

$$
z^{n}\left(z- {1 \over2}\right)^{m}
=
\left(-1\right)^{m}
\sum_{\ell = 0}^{\infty}{m \choose \ell}{1 \over 2^{m - \ell}}\,
{\left(-1\right)^{\ell} \over z^{-n - \ell}}
$$

$$
z^{n}\left(z- {1 \over2}\right)^{m}
=
\left[{1 \over 2} + \left(z - {1 \over 2}\right)\right]^{n}\left(z- {1 \over2}\right)^{m}
=
\sum_{\ell = 0}^{\infty}{n \choose \ell}{1 \over 2^{n - \ell}}\,
{1 \over \left(z - 1/2\right)^{-m - \ell}}
$$

where $\displaystyle{x \choose y}$ is the
$\it\underline{\mbox{generalized binomial coefficient}}$ as explained
here.
When $m \leq -1$ and $n \leq -1$ ( $m$ and $n$ integers ) we have to consider both poles: At $z = 0$ and at $z = 1/2$. The result turns out to be:
\begin{align}
\int_{\left\vert\, z\,\right\vert\ =\ 1}
z^{n}\left(z- {1 \over2}\right)^{m}\,{\rm d}z
&=
2\pi{\rm i}\left[%
{m \choose -n - 1}\left(-\,{1 \over 2}\right)^{m + n + 1}
+
{n \choose -m - 1}{1 \over 2^{n + m + 1}}\right]
\\[3mm]&=
2\pi{\rm i}\left[%
{n \choose -m - 1} + \left(-1\right)^{m + n + 1}{m \choose -n - 1}
\right]\,{1 \over 2^{m + n + 1}}
\\[3mm]&=
2\pi{\rm i}\left[%
\left(-1\right)^{m + 1}{-m - n - 2 \choose -m - 1}
+
\left(-1\right)^{m}{-m - n - 2\choose -n - 1}
\right]\,{1 \over 2^{m + n + 1}}
\\&
\phantom{%
\left[%
{n \choose -m - 1} + \left(-1\right)^{m + n + 1}{m \choose -n - 1}
\right]}
m, n \in {\mathbb Z}\,,\quad m \leq -1\,,\quad n \leq -1.
\end{align}
Comment: What formula do you use in the line after "The results turns out to be"?
Comment: Cauchy's Residue Theorem:
$\displaystyle{\large\int_{\left\vert z\right\vert = 1}
{{\rm d}z \over 2\pi{\rm i}}\,{1 \over z^{k}}
=
\delta_{k,1}}$.

http://en.wikipedia.org/wiki/Residue_theorem
Comment: Okay, thank you. As I said in the edit, though, I would still like to see a way without the residue theorem.
Comment: Without RT, we just replace $\displaystyle{\large z = {\rm e}^{{\rm i}\theta}}$. We get $\displaystyle{\large\int_{0}^{2\pi}{\rm e}^{-{\rm i}\left(k - 1\right)\theta}\ {{\rm d}\theta \over 2\pi} = \delta_{k,1}}$


Data sharing in Hadoop Map Reduce chaining

Question: Is it possible to share a value between successive reducer and mapper?
Or is it possible to store the output of first reducer into memory and second mapper can access that from memory ?
Problem is ,
I had written a chain map reducer like Map1 -> Reducer1 --> Map2 --> Reducer2.
Map1 and Map2 is reading the same input file.
Reduce1 is deriving a value suppose 'X' as its output.
I need 'X' and input file for Map2.
How can we do this without reading the output file of Reduce1?
Is it possible store 'X' in memory to access for Mapper 2 ?
Comment: Can you be more specific? Why you ever need Map2 and can't combine Reducer1 and Reducer2 in one Reducer?
Comment: My Requirement is , I have an input in a text file like ID,PRICE,COUNT.  I need to find sum(Count) first (Done with first reducer) . Then need to calculate A = count*100/sum for each row and then need to find cumulative A for each row , then if am entering a value (ex:64) need to find which row corresponding to that.(which is the first row having cumulative A > 64)
Answer: Each job is independent of each other, so without storing the output in intermediate location it's not possible to share the data across jobs.
FYI, in MapReduce model the map tasks don't talk to each other. Same is the case for reduce tasks also. Apache Giraph which runs on Hadoop uses communication between the mappers in the same job for iterative algorithms which requires the same job to be run again and again without communication between the mappers.
Not sure about the algorithm being implemented and why MR, but every MR algorithm can be implemented in BSP also. Here is a paper comparing BSP with MR. Some of the algorithms perform well in BSP when compared to MR. Apache Hama is an implementation of the BSP model, the way Apache Hadoop is an implementation of MR.
Answer: If number of distinct rows produced by Reducer1 is small (say you have 10000 (id,price) tuples), using two stage processing is preferred. You can load results from first map/reduce into memory in each Map2 mapper and filter input data. So, no uneeded data will be transferred via network and all data will be processed locally. With use of combineres amount of data can be even less.
In case of huge amount of distinct rows looks like you need to read data twice.


Fazer algo após um script externo ser totalmente carregado via jQuery append

Question: Tenho um ) senão ele não funciona neste caso específico, pois ele ainda possui um id () e é baseado nesse id que o script funciona, contornei o problema da seguinte forma:
$("body").append('


Who gets Super Bowl rings?

Question: When a team wins the Super Bowl, there are a lot of players and organizational members that helped in the process. For each team playing this year, there are multiple players on injured reserve that helped the teams early on, but won't be playing for the Lombardi trophy. Who actually gets a Super Bowl ring? Are IR players like Mario Manningham (49ers) and Lardarius Webb (Ravens) eligible to receive rings? What about all of the coaches and coordinators and front-office employees?
Comment: The losing team does not get Super Bowl rings.
Comment: If the team loses do they also get Super Bowl rings
Answer:
Every member of the active roster
The coaching staff
The entire front office and ownership
The cheerleaders get rings depending on ownership's decision. But it has been the tradition lately for cheerleaders to get rings.
Injured Reserve and practice squad get rings if their team decides to give them out to them. Usually they do.
Also, in some cases, players traded during the season will get them too, if they suited up and played during they regular season. This is also by ownership's decision

To sum up, the ownership pays for all the rings and decides who receives them. The list above shows the norm.

Source
Source
Answer: I think players who get cut and may be out of the league get rings if they were on the 53 man roster for atleast 1 week. I am not 100% sure if this is required.
Comment: At Sports SE, we encourage expert, well-researched answers. Are there any sources that back up your "thoughts?"

Who gets Super Bowl rings?


GLMERTREE with reponse in [0, 1] and multilevel design

Question: I have multilevel data (with nested random effects: (1 | cluster-of-cluster/cluster) in lme4 syntax) where the response is a continuous variable between $[0, 1]$ (i.e., including 0 and 1).
Usually, I'd model this data using a generalized linear mixed-effects model (e.g., with glmmTMB: https://cran.r-project.org/web/packages/glmmTMB/index.html), possibly after transforming the response as in Smithson and Verkuilen, 2006 (the "better lemon squeezer" paper: https://doi.apa.org/doiLanding?doi=10.1037%2F1082-989X.11.1.54), where $y' = \frac{y * (N - 1) + (1/2)}{N}$.
I want to model the data using recursive partitioning. glmertree (https://cran.r-project.org/web/packages/glmertree/index.html) is the closest to what I need. I'd be using models similar to the one in section 2 of the glmertree vignette (https://cran.r-project.org/web/packages/glmertree/vignettes/glmertree.pdf), where the node-specific model is just an intercept, and in section 3, where a discrete-level treatment effect is fitted in the nodes.
My questions are:

Do I gain anything using Smithson and Verkuilen's transformation? I am not fitting a beta model.

I am using a gaussian linear-mixed effects model underneath. Are there better options?
I thought about using ctree, from partykit (https://cran.r-project.org/web/packages/partykit/index.html), with the default identity function for influence, which I think makes no particular distributional assumptions for this case. But I have multilevel data, and different partitioning variables are measured at different levels (observation, clusters of observations, and clusters of clusters), and using the cluster argument in ctree precludes finding splits in variables measured at the cluster and 'cluster of cluster' levels (I've run some toy examples, and in p. 28 of the vignette, https://cran.r-project.org/web/packages/partykit/vignettes/ctree.pdf says: "the variance of the test statistics used for variable selection and also splitting is computed separately, leading to stratified permutation tests (in the sense that only observations within clusters are permuted)").

lmertree also  accepts a cluster argument but I am not sure I really should use it. Toy examples I have simulated show that using it vs. not using it does not affect like in ctree and generally has minor effects but its usage is discussed in section 4 of the vignette and in Maaike Jorink's MSc's thesis (https://openaccess.leidenuniv.nl/bitstream/handle/1887/69342/Jorink%2C%20Maaike-s1907387-MA%20Thesis%20MS-2018.pdf).
Answer: Before addressing your three questions, I would like to point out that the answers depend on which model you really want to fit to the data.
Regressors: I think in terms of predictors you want to have (a) fixed effects that capture a treatment-subgroup interaction (where the appropriate groups have to be learned from the data) and (b) random effects capturing the correlation from the nested cluster structure.
Response: In terms of response distribution you say that your data are in $[0, 1]$ but that you don't want to fit a beta distribution. But do you adopt another probabilistic model that can fit such data well? Or are you adopting an approximately normal model and then end up using it as a conditional mean model rather than a conditional distributional model?
Trees with mixed effects: The general strategy implemented in glmertree that we slightly extended from the idea underlying REEMtree is to iterate between estimation of the groups for the fixed effects (via a tree, given a specification of the random effects) and estimation of the random effects (via a mixed-effects model, given the groups from the tree). In REEMtree this is done by estimating the random effects, subtracting them from the response, and then fitting the tree to the adjusted response - before doing it vice versa. In glmertree we are slightly more general by treating one of the effects as an offset and then estimating the other. The advantage is that you can then fit the resulting model as a single mixed-effects model and you converge a little bit faster. If you are planning to use an approximately normal response, then you can try out either REEMtree (based on ctree and nlme) or lmertree (based on lmtree and lme4). Or you can also try to "roll your own" algorithm by plugging a suitable tree flavor together with glmmTMB for example. The iterations between the two models typically converge very quickly.
Answer to your questions:

The ad-hoc transformation by Smithson & Verkuilen is just a "trick" to make the response fit in (0, 1) when it would actually by [0, 1]. This is only useful if you fit a model that needs the response to be in the open interval (such as a standard beta distribution) and if the extreme values 0 and 1 in the original scaling are driven by the same effects as observations slightly larger than 0 or smaller than 1, respectively. Thus: If you're not fitting a beta distribution I guess that you don't need the transformation - but I wonder how your model then fits the data (see above).
My feeling is that what cluster in ctree does is too strict for your data. It really treats the data as separate blocks, only permuting within blocks.
In contrast lmtree (which is underlying lmertree) just adjusts the inference for within-cluster correlation. The latter typically only has an effect if explanatory variables are correlated with the clustering variable. If these are approximately uncorrelated, however, the cluster argument has almost no effect. See also the simulation study in vignette("sandwich-CL", package = "sandwich").

I hope that this gets you a few steps further in your modeling approach!
Comment: Thanks a lot for the detailed response; this clarifies my doubts. Comments to some  issues you raise:

**Response**:  I have a large data set and most terminal nodes have thousands of observations and I am for now only using models where the node-specific model is just an intercept (i.e., no treatment-subroup interaction).

So  "adopting an approximately normal model and then end up using it as a conditional mean model rather than a conditional distributional model" is exactly my approach (I am using `lmertree`).


aonde montar a tabela em um projeto MVC PHP com ajax?

Question: Dentro da model eu tenho uma série de tratativas para mostrar o resultado final.
//CONTROLLER
public function index(){
    $this->view->render("views/index.php");
}

public function read(){
    $data = array();
    $data['id'] = $_POST['id'];
    $this->model->showAlgo($data);
}

//MODEL

public function showAlgo($data){
    //Faz um select com o  $data['id'] e retorna uma a table já montada
    $resultadoDaQuery = "

".$resultado['algumacolunadobanco']."

";
    echo json_encode($resultadoDaQuery);
}

script:
$.ajax({
    url: "nome/read",
    type: "POST",
    success: function(dados){
        //monta os dados aqui e envia pro html via jquery
    },
    error: function(){}
});

qual é a maneira correta de montar o resultado?
posso fazer isso no model como no exemplo acima e enviar diretamente para o ajax (no success)?
ou deve-se montar a tabela dentro do ajax (na função success)?
Answer: O código HTML nesse caso deveria estar na View.
Há uma confusão geral também sobre o que é model e view, tal como o uso do controller.
Leia esse tópico recente:
https://pt.stackoverflow.com/a/116422/4793


Query to get termID, term name and number of posts that has that term

Question: I can figure out how to construct a db query that fetches term id and term name. But how do I associate a count of nid's that has this term? I'm looking to do this programatically through the DB api.
Any help would be greatly appreciated, as I'm running low on time.
Answer: You can write a separate query to select nodes with term id = x, then execute the rowCount method on the resultset like:
<code>$results = $query->execute();
$num = $results->rowCount();
</code>
(Source)
But more direct approach is using addExpression, join and groupBy:
<code>$query = db_select('taxonomy_term_data', 'ttd');
$query->join('taxonomy_index', 'ti', 'ttd.tid = ti.tid');
$query->fields('ttd', array('tid', 'name'));
$query->groupBy('ti.tid');
$query->addExpression('COUNT(ti.nid)', 'nid_count');

$results = $query->execute();
</code>
You can also use db_query straight away:
<code>$results = db_query('SELECT ttd.`tid`, ttd.`name`, COUNT(ti.`nid`) AS `nid_count` FROM `taxonomy_term_data` ttd JOIN `taxonomy_index` ti ON ttd.`tid` = ti.`tid` GROUP BY ti.`tid`');
</code>


What is the stable9 theme? When should I use it instead of stable?

Question: https://www.drupal.org/node/3066038
Has this cryptic statement:

However, defaulting to base theme: stable prevents automatic updates to the next major version of Drupal, since each major version may have a different version of "the stable theme"

and proceeds to list these without any explanation.
The READMEs in the relevant directories are no help.

Warning: Themes that opt out of using Stable as a base theme will need
continuous maintenance as core changes, so only opt out if you are prepared to
keep track of those changes and how they affect your theme.

Warning: Themes that decide to not use Stable 9 as a base theme will need
continuous maintenance as core changes, so only opt out if you are prepared to
keep track of those changes and how they affect your theme.

I have a Drupal 8 theme, I am upgrading to Drupal 9 should I specify stable or stable9? This is really confusing.
Answer:
My theme is extending Drupal 8 Stable, what should I do?
Upgrading to a Stable 9 can be a tedious task. Therefore, we have
decided to continue to support previous versions of Stable. Drupal 8
Stable will be shipped in Drupal 9 along Stable 9. Drupal 8 Stable
will be deprecated during the Drupal 9 lifecycle to be removed in
Drupal 10 so that the theme can be moved into a contrib project.

https://www.drupal.org/node/3107179
Comment: They kept the old machine name because that theme is deprecated in Drupal 9. It would not make sense to change its machine name, which would not be a BC change, and then deprecate the theme.
Comment: _facepalm_ Opening `stable.info.yml` finds `description: A default base theme using Drupal 8.0.0's core markup and CSS.` Why on earth was this not named **stable8** ?
Answer: If you want to use it you have to enable the theme before using it.
e.g. drush theme:enable stable9
From the .info
description: A base theme using Drupal 9.0.0's core markup and CSS.
So in other words all the new markup in html plus the old markup, css etc in d9+


Find name of the value which is in '.csv' fomat in array

Question: I have an array with different extension's values, Now i want check whether '.csv' is IN this Array or not . If it is then whats the name.
    Ex: -  Array
(
    [0] => xyz.mp4
    [1] => bulk_sample.csv
    [2] => abc.avi
    [3] => pqr.3gp

)

Here 'abc.csv' is available in array. and name should be in $name='abc.csv';
Comment: What do you have so far and how is it failing?
Answer: Simple "one-line" solution using preg_grep function:
$names = preg_grep("/\.csv$/i", $val);
print_r($names);

The output:
Array
(
    [3] => abc.csv
)

Note, that hypothetically there could be multiple .csv items
Comment: @Divakarcool, so? My solution works fine with a given array and your notation *name should be in $name='abc.csv'*
Comment: i have tried but not working
Comment: Yes It is working , Thanks
Answer: Try this code :
In this foreach loop is checking for sub string which is .csv for all elements in array.
<?php
$array =array('test.mp4','abc.avi','xyz.3gp','abc.csv');
$flag=false;
$filename="";
foreach($array as $check) {
    $place = strpos($check, ".csv");
    if ($place>0) {
        $flag=true;
        $filename=$check;
        break;
    } else {
        $flag=false;
    }
}

if($flag){

    echo "File Name:".$filename;
}else{
echo "not found any .csv in array"."
";
}

?>

Note: it will return first found name with .csv extension.
Comment: Actually my array is in
[0] => xyz.mp4
[1] => bulk_sample.csv
[2] => abc.mp4
[3] => jkl.3gp
Comment: Thanks its working..


PHPExcel export to excel in Codeigniter looping data array

Question: I have a problem in PHPExcel in Codeigniter. I want to export data into excel file. It has 10 row data, like this:
-----------------------------------------------
No | NIM | Mahasiswa | Benar | Salah | Nilai
-----------------------------------------------
1  | G1A007001 | Hikmah Faridah | 16 | 84 | 16
-----------------------------------------------
.. | ..........| .............. |....|....|....
-----------------------------------------------
10 | K1A006001 | Erni Noviani   | 0  |  5 | 0
-----------------------------------------------

Here's my controller :
  public function export(){
        $id=$this->uri->segment(3);
        $this->load->model('m_user');
        $mhs=$this->m_user->edit_sesi($id);
        foreach($mhs->result() as $m):
            $nama_sesi=$m->nama_sesi;
            $nama_blok=$m->nama_blok;
            $tgl=$m->tgl;
        endforeach;
        $nilai=$this->m_user->lihat_nilai_sesi($id);
        $heading=array('No','NIM','Mahasiswa','Benar','Salah','Nilai');
        $this->load->library('PHPExcel');
        //Create a new Object
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getActiveSheet()->setTitle($nama_sesi);
        //Loop Heading
        $rowNumberH = 1;
        $colH = 'A';
        foreach($heading as $h){
            $objPHPExcel->getActiveSheet()->setCellValue($colH.$rowNumberH,$h);
            $colH++;
        }
        //Loop Result
        $totn=$nilai->num_rows();
        $no=1;
        for($i=2;$i<=$totn+1;$i++){
            foreach($nilai->result() as $n):
                $objPHPExcel->getActiveSheet()->setCellValue('A'.$i,$no);
                $objPHPExcel->getActiveSheet()->setCellValue('B'.$i,$n->nim);
                $objPHPExcel->getActiveSheet()->setCellValue('C'.$i,$n->nama);
                $objPHPExcel->getActiveSheet()->setCellValue('D'.$i,$n->benar);
                $objPHPExcel->getActiveSheet()->setCellValue('E'.$i,$n->salah);
                $objPHPExcel->getActiveSheet()->setCellValue('F'.$i,$n->nilai);
            endforeach;
            $no++;
        }
        //Freeze pane
        $objPHPExcel->getActiveSheet()->freezePane('A2');
        //Save as an Excel BIFF (xls) file
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="Nilai-'.$nama_sesi.'-'.$nama_blok.'-'.$tgl.'.xls"');
        header('Cache-Control: max-age=0');

        $objWriter->save('php://output');
        exit();
    }

And here's my model :
function lihat_nilai_sesi($id){
    $this->db->select('*');
    $this->db->from('hasil');
    $this->db->join('mahasiswa','mahasiswa.username=hasil.username','left');
    $this->db->order_by('mahasiswa.nim','asc');
    $this->db->where('id_sesi',$id);
    $query=$this->db->get();
    return $query;
}

And the result of excel file like this :
---------------------------------------------
No | NIM | Mahasiswa | Benar | Salah | Nilai
---------------------------------------------
 1 | K1A006001 | Erni Noviani | 0 | 5 | 0
---------------------------------------------
 2 | K1A006001 | Erni Noviani | 0 | 5 | 0
---------------------------------------------
 3 | K1A006001 | Erni Noviani | 0 | 5 | 0
---------------------------------------------
 4 | K1A006001 | Erni Noviani | 0 | 5 | 0
---------------------------------------------
 5 | K1A006001 | Erni Noviani | 0 | 5 | 0
---------------------------------------------
 6 | K1A006001 | Erni Noviani | 0 | 5 | 0
---------------------------------------------
 7 | K1A006001 | Erni Noviani | 0 | 5 | 0
---------------------------------------------
 8 | K1A006001 | Erni Noviani | 0 | 5 | 0
---------------------------------------------
 9 | K1A006001 | Erni Noviani | 0 | 5 | 0
---------------------------------------------
10 | K1A006001 | Erni Noviani | 0 | 5 | 0
---------------------------------------------

The result is only show 10 rows with same data/person. I think the loop is not working. Any body help me?
Thanks for your attention
Comment: insire the foreach add `var_dump($n)` and see if its the expected result
Comment: Coba librarynya dipindah pake PhpSpreadsheet karena PHPExcel udah gak di maintenance lagi
Answer: SOLVED
here's my controller :
public function export_nilai_sesi(){
    $id=$this->uri->segment(3);
    $this->load->model('m_user');
    $mhs=$this->m_user->edit_sesi($id);
    foreach($mhs->result() as $m):
        $nama_sesi=$m->nama_sesi;
        $nama_blok=$m->nama_blok;
        $tgl=$m->tgl;
    endforeach;
    $nilai=$this->m_user->lihat_nilai_sesi($id);
    $heading=array('No','NIM','Mahasiswa','Benar','Salah','Nilai');
    $this->load->library('PHPExcel');
    //Create a new Object
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getActiveSheet()->setTitle($nama_sesi);
    //Loop Heading
    $rowNumberH = 1;
    $colH = 'A';
    foreach($heading as $h){
        $objPHPExcel->getActiveSheet()->setCellValue($colH.$rowNumberH,$h);
        $colH++;
    }
    //Loop Result
    $totn=$nilai->num_rows();
    $maxrow=$totn+1;
    $nil=$nilai->result();
                $row = 2;
        $no = 1;
        foreach($nil as $n){
            //$numnil = (float) str_replace(',','.',$n->nilai);
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$row,$no);
            $objPHPExcel->getActiveSheet()->setCellValue('B'.$row,$n->nim);
            $objPHPExcel->getActiveSheet()->setCellValue('C'.$row,$n->nama);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('D'.$row,$n->benar,PHPExcel_Cell_DataType::TYPE_NUMERIC);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('E'.$row,$n->salah,PHPExcel_Cell_DataType::TYPE_NUMERIC);
            $objPHPExcel->getActiveSheet()->getStyle('F'.$row)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('F'.$row,$n->nilai,PHPExcel_Cell_DataType::TYPE_NUMERIC);
            $row++;
            $no++;
        }
    //Freeze pane
    $objPHPExcel->getActiveSheet()->freezePane('A2');
    //Cell Style
    $styleArray = array(
        'borders' => array(
            'allborders' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN
            )
        )
    );
    $objPHPExcel->getActiveSheet()->getStyle('A1:F'.$maxrow)->applyFromArray($styleArray);
    //Save as an Excel BIFF (xls) file
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');

    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="Nilai-'.$nama_sesi.'-'.$nama_blok.'-'.$tgl.'.xls"');
    header('Cache-Control: max-age=0');

    $objWriter->save('php://output');
    exit();
}

Answer: try this to loop result :
    $fields = $nilai->list_fields();
    $row = 2;
    foreach($nilai->result() as $data)
    {
        $col = 0;
        foreach ($fields as $field)
        {
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
            $col++;
        }
        $row++;
    }

Comment: thanks for your answer but I've found the solution, here's my code

$nil=$nilai->result();
$row = 2;
$no = 1;
   foreach($nil as $n){
   $objPHPExcel->getActiveSheet()->setCellValue('A'.$row,$no);
    $objPHPExcel->getActiveSheet()->setCellValue('B'.$row,$n->nim);
Comment: $objPHPExcel->getActiveSheet()->setCellValue('C'.$row,$n->nama);
    $objPHPExcel->getActiveSheet()->setCellValueExplicit('D'.$row,$n->benar,PHPExcel_Cell_DataType::TYPE_NUMERIC);
    $objPHPExcel->getActiveSheet()->setCellValueExplicit('E'.$row,$n->salah,PHPExcel_Cell_DataType::TYPE_NUMERIC);
    $objPHPExcel->getActiveSheet()->getStyle('F'.$row)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
    $objPHPExcel->getActiveSheet()->setCellValueExplicit('F'.$row,$n->nilai,PHPExcel_Cell_DataType::TYPE_NUMERIC);
    $row++;
    $no++;
   }
Comment: I set each cell value up with each data value from db.
Thanks for your answer.


Corollary of Lagrange's Theorem in Number Theory

Question:
Lagrange's Theorem: If $p$ is a prime and $$f(x)=a_nx^n+a_{n-1}^{n-1}+....+a_0, \text{ where }a_n\not\equiv 0\pmod p.$$ is a polynomial of degree $n\geq 1$ with integral coefficients, then the congruence $$f(x)\equiv 0\pmod p$$ has at most $n$ incongruent solutions.
Corollary: If $p$ is a prime and $d|p-1$, then the congruence $$x^d-1\equiv 0\pmod p$$ has exatcly $d$ solutions.

I am facing some difficulty in understanding the proof outlined in the book Elementary Number Theory by David M. Burton.

Since $d|p-1$ we have $x^{p-1}-1=(x^d-1)f(x)$, where the degree of $f(x)$ is $p-1-d.$ We know that $x^{p-1}-1\equiv 0\pmod p$ has exactly $p-1$ incongruent solutions modulo $p$, the solutions being $1,2,3,...,p-1.$ Now any solution $x=a$ of $x^{p-1}-1\equiv 0\pmod p$ which is not a solution of $f(x)$ must be a solution of $x^d-1\equiv 0\pmod p.$ Since $f(x)\equiv 0\pmod p$ has atmost $p-1-d$ (Due to Lagrange's Theorem) and $x^{p-1}-1\equiv 0\pmod p$ has $p-1$ solutions, this implies that the equation $x^d-1\equiv 0\pmod p$ has  at least $$p-1-(p-1-d)=d$$ solutions and since the maximum possible number of solutions is $d$ (Lagrange's Theorem) we conclude that $x^d-1\equiv 0\pmod p$ has exactly $d$ solutions.

I don't understand the part in bold. Please explain. (Using elementary knowledge of Number Theory)
Comment: "Lagrange's theorem"? Never heard of this name for this theorem, but what it says follows at once from what we know about fields: over a field, **any field**, a polynomial equation $\;f(x)=0\;$ has at most $\;\deg f\;$ *different* solutions (or different roots of the polynomial $\;f\;$ ), and they **even** use this in the proof you post, as how otherwise can be justified their claim that $\;x^{p-1}=0\pmod p\;$ has $\;p-1\;$ solutions? Unless they're working all this **without any field theory** and using Fermat's Little Theorem and etc...
Comment: $f(x)$ is actually a monic polynomial, so, in particular, its leading coefficient is $\not\equiv 0\mod p$ and hence Lagrange's Theorem is applicable.
Answer: The Lagrange Theorem you're talking about is different from the more known Langrange Theorem about Groups. This one says that a polynomial $f(x)$ either has all of it's coefficients divisible by prime $p$, or $f(x) \equiv 0 \pmod p$ has at most $\deg f$ incongruent solutions. You can read about this one here
Now back to your question. $x^{p-1} - 1$ has exactly $p-1$ zeros modulo $p$. Now from the Theorem $f(x)$ has at most $\deg f = p-1-d$ zeroes modulo $p$. But since $x^{p-1} - 1 = (x^d - 1)f(x)$ it means that $(x^d - 1)f(x)$ has exactly $p-1$ zero modulo $p$. But for a zero of this polynomial at least one of the factors must be zero. As $f(x) \equiv 0 \pmod p$ for at most $p-1-d$ zeroes of $x^{p-1} - 1$ it follows that $x^d - 1$ is equivalent to $0$ modulo $p$ for at least $p-1 - (p-1-d) = d$ zeroes.


Chord Progression: I iv bVI V

Question: Can anyone shed some light on what makes this chord progression work?
I know that bVI is a common bit of modal mixture, and minor iv often replaces IV, but I'm wondering what makes them work together here.
Comment: the flat 6 chord being a semitone above the 5 chord makes it work to "anticipate" it.  In simple terms: chords a semitone above often work to resolve down.  As a jazzer you can treat it as a tritone substitution if you like too, viewing the bVI as a substitution for a ii, but it's not really necessary.  Another thing is that walking up from a major chord to the chord 1 minor 3rd above it is often quite a nice effect, it works sort of like changing that chord to a minor chord, but it's less stark and there's more movement.  I bIII IV V for example, or I bIII bVI V
Comment: Also note that iv is the relative minor of bVI (or bVI is the relative major of iv).
Answer: Like with anything else in music, follow the notes and the common tones and they'll tell you all you need to know. The basic idea that is presented in this progression combination of chromatizim though modal mixture along with the traditional resolutions we expect. Let's put a key to this progression. If we were in C major, this progression would map to C, Fm, A♭, and G.

C  - C, E, G
Fm - F, A♭, C
A♭ - A♭, C, E♭
G - G, B, D

Notice that the C is common in all chords except the G which is taking you right back C chord and is approached by all notes moving down by half step. Also note while we are keeping C as a common tone, we are introducing other tones borrowed from the parallel minor which is adding a contrasting color to the progression. If you were to just move each note to the next closest tone, you would find this.

C -> C -> C ->   B  ->  C
E -> F -> E♭ ->  D ->  E
G -> A♭ -> A♭ -> G -> G

As you can see, two of the 3 notes don't move at all except moving away by half step and back. This if used effectively can create a lot of motion though use of chords not typically found in C major without actually having the notes move to far.
Answer: Chords that work together are found using the diatonic notes - C, Dm, Em, F, G Am and Bo. Also found to work are the chords from the parallel minor. So, Cm, Do, Eb, Fm, Gm , Ab and Bb. The chords in the sequence are C, Fm, Ab and G. All part of the previous lists.
Comment: Then there's C#dim, which works very well between C and Dm.   Or Ebdim which does the same thing coming down from C/E.  Or Db7 which stands in well for G7.  Or... just about anything else.  It's really a bit silly making lists of what chords are 'allowed'.   We can find a justification for any one.
Sorry I keep implying that much 'theory' is rubbish.  But it is!
Comment: @LaurencePayne - it's all true. However, so many budding musos need parameters. So, to an extent, apart from attempting to explain the phenomena of what works with what, the 'theory' gives guidelines that are the crutch so many feel they need. Luckily, through the ages, most decent composers knew the 'rules', but had the temerity and bravery to go beyond them - won't necessarily say break them - some to their detriment, as their genius wasn't recognised in their lifetime, so accolades fell on deaf (or dead) ears.
Comment: Good point for a student working on schoolroom SATB exercises.  'Stick to what Bach did for now - it's a coherent system that corresponds with a whole lot of real music'.   But there seem to be rules in 'guitarist theory'  that don't line up with any actual style of playing/composition/improvisation.   Hence the continual queries here from people who want to know 'why this works' having found yet another real-world example that doesn't conform.

Chord Progression: I iv bVI V


Restricting the term reference field from creating a new vocabulary term

Question: I have a term reference field in a form and it is an auto-complete term widget, it has a vocabulary that supplies the values to it. My intention is to allow users to input only the terms which are defined with in the vocabulary and it shouldn't accept entries other than the vocabulary terms. But, the field is allowing other entries from the user.
For example, consider the term reference field is associated with a vocabulary. Now,if an user enters the values(other than the vocabulary terms) within that field and submits the form. It accepts the values and inturn creating a new vocabulary term with the given values. Here I want to restrict the automatic creation of terms. If the value is not defined in the vocabulary terms, it shouldn't accept the form.
I want to restrict user to enter the values which are defined. If a user enters the value which is not defined in the vocabulary, it should give an error message.
Here, my problem is the vocabulary has already been assigned with some data and I couldn't delete the vocabulary anymore.
Any alternatives to restrict the term references??
Answer: Is there a specific reason why you want users to type in the term? You should be able to change the widget type to something else (select list or multiselect). This has also been discussed at length as an issue against the Taxonomy module (Autocomplete term widget: disable creation of new terms).
Comment: I tried to patch the file ($ patch -p1 < file.patch) and got this message

"bash: 1078878-DisableAutocreation-D7-UTF-8.patch: No such file or directory"

How to overcome the issue??
Comment: That's a question to ask on the drupal.org page for the patch.
Answer: Thanks to @Molot for directing me to the post Limit of the creation of tags. It works and the key is Content Taxonomy module.


How to use ranges as function parameter?

Question: I would like to use a range as a function parameter, i.e. call something like:
foo(arr,1..23)

In the function I want to do something like
int arr[22]
arr[21] = some_other_arr[<range>]

where <range> is 1..23 from the above call.
Is that possible? How would I have to declare foo?
Comment: `auto arr[22] = ...` is not valid D code.
Comment: @DejanLekic: err... I always make this mistake...
Comment: You can't do `foo(arr, 1..23)` but you can do `foo(arr, iota(1, 23))` or similar...
Answer: First, 1..23 isn't a range -- it's just special syntax that works only inside foreach statements.
A range that does the same as 1..23 is iota(1, 23) from std.range; it returns a range of successive values (such as integers).
To pass a range into a function, you generally want to use templates:
void foo(Range)(Range r)
{
    foreach (e; r)
        writeln(e);
}

Which you can then call the way you want:
foo(iota(1, 23)); // print the numbers from 1 to 23 (exclusive)

Note: if arr is an array, and you want a range of the values at indices 1..23 then you can use a slice:
foo(arr[1..23]);

A slice of an array is a range.
To have a function accept this, you don't need to use templates. foo could be written:
void foo(int[] r)
{
    foreach (e; r)
        writeln(e);
}

Comment: I wnat to use the range to access items in an `array`. I will edit the question...
Comment: Without reviving the entire question, I'd like to note you miss the template constraint. I think, it is fundamental for the understanding of how D works. For example, D defines interfaces "InputRange", "ForwardRange", etc. The problem with them as I understand: they only work with inheritance (classes). In order to support non-class ranges, you need template constraints (the "if-clause" between argument tuple and braces). The constraint freely specifies minimum template parameter properties (of range type) needed for instantiation. So use: `void func(R)(R range) if (isInputRange!R) {}`
Answer: An array slice is the most powerful range - a random-access range. So why not simply use slice for what you need:
import std.stdio;
import std.conv;

int main() {
    int[] ina = [0, 1, 22, 11, 5, 9, 3];
    auto arr = ina[2..5];
    writeln(arr); // this is an example of a "function" with range as parameter
    return 0;
}

/*** output:
[22, 11, 5]
****/

You can toy with it here: http://dpaste.dzfl.pl/95568985 (fork and run).
Frankly, I would accept Peter's answer because it shows everything you need to know. :)
Comment: What I want is to put the line starting with `auto arr` into a function and pass the `2..5` as a function parameter.
Comment: `myfun(2..5)` is not possible, as Peter already explained. `myfun(some_array[2..5])` is possible.


How can I use ansible playbook to get group name on each of hosts?

Question: I using ansible playbook for audit script
I use ansible playbook with Jinja2 for creating a dashboard in HTML
Here is my inventory
<code>[Ubuntu16]
target1.com
[CentOS7]
target2.com
</code>
I run all hosts to check the connection and I want to do the following steps

Count all hosts in inventory separate by group
In case of connection passed, register to a parameter (separate by group)
and then send a parameter of the result to Jinja2 template

The result should be like this
<code>Ubuntu16_sum_all = 1
Ubuntu16_alive = 1
Ubuntu16_dead = 1
CentOS7_sum_all = 1
CentOS7_alive = 1
CentOS7_dead = 1
</code>
I have no idea to get a group name of a host while I running all hosts in the playbook. Please help
Answer: I dont think so there is a direct way of using the inventory format above directly. My suggestion would be take the hostnames inside a variable something like below:
<code>---
hosts:
  - Ubuntu:
      - 1
      - 2
  - Centos:
      - 1
      - 2
  - Fedora:
      - 1
      - 2
</code>
In the above inventory you can loop through all the hosts name directly
Comment: But, I want to create template in the one time. Because I need a centralized dashboard includes the result of centos and ubuntu on the same page.
Comment: Since your need is to create a template best thing as per me would be to refer the above file as vars file. Check if the connection exists if the connection exists then create a template file for all the valid connections


Duvida de como reverter valores em uma lista estatica em C

Question: Olá, estou com duvida em uma questão de um trabalho da universidade de como reverter uma sequencia de números em uma lista estática em C.
A parte em especifico que estou em duvida é :
<code>**int SList_reverse(SList* lista, int dado){
      if(!SList_cheia(lista)){
      int i;
      for(i=0; i< lista->qty; i++)
        printf("<-[%d] ", lista->data[i]);
      putchar('\n');
      }
      return 0;
    }**
</code>
Código completo:
<code>#include "StaticList.h"
#include <stdlib.h>
#include <stdio.h>

#define MAX 10
typedef struct list{
  int qty;
  int data[MAX];
} TList;

TList* SList_create(){
  TList* nova = (TList*) malloc(sizeof(TList));
  if(nova!=NULL){
    nova->qty = 0;
  }
  return nova;
}

int SList_insert(SList* lista, int dado){
  if(!SList_cheia(lista)){
    lista->data[(*lista).qty++] = dado;
    return 1;
  }
  return 0;
}

void SList_print(SList* lista){
  int i;
  for(i=0; i< lista->qty; i++)
    printf("[%d]-> ", lista->data[i]);
  putchar('\n');
}

int SList_search(SList* lista, int dado){
  int i;
  for(i=lista->qty-1; i>=0; i--)
    if(lista->data[i] == dado)
      break;
  return i;
}

int SList_remove(SList* lista, int dado){
  if(!SList_vazia(lista)){
    int i = SList_search(lista, dado);
    if(i>=0){
      int j;
      for(j=i; j<lista->qty-1; j++){
        lista->data[j] = lista->data[j+1];
      }
      lista->qty--;
      return 1;
    }

  }
  return 0;
}

int SList_reverse(SList* lista, int dado){
  if(!SList_cheia(lista)){
  int i;
  for(i=0; i< lista->qty; i++)
    printf("<-[%d] ", lista->data[i]);
  putchar('\n');
  }
  return 0;
}

void SList_destroy(SList* lista){
  if(lista!= NULL)
    free(lista);
}

int SList_getQty(SList* lista){
  if(lista!= NULL)
    return lista->qty;
  return 0;
}

int SList_cheia(SList* lista){
  return (lista->qty == MAX);
}

int SList_vazia(SList* lista){
  return (lista->qty == 0);
}
</code>
Comment: Quando você diz `reverter uma sequencia de números`, você quer inverter a ordem dos número? Exmeplo: `123456789` em `987654321`.
Comment: Exatamente isso mesmo.
Answer: Nesse caso você nem precisa verificar se a lista está cheia, basta inverter os itens conforme o código abaixo.
<code>int SList_reverse(SList* lista, int dado){
  int i;
  int aux;

  for(i=0; i< lista->qty /2; i++) {
    aux = lista->data[i];
    lista->data[i] = lista->data[(lista->qty - 1) - i];
    lista->data[lista->qty - i] = aux;
    printf("<-[%d] ", lista->data[(lista->qty - 1) - i]);
  }
  putchar('\n');
  return 0;
}
</code>
Comment: Repare que no seu código haverá um acesso a um local de memória fora do vetor da lista. Quando `i = 0`, então `lista->data[lista->qty - 0]`, considerando q o último elemento do vetor é `lista->data[lista->qty - 1]`, logo `lista->data[lista->qty - 0]` não faz parte do vetor. Isto é, se o tamanho for `10`, então o limite do vetor é `[9]`, logo `[10 - 0]` == `[10]`, que não é uma posição válida no vetor. Outro erro é que o `for` precisa repetir apenas metade das vezes que você colocou, pois quando chegar no meio ele vai desinverter o que foi invertido.
Comment: Teria que ser assim `lista->data[(lista->qty - 1) - i]` para corrigir o primeiro problema. O segundo basta colocar `i < (lista->qty / 2)` dentro do `for`
Comment: Verdade, postei correndo, as duas correções que você citou são necessárias.