text:
Q: How to plot model glm result with a lot of parameters I really need help with this. I want to make a predict model for my glm quasipoisson. I have a problems since i wrongly make a glm model with my dataset.
I used to make a predict model based on my glm quasipoisson for all my parameters, but I ended up predicting for each parameter, and the result is different from the glm quasipoisson data.
Here is my dataset. I use a csv file for all my dataset. Idk how to upload this csv data in this post, pardon me for this.
Richness = as.matrix(dat1[,14])
Richness

 8
 3
 3
 4
 3
 5
 4
 3
 7
 8

Parameter = as.matrix(dat1[,15:22])
Parameter
  JE Temp Hmdt  Sond   HE    WE   L    MH
   1 31.3   93  63.3 3.89  4.32  80  7.82
   2 26.9   92  63.5 9.48  8.85  60  8.32
   1 27.3   93  67.4 1.23  2.37  60 10.10
   3 31.6   99 108.0 1.90  3.32  80  4.60
   1 29.3   99  86.8 2.42  7.83 460 12.20
   2 29.4   85  86.1 4.71 15.04 200 10.10
   1 29.4   87  93.5 3.65 14.70 200 12.20
   1 29.5   97  87.5 1.42  3.17  80  4.07
   1 25.9   95  62.3 5.23 16.89 140 10.03
   1 29.5   95  63.5 1.85  6.50 120  6.97

 Rich = glm(Richness ~ Parameter, family=quasipoisson, data = dat1)
 summary(Rich)

 Call:
 glm(formula = Richness ~ Parameter, family = quasipoisson, data = dat1)

 Deviance Residuals:
    1          2          3          4          5
 -0.017139   0.016769  -0.008652   0.002194  -0.003153
    6          7          8          9         10
 -0.016828   0.022914  -0.013823  -0.012597   0.030219

 Coefficients:
            Estimate Std. Error t value Pr(>|t|)
 (Intercept)   -7.4197959  0.5061733 -14.659   0.0434 *
 ParameterJE    0.1833651  0.0224198   8.179   0.0775 .
 ParameterTemp  0.2441301  0.0073380  33.269   0.0191 *
 ParameterHmdt  0.0393258  0.0032176  12.222   0.0520 .
 ParameterSond -0.0319313  0.0009662 -33.050   0.0193 *
 ParameterHE   -0.0982213  0.0060587 -16.212   0.0392 *
 ParameterWE    0.1001758  0.0027575  36.329   0.0175 *
 ParameterL    -0.0014170  0.0001554  -9.117   0.0695 .
 ParameterMH    0.0137196  0.0073704   1.861   0.3138
 ---
 Signif. codes:
 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

 (Dispersion parameter for quasipoisson family taken to be 0.002739787)

Null deviance: 7.8395271  on 9  degrees of freedom
Residual deviance: 0.0027358  on 1  degrees of freedom
AIC: NA

Number of Fisher Scoring iterations: 3

This is the model that i tried make with ggplot
ggplot(dat1, aes(Temp, Richness))+
geom_point() +
geom_smooth(method = "glm", method.args = list(family = quasipoisson),
          fill = "grey", color = "black", linetype = 2)``

and this is the result.

I make for each parameters, but i just know this result turn wrong because it used a quasipoisson data for each parameter, what i want is the predict model based on quasipoisson data like in the summary above.
I tried to used the code from plot the results glm with multiple explanatories with 95% CIs, but i really confuse to set my data like the example there. But the result in that example is nearly like what i want.
Can anyone help me with this? How can I put the glm predict model for all parameters in one frame with ggplot?
Hope anyone can help me to fix this. Thank you so much!

A: Have you tried the plot_model function from sjplot package?
I'm writing from my phone, but the code is something Like this.
library(sjPlot)
plot_model(glm_model)
More info:
http://www.strengejacke.de/sjPlot/reference/plot_model.html
code:
data("mtcars")
glm_model<-glm(am~.,data = mtcars)
glm_model

library(sjPlot)
plot_model(glm_model, vline.color = "red")
plot_model(glm_model, show.values = TRUE, value.offset = .3)


text:
Q: Related posts in all categories of current post (custom post types) A client of mine has custom post types that they set up using a plugin rather than defining them in the functions.php. (So, YARPP for the solution won't work).  In this custom post types, they have various categories.  Each post belongs to one or more categories.  After each post, they would like to display 5 posts that are in ALL the same categories (could be one or many categories).
So, what I need to do is set up a way to dynamically find all the categories a post belongs to (I've done that & have it set up as an echo right now until I work this out), then query to find 5 posts that belong to the exact same categories (either they belong to all of them or they shouldn't be displayed).
Here's the code I've come up with - but, I can't figure out how to "combine them" so it not only gets the terms (categories) but also forces the query to use those terms to filter the 5 "related" programs.
  //get the post's terms (troubleshooting - can be removed once figured out!
$category_terms = wp_get_object_terms($post->ID, 'category');
if(!empty($category_terms)){
  if(!is_wp_error( $category_terms )){
    echo 'Terms
';
    foreach($category_terms as $term){
      echo '
slug, 'category').'">'.$term->name.'
';
    }
    echo '
';
  }
}
//get post terms done
    // get the custom post type's taxonomy terms

    $custom_taxterms = wp_get_object_terms( $post->ID,
                'category', array('fields' => 'ids') );
    // arguments
    $args = array(
    'post_type' => 'program_listings',
    'post_status' => 'publish',
    'posts_per_page' => 5, // you may edit this number
    'orderby' => 'rand',
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field' => 'id',
            'terms' => $custom_taxterms
        )
    ),
    'post__not_in' => array ($post->ID),
    );
    $related_items = new WP_Query( $args );
    // loop over query
    if ($related_items->have_posts()) :
    echo '
Other Programs in this category

';
    while ( $related_items->have_posts() ) : $related_items->the_post();
    ?>

<a href="<?php the_permalink(); ?>"
                   title="<?php the_title_attribute(); ?>">
            <?php the_title(); ?>

    <?php
    endwhile;
    echo '
';
    endif;
    // Reset Post Data
    wp_reset_postdata();

So, get the posts terms & echo them (it won't be an echo when it's finished - I was doing that to make sure it actually got the categories/terms) works great.  It displays every "category" the post is in.  But, the second bit displays posts from any of those categories rather than posts that are only in ALL the categories.
Basically, I need to combine the first & second pieces so that the query only returns results of posts that are in ALL categories of the current post.  If a post is not in all the same categories (exact match for ALL categories of current post), it should not be returned.  (For example, if a post is in the parent "North America" category, but, not any of the other categories that the post is in, it should NOT be returned in the results).

A: Have you tried adding an 'operator' to your tax_query:
'tax_query' => array(
    array(
        'taxonomy' => 'category',
        'field' => 'id',
        'terms' => $custom_taxterms,
        'operator' => 'AND'
    )
),

A: This is the code that was needed in order to make it show only the posts (that were of a specific custom post type) that matched the same child category (therefore matching all the other categories):

<?php
//this gets the lowest hierarchical child term for current post
$categories = get_the_category($post->ID);
foreach($categories as $category) :
    $children = get_categories( array ('parent' => $category->term_id ));
    $has_children = count($children);
    if ( $has_children == 0 ) {
    $current_child = $category->name;
    }
endforeach;
//this starts the query for the program listings custom post types
$post_type = 'program_listings';
$tax = 'category';
$tax_terms = wp_get_object_terms($post->ID, 'category');
if ($tax_terms == $category_terms) {
  foreach ($tax_terms  as $tax_term) {
    $args=array(
      'post_type' => $post_type,
      "$tax" => $tax_term->slug,
      'post_status' => 'publish',
      'operator' => 'AND',
      'posts_per_page' => 5,//limits the listing to 5
      'caller_get_posts'=> 1,
      'post__not_in' => array ($post->ID),
      'orderby' => 'ID', //orders by ID, you could also tell it to order by: 'author' 'title''name''date' or 'rand'
'order' => 'ASC', //tells it the display order should be ascending, DSC would indicate a descending order

    );
    $my_query = null;
    $my_query = new WP_Query($args);
        if( $my_query->have_posts() && $tax_term->name == $current_child)//now only display categories the current post is in
         {
      echo '
Other programs in this category

';
      while ($my_query->have_posts() && $tax_term->name==$current_child ) : $my_query->the_post(); ?>

<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>

        <?php
      endwhile;
    }
    wp_reset_query();
  }
}
echo '
';
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use MS Ajax PageMethods to call a function on the server I have a project that uses PageMethods to call functions on the server.
The server functions (written in C#) return the values as array of strings, without doing any kind of serialization and in the client side (from Js) the accessing of the return values is by using static variable called arguments.
I found that sometimes for some users (cases are not repro) sometimes an exception occured
"WebServiceFailedException the server method 'Foo' returned invalid data.
the 'd' property is missing from JSON."
Some searching on google I found that people are serializing the return values using DataContractJsonSerializer class and in js accessing the return value using one of the callback function
Example:

function OnRequestComplete(result,
  userContext, methodName) {
  var Person = eval('(' + result + ')');
  alert(Person.Forename);
  alert(Person.Surname);        }

So is the first technique is correct? or what?
P.S:
the function on the server is defined on the default.aspx.cs file as follows:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] Foo(string s);

from the client side the calling is as follows
PageMethods.Foo("value",OnSuccess);

Also all the users have the same browser version (IE8)

A: I don't know if it's the entire problem, but your first issue is manually serializing the return value.  PageMethods and ScriptServices automatically JSON serialize their return values.  Nesting two levels of JSON could definitely be throwing a wrench in the framework's client-side deserialization process (which is also happening automatically, before your eval() code).
To return an instance of your Person class, this is all you need:
public static Person GetPerson() {
  Person p = new Person();

  // Populate the Person object here.

  return p;
}

Then, on the client-side you can work with the object's properties as expected:
function OnRequestComplete(result, userContext, methodName) {
  console.log('Person name: ' + result.Forename + ' ' + result.Surname);
}

Alternatively, if you're using jQuery for other tasks and already have it on the page, you don't even need the ScriptManager and MS AJAX to call page methods.  You can directly call page methods with jQuery and skip all that overhead.

A: Without knowing how the request is made and how the server end is coded, my answer may not be accurate.
Where is the WebMethod decorated method in your server side code? If it is an a separate class with the ScriptService attribute, and if JSON is specified while making the request, then the JSON values should have been automatically serialized and dont need to be serialized manually again. With this set up ASP.NET 3.5 wraps the response in a "d" object
Some users getting the exception might be due to the browser that they are using. If you are using jQuery, I'd specify the content type as so in the ajax request body
contentType: "application/json; charset=utf-8",

Hakeem

A: This is a bit funky. ASP.NET always adds the "d" to all results. So it either should work or not. Here is some background on the "d" issue:
http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/


text:
Q: Converting this complex number to polar form? Given $ z = -1 - i$
,I converted it to polar form, resulting  r =$\sqrt  2$.
And  $\theta = \tan^{-1} (\frac{-1}{-1}$) = 0.785 rads, which seems incorrect with the solutions of my instructor I don't understand why...

A: Hint:
In which quadrant of the plane does that point reside?

A: $-1-i$ is in the 3rd quarant, reasonable values for $\theta$ are between $\pi$ and $\frac32\pi$ (or $-\pi$ and $-\frac\pi2$ if you prefer values between $-\pi$ and $\pi$). $\tan^{-1}$ gives values between $-\frac\pi2$ and $\frac\pi2$, so you need to correct it by either adding or subtracting $\pi$.


text:
Q: Why did my friend lose all his money? Not sure if this is a question for math.se or stats.se, but here we go:
Our MUD (Multi-User-Dungeon, a sort of textbased world of warcraft) has a casino where players can play a simple roulette.
My friend has devised this algorithm, which he himself calls genius:

*

*Bet 1 gold

*If you win, bet 1 gold again

*If you lose, bet double what you bet before. Continue doubling until you win.

He claimed you will always win exactly 1 gold using this system, since even if you lose say 8 times, you lost 1+2+4+8+16+32+64+128 gold, but then won 256 gold, which still makes you win 1 gold.
He programmed this algorithm in his favorite MUD client, let it run for the night. When he woke up the morning, he was broke.
Why did he lose? What is the fault in his reasoning?

A: Suppose, for simplicity, that the probability of winning one round of this game is $\frac{1}{2}$, and the probability of losing is also $\frac{1}{2}$. (Roulette in real life is not such a game, unfortunately.) Let $X_0$ be the initial wealth of the player, and write $X_t$ for the wealth of the player at time $t$. Assuming that the outcome of each round of the game is independent and identically distributed, $(X_0, X_1, X_2, \ldots)$ forms what is known as a martingale in probability theory. Indeed, using the bet-doubling strategy outlined, at any time $t$, the expected wealth of the player at time $t + 1$ is
$$\mathbb{E} \left[ X_{t+1} \middle| X_0, X_1, \ldots, X_t \right] = X_t$$
because the player wins or loses an equal amount with probability $\frac{1}{2}$ in each case, and
$$\mathbb{E} \left[ \left| X_t \right| \right] < \infty$$
because there are only finitely many different outcomes at each stage.
Now, let $T$ be the first time the player either wins or goes bankrupt. This is a random variable depending on the complete history of the game, but we can say a few things about it. For instance,
$$X_T = \begin{cases} 0 & \text{ if the player goes bankrupt before winning once} \\
 X_0 + 1 & \text{ if the player wins at least once} \end{cases}$$
so by linearity of expectation,
$$\mathbb{E} \left[ X_T \right] = (X_0 + 1) \mathbb{P} \left[ \text{the player wins at least once} \right]$$
and therefore we may compute the probability of winning as follows:
$$\mathbb{P} \left[ \text{the player wins at least once} \right] = \frac{\mathbb{E} \left[ X_T \right]}{X_0 + 1}$$
But how do we compute $\mathbb{E} \left[ X_T \right]$? For this, we need to know that $T$ is almost surely finite. This is clear by case analysis: if the player wins at least once, then $T$ is finite; but the player cannot have an infinite losing streak before going bankrupt either. Thus we may apply the optional stopping theorem to conclude:
$$\mathbb{E} \left[ X_T \right] = X_0$$
$$\mathbb{P} \left[ \text{the player wins at least once} \right] = \frac{X_0}{X_0 + 1}$$
In other words, the probability of this betting strategy turning a profit is positively correlated with the amount $X_0$ of starting capital – no surprises there!

Now let's do this repeatedly. The remarkable thing is that we get another martingale! Indeed, if $Y_n$ is the player's wealth after playing $n$ series of this game, then
$$\mathbb{E} \left[ Y_{n+1} \middle| Y_0, Y_1, \ldots, Y_n \right] = 0 \cdot \frac{1}{Y_n + 1} + (Y_n + 1) \cdot \frac{Y_n}{Y_n + 1} = Y_n$$
by linearity of expectation, and obviously
$$\mathbb{E} \left[ \left| Y_n \right| \right] \le Y_0 + n < \infty$$
because $Y_n$ is either $0$ or $Y_{n-1} + 1$.
Let $T_k$ be the first time the player either earns a profit of $k$ or goes bankrupt. So,
$$Y_{T_k} = \begin{cases} 0 && \text{ if the player goes bankrupt} \\
Y_0 + k && \text{ if the player earns a profit of } k \end{cases}$$
and again we can apply the same analysis to determine that
$$\mathbb{P} \left[ \text{the player earns a profit of $k$ before going bankrupt }  \right] = \frac{Y_0}{Y_0 + k}$$
which is not too surprising – if the player is greedy and wants to earn a larger profit, then the player has to play more series of games, thereby increasing his chances of going bankrupt.
But what we really want to compute is the probability of going bankrupt at all. I claim this happens with probability $1$. Indeed, if the player loses even once, then he is already bankrupt, so the only way the player could avoid going bankrupt is if he has an infinite winning streak; the probability of this happening is
$$\frac{Y_0}{Y_0 + 1} \cdot \frac{Y_0 + 1}{Y_0 + 2} \cdot \frac{Y_0 + 2}{Y_0 + 3} \cdot \cdots = \lim_{n \to \infty} \frac{Y_0}{Y_0 + n} = 0$$
as claimed. So this strategy almost surely leads to ruin.

A: This betting strategy is very smart if you have access to infinite wealth or can go into infinite debt. In reality however, you will eventually lose all or most of your money.
Say your friend had $k$ gold at the beginning. I assume that this simple roulette has a probability of both win and loss equal to $0.5$.
First, let's see how many times you need to lose in a row in order to lose all your wealth.
\begin{align} 1 + 2 + 2^2 + 2^3 + ... + 2^n &\geq k \\
2^{n+1} - 1 &\geq k
\\ n &\geq \log_{2}(k+1) - 1
\end{align}
So even if you start with $10000$ gold, after $13$ lost bets you are broke and in debt. Continuing this example, the probability of this happening in a one shot-game is a mere $0.02$%. However, if you keep the algorithm running all night for $8$ hours betting every $5$ seconds, your chances of having a losing streak of $13$ in a row go up to $29.61$%.
Assuming that you cannot go into debt and $12$ losses is the most you can handle, then with the same data the chance of losing most of your money goes up to $50.5$%.

A: Repeated bets in roulette is a random walk on the wealthy variable. Since there is a dead end, when you can't continue the walk (when you're broke), the probability of losing everything is greater than zero.

A: I suppose he was betting on a red/black or even/odd system. Now, there is a "0" which is green/not even or odd, so if you hit that zero, you lose.
There are 36 numbers you can hit, plus that 0 . Even if you chose red or black, even or odd, there are bigger chances to lose than win.


text:
Q: How to make AfterBeanDiscovery get triggered in JUnit I have the following four classes: DataConsumer, DataProducer, SomeQualifier, a META-INF/beans.xml and a test.  The class files are coded as follows:
public class DataConsumer {

private boolean loaded = false;

@Inject
@SomeQualifier
private String someString;

public void afterBeanDiscovery(
        @Observes final AfterBeanDiscovery afterBeanDiscovery,
        final BeanManager manager) {
    loaded = true;
}

public boolean getLoaded() {
    return loaded;
}

public String sayHello() {
    return someString;
}

}

public class DataProducer {

@Produces
@SomeQualifier
private final String sample = "sample";
}

public @interface SomeQualifier {

}

The unit test looks like this.
public class WeldTest {
@Test
public void testHelloWorld() {
    final WeldContainer weld = new Weld().initialize();
    final DataConsumer consumer = weld.instance()
            .select(DataConsumer.class).get();
    Assert.assertEquals("sample", consumer.sayHello());
    Assert.assertTrue(consumer.getLoaded());
}
}

However, it is failing on the assertTrue with getLoaded() it appears that the @Observes does not get fired.

A: Take a look at arquillian: www.arquillian.org. It'll take care of all of this for you.

A: I found a similar question that had answered my question
CDI - Observing Container Events
Although I am unable to use DataConsumer as both an Extension and a CDI managed bean.  So it needs a third class just to be the Extension.  However, because Extension have no access to managed beans since they are not created yet, I conclude that is no possible solution to use an @Observes AfterBeanDiscovery to modify the bean data.  Even the BeanManager that gets passed in cannot find any of the beans.


text:
Q: Do self signed SSL certificates cause websites to get flagged as unsafe? I'm thinking about using a self signed cert for a staging area of my app.  However, this staging area is located on the same server as production, and I'm worried that using a self signed cert may cause the server to be flagged as malicious/suspicious.  Should I just go ahead and pay for a real cert?

A: There is theoretically nothing wrong with a self-signed certificate, but browsers like Chrome will definitely raise a flag. I'd recommend getting a real certificate.


text:
Q: Making a "voltage switch" I'm an electronics newbie. I have a circuit in which I have two input voltages, Vin and Vflag, and one output, Vout. Basically I want the following: If  Vflag =0, Vout =0. If Vflag = 1, Vout = Vin. My friend told me I can do it with a MOSFET, but from what I understood, a mosfet either lets current pass through or acts like an open circuit. Basically, a gate for current, while I want a gate for voltage.
Any help will be greatly appreciated.

A: You want a gate for voltage ...but at zero current?   Is there any current through the Vout connection?   What connects to Vout, just a DMM voltmeter?
A simple way to perform your task is to connect a resistor "R" between Vin and Vout.   This makes Vin=Vout, but only as long as Vout isn't loaded down with an external resistor to gnd.   Next, connect your mosfet from Vout to gnd (Drain connects to Vout, Source connects to gnd.)  When turned on, the mosfet will "short out" or "pull down" the Vout terminal, giving Vout=zero volts.   Now go find a "logic level" mosfet which will turn on when Vgs = 1.0V.   Connect Vflag to the mosfet gate.
On the other hand, if you're connecting Vout to an LED or motor or something, then Vout must supply significant current, and your "R" resistance would have to be fairly low, and when the mosfet turns on, the resistor gets hot.
Other solutions:  use a mechanical SPDT relay, with a sensitive coil which turns on at 1.0V.  The COM relay terminal becomes Vout, the N.C. terminal goes to gnd, and the N.O. terminal goes to Vin.
Or, the professional version:  use mosfet-based "analog switches" which can connect two signals together, or short a signal to ground.   For example, here's a Digikey search.

A: I use this to control a 3.3v output.
The mosfet acts as a switch.
This is not tested for a high current system. My maximum load on the Vout side is around 500mA on 3.3v


text:
Q: Suggest an algorithm to measure how a node is connected to road network I try to measure how well a node is connected to the rest of the network. If a city has a distant suburb connected with one sole road, it's connectedness is, say 1. If it's connected by 2 roads, it's 2, and so on. A point in the middle of the city is connected infinitely.
What are plugins or algorithms available?
I personally prefer open source solutions (QGIS, PostGIS, or python-based), but other options are also welcome.

A: I think that "node centrality" concepts, in the graph theoretic literature, may be helpful. Here is an introduction to centrality measures in graphs.

A: You do not specify which GIS system you wish to implement your analyses so you could investigate the sDNA which can be run in ArcGIS, python or AutoCAD.


text:
Q: Simple console.log controller action method in Ember.js In my application.js controller I have the following actions:
export default Ember.ObjectController.extend({
    //------------------------------------------------------------
    currentPathChanged: function () {
        window.scrollTo(0, 0);
    }.observes('currentPath'),
    //------------------------------------------------------------
    actions: {
        //------------------------------------------------------------
        pageBlock: function(desc_text){
            if(typeof desc_text === 'undefined'){
                desc_text='Processing';
            }
            $.blockUI.defaults.css = {};
            $.blockUI({message: desc_text});
        },
        pageUnBlock: function(){
            $.unblockUI({fadeOut:200});
        }
        //------------------------------------------------------------
    }
    //------------------------------------------------------------
});

Since I am rather new to debugging Emberjs applications, how do I call those actions from the console?  Basically I want to confirm they work correctly and want to hook them up to child views.
I am using the ember cli project to build my ember application.
Current setup at the time of this post:
DEBUG: -------------------------------
DEBUG: Ember      : 1.5.1
DEBUG: Ember Data : 1.0.0-beta.7+canary.b45e23ba
DEBUG: Handlebars : 1.3.0
DEBUG: jQuery     : 2.1.1
DEBUG: -------------------------------

A: Create an instance of it.  When you create an instance the actions hash is moved to _actions.
foo = App.ApplicationController.create();

foo._actions.pageBlock();

Personally I usually just throw a button on the application template
<button {{action 'pageBlock' foo}}>Block action</button>

http://emberjs.jsbin.com/lorocere/1/edit
Additionally you can use the Ember Inspector to get an instance of the controller in the console really easily by clicking on the $E for the application controller in the Ember tab in the debugger tools.  https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi?hl=en

A: I am hoping to find a better answer for this, but here is how I did it. First, using the debugger output find you application view id.  Then you can run the following in the console.log:
foo = Ember.View.views['ember277'].get('controller');
foo._actions.pageBlock();
foo._actions.pageUnBlock();

The post I referenced was Ember-JS-Best-Practices-helpful-debugging-tools.


text:
Q: Prestashop apply coupon code automatically I need to apply 10% discount on order total on checkout page.
Is there any option available to apply discount coupon automatically on checkout page with help of overriding controller or ajax based or any other method?

A: You don't need to override the classes or edit the code to apply the automatic coupon on any cart.
In order to achieve this, you can add a 'Catalog Price Rules' from the admin panel of your store to apply 10% discount on all products in the cart or specific country or specific currency etc.
Admin Path:
Price Rules -> Catalog Price Rules

A: go to price rules->cart rule->add

in conditions enter the minimum amount
in actions apply discount % and Apply a discount to order

(prestashop 1.6)
Ok an other way (quick and dirty) :

edit Cart.php in classes and modify the return of getOrderTotal
return Tools::ps_round((float)$order_total * my_discount,
  $compute_precision);

Override method :
class Cart extends CartCore
{
    public function getOrderTotal($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true)
    {
    return parent::getOrderTotal(true, Cart::ONLY_PRODUCTS) * mydiscount;

    }

}


text:
Q: Multiple Ajax Calls using AngularJS Issues I am fairly new to AngularJS.  A particular project necessitated using a MVC and I choose angular for it's ability to template and do seamless DOM insertions.
I'm loading a local config file to load specific API endpoints (created by the client) and then doing two AJAX calls to populate an object. Problem is that the second ajax call isn't working. It shows a console error similar to what you would see if you've encountered a CORS issue but I know by testing the endpoint via a REST client that the endpoint and parameters are correct (also tested it using a regular JQuery ajax call). I do not want to revert to jQuery code and would prefer to use angular to accomplish this.
This is the error I get:
XMLHttpRequest cannot load https://this/url/endpoint. Response for preflight is invalid (redirect)
Code:
var object = {};

angular.module('myApp').controller('myController', function ($scope, $http) {

    $http.get('data.json').then(function (data) {

        var url1 = data.url;
        var httpMethod1 = data.http1;
        var url2 = data.url2;
        var httpMethod2 = data.http2;

        $http({
            method: httpMethod1,
            url: url1,
            headers: {"token": token},
            dataType: 'json'
        }).success(function (data, status, headers, config) {

            object.attr1 = data.att0;
            object.attr2 = data.att1;

        }).error(function (data, status, headers, config) {
            alert('failed');
        });
        //THIS ONE FAILS
        $http({
            url: httpMethod2,
            type: url2,
            headers: {"token": token},
            data: { "value" : "value"}
            dataType: 'json',
        }).success(function (data, status, headers, config) {

            object.attr3 = data.att0;
            object.attr4 = data.att1;

        }).error(function (data, status, headers, config) {
            alert('failed');
        });
    });
});


text:
Q: Set-Location : A positional parameter cannot be found that accepts argument '7' in powershell I tried to go to another directory using windows 10 powershell.
It's located in my E:\SEMESTER 7 directory.
But, when I typed on my windows powershell
cd semester 7 it always gives me an error. I tried with another directory file which is not contain number on it,and it worked.
How do I make it work for directory file that contains number?
Here is the screenshot:

A: Tab completion finishes it this way:
cd '.\semester 7\'


text:
Q: How do I install Meteor Atmosphere packages locally so I can make modifications to it? I am trying to get up and running with Meteor and seeing what it can offer, while I like it overall, it seems it's a very very rigid system.
I set up a small testing setup using Velocity, it opens a small overlay window on the side which has a class of "velocityOverlay". The overlay is really small and makes error stack traces wrap. All I wanted to do was to edit the css of the "velocityOverlay" and increase the width.
I somehow (after wasting time) managed to find that Meteor is actually putting all the packages in my user directory by default, once I found that, I found the needed css file...

velocity_html-reporter/.0.5.1.aykpxq++os+web.browser+web.cordova/web.browser/packages/velocity_html-reporter/lib/client-report.less.css

And I did a small edit to the width, next thing you know the meteor app crashes when trying to launch using the "meteor" command throwing a "Error: couldn't read entire resource" error. I can't even edit the bootstrap.css file I installed using "ian_bootstrap-3".
Further more, I can't find any way to install packages locally just for my particular project, what if I wanted to modify a package only for my particular project? this is very easy to do in vanilla Node.js, you simply don't use the "-g" when using "npm install".
To add to that, within my project root, there is another ".meteor/local/build/web.browser" folder with most of the global package files replicated again. When does Meteor use which? This is very confusing.

A: You can run a package locally very easily.
Download it from Github (for example) and put it in the packages/ directory of your application like this /packages/package_name.
Then add it to your application with the same meteor add package_name command as usual.
Meteor will automatically look in the local folder before anywhere else and compile the package with the rest of your code.
This allows you to do any modification you want on the package and test it locally before publishing it to the registry.
Also, folders located in .meteor/local/* are used for building purpose only and are generated automatically by Meteor. So it is not the best place to edit the files!

A: Steps:

*

*Download (or clone) package from GitHub to local dir

*Stop meteor if running
2.1. Make sure you have a packages folder: mkdir packages

*Locally link your package:
3.1 If you have mrt installed: Run mrt link-package /path/to/package in a project dir
 3.2 If you don't have mrt: ln -s /path/to/package packages/package

*Then run meteor add developer:package-name, do not forget to change package name

*Run meteor in a project dir

*From now any changes in developer:package-name package folder will cause rebuilding of project app

A: This worked for me https://atmospherejs.com/i/publishing. mrt link-package didn't work for me, might just be outdated code.

A: Download the package and place it in new package directory in your project root.
open the package.js inside the downloaded package and remove the author's name in the property "name:"
 e.g: - name:'dburles:google-maps' to name:'google-maps'

then run
meteor add google-maps


text:
Q: iTunes crashes when connected to Wi-Fi I have already posted once, but the problem is so weird. Initially, when it started crashing (all of a sudden), I reinstalled iTunes and it was working fine. After a week, it happened again. I reinstalled it again. Two weeks later, it started crashing again. Then after some research on Google, it turns out that when I switch off Wi-Fi, it works fine.
By the way, I tried opening iTunes in safe made (command+shift+click). It crashed on safe mode as well!
https://discussions.apple.com/thread/5822899?tstart=0
These are the results from console at the time of crashing:
04/09/16 7:25:28.805 PM iTunes[426]: ApplePushService: APSConnection being used without a delegate queue
04/09/16 7:25:35.946 PM com.apple.xpc.launchd[1]: (com.apple.iTunes.118752[426]) Service exited due to signal: Terminated: 15
04/09/16 7:25:36.060 PM UserNotificationCenter[428]: *** WARNING: Method userSpaceScaleFactor in class NSWindow is deprecated on 10.7 and later. It should not be used in new applications. Use convertRectToBacking: instead.
04/09/16 7:25:37.421 PM spindump[383]: Saved hang report for iTunes version 12.4.3 (12.4.3) to /Library/Logs/DiagnosticReports/iTunes_2016-09-04-192537_Ns-MacBook-Pro.hang


text:
Q: Conditionally load AngularJS component I have a component for my responsive view:
<responsive-navigation></responsive-navigation>

I want to only load this component when the app is not loaded on a desktop view. Through the current-device library I can detect the current device. So in the $onInit of the component I have:
public $onInit() {
    console.log(!window.device.desktop());
}

This works fine. Is it possible to use the current-device data to conditionally load the component?

A: Do the device check out of the component. You can add a boolean to $rootScope, as it is a global app information:
$rootScope.isDesktop = window.device.desktop();

Then, using ng-if you can load the component conditionally:
<responsive-navigation ng-if="::!isDesktop"></responsive-navigation>


text:
Q: socket.io connected but refuses to emit i have a problem with socket io it is connected and i can read both connected and disconnected event but i can't emit from both server nor the client side. emit just doesn't work.
i always worked with socket io in the past year this is the first time it happens


text:
Q: Objective-C static "constructors" - do I need to retain? I know that if I get an object, for example an NSArray, with a method like [NSArray array], it will be autoreleased. So I don't have to do a release myself. My question is, do I have to retain it after I get it this way? I wouldn't have thought so, since the count starts at 1 and it won't be released until the pool is released, but I've gotten a few bad access errors from these objects when I don't. So to fix them, I'm retaining these objects, and then releasing them myself later. What's going on in this case? Am I still not grasping objective-c memory management?

A: I heartily advise you to stop thinking about retain counts. Instead, think about ownership: do you want to claim a piece of ownership of an instance (i.e. do you want to make sure it stays around until you say otherwise)? If so, -retain it. Otherwise, do not -retain it. Anytime you retain an ownership interest in an instance, you must -release that interest some time in the future or the instance will never be deallocated.
You can assume that any method that doesn't match the alloc/new/copy pattern returns instances in which you do not have an ownership interest. If you want them to stick around beyond the current stack frame, retain them.
For this and all other Objective-C memory questions, read the Memory Management Programming Guide. Then re-read it. Again. It is the authoritative reference on the subject. It will be your friend.

A: An autoreleased object will have its retain count decremented at the end of the run loop.  So if you have an object that you want to keep around longer than the end of the run loop, yes, you have to retain it.

A: You don't retain unless you need to claim ownership of the object. You need to post some code or describe what you're doing before anyone can help you determine how and why you're getting errors.


text:
Q: OnClick wrong item getting selected I have a listview with names and mobile numbers as the two textviews in it. OnItemClickListener returns a different item onclick. This is happening inconsistently- sometimes it selects the right item but sometimes it does not.
private void showCustomers(String json) {
        ParseCustomer parseCustomer = new ParseCustomer(json);
        parseCustomer.parseJSON();
 lv = (ListView) findViewById(R.id.list_customerInfo);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
 adapter = new ArrayAdapter<String>(this,R.layout.list_customerinfo, R.id.customer_name,ParseCustomer.name);

        final List<Map<String, String>> cust = new ArrayList<Map<String, String>>();
        Map<String,String> map;
        int counter = ParseCustomer.name.length;
        for (int i=0;i<counter; i++){
            map = new HashMap<>();
            map.put("name",ParseCustomer.name[i]);
            map.put("mobile",ParseCustomer.mobile_no[i]);
            cust.add(map);
        }

        newAdapter = new SimpleAdapter(this,cust,R.layout.list_customerinfo,new String[]{"name","mobile"},new int[]{R.id.customer_name,R.id.customer_mobile});
        lv.setAdapter(newAdapter);

        inputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                lv.setVisibility(View.INVISIBLE);

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            lv.setVisibility(View.VISIBLE);

            }

            @Override
            public void afterTextChanged(Editable s) {

                AddInvEst.this.newAdapter.getFilter().filter(s);
                lv.setVisibility(View.VISIBLE);
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map custSel = cust.get(position);
                custSelected = (String) custSel.get("name")+" "+ custSel.get("mobile");
                inputSearch.setText(custSelected);
                lv.setVisibility(View.GONE);
                Toast.makeText(AddInvEst.this, "Your selected customer is "+custSelected, Toast.LENGTH_LONG).show();
            }
        });
}

I have an edit text field which I am using to search or filter the listview.
Can anyone just spot my mistake or guide me to a better solution? Thanks :)

A: SimpleAdapter class manage two List, One to store your original List and second to store filter data. So whenever you apply filter on SimpleAdapter class, filter List has less number of item then the original one.
So in current scenario whenever you click on particular item, you getting click position of filtered List but you are getting item from unfiltered(original) List, Hence wrong item.
So to get click item from SimpleAdapter use:
Map custSel = (Map) newAdapter.getItem(position);


text:
Q: Migrating MySQL blob (image) to FileMaker container using PowerShell In searching I've found a number of other people that have tried, but none that have been successful.
Here's the problem. I want to take a bunch of images I have stored on my MySQL server in blobs and move them into FileMaker containers.
The best lead I've got is the putas command. It looks something like putas ('$Image','JPEG').
My particular application is as follows. $DataSet.Image1 is a JPEG file stored as "0xFFD8....". The data being in this format may well be the issue, but I don't know what I'd need to convert it to first.
$cmd.CommandText = "update Checklists set Image1 = PutAs('$($DataSet.Image1)', 'JPEG')"
$cmd.ExecuteNonQuery();

All I keep getting is syntax error, but I've tried the syntax many different ways I can't get it to go no matter what I do.
I'd very much like to see someone having success with this to post their example. Any other ideas or workarounds are welcome as well.
Edit:
Here is some extra info. Greg Lane at Skeleton Key gives this example, but I'm not sure how to translate it to PowerShell.
import java.sql.*; import java.io.*;
def url = "jdbc:filemaker://localhost/fmserver_sample";
def driver = "com.filemaker.jdbc.Driver";
def user = "admin";
def password = "";
System.setProperty("jdbc.drivers", driver);
connection = DriverManager.getConnection (url, user, password);
filename = "/Users/Greg/Pictures/vacation/DSC_0202.jpg";
file = new File (filename);
inputstream = new FileInputStream (filename);
sql = "INSERT INTO english_nature (ID, img) VALUES (-1, PutAs(?, 'JPEG'))";
pstatement = connection.prepareStatement ( sql );
pstatement.setBinaryStream (1, inputstream, (int)file.length ());
pstatement.execute ();
//cleanup
pstatement = null;
inputstream = null;
file = null;
connection.close();

A: I figured it out. For anyone in the future here is how you do it.
$cmd.CommandText = "update Checklists set Image1 = PutAs(?, 'JPEG') where serial = '$($DataSet.serial)' AND ChecklistNumber = 1"
$cmd.Parameters.Add('?', $DataSet.Image1)
$cmd.Prepare()
$cmd.ExecuteNonQuery();


text:
Q: jquery && operator doesn't work I have a issue with the following piece of code.
Button to toggle a div.
Inside the toggle div a have a few other divs and other elements.
$(function () {
    $('#btn').click(function (e) {
        e.preventDefault();
        console.log('clicked toggle');
        $('#Popover').toggle();
        if ($('#Popover:visible').length == 0) {
            $('#Popover').hide();
        } else {
            $('#Popover').show();
        }
    });
});

$(document).on('click', function (e) {
    var container = $('#Popover');
    var trigger = $('#btn');

    if (($(e.target).closest(trigger).length === 0) && ($(e.target).closest(container).length === 0)) {
        container.hide();
    }
});

It work great the button toggles the div. When I click outside the button / togglediv the togglediv hides.
The issue is when is click on a div inside the toggle div the div also hides.
it seems that the && operator doesnt work or is there something else wrong with my code.
Maybe it is a postback issue
The following code is the onclick method for a div (div id="hourInc") inside the toggle div
 $('#hourInc').click(function (e) {
        e.preventDefault();
        var hour = $('#cn_TimeHour').val();
        if (hour < 12) {
            hour = (hour * 1) + 1;
        }
        else {
            hour = 0;
        }
        $('#cn_TimeHour').val(("0" + hour).slice(-2));
        setTime();
    });

A: The "==" acts slightly differently to "===".
The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.
Reference: Javascript Tutorial: Comparison Operators
The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. It's this case where === will be faster, and may return a different result than ==. In all other cases performance will be the same.

A: Thanks for the feedback
The issue where the click event.
I inserted return false at the bottom of these methods.
That's seems to work


text:
Q: How to use Nightwatch.js to load other js framework? I need to develop automated tests for an application created in extJS and I was planning to use Nightwatch.js to create tests.
It is possible to load the extJS framework through Nightwatch.js to be possible use the functions of extJS (search functions of elements)? Because each time the page is loaded, the IDs from the elements can change.


text:
Q: unable to run the react-native-background-task. error while inserting code to MainApplication.java One manual step is still needed - in your project file android/app/src/main/java/myapp/MainApplication.java, add the following to the end of the onCreate() method:
            BackgroundTaskPackage.useContext(this);
Task :app:compileDebugJavaWithJavac FAILED
Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.5/userguide/command_line_interface.html#sec:command_line_warning
23 actionable tasks: 2 executed, 21 up-to-date
G:\background\android\app\src\main\java\com\background\MainApplication.java:19: error: cannot find symbol
          return BuildConfig.DEBUG;
                 ^
  symbol: variable BuildConfig
G:\background\android\app\src\main\java\com\background\MainApplication.java:47: error: cannot find symbol
    BackgroundTaskPackage.useContext();

A: This can be solved in React Native 0.61 by manually linking the module (and disabling auto-linking for the package: https://github.com/react-native-community/cli/blob/master/docs/autolinking.md)


text:
Q: How add child to existing duiring parent saving in hibernate? Suppose that Parent already exisits with id=1. And it already has 2 children. How to make code:
 Parent parent = parentDao.getbyId(1);
 //here somebody added a collection of children
 parent.setChildren(myNewCreatedChildren)
 parentDao.save(parent);

How save parent to get parentDao.getbyId(1).getChildren() return somebody children + myNewCreatedChildren after that? E.g. call parentDao.save(parent) should add children but do not override.
Note
The question is about situation when chidren are added outside of java code (or may be in other thread) to the parent after it was loaded by doa but before it saved to database.

A: I guess  it should be Collection<Children> children,    and your code parent.setChildren(myNewCreatedChildren) should be replaced with parent.getChildren().addAll(children);
But from my experience it is a bit easier not to deal with @ManyToOne(mappedBy="parent") and fetch policies at all, it is much easier to provide  childrenDao.fetchChildrensOfParent(parent)  and childrenDao.storeChildren(parent, children) methods and work with those only when it is needed , with such constructions even easier to add Caching to application and provide better control on its population and eviction.


text:
Q: mouse keeps loading after opening visual studio code Whenever I open visual studio code my mouse keeps loading endlessly.
But the moment I close VS Code it just stops.
I'm not sure if it's because of some extension I installed or something else.


text:
Q: What does "size" refer to in git diff output? git diff generates the output in the attached image. The file's hash has changed. What I don't quite understand is what specifically the "size" parameter indicates.

I assume this is size on disk. The output is generated from a cygwin linux installation on Windows so it is possible the line endings are what changed when examining and saving the file.
(side note: -1,3 and +1,3 indicate the first three lines in the file have been changed; might this be referring to metadata or is this file contents only?)
I don't see any reference to this parameter in the official documentation:

*

*Official git-diff Documentation

*GNU Diffutils Documentation

*diff wikipedia page
or these somewhat related questions:

*

*Git: what does the number of +/- signs in diff / merge output mean? [duplicate]

*What does "@@ -1 +1 @@" mean in Git's diff output?
It is a text file so I expect to see meaningful output if the contents changed. What reassurance do I have that the contents have not been altered?

A: Git diff shows '+' for new lines and '-' for removed lines for each file. If you open file.ipynb in a text editor, you should be able to see a line containing "size 33626"

A: Besides Adam's answer, note that the files that Git knows about read, in their entirety:
version https://git-lfs.github.com/spec/v1
oid <big ugly oid>
size <value>

where the OID and size values changed.  The first line is a directive to the LFS wrappers that tells them: these aren't the files you're looking for.  The second line tells the LFS wrappers which files they are looking for, and the third line tells the wrappers how big those files are.
But hold on a minute: what the <epithet> is all this about "LFS wrappers" anyway?
LFS is a system that is not Git, but that uses Git.  LFS stands for Large File Storage.  Git itself is blissfully unaware of the existence of LFS.  When you install Git-LFS, it "wraps" Git and inserts, in a few strategic locations, filters that Git invokes when Git is attempting to check out (with git checkout, git reset, and the like) or add (with git add and the like) some file's content.
These filters secretly hide the actual file somewhere outside of Git.  They send the file contents over to a separate server—the LFS server, which stores only the large or otherwise secreted-away files—and trick Git into storing, in the Git repository, these funny little "pointer files" that consist of the three lines you just saw.
Git does not know this has happened.  If you use Git, instead of LFS-Git, you'll see the funny little pointer files.  Only if you wrap your Git with the LFS wrappers, and invoke them—once you've wrapped your particular repository properly, Git will actually invoke them for you in most cases—will you see the files themselves.
Since you're viewing the wrappers, you are using an unwrapped Git.  That's all there is to it.  The unwrapped Git sees the pointer files.  A wrapped Git is carefully tricked by the wrappers so that Git sees the substitute files but you see the real files.  If and when you see the substitute files, that's a failure of the abstraction: you're seeing the underlying mechanism.
If you install and set up the LFS wrappers—use the link above to find them—your Git will see the wrapped files but the wrappers will sneakily substitute in the large files instead, and you should see the files that someone wants you to use.  That someone, whoever that is, doesn't want you to use the wrappers: they're just for LFS.


text:
Q: Python colon as value How can a variable replace a colon?
For example, index slicing of
data[2,10] can be replaced by variables data[x,y] to get all the data after x, data[x,:].
So what would allow a function
def sliceData(data,x,y):
    return data[x,y]

and instead allow for not entering a value using a colon as a default
def sliceData(data,x=:,y=:):
    return data[x,y]

A: You can try to use eval function for your purpose of job:
>>> new = np.array([[1,2,3,4,5,6,7,8,9],[2,3,4,56,78,8,9,7,5]])

>>> def slice(data, x=':', y=':'):
...     return eval(f'{data}[{x}, {y}]')
...
>>> slice('new', 1, 2)
4
>>> slice('new')
array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9],
       [ 2,  3,  4, 56, 78,  8,  9,  7,  5]])


text:
Q: reverse java code to UML notation? Class Engine has "start(c:Component)" method. So do we need to draw an association between Engine and Component Class IF there is no "new Component()" inside Engine class.

A: NetBeans has a UML modelling tool to to reverse engineer java code. See  Generating UML From the NetBeans IDE for details.

A: MyEclipse Professional also has a UML reverse-engineering tool.


text:
Q: Not getting data from server with [FIRRemoteConfig remoteConfig] In the iOS code below,  the status of the fetch is FIRRemoteConfigFetchStatusSuccess. When  activateFetched is applied in the handler, the result is true. It looks to me therefore as if it should be the case that you can access the remote config values from the server. However, it is only the local value that is obtained when  do [FIRRemoteConfig remoteConfig][@"greeting"].stringValue;
On Firebase console have set a parameter called "greeting". What possible reasons are there to explain why it is not retrieving the server value for this parameter?
- (void)fetchFirebaseRemoteConfig {

long expirationDuration = 43200;
if ([FIRRemoteConfig remoteConfig].configSettings.isDeveloperModeEnabled) {
    expirationDuration = 0;
}

[[FIRRemoteConfig remoteConfig] fetchWithExpirationDuration:expirationDuration completionHandler:^(FIRRemoteConfigFetchStatus status, NSError *error) {
    if (status == FIRRemoteConfigFetchStatusSuccess && error == nil) {
          BOOL didApply = [[FIRRemoteConfig remoteConfig] activateFetched];
       ALog("Did apply remote config OK: %d", didApply);
    } else {
        ALog(@"Error %@", error.localizedDescription);
    }
    NSString *greeting = [FIRRemoteConfig remoteConfig][@"greeting"].stringValue;
        ALog(@"greeting: %@", greeting);

    }];
}


text:
Q: IP address changes frequently & Computer is not available via hostname I have a cable modem from my ISP to which I can only connect wirelessly.
Currently I have a desktop PC(windows 7 x64) a dell laptop(windows 7 x64) an iPod(iOS 3.1.3) and a linksys wrt54g router (v8 with dd-wrt)
Laptop and ipod behave as expected. They get an IP that stays mostly the same. for example 192.168.0.4 & 192.168.0.2
My desktop PC does not have a wireless card so I wired it to the linksys router.
The router is configured as follows (as outlined in the dd-wrt.com help & tutorial pages):

*

*Wireless mode: Client Bridge

*SSID and wireless security is configured exactly as in the ISPs modem

*DHCP is disabled

*fixed ip address 192.168.0.50

At first all seemed OK. But then I started to notice that the desktop PC could not be pinged with the hostname. Only by IP.
I then noticed that the desktop IP address would change even though the computer was not shut down. Not even it's IP released/renewed. Sometimes it changes every few minutes. sometimes after a few hours and other times not at all for the whole day.
It keeps adding up. So if the ip was  192.168.0.8 it would then be 192.168.0.9 now it's at .0.100. It is a problem since connectivity is lost while transferring files, streaming, shared folders, etc.
I suspect it is the routers fault but I don't know where to start looking to correct this issue. Any help or pointers are appreciated. Thanks!

A: Without logs (from the router) to shed light on why it's happening in the first place, I'll describe what should be the simplest fix and also help troubleshoot a possible cause.
You can set a static IP address on your desktop; under the network adapter settings for IPv4, switch from "Automatically Assigned" to an manual, and set your IP to an unused IP (something like 192.168.0.20.  Set your subnet to you 255.255.255.0 and gateway to your routers IP address.  You should also be able to set your DNS servers to either your routers IP, or a public DNS service (Google provides this @ 8.8.8.8 and 8.8.4.4).
If you continue having issues after you do this, I suspect you have a bad ethernet cable, ethernet card, or port on your router.


text:
Q: RegionPlot empty when equation is returned from Solve I have two concentric cones, one slightly bigger than the other and I want to plot their conic sections in 2D intersecting them with the same plane. I want to plot the contour of the inner conic and fill the area in between like
eq1 = 25 ((i - 0.00237 j)^2 + (-0.00237 i + 0.928 j)^2) - (-4.94 +
     0.01229 i + 0.37 j)^2;
eq2 = 25 ((i - 0.00237 j)^2 + ( -0.00237 i + 0.928 j)^2) - (-5.9598 +
     0.01229 i + 0.37 j)^2;

Show[{
  RegionPlot[
   {eq1 > 0 && eq2 < 0},
   {i, -2, 2}, {j, -2, 2}, BoundaryStyle -> None,
   PlotStyle -> Lighter[Green, 0.8]],
  ContourPlot[eq1 == 0, {i, -2, 2}, {j, -2, 2}, ContourStyle -> Orange]
  }]

The problem is that eq1 and eq2 are not given by hand like in the example above but are the result of the following function
getConicSection[cone_, toPlaneCoordinates_] :=
  Module[{h, R, cx, cy, cz, rotatedCone},
   (* Get the cone equation in the plane coordinate system *)
   h = cone["distanceToApex"];
   R = cone["bottomRadius"];
   {cx, cy, cz} = cone["bottomPosition"];
   rotatedCone = ((x - cx)^2 + (y - cy)^2)/(R/h)^2 - (z - cz -
        h)^2 /. Solve[{i, j, k} == toPlaneCoordinates[{x, y, z}], {x,
       y, z}];
   (* When k=0 we get the conic *)
   rotatedCone /. k -> 0
   ];

If I do so the ContourPlot still works but the RegionPlot is empty.

Any ideas what am I doing wrong?
(Mathematica 10.1 in Win7)

A more minimal example
getEq[n_] := Module[{eq, newEq},
   eq = If[n == 1,
     25 ((x - 0.00237 y)^2 + (-0.00237 x + 0.928 y)^2) - (-4.94 +
        0.01229 x + 0.37 y)^2,
     25 ((x - 0.00237 y)^2 + ( -0.00237 x + 0.928 y)^2) - (-5.9598 +
        0.01229 x + 0.37 y)^2];
   newEq = eq /. Solve[{i == x, y - k == j}, {x, y}];
   newEq /. k -> 0
   ];

eq1 = getEq[1];
eq2 = getEq[2];

Show[{
  RegionPlot[
   {eq1 > 0 && eq2 < 0},
   {i, -2, 2}, {j, -2, 2}, BoundaryStyle -> None,
   PlotStyle -> Lighter[Green, 0.8]],
  ContourPlot[{eq1 == 0, eq2 == 0}, {i, -2, 2}, {j, -2, 2},
   ContourStyle -> {Orange, Green}]
  }]

A: Your eq1 from the first example is different than your eq1 = getEq[1];, in the second case you are returning a list with one element, take the First and it will work as you expected. Doing:
eq1 = First@getEq[1];
eq2 = First@getEq[2];

Fixes your example.

A: The difficulty is that getEq returns a List, e.g.
getEq[1]
(*
 {25 ((i - 0.00237 j)^2 + (-0.00237 i + 0.928 j)^2)
  - (-4.94 + 0.01229 i + 0.37 j)^2}
*)

So, the inequalities do not make sense. The solution is to simply pull out the formulas, e.g.
eq1 = getEq[1][[1]];
eq2 = getEq[2][[1]];

Then it plots correctly


text:
Q: Informix ESQL/C — How to initialize fields? How can I write a routine in ESQL/C which will initialize to 0 (zero) all numeric fields (smallint, decimal, etc) and to a space the other fields in a table?

A: You asked this question on one of the IIUG (International Informix Users Group) mailing lists, and received answers there.
As I mentioned when I responded this morning, you need to think rather carefully about some of the types you don't mention.  Zeroing a DATE sets it to 1899-12-31.  Zeroing an INTERVAL makes sense (though you don't do it by setting all bytes zero; a similar comment applies to DECIMAL and MONEY and related types).  Zeroing a DATETIME generates an invalid value.  And BYTE, TEXT, BLOB, CLOB have separate sets of issues.
Setting character fields to a space is easy enough.  Setting integer fields of various sorts to zero is also easy enough.
You can look at the code in either Art Kagel's utils2_ak package or in my SQLCMD package, both available from the IIUG Software Archive.  They have code that cover many of the situations you're likely to encounter.
If they're not sufficient to help, then you need to show the code you're having problems with, explaining what is happening, what you want to happen, and (if appropriate) any messages your getting that are preventing it happening.


text:
Q: ajax called django form loosing value on adding another form i am new to django and jquery and trying do develop first application. My problem is django generated modelformset field values are going blank (reset to default) when I add another (second and subsequent) modelformset to div via ajax call.
'.additem` is class for button calling django view function which is generating formset.
I believe it is something related to binding values to form resetting form values to default. I tried adding event.preventdefault() but no success.
jQuery code with ajax call is as follows:
$(document).on("click", '.additem', function(event) {
    $.ajax({
        url: 'additem',
    data: { additem: 1},
    type: 'get',
    success: function(response){
    event.preventDefault();
            console.log(response);
            var form_idx = parseInt($("#id_detail-TOTAL_FORMS").val());
            modified_response = response.replace(/ detail - 0 / g, "detail-" + form_idx);
    $('#detail').html($('#detail').html() + modified_response);
    $("#id_detail-TOTAL_FORMS").val(parseInt(form_idx) + 1);
        },
    failure: function(data) {
            alert('Got an error dude');
        }
    });
});

# django view code

    if request.method == 'GET' and 'additem' in request.GET:
        f = self.detailform_class
        fd = f._meta.fields

        formsetclass = modelformset_factory(detailmodel_class, form= f, fields= fd,extra =1, can_delete=True  )
        formset = formsetclass(queryset=detailmodel_class.objects.none(), prefix='detail',initial =[{self.related_field:pk}])
        html = render_to_string('mm/formset4.html', {'sub_form': formset})
        return HttpResponse(html)


text:
Q: What does ${_[0]} mean in bash? When I type this in bash command line
$ x=hi; printf '%s ' "$x" "${x[0]}"; echo "${_[0]}"

I have this output:
hi hi hi

*

*Why "${_[0]}" turns out to be "hi" in the output?

*Why could we use the "x[0]" syntax, given that "x"is just a string instead of an array?

A: As others have mentioned ${_[0]} is extra typing for ${_} which in turn can be abbreviated into $_ as it is most commonly used.
As mentioned previously it is a variable that contains the last parameter of the last command used. A practical application is like this:
$ ll /etc/lsb-release
-rw-r--r-- 1 root root 105 Feb 20  2019 /etc/lsb-release

$ cat $_
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.6 LTS"

In the first command the last parameter is /etc/lsb-release. In the second command the parameter is $_, which repeats /etc/lsb-release so you don't have to retype it.

A: The _ parameter has several meanings depending on context, but it is never an array. Likewise, in your example, x is not an array. The reason you're able to treat it as if it is an array is that Bash allows non-array variables to be treated as if they were one-element arrays. Bash likewise allows array variables to be treated as if they were non-arrays, giving the first element.
As man bash says:

Referencing an array variable without a subscript is equivalent to referencing the array with a subscript of 0.  Any reference to a variable using a valid subscript is legal, and bash will create an array if necessary.

So "${_[0]}" behaves the same as "${_}" or "$_", because _ is not an array. Likewise, "${x[0]}" behaves the same as "${x}" or "$x", because x is not an array.

As for why _ holds the value hi: In the usage you've shown, performing parameter expansion on the special _ parameter yields the last argument of the most recent (synchronously executed) command.
As man bash says of _:

At shell startup, set to the absolute pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous simple command executed in the foreground, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file currently being checked.

(emphasis mine)
In this case, the most recently executed command was:
printf '%s ' "$x" "${x[0]}"

The arguments passed to printf were:

*

*%s , on which only quote removal was performed.

*hi, on which parameter expansion was performed, followed by quote removal.

*hi, on which a more complex form of parameter expansion yielding the same result was performed, followed by quote removal.

A: $_ is a special parameter.  It is used in a number of ways but, in your case, it refers to the last argument of the previous command:
$ echo hi Hi Hello
hi Hi Hello
$ echo "$_"
Hello

Since $_ is a variable, not an array, the syntax ${_[0]} is just useless clutter that accesses $_:
$ echo "$_"
Hello
$ echo "${_[0]}"
Hello

Documentation
From man bash:

$_ At shell startup, set to the absolute pathname used to invoke  the
shell  or   shell  script  being  executed as passed in the
environment or argument list.   Subsequently, expands to the last
argument to the previous simple command executed  in  the
foreground,  after expansion.  Also set to the full pathname   used to
invoke each command executed and placed in the  environment  exported
to  that  command.   When checking mail, this parameter holds the name
of the   mail file currently being checked.

I highlighted in bold the part relevant to your usage.


text:
Q: Spring Session, Websocket, REST Token Security We currently have a Spring application which contains a REST API and also Websocket broker endpoints to get realtime updates on database changes.
We've successfully migrated to the Spring Session project with an embedded redis server which authenticates by basic auth and a session id can be used  on subsequent requests as an x-auth-token header.
The issue we're having is to secure the Websocket. On Angular, we have a wrapper directive around the stomp.js / sockjs libraries but we can't seem to figure out how to set the x-auth-token header on the Websocket upgrade requests.
Are we doing something wrong? What would be the recommended way to approach this kind of security scheme?
Stack:

*

*Tomcat 7.0.57

*Spring Security 4.0.0.RC2

*Spring Session 1.0.0.RELEASE

*Spring MVC 4.1.4

*AngularJS 1.2.28

A: Looks like the JS Websocket API doesn't allow setting HTTP headers on the initial handshake and upgrade request.
The proper scheme would be to send an authentication token on the CONNECT frame and handle it accordingly on the server side. So for now we've migrated to browser cookie sessions until we can find a suitable implementation for this on the server side.


text:
Q: Does the intersection of two finite index subgroups have finite index? Let $(G,*)$ be a group and $H,K$ be two subgroups of $G$ of finite index (the number of left cosets of $H$ and $K$ in $G$). Is the set $H\cap K$ also a subgroup of finite index? I feel like need that $[G\colon(H\cap K)]$ is a divisor of $[G\colon H]\cdot[G\colon K]$, but I dont't know when this holds.
Can somebody help me out?

A: Let $C$ be the set of left cosets of $S = H \cap K$ in $G$, $C_1$ the set of left cosets of $H$ in $G$, and $C_2$ the set of left cosets of $K$ in $G$. Consider the function $f: C \to C_1 \times C_2$ defined by $f(xS) = (xH, xK)$. It is easy to check that this function is well-defined. Furthermore, this function is injective. Hence, $|S| \leq |C_1| \cdot |C_2|$, which proves that $[G: S]$ is finite.

A: Another way to see that the answer is "yes": In this thread it is shown that any finite index subgroup of $G$ contains a subgroup which is normal and of finite index in $G$. Find such subgroups $N_1 \subset H$ and $N_2 \subset K$. Then $G/N_1 \times G/N_2$ is a finite group; do you see why this implies that $N_1 \cap N_2$ has finite index in $G$?

A: Proof $1$: $\quad[G:H\cap K]=[G:H][H:H\cap K]=[G:H][HK:K]\le [G:H][G:K].$
We do not assume normality on $H,K$ and therefore cannot assume $HK$ is a group. But it is a disjoint union of cosets of $K$, so the index makes sense. Also, $[H:H\cap K]=[HK:K]$ follows from the orbit-stabilizer theorem: $H$ acts transitively on $HK/K$ and the element $K$ has stabilizer $H\cap K$.
Proof $2$: Consider the diagonal action of $G$ on the product of coset spaces $G/H\times G/K$. The latter is finite so the orbit of $H\times K$ is finite, and the stabilizer of it is simply $H\cap K$. Invoke orbit-stabilizer.

A: $H, K$ be subgroups of $G$. Any $A \in {G}/({H \cap K})$ can be written as $A = B \cap C$, where $B \in G/H$ and $C \in G/K$ as follows. For any $g \in G$
$$g(H\cap K) = gH \cap gK.$$
Hence,
$$[G:H \cap K] \leq [G:H] [G:K].$$

A: I'm not really adding something to the answers, and surely you already have what you need, but I'll leave this here just for people having the same problem who will eventually end up here.
Since both $H$ and $K$ are finite index subgroups of $G$, we can consider the right cosets $G/H$ and this is finite by hypothesis. In particular $G$ acts (transitively) on $G/H$ by right multiplication, i.e.
$$
 G/H \times G \to G, \qquad
 (Hx, g) \mapsto Hxg.
$$
If we now restrict the action to $K$, and consider the $K$-orbit of $H$, call it $\mathcal{O}_K(H)$, then it must be finite since it's contained in $G/H$. But now by what Isaacs calls the Fundamental Counting Principle (see "Finite Group Theory", theorem 1.4) we exactly know the following equality
$$
 |\mathcal{O}_K(H)| = [K : \text{Stab}_K(H)],
$$
where $\text{Stab}_K(H)$ is the stabiliser of $H$ under the $K$-action. Notice that $\text{Stab}_K(H) = K \cap \text{Stab}_G(H)$, and what's the stabiliser of $H$ for the $G$-action? But of course $H$ itself, so $\text{Stab}_K(H) = K \cap H$, and finally we conclude that $[K : K \cap H]$ is finite. Hence $[G : H \cap K] = [G : K][K : K \cap H]$ must be finite as well.

A: Let $\{H_1,\dots,H_m\}$ be the left cosets of $H$, and let $\{K_1,\dots,K_n\}$ be the left cosets of $K$. For each $x\in G$ there are unique $h(x)\in\{1,\dots,m\}$ and $k(x)\in\{1,\dots,n\}$ such that $x\in H_{h(x)}$ and $x\in K_{k(x)}$. Let $p(x)=\langle h(x),k(x)\rangle$. Note that the function $p$ takes on at most $mn$ different values. Now show:

Proposition: If $x$ and $y$ are in different left cosets of $H\cap K$, then $p(x)\ne p(y)$.

It follows immediately that $H\cap K$ can have at most $mn$ left cosets.
It may be easier to consider the contrapositive of the proposition:

If $p(x)=p(y)$, i.e., if $x$ and $y$ are in the same left coset of $H$ and the same left coset of $K$, then $x$ and $y$ are in the same left coset of $H\cap K$.

You may find it helpful to recall that $x$ and $y$ are in the same left coset of $H$ iff $x^{-1}y\in H$.

A: Let $l := [G:H]$, $m := [G:K]$, $h_1,...,h_m,k_1,...,k_l \in G$ and $G$ be partitioned as $$G=h_1H \cup \dots \cup h_lH = k_1K \cup \dots \cup k_mK.$$
I will find $a_1,...a_n \in G$ s.t. $G$ is partitioned as $$G=a_1(H \cap K) \cup \dots\cup a_n(H \cap K)$$ which means $n=[G:H \cap K] < \infty$.
Let $b_1 \in G$. Then $\exists i_1 \in \{1,...,m\}, j_i \in \{1,...,l\}$ s.t. $b_1 \in h_{i_1}H \cap k_{j_1}K=b_1H \cap b_1K = b_1(H \cap K)$. Next, let $b_2 \in G \ \setminus \ b_1(H \cap K)$. Then $b_2 \in b_2(H \cap K)$ where $b_2(H \cap K) \cap b_1(H \cap K) = \emptyset$ because $$b_1H \cap b_2H = h_{i_1}H \cap h_{i_2}H = \emptyset = k_{j_1}K \cap k_{j_2}K = b_1K \cap b_2K$$
where $$h_{i_2}H=b_2H, k_{j_2}K=b_2K, i_2 \in \{1,...,m\} \ \setminus \ \{i_1\}, j_2 \in \{1,...,l\} \ \setminus \ \{j_1\}$$ This process continues at most $lm$ times for $a_p=b_p, p \in \{1,2,...,n\}$ Thus, $n \le lm < \infty.$


text:
Q: Splitting comma separated strings in MYSQL for dynamic drop down list Right now I am having trouble with splitting up entries in my ethnicity column that contain entries that are separated by commas for example take a look at my
Ethnicity table
I want to be able to split up these strings into individual strings so they can all be their own entries (ex: asian, chinese, catina would all be seperate entries). I don't want to make any changes to my existing table I just want to be able to seperate these strings because I am using php to create a dynamic drop down list based on what is stored in this ethnicity column:

*Category

   <select name="category" multiple>
   <?php
    $conn = mysqli_connect(db, root, pass, table);
    // Check connection
    if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
    }
      $result = mysqli_query($conn,"SELECT DISTINCT restaurant_id, ethnicity FROM ethnicity");
      while ($row = mysqli_fetch_assoc($result)) {
              unset($restaurantID, $ethnicity);
              $restaurantID = $row['restaurant_id'];
              $ethnicity = $row['ethnicity'];
              echo '<option value="'.$ethnicity.'">'.$ethnicity.'</option>';
  }

  ?>
  </select>

Right now the drop down list is including the comma separated strings and I just want it to be able to display the distinct ethnicities individually. Any suggestions?

A: I'd start buy doing the query above and exploding all the ethnicities into a new array and then printing them out:
(I haven't tested syntax just used notepad, hopefully you get the idea though.)

*Category

<?php
 $conn = mysqli_connect(db,root,pass,table);
 // Check connection
 if (!$conn) {
   die("Connection failed: " . mysqli_connect_error());
 }

 $ethnicity_array = [];

 $result = mysqli_query($conn,"SELECT DISTINCT restaurant_id, ethnicity FROM ethnicity");
 while ($row = mysqli_fetch_assoc($result))
 {
    unset($restaurantID, $ethnicity);
    $restaurantID = $row['restaurant_id'];
    $ethnicity = $row['ethnicity'];

    $split_ethnicity = explode("," $ethnicity);
    foreach ($split_ethnicity as $value)
    {
        if (!in_array($value, $ethnicity_array))
            $ethnicity_array[] = $value;
    }
}

?>

<select name="category" multiple>
  <?php
    foreach ($ethnicity_array as $ethnicity)
    {
      echo '<option value="'.$ethnicity.'">'.$ethnicity.'</option>';
    }
  ?>
</select>


text:
Q: Postgresql character varying strange behaviour I have a table in which client_code is a character varying(10) column.
Now, this query does not work :
insert into mydb.mytable (CLIENT_CODE) values ('0123456789');

I get ERROR: value too long for type character varying(10).
When putting 9 characters in the query, it runs fine.
It seems strange to me. It's not the definition of character varying i've read.
I use PostgreSQL 9.3.19 with ENCODING = 'UTF8' and LC_CTYPE = 'French_France.1252'.

A: below row 1 is copypasted your string and row two is intered manually by me:
t=# with d(s,t) as (values(1,'0123456789'),(2,'0123456789'))
select *,char_length(t),ascii(t),ascii(substring(t,2,1)) from d;
 s |     t      | char_length | ascii | ascii
---+------------+-------------+-------+-------
 1 | 0123456789 |          11 | 65279 |    48
 2 | 0123456789 |          10 |    48 |    49
(2 rows)

you have http://www.fileformat.info/info/unicode/char/feff/index.htm ZERO WIDTH NO-BREAK SPACE as fisrt char - you dont see it, but postgres does


text:
Q: Check framework example giving me error when running './configure' I'm building the check framework example 'check_money', but it's not building on my machine. The error is:
configure: error: cannot find install-sh, install.sh, or shtool in "." "./.." "./../.."

I've tried installing it using:
libtoolize --force
aclocal
autoheader
automake --force-missing --add-missing
autoconf
./configure

It's still giving me the same error.
So, I copied the same directory to another directory and ran:
autoreconf --install
./configure

And it's still giving me the same error. I don't know what else to try.
I'm on Mac OS X Mavericks (10.9)

*

*Autoconf 2.69

*Automake 1.15

*Libtool 2.4.6

*Check 0.9.14

A: I was able to figure out what was causing the errors - it was due to automake and libtools which I installed using brew install. Despite already installing autoconf which installed all the necessary tools I needed.
In addition, I looked at the configure script that autoconf created and I found that the variables wasn't being set-up properly which is why it was giving me the install-sh error because the $ac_dir wasn't assigned.
Here is what I did.
I uninstalled libtools and automake -
brew uninstall libtool automake
autoreconf -i
./configure

It ran with out any errors. I still don't know the reason why installing those 2 packages messed in building the project.


text:
Q: What is the difference between the Big O and Big O star (asterisk) operator? I'm doing some research on algorithms complexity and in different papers I notice both the use of the regular Big-O operator O(...) and a variant O*(...).
I never saw the definition of the latter one, which has an asterisk. I can't seem to find a definition anywhere. (Disclaimer: Googling for symbols is nearly impossible.)
What is the name and definition of the O*(...) operator? And how does it differ from the regular Big-O operator?

A: In parametrized algorithms, the algorithm gets an input $x$ and a parameter $k$.
The usual usage of $O^*(f(k))$ is saying there exists an algorithm which runs in time $$O(f(k)\cdot \text{poly}(|x|))$$
(e.g. $O^*(2^{2^k})$ means the algorithm is allowed to run in $O(2^{2^k}|x|^6)$, but not in $O(2^{2^k+k}+|x|)$)
This is somewhat different from the $\widetilde O$ notation for ``standard'' (non-parametric) algorithms which hides poly-logarithmic factors, i.e.
$$O(2^nn^4)\subset\widetilde O(2^n)$$


text:
Q: Why am I getting incorrect results for these simple operations in Julia? I've started using the Julia language, but I'm surprised to get seemingly incorrect results with even basic operations:
julia> 0.05*0.05
0.0025000000000000005

and
julia> 1.0-0.85-0.1
0.05000000000000002

How can this be? And what can I do to obtain exact results?

A:
I'm surprised to get seemingly incorrect results with even basic operations [...] How can this be?

Binary IEEE-754 floating-point numbers (which Julia uses) cannot represent numbers such as 0.05, 0.85, and 0.1 exactly.
For instance, when you write 0.05 in Julia, the number that the machine manipulates is a number very close to the actual number 0.05, but not exactly 0.05. Therefore, you cannot expect Julia expressions such as 0.05*0.05 to evaluate to exactly 0.0025.
More counterintuitive examples? Try
julia> 1-0.2-0.2-0.2-0.2-0.2
5.551115123125783e-17

julia> 0.6/0.2 == 3
false

If you're interested (and even if you're not!), I strongly recommend
David Goldberg's What every computer scientist should know about floating-point arithmetic. You may also be interested in this related answer of mine on the TeX sister site.

And what can I do to obtain exact results?

Are you only manipulating rational numbers? If so, know that Julia provides a rational types, i.e. types that allow you to represent fractions exactly.
The rational type used by default, Rational{Int64}, is capable of representing any rational number whose numerator and denominator fall in the range of 64-bit integers.
You can use this rational type to carry out exact operations (barring integer overflow) on rational numbers:
julia> 1//20 * 1//20
1//400

julia> 1 - 17//20 - 1//10
1//20

Moreover, if you want arbitrary-precision rational numbers, you can use the Rational{BigInt} type (see Mr Alpha's comment)


text:
Q: How do I match latin unicode characters in ColdFusion or Java regex? I'm looking for a ColdFusion or Java regex (to use in a replace function) that will only match numbers [0-9], letters [a-z], but include none ASCII Portuguese letters (unicode latin, like ç and ã).
Some like this:
str = reReplaceNoCase(str, "match none number/letter but keep unicode latin chars", "", "ALL");

Input string: "informação 123 ?:#$%"
Desired outcome: "informação 123"
I know I can match letters and numbers with [a-z][0-9], but this doesn't match letters such as ç and ã.

A: Try alphanumeric character class: \w, it should match letters, digits, and underscores.
Also you can use special named class \p{L} (I don't know, does Java RegEx parser support it).
So in C# your task can be done using following code:
var input = "informação 123 ?:#$%";
var result = Regex.Replace(input, @"[^\p{L}\s0-9]", string.Empty);

Regex [^\p{L}\s0-9] means: any character not in this class (all letters, white space, digits). Thereby it matches in your example ?:#$% and we can replace these characters with empty string.


text:
Q: ClassNotFoundException using wscompile task We are using the wscompile ant task and getting classnotfound error.
[wscompile] RmiModeler error: java.lang.ClassNotFoundException: org$soa$soap$UserService
[wscompile]     at com.sun.xml.rpc.processor.modeler.rmi.RmiModeler.modelPort(RmiModeler.java:685)
[wscompile]     at com.sun.xml.rpc.processor.modeler.rmi.RmiModeler.buildLiteralModel(RmiModeler.java:603)
[wscompile]     at com.sun.xml.rpc.processor.modeler.rmi.RmiModeler.buildModel(RmiModeler.java:457)
[wscompile]     at com.sun.xml.rpc.processor.config.ModelInfo.buildModel(ModelInfo.java:88)
[wscompile]     at com.sun.xml.rpc.processor.Processor.runModeler(Processor.java:63)
[wscompile]     at com.sun.xml.rpc.tools.wscompile.CompileTool.run(CompileTool.java:714)
[wscompile]     at com.sun.xml.rpc.util.ToolBase.run(ToolBase.java:43)
[wscompile]     at com.sun.xml.rpc.tools.ant.Wscompile.execute(Wscompile.java:746)
[wscompile]     at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
[wscompile]     at sun.reflect.GeneratedMethodAccessor6.invoke(Unknown Source)
[wscompile]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[wscompile]     at java.lang.reflect.Method.invoke(Method.java:592)
[wscompile]     at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
[wscompile]     at org.apache.tools.ant.Task.perform(Task.java:348)
[wscompile]     at org.apache.tools.ant.Target.execute(Target.java:390)
[wscompile]     at org.apache.tools.ant.Target.performTasks(Target.java:411)
[wscompile]     at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1397)
[wscompile]     at org.apache.tools.ant.Project.executeTarget(Project.java:1366)
[wscompile]     at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
[wscompile]     at org.apache.tools.ant.Project.executeTargets(Project.java:1249)
[wscompile]     at org.apache.tools.ant.Main.runBuild(Main.java:801)
[wscompile]     at org.apache.tools.ant.Main.startAnt(Main.java:218)
[wscompile]     at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
[wscompile]     at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
[wscompile]
[wscompile] CAUSE:

The interesting thing this is this happens only when the no of services goes up, meaning the no class file go up... I think there should be some setting for the  memory in ant or wscompile?
<wscompile server="true"
               keep="true"
               features="documentliteral"
               sourceBase="${gen.dir}/wscompile/src"
               nonClassDir="${gen.dir}/wscompile/nd"
               base="${gen.dir}/wscompile/classes"
               model="${gen.dir}/wscompile/user-model.gz"
               xPrintStackTrace="true"
               verbose="true"
               config="build/config-user_service.xml">
      <classpath>
        <pathelement path="dist/lib/$javacode.jar}"/>
      </classpath>
    </wscompile>

when the size of javacode.jar is 52MB this works and the size grows to say 53MB the above error is generated.

A: I'd say it's very likely the cause of this is your PermGen is running out of memory. PermGen stores the meta-info about each class, so the larger the number of classes the larger this will grow. Try increasing the MaxPermSize you're passing to the wscompile task and see if it fixes the problem.


text:
Q: control reaches end of non-void function [-Werror=return-type] Even after using default else statement I am getting this error
int max_of_four(int a, int b, int c, int d)
{
    if((a>b)&&(a>c))
    {
        if(a>d)
            return a;
    }
    else if((b>c)&&(b>d))
    {
        return b;
    }
    else if(c>d)
    {
        return c;
    }
    else
        return d;
}

A: Your first if is the problem
if((a>b)&&(a>c))
{
    if(a>d)
        return a;
    // what about else?
}

If your outer condition is true, but the inner condition is false, it will not have any return case.
By the way, your method is a very convoluted way to solve this, or at least difficult to read. I would do something like this.
#include <algorithm>
int max_of_four(int a, int b, int c, int d)
{
    return std::max(std::max(a, b), std::max(c, d));
}

You could also use
#include <algorithm>
int max_of_four(int a, int b, int c, int d)
{
    return std::max({a, b, c, d});
}

A: the "control reaches end of non-void function [-Werror=return-type]"
error happens during the compiling phase, when there is a possibility(branch) that your non-void function (which is defined to return a value) could not return a value. Although, depends on the input, it does not necessarily reach that dead-end.

A: put else condition in first if:
int max_of_four(int a, int b, int c, int d)
{
     if((a>b)&&(a>c))
    {
        if(a>d)
            return a;
         else
             return d;
    }
    else if((b>c)&&(b>d))
    {
        return b;
    }
    else if(c>d)
    {
        return c;
    }
    else
        return d;
}


text:
Q: If-Else statement works weird in Python import numpy as np
import sklearn
import sklearn.datasets
from sklearn import svm
x = np.array([1,3,67,8])
print(x)
print(type(x))

if type(x) != int:
    y = x.astype(int)
    print(y)
    print(type(y))
else:
    print ("X is already an integer")

This is my code here if x is not integer then convert it to integer else print it as integer but it works weirdly that code in if statement is executed even if x is integer or float.

A: I believe this is what you are looking for. To check whether a value is an integer (even if in a float array), then you can test x == int(x).
import numpy as np

arr = np.array([1, 3, 67, 8, 7.5])

print(arr, type(arr))

for x in arr:
    if x != int(x):
        y = x.astype(int)
        print(y, type(y))
    else:
        print(str(int(x)) + ' is already an integer')

# [  1.    3.   67.    8.    7.5] <class 'numpy.ndarray'>
# 1 is already an integer
# 3 is already an integer
# 67 is already an integer
# 8 is already an integer
# 7 <class 'numpy.int32'>


text:
Q: How would you do a removeIf on a list or set for primitives in eclipse collections? On regular java collections it's possible to remove an element given an input Predicate.

persons.removeIf(person -> person.isMale());

In eclipse collections it seems possible to do this as long as the collection being used extends Iterable<T>.
For primitive collections that extend PrimitiveIterable, there doesn't seem to be a method provided to do the same. Is it not supported? If not, why?
EDIT:
I should add that I'm looking for a method that removes an item in-place without creating a new set, as reject does.

A: The method removeIf doesn't exist for mutable primitive collections in Eclipse Collections today.  It makes sense to add, as it has been on the mutable object collections since at least version 2.0 which was released in August 2012.  I just started working on it.  It can be added as a default method so should hopefully be available in the 9.1 release.
Update: The method removeIf was added to mutable primitive collections in the 9.1 release of Eclipse Collections.


text:
Q: Different ouput in similar code - Webscraping with Python In this link, I try to count all the numbers that appear as links above the table of the webpage. Check the link to have a better idea. I have two codes that are very similar, but just the first code gives the expected output. So, what is wrong with my second code?
import urllib2
from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen("http://www.admision.unmsm.edu.pe/admisionsabado/A/011/0.html"))
c=[]
for n in soup.find_all('center'):
    for b in n.find_all('a')[1:]:
        c.append(b.text)

t = len(c) / 2

print t

The result is 41. In the webpage there 41 numbers which appear as links above the table of the webpage, so the output is right.
In the wrong code, I define a function which its input is a subset of the url. The code is below:
import urllib2
from bs4 import BeautifulSoup

def record(part):
    soup = BeautifulSoup(urllib2.urlopen("http://www.admision.unmsm.edu.pe/admisionsabado".format(part)))
    c=[]
    for n in soup.find_all('center'):
        for b in n.find_all('a')[1:]:
            c.append(b.text)

    t = len(c)/2
    print t

As you see the method for counting the numbers are the same. So, I run the function:
record('/A/011/0.html')

Unfortunately, the output is 0.

A: Inside the function, you are formatting the URL string with the passed in parameter, but the format string didn't have the placeholder {} in it to place the value at. Here it is with it.
"http://www.admision.unmsm.edu.pe/admisionsabado{}".format(part)


text:
Q: How to plot gaussian mixtures overlayed with heatmap in Python? I have a 2D NumPy ndarray which consists of densities in a sparse matrix. I would like to plot it as a heatmap while also plotting ellipsoids derived from a couple of Gaussian mixture models fitted to my data. How can I accomplish this in Python?
The array looks something like this:
a = np.array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
    1., 0., 0., 0., 0., 0., 1., 1., 2., 1., 2., 1., 1., 1., 0., 0.,
    0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 0., 0., 1., 0., 0.,
    1., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0.,
    0., 0., 0., 0., 0.],
   [0., 0., 2., 1., 2., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
    0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1.,
    0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
    0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1.,
    1., 1., 1., 0., 0.],
   [0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
    0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.,
    0., 0., 0., 0., 0.]])

And to fit the data I use sklearn.mixture, but first I convert the 2D array to a density array:
def convert_to_density_array(array):
    """
    Convert an array to a density array
    """
    density_list = []
    # iterate over each i,j coordinate in the array
    for (i, j), value in np.ndenumerate(array):
        for x in range(int(value)):
            density_list.append((i, j))
    return np.array(density_list)

# Create density array
density_array = convert_to_density_array(a)
gaussian_mix_4_components = mixture.GaussianMixture(n_components=4).fit(density_array)


text:
Q: Spring cloud stream errors channel not working EDIT:
Use Case: receive request, process them and notify someone when the request finished. Put in another queue when the process has an error to reprocess later.
I need an API which receives a payload and sends it to a queue (jobs to be processed). Then pickup the messages and start using that payload to invoke another rest service, and queue the response of that call into a new queue (jobs done) which then another service will pick that messages and notify another service about it's completion.
So API POST stores in a queue, pick up the message process it, store the result of that process in another queue.

I have an application with two bindings, one for idle jobs and one for processed jobs. The application work as intended, but when I throw an exception, after spring tries to reprocess the message 3 times, it's not sending a message to processed.default.errors, instead it throws an exception:

Caused by: org.springframework.messaging.MessageDeliveryException: failed to send Message to channel 'processed.default.errors'; nested exception is org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Retry Policy Exhausted

@Component
public interface JobBinding {

    String INPUT = "jobs-in";
    String OUTPUT = "jobs-out";

    @Input(INPUT)
    SubscribableChannel input();

    @Output(OUTPUT)
    MessageChannel output();
}

-
@Component
public interface ProcessedBinding {

    String INPUT = "processed-in";
    String OUTPUT = "processed-out";

    @Input(INPUT)
    SubscribableChannel input();

    @Output(OUTPUT)
    MessageChannel output();
}

I enable both of them:
@EnableBinding({JobBinding.class, ProcessedBinding.class})
public class BindingsConfiguration {
}

Then i process the job:
@Component
@Slf4j
public class JobProcessor {

    @StreamListener(JobBinding.INPUT)
    @SendTo(ProcessedBinding.OUTPUT)
    public Message<Job> handleJob(@Payload Job job) {
        log.info("Processing {}", job);
        job.addMetadata("status", "processed");
        return MessageBuilder.withPayload(job).build();
    }
}

And then I k-boom:
@Component
@Slf4j
public class DoneProcessor {

    @StreamListener(ProcessedBinding.INPUT)
    public void handleJob(@Payload Job job) {
        log.info("Notifying {}", job);
        throw new RuntimeException("puff");
    }
}

My application.properties looks like:
spring.cloud.stream.bindings.jobs-out.destination=jobs
spring.cloud.stream.bindings.jobs-in.destination=jobs
spring.cloud.stream.bindings.jobs-in.group=default

spring.cloud.stream.bindings.processed-out.destination=processed
spring.cloud.stream.bindings.processed-in.destination=processed
spring.cloud.stream.bindings.processed-in.group=default

spring.cloud.stream.default.contentType=application/json

I tried reading the docs of spring stream cloud by I couldn't find a solution. The queue should be created automatically.


text:
Q: objects not properly pushed in array The code below is supposed to decompose a json object sent from Postman into smaller objects that will be stored in a array. The problem is that if I console.log the result, I do see each and every objects decomposed as expected but the array.push method only push the last element of the inner array :
app.post('/commande',async(req,res)=>{

if( await authentification(req.query.login, req.query.pass)){

  var data = req.body.data; // array containing json object to be posted
  var dataLength = data.length;
  var bigObj= []; //array to store objects
  for (var i = 0; i<dataLength; i++) {

    var orderLines = data[i].orderLines;//array of orders
    var info ={};// object unit
    info.CptClient = data[i].clientAccount;
    info.customerOrderNumber= data[i].customerOrderNumber;
    info.orderLabel = data[i].orderLabel;
    var shipTo = data[i].shipTo;
    info.recepientName = shipTo.recepientName;
    info.contactName = shipTo.contactName;
    info.ad1 = shipTo.ad1;
    info.ad2 = shipTo.ad2;
    info.ad3 = shipTo.ad3;
    info.postalCode = shipTo.postalCode;
//"etc..."

  //
  for (var j = 0; j<orderLines.length;j++) {

    info.itemRef = orderLines[j].itemRef;
    info.itemQty = orderLines[j].itemQty;
    info.unitPrice = orderLines[j].unitPrice;

    console.log(info);//displays unique orderLabel :      ABC01 ABC02 ABC03 XYZ01 XYZ02 XYZ03
    bigObj.push(info); // stores only last of each type : ABC03 ABC03 ABC03 XYZ03 XYZ03 XYZ03

}
  }
res.json(bigObj)
}else {
  res.send("not authorized");
}

})

As explained in the comments, the console.log displays the right information as the objects are being created but the push method somehow would only push the last element of the orderLines array. Is there somebody to explain this phenomenon? Any idea? Thank you.


text:
Q: Get Serilog to append its first log file with _001 Is it possible to configure Serilog so that the default log file is appended with _001 and if the file limit is reached, that subsequent files are appended with _002, _003 etc.
This is in the context of a ASP.NET Core application.

A: Unfortunately it's not possible to express this given how the config API has worked since very early days, and, there's no obvious way you make it possible without making the API messy and/or risking breaking people's configs...
As Nick replied to my suggestion

makes sense - the only drawback is that we would risk breaking existing apps by making it the default, and yet it seems too minor to warrant a new top-level configuration option.