text:
Q: Restricting ForeignKey choices on sub-classes I have a set of models, regarding restaurants and the chefs that run them*:
class Chef(models.Model):
    name = models.TextField()

class Restaurant(models.Model):
    name = models.TextField()
    chef = models.ForeignKey(Chef)

class FrenchChef(Chef):
    angryness = models.PositiveIntegerField()

class FrenchRestaurant(Restaurant):
    region = models.TextField()

Unfortunately, this current model means a non-FrenchChef can run a FrenchRestaurant.
Is there away that I can restrict the queryset for the ForeignKey of a subbclassed model to be a subset of those available on the parent class?
* My modelling isn't actually chefs and restaurants, but this is easier to explain. It might not seem obvious, but Chefs and FrenchChefs do need to be modelled differently.

A: You could try defining clean method if you're concerned about that
class FrenchRestaurant(models.Model):
    # ...

    def clean(self):
        if not isinstance(self.chief, FrenchChief):
            raise ValidationError()

A: By doing this:
class FrenchChef(Chef):
    angryness = models.PositiveIntegerField()

you are creating one more table in database besides Chef. Read about types of model inheritance here: https://docs.djangoproject.com/en/1.7/topics/db/models/#model-inheritance
I think you should create one table for chefs and one table for restaurants, no inheritance needed here:
class Chef(models.Model):
    name = models.TextField()
    # all chefs with not null angryness is frenchchefs...
    # but you can add some field to explicitly save chef type
    angryness = models.PositiveIntegerField(null=True)

class Restaurant(models.Model):
    name = models.TextField()
    chef = models.ForeignKey(Chef)
    region = models.TextField()
    # rtype added here but it is not necessarily
    rtype = models.IntegerField(choices=restaurans_types)

And restriction (filtering) of choices should be in forms:
class FrenchRestaurantForm(forms.ModelForm):
    def __init__(self, *args,**kwargs):
        super (FrenchRestaurantForm, self ).__init__(*args,**kwargs)
        self.fields['chef'].queryset = Chef.objects.filter(
            angryness__gte=MIN_ANGRYNESS_LVL)
    def save(commit=True):
        model = super(FrenchRestaurantForm, self).save(commit=False)
        model.rtype = SomeFrenchRestTypeConst
        if commit:
            model.save()
        return model
    class Meta:
        model = Restaurant

To check user input you can add clean method to form field https://docs.djangoproject.com/en/1.7/ref/forms/validation/#cleaning-a-specific-field-attribute
If FrenchChef was created intentionally (it is a different table in database), then you should add it to FrenchRestaurant (another table -> another fk id):
class FrenchRestaurant(Restaurant):
    region = models.TextField()
    frenchchef = models.ForeignKey(FrenchChef)

A: Like I was mentioning in the comment, You can look at django model data validation methods. Just found another note at this post.
Adding Custom Django Model Validation
Below is a common pattern followed to do validation. code snippet is extract from one of the answers in the abouve mentioned post . answered by https://stackoverflow.com/users/247542/cerin

class BaseModel(models.Model):

    def clean(self, *args, **kwargs):
        # add custom validation here
        super(BaseModel, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(BaseModel, self).save(*args, **kwargs)

You can go ahead and read more about validation in django documentation.
If you are looking for any type/inheretance based solutions that might exist. I am not sure if they might exist. I would still like to see if someone comes up with such provision in django.


text:
Q: An exponential function between zero and one Alrighty, math noob here, so be nice :P. We're building an app and need an exponential function that exists between zero and one, and, depending on the importance we give it, will fluctuate between rising near the beginning or end of the graph.
Lemme know if you have any ideas or need clarification :P

A: Sounds like you want the Logistic function.  The values are between 0 and 1, though the growth is centered around $0$ and it has an exponential in it.  You can shift it horizontally by adding a constant to $x$ and change the steepness by changing $e^{-x}$ to $e^{-ax}$ for your choice of $a$.  Does that work?

A: Maybe you mean power law rather than exponential. In that case @fedja's suggestion is great: $x^a$. $a<1$ for low importance and $a>1$ for high importance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery plugin slider feature not displaying on summary I have a Jquery plugin that does calculations. The plugin is working almost perfectly except one feature is not triggering.
In this FIDDLE you will see a yellow box on the right with the heading "Summary". The summary lists different items from events on the right. All of the events on the right, except the one titled "Slider" properly list themselves in the right yellow summary box as you can see in this screenshot:

If it worked right it would look like this:

This following code is what is used to display the slider, the o-4 and the f-4 is what is used to tell the Jquery plugin to display it in the yellow summary box:

Slider:

        <input class="i-slider" type="number" id="f_4" name="f_4" data-slider="true" value="3" min="0" max="10" step="1" data-cost="2"/> - $2 AUD per unit

In addition to the html I have pasted above, the inline jquery script needs this added to it to work, you will see f_4 says Slider:
"items": {
    "f_1": "Balances",
    "f_2[]": "Card Balances",
    "f_3[]": "Program Fee",
    "f_4[]": "Slider",
    "f_5[]": "Monthly Maintenance",
    "f_6[]": "Total Montly Fees",
    "q_1": "Percentage Rate",

Lastly, here is link to a working demo script of the plugin, you will see they have a slider also and it displays properly in the right yellow summary box.
http://preview.benmartinstudios.com.au/jquery-price-calculator-pro/all-inputs.html

A: UPDATE: solved it, try the fiddle below
Fixed Fiddle
// old code was
"f_4[]": "Activation fee",
// change to
"f_4": "Activation fee",

This works because this particular variable is a number only, not a list of things like a dropdown like the others.  Thats why the others required a [] after it, because that denotes an array, whereas activation fee is a single integer.


text:
Q: Wen i delete my document from Firestore the corresponding image still remain in Storage I am new in flutter, I am facing a problem which is how to delete Firestore photos.
I have created a Subcollection where I am storing my products details, this product also contains an image that is stored in Firebase Storage. If delete my product, like I have 10 products but I want to delete a specific product, when I am pressing the delete button it is deleting my products which is a document but it does not delete the corresponding image from Firebase Storage.
I have tried some way but it's not working, it's just deleting my Cloud Firestore document but the photo remains in Firebase Storage.
I am using the image URL to show the photo.  I want that when I click on my delete Button it also delete the corresponding image from Firebase Storage. so I am using this to delete my Cloud Firestore document.
TextButton(
  onPressed: () async {
    await FirebaseFirestore.instance
        .collection('users')
        .doc(LoginUser!.uid)
        .collection('products')
        .doc(document.id)
        .delete()
        .then((value) async {
      //await FirebaseStorage.instance.ref().child('productImage').child('productImageUrl').delete();

      print(
          'Product Deleted But image is still there in Storage Folder');
    });
  },
  child: Text('Delete')),

I am using This code to save my image Url in Cloud Firestore
final productImgRef = FirebaseStorage.instance
    .ref()
    .child('productImage')
    .child(FirebaseUser.uid +time +'.jpg');
await productImgRef.putFile(pickImageFile!);
var productImageUrl = await productImgRef.getDownloadURL();

await FirebaseFirestore.instance
    .collection('users')
    .doc(FirebaseUser.uid)
    .collection('products')
    .add({
  'productName': _productName,
  'productDes': _productDes,
  'bidPrice': _bidPrice,
  'auctionDate': _auctionDate,
  'submitBy': userName,
  'productImageUrl': productImageUrl,
});

A: Assuming that this commented out line is what you tried:
await FirebaseStorage.instance.ref().child('productImage').child('productImageUrl').delete();

The quotes around 'productImageUrl' are a mistake there. With this code it tries to delete the image named productImageUrl, which is not what your image is called.
That the very least it should be:
await FirebaseStorage.instance.ref().child('productImage').child(productImageUrl).delete();

By removing the quotes from around productImageUrl, the code will use the value of the variable.

But more likely the productImageUrl contains a download URL, in which case your first need to map that back to a Storage Reference by calling the refFromURL method:
var storageRef = FirebaseStorage.instance.refFromURL(productImageUrl);
await storageRef.delete();


text:
Q: Running command found in PATH? I'm trying to run a command via QProcess but it's not working. My command is something like utility -someflag /path/to/file. utility is in the PATH, however it seems QProcess is not using this environment variable.
The command simply fails and I need to specify the full path of the utility (which I'd like to avoid).
Is there any way around this? Basically some way to make QProcess use the PATH variable?

A: So the problem is that it depends on how the application is started. This is on OSX but it might be similar in other platforms:

*

*If it's a command line application and started from a terminal then it will have access to the env variables.

*If it's started from Qt Creator, it will not have access to any env variable.

*If it's a GUI application (.app), it will not have access to the env variables.
The solution in my case, since it is a GUI application, was to update the .app package manually. First the file Info.plist needs to be changed from this:
<key>CFBundleExecutable</key>
<string>MyApplication</string>

to this:
<key>CFBundleExecutable</key>
<string>MyApplication.sh</string>

Then, still in the app package, in Contents/MacOS, create a new file with the same name as the application, but with a .sh extension, eg. "MyApplication.sh". Then create the launcher:
#!/bin/sh
SCRIPT_DIR=$(dirname "$0")
source ~/.bash_profile
logger "$SCRIPT_DIR/MyApplication"
exec "$SCRIPT_DIR/MyApplication" $@

The source ~/.bash_profile line in particular ensures that all the environment (including PATH variable) will be set properly.


text:
Q: Laravel is too slow I just set this page in the routing file web.php:
Route::get("/speedtest","SpeedController@speed_test");

Here is the speed test function:
public function speed_test(){
    return view("speedtest");
}

That returns speedtest.blade.php which contains just a hello world.
It takes between 2.5 s and 3.5 to load this page.
Other pages that use a middleware and some queries needs between 3.5 and 6.5 seconds. The database is almost empty and the queries returns just 3 or 4 items (something like Files::where(user_id, Auth::user()->id)->get() ).
So everything is slow, even empty sites. There is definitely something wrong.
The site is alone in a server with 4 GB RAM, SSD and 1 Gbit connection
Any help?

A: Things to do to increase speed:
# Optimize the autoloading (very important!)
composer dumpautoload -o
# Cache the Laravel routes (very important on slower servers)
php artisan route:cache
php artisan api:cache
# Cache the core laravel configurations (including service providers, etc.)
php artisan config:cache
# Finally, tell Laravel to enable "production-ready optimizations."
#php artisan optimize # No longer needed/available in Laravel 5.6.

Run all that and report the time improvements!
You also, for best performance, make sure that Zend OPcache extension is installed and loaded (that's another question).
php -m
....
[Zend Modules]
Zend OPcache


text:
Q: How to plot a two-columned grid of time series with custom titles using R? I have the following code (although without data, sadly):
detrend_plot <- cbind(l_p_lng,l_vol_lng,l_p_oil,l_rgdpe, ldiff_p_lng,ldiff_vol_lng,ldiff_p_oil,ldiff_rgdpe)

plot.ts(detrend_plot, main="",)

which gives the following plot:

What I want to do is to add custom titles, individual y-axis labels, and x-axis labels. I know that this is possible using GGPLOT, although my knowledge of it is sparse. Has anyone encountered a similar problem? I don't think this is possible using the regular plot.ts( ) function.

A: I don't think you can pass multiple titles and labels to plot.ts directly, but you can just loop over your columns with vectors of labels for each:
set.seed(1)
z <- ts(matrix(rt(200 * 8, df = 3), 200, 8), start = c(1961, 1), frequency = 12)

## vectors of x, y, and main labels
xl <- sprintf('x label %s', 1:8)
yl <- sprintf('y label %s', 1:8)
ml <- sprintf('main label %s', 1:8)

par(mfrow = c(4, 2), mar = c(5, 5, 1, 1), oma = c(0, 0, 1, 2))
lapply(1:8, function(ii) {
  x <- z[, ii, drop = FALSE]
  plot(x, xlab = xl[ii], ylab = yl[ii], main = ml[ii])
})

You can also pass vectors of arguments (eg, for x- or y-axis limits) using lists:
ylim <- list(c(-10, 10))
ylim <- rep(ylim, 8)

par(mfrow = c(4, 2), mar = c(5, 5, 1, 1), oma = c(0, 0, 1, 2))
lapply(1:8, function(ii) {
  x <- z[, ii, drop = FALSE]
  plot(x, xlab = xl[ii], ylab = yl[ii], main = ml[ii], col = ii, ylim = ylim[[ii]])
})

To get a figure closer to the default plot.ts look, you can just set top and bottom margins to 0 and adjust the axes (which is what plot.ts is doing under the hood). This method is a bit more verbose than plot.ts but will allow for more customization:
par(mfrow = c(4, 2), mar = c(0, 5, 0, 1), oma = c(5, 0, 3, 2))
lapply(1:8, function(ii) {
  x <- z[, ii, drop = FALSE]
  plot(x, xlab = xl[ii], ylab = yl[ii], col = ii, axes = FALSE)
  axis(2, las = 1)
  box()
  if (ii %in% 7:8) {
    axis(1)
    title(xlab = 'Year', xpd = NA)
  }
  if (ii %in% 1:2)
    title(main = c('Group 1', 'Group 2')[ii], xpd = NA, line = 1)
})


text:
Q: Install libssl1.0.0 on ubuntu 10.04 offline quickly I need to install libssl1.0.0 on a ubuntu 10.04 machine offline.
After lots of search, I still cannot find any libssl1.0.0 packages built for ubuntu 10.04. Building it from source is not accepted, because it takes several minutes to complete the build and installation process while I only have few seconds to finish the job.
Please advise me how to quickly install libssl1.0.0 on ubuntu 10.04 offline.

A: Finally I use checkinstall to build debian package from last version of source. If checkinstall does not exist in the system, it can be installed by apt-get install checkinstall. The rest of steps are:
tar xf openssl-1.0.1e.tar.gz
cd openssl-1.0.1e
./config --prefix=/usr shared
make
checkinstall

Then openssl_1.0.1e-1_amd64.deb will be available under openssl-1.0.1e folder.


text:
Q: long-distance sound detection/recording solution? My general requirement is an audio input system which can effectively detect sound signal (80dB at about 5cm) over 30 meters away. The supply voltage should be within 5V so that the system can work with an embedded system such as a DSP microcontroller. I think the gain of the op-amp should be higher than 60 dB, AGC is preferred but not necessary.
Is there a solution or such an audio op-amp can meet my requirement?

A: If your sound is 80dB (I assume you mean at a level of 80dBSPL) at 5cm, it will be at a level of 25dBSPL at 30m.
You need to start with the sensitivity and noise level of microphones. Most document the sensitivity, some document their noise level. Unless the signal to noise ratio at the output of the microphone is good enough for detection, then no amount of 'good' op-ampery will make it better. A bad op-amp can make it worse however.
If the original sound signal has enough structure to allow DSP to do something useful, so if it's a narrowband tone, or a chirp, or something predictable, then you can reduce the effective noise bandwidth with DSP processing.
Your fundamental problem is the 25dBSPL level. This can be improved without additional noise by a directional microphone, either a parabolic or shotgun, or at some expense with a microphone array.


text:
Q: Brownian motion conditional probability If $B$ is the standard brownian motion and $a,b >0$ I want to show, using the reflection principle
$$\mathbb{P}\left(B_t\geq a-b | \inf_{s\leq t} B_s \geq -b\right) = \frac{\mathbb P(|B_t+x|\leq b)}{\mathbb P(|B_t|\leq b)}$$
and the reflection principle that I know is for $x>0$ and $y<x$:
$$\mathbb P\left(\sup_{s\leq t} B_s \geq x, B_t < y\right) = \mathbb P\left(B_t > 2x-y\right)$$
Now I wrote the conditional probability
$$\mathbb{P}\left(B_t\geq a-b | \inf_{s\leq t} B_s \geq -b\right) = \frac{\mathbb{P}(B_t\geq a-b , \inf_{s\leq t} B_s \geq -b)}{\mathbb{P}(\inf_{s\leq t} B_s \geq -b)}$$
and I rewrote the numerator, trying to get something like the reflection principle
$$\mathbb P(B_t\geq a-b , \inf_{s\leq t} B_s \geq -b)=\mathbb P\left(-\sup_{s\leq t} (-B_s) \geq -b, B_t \geq a-b\right)=\\ = \mathbb P\left(\sup_{s\leq t}(-B_s)\leq b, B_t \geq a-b\right)$$
but I don't know how to procede, it does not look like what I need...


text:
Q: Is it true that at least two of any consecutive $2m$ positive integers cannot be divided by odd prime numbers less than $2m$? Let $m>1$ and $p_2,\cdots,p_k$ are all odd prime numbers less than $2m$.
$q,a_2,\cdots,a_k$ are arbitrarily selected integers(I mean no matter how you choose these numbers).
$$G_1=\lbrace n\in \mathbb Z|q < n \leq q+2m \rbrace,$$
$$G_i=\lbrace n\in \mathbb Z|n\not\equiv a_i \mod {p_i}\rbrace,$$
for $i=2,3,\cdots,k$.
$$G=\bigcap_{i=1}^k{G_i}.$$

Is it always true that #$|G|\geq 2$?

Especially,is it true that at least two of any consecutive $2m$ positive integers cannot be divided by odd prime numbers less than $2m$?
In other words, if you write $2m$ consecutive positive integers and cross out the multiples of $3, 5,\cdots,p_k$, then at least two of these $2m$ numbers will not be crossed out.
(1) When $m=2,k=2,p_2=3,$ four consecutive integers $q+1,q+2,q+3,q+4$,no matter what is $a_2$,we know that $G$ has at least two elements.
(2) For every $m>1$, we can choose $q$ and $a_i$ so that #$|G|=2$,for example, if
$$q=\frac{R-1}{2}-m,R=\prod_{i=2}^k{p_i},$$
$$a_i=0,i=2,\cdots,k,$$
then $G=\lbrace \frac{R-1}{2},\frac{R+1}{2} \rbrace.$
(3) The case $m=3,k=2,p_2=3,p_3=5.$
#$|G_1 \setminus G_2|=6/3=2,$ #$|G_1 \setminus G_3|\leq [6/5]+1=2,$
hence #$|G|\geq 2.$
(4) When $m\geq 36$, as $$\sum_{2<p<2m}{[\frac{2m}{p}]}>2m-2$$ maybe hold, I don't know if there's a counterexample.

A: To end this question, someone find a counterexample for $m=70$, where
$$q\equiv -\lbrace 1,2,1,8,1,9,5,6,10,11,3,2,22,1,33,21,1,23,18,20,4,18,21,19,35,38,44,45,51,54,56,59,69 \rbrace  \\ \mod {\lbrace 3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139 \rbrace }.$$
This means that $q\equiv -1\pmod 3,q\equiv -2\pmod 5,\cdots,q\equiv -69\pmod {139}.$
A solution is $q=264782491305295395386123607229983302927523861123269753$ and every number in $q+1,\cdots,q+140$ can be divided by some odd prime number less that $140$.

A: OP asks about every possible choice of $q$. Counterexamples are to be found for low values of $q$, such as sequences $2,3,\dots,2m+1$ and $3,4,\dots,2m+2$, where every member of the sequence must be composed entirely of prime factors $<2m$, and where no two consecutive numbers can each be a power of $2$, i.e. numbers entirely lacking odd prime factors.
In general, if an odd member of a suitable pair of consecutive integers has no (necessarily odd) prime factors smaller than $2m$, then that odd number must either be a prime number larger than $2m$ or a composite number larger than $4m^2$. This suggests that there will be some minimum value of $q$ (a function of $m$) below which OP's conjecture cannot hold.


text:
Q: Slowness in Vim's bracket-matching with the default PHP syntax I am experiencing a noticeable slowness in Vim's bracket-matching and -highlighting feature. When the cursor is placed over a parenthesis or bracket, there is a delay of about 300ms on the console's responsiveness. As stated, this only seems to occur when working with PHP files. I am running Vim 7.2 on Debian Squeeze with a .vimrc file:
  1 set autoindent
  2 set smarttab
  3 set ruler
  4 set expandtab
  5 set termencoding=utf-8
  6 set fileformat=unix
  7 set number
  8 set tabstop=4
  9 set encoding=utf-8
 10 set shiftwidth=4
 11 set noswapfile
 12 set backspace=indent,eol,start
 13 set shortmess=lrwxI
 14 set history=50
 15 set background=dark
 16
 17 let php_folding=2
 18 let php_asp_tags=0
 19
 20 colorscheme desert

Is there any way to alleviate this slowdown?

A: Type this to turn it off per-instance:
:NoMatchParen

(capitalization is important)
Add this to your ~/.vimrc to disable it before the module loads:
let loaded_matchparen = 1

You only need one.  With the first, you have to type it every time you open a PHP file, but you can turn it on again at any time.  With the second, it's always off, but you can't simply turn it on again.

A: I don't see this locally; the matching parens is instantly highlighted.  Try this:
:set filetype=txt

...and see if things improve.  If so, something in vim's PHP handling configuration may be a bit out of whack.  Do you see the same behaviour on very small PHP files?  I'm on 7.2 on ubuntu and not seeing what you're seeing.
Hope this helps!
-Paul
UPDATE:  thanks for updating your question to include your .vimrc - this leads to another thing for you to test.  Please see if this doesn't help the situation - change php_folding to 1 rather than 2.  2 folds all { } regions so this may be somehow interacting with the parens-matching logic and causing the delay.


text:
Q: How to delete and disable logs for an Amazon RDS SQL Server instance? I have a minuscule Amazon RDS instance running SQL Server and its storage almost reached the maximum allowed free tier storage of 20GB.
I have read that this might be due to the db logs. I am only using the db to get acquainted to RDS so I don't think I need any logs at the moment.
But I cannot find a way to remove the logs, nor to disable them so that the size will not increase back.
There is a way to view them or download them, but not to remove or disable.
For other types of db engines, like MySQL, AWS does provide a way to remove them, by calling the rotation procedure twice in a row. Is there a similar way for SQL Server engines?


text:
Q: cxf runtime exception unknown client side exception I am using a simple mule flow which takes a spring bean as a component and executes it periodically using quartz endpoint. My cxf client and configuration all look fine to me but for some reason i get an exception when trying to send request.
my class is as follows:
@Component
@DependsOn("restfulClient")
public class Transmitter implements Callable{

    private static final Logger logger =
    LoggerFactory.getLogger(Transmitter.class);

    @Autowired
    private RestfulClient restfulClient;

    public Object onCall(MuleEventContext eventContext) throws Exception {
        logger.info("In Transmitter");
        try {
            String result = restfulClient.ping();
            logger.info("Result: {}" , result);

        } catch (Exception e){
            logger.error("Exception in Transmitter" ,e);
        }
        return null;
    }
}

my client:
@Produces({"text/plain"})
@Path("/subscription")
public interface RestfulClient {

    @GET
    @Path("/ping")
    public String ping();
}

in applicationContext.xml i have defined the cxf bean and enabled cxf logging:
<jaxrs:client id="restfulClient"
                serviceClass="com.ws.RestfulClient"
                address="${prop.restful.url}">
    <jaxrs:features>
        <cxf:logging/>
    </jaxrs:features>
</jaxrs:client>

and the url is defined in application.properties file and when in debugging mode it constructs the url successfully.
When i try the url on postman it works fine and i get OK as result but it is not working in the code.
the exception i get is:
java.lang.RuntimeException: Unknown client side exception
at org.apache.cxf.jaxrs.client.AbstractClient.setResponseBuilder(AbstractClient.java:331)
at org.apache.cxf.jaxrs.client.ClientProxyImpl.handleResponse(ClientProxyImpl.java:451)
at org.apache.cxf.jaxrs.client.ClientProxyImpl.doChainedInvocation(ClientProxyImpl.java:445)
at org.apache.cxf.jaxrs.client.ClientProxyImpl.invoke(ClientProxyImpl.java:177)
at com.sun.proxy.$Proxy27.ping(Unknown Source)
at com.processor.Transmitter.onCall(Transmitter.java:77)
at org.mule.model.resolvers.CallableEntryPointResolver.invoke(CallableEntryPointResolver.java:46)
at org.mule.model.resolvers.DefaultEntryPointResolverSet.invoke(DefaultEntryPointResolverSet.java:36)
at org.mule.component.DefaultComponentLifecycleAdapter.invoke(DefaultComponentLifecycleAdapter.java:339)
at org.mule.component.AbstractJavaComponent.invokeComponentInstance(AbstractJavaComponent.java:82)
at org.mule.component.AbstractJavaComponent.doInvoke(AbstractJavaComponent.java:73)
at org.mule.component.AbstractComponent.invokeInternal(AbstractComponent.java:122)
at org.mule.component.AbstractComponent.access$000(AbstractComponent.java:57)
at org.mule.component.AbstractComponent$1$1.process(AbstractComponent.java:238)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:58)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
at org.mule.processor.chain.DefaultMessageProcessorChain.doProcess(DefaultMessageProcessorChain.java:94)
at org.mule.processor.chain.AbstractMessageProcessorChain.process(AbstractMessageProcessorChain.java:67)
at org.mule.processor.chain.InterceptingChainLifecycleWrapper.doProcess(InterceptingChainLifecycleWrapper.java:50)
at org.mule.processor.chain.AbstractMessageProcessorChain.process(AbstractMessageProcessorChain.java:67)
at org.mule.processor.chain.InterceptingChainLifecycleWrapper.access$001(InterceptingChainLifecycleWrapper.java:22)
at org.mule.processor.chain.InterceptingChainLifecycleWrapper$1.process(InterceptingChainLifecycleWrapper.java:66)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:58)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
at org.mule.processor.chain.InterceptingChainLifecycleWrapper.process(InterceptingChainLifecycleWrapper.java:61)
at org.mule.component.AbstractComponent.process(AbstractComponent.java:156)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:58)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
at org.mule.processor.chain.DefaultMessageProcessorChain.doProcess(DefaultMessageProcessorChain.java:94)
at org.mule.processor.chain.AbstractMessageProcessorChain.process(AbstractMessageProcessorChain.java:67)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
at org.mule.processor.AbstractInterceptingMessageProcessorBase.processNext(AbstractInterceptingMessageProcessorBase.java:102)
at org.mule.interceptor.AbstractEnvelopeInterceptor.process(AbstractEnvelopeInterceptor.java:51)
at org.mule.processor.AsyncInterceptingMessageProcessor.processNextTimed(AsyncInterceptingMessageProcessor.java:118)
at org.mule.processor.AsyncInterceptingMessageProcessor$AsyncMessageProcessorWorker$1.process(AsyncInterceptingMessageProcessor.java:189)
at org.mule.processor.AsyncInterceptingMessageProcessor$AsyncMessageProcessorWorker$1.process(AsyncInterceptingMessageProcessor.java:182)
at org.mule.execution.ExecuteCallbackInterceptor.execute(ExecuteCallbackInterceptor.java:16)
at org.mule.execution.HandleExceptionInterceptor.execute(HandleExceptionInterceptor.java:30)
at org.mule.execution.HandleExceptionInterceptor.execute(HandleExceptionInterceptor.java:14)
at org.mule.execution.BeginAndResolveTransactionInterceptor.execute(BeginAndResolveTransactionInterceptor.java:54)
at org.mule.execution.ResolvePreviousTransactionInterceptor.execute(ResolvePreviousTransactionInterceptor.java:44)
at org.mule.execution.SuspendXaTransactionInterceptor.execute(SuspendXaTransactionInterceptor.java:50)
at org.mule.execution.ValidateTransactionalStateInterceptor.execute(ValidateTransactionalStateInterceptor.java:40)
at org.mule.execution.IsolateCurrentTransactionInterceptor.execute(IsolateCurrentTransactionInterceptor.java:41)
at org.mule.execution.ExternalTransactionInterceptor.execute(ExternalTransactionInterceptor.java:48)
at org.mule.execution.RethrowExceptionInterceptor.execute(RethrowExceptionInterceptor.java:28)
at org.mule.execution.RethrowExceptionInterceptor.execute(RethrowExceptionInterceptor.java:13)
at org.mule.execution.TransactionalErrorHandlingExecutionTemplate.execute(TransactionalErrorHandlingExecutionTemplate.java:109)
at org.mule.execution.TransactionalErrorHandlingExecutionTemplate.execute(TransactionalErrorHandlingExecutionTemplate.java:30)
at org.mule.processor.AsyncInterceptingMessageProcessor$AsyncMessageProcessorWorker.doRun(AsyncInterceptingMessageProcessor.java:181)
at org.mule.work.AbstractMuleEventWork.run(AbstractMuleEventWork.java:39)
at org.mule.work.WorkerContext.run(WorkerContext.java:286)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

A: I found the problem. The problem is in
<jaxrs:features>
    <cxf:logging/>
</jaxrs:features>

which belonged for malformed schema...  (honestly am wondering why wouldn't mule give a name to such an error instead of vague unknown client side exception!)
<mule xmlns:cxf="http://www.mulesoft.org/schema/mule/cxf
<!-- -->
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://www.mulesoft.org/schema/mule/cxf
http://www.mulesoft.org/schema/mule/cxf/current/mule-cxf.xsd" >

the last link gives not found..


text:
Q: Replace Tokens Task Ambiguity Issue in Azure YAML pipeline I'm having some namespace conflict issues with a particular task in the YAML pipeline for Azure.  Here's the code for the "replace tokens" task I'm having issues with:
      - task: replacetokens@4
        displayName: Replace tokens in localSettings.xml
        inputs:
          rootDirectory: '$(System.DefaultWorkingDirectory)\path_to_tests'
          targetFiles: 'localSettings.xml'
          encoding: 'auto'
          tokenPattern: 'default'
          writeBOM: true
          actionOnMissing: 'warn'
          keepToken: false
          actionOnNoFiles: 'continue'
          enableTransforms: false
          useLegacyPattern: false
          enableTelemetry: true

It works fine at compile time.  No issues.  However, I get this runtime error when I try to run the pipeline:
Job DEV_Tests: Step task reference is invalid. The task name replacetokens is ambiguous. Specify one of the following identifiers to resolve the ambiguity: qetza.replacetokens.replacetokens-task.replacetokens, colinsalmcorner.colinsalmcorner-buildtasks.replace-tokens-task.ReplaceTokens

It seems to me that there's multiple versions of "replacetokens@4" which is why I get this ambiguous error.  However, when I try to use either the "qetza" or "colinsalmcorner" namespaces as advised in the error, I get another compile time error suggestion that those namespaces don't exist:
String does not match the pattern of "^UseRubyVersion@0$".

Value is not accepted. Valid values: "UseRubyVersion@0", "deployApi@3", "deployApi@4", "deployApi@5", "ReviewApp@0", "AzureAPIImport@1", "AzureAPIImport@3", "AzureAPIImport@4", "AzureAPIImport@5", "AzureAPIImport@6", "AzureAPIUrlImport@0", "AzureAPIImport@2", "AppCenterDistribute@2", "AppCenterDistribute@3", "AppCenterDistribute@1", "AppCenterDistribute@0", "CopyFiles@2", "C

Any ideas why those namespaces aren't recognized in the pipeline and yet "replacetokens@4" is recognized with a namespace conflict?

A: I checked this and what I get when I use full namespace is just a warning like this:

This is probably schema used for validation doesn't allow to use full names, however this is just a warning.
When I validate pipeline I got OK.


text:
Q: How to create rating system using only css How to create rating system using only css. I don't want to use javascript/jquery or anything else. I don't want to use image/image sprites also. I need it only in hover(mouse over) not in click and in pure css.
here is the sample image I want.

A: html code...

☆

☆

☆

css code...
  .rate{
        color:black;
        cursor:pointer;
    }
    .rate:hover{
        color:red;
    }
    .rate-item{
        float:left;
        cursor:pointer;
        margin:0px 15px 0px 15px;
    }
    .rate-item:hover ~ .rate-item {
        color: black;
    }

You can follow this example
http://jsfiddle.net/tanvir0604/JqKjL/1/
You can use fontawsome for better performance or just change the background image property besides the color property of my code.

A: HTML

    <input class="rb0" id="Ans_1" name="numericRating" type="radio" value="0" checked="checked" />
    <input class="rb1" id="Ans_2" name="numericRating" type="radio" value="1" />
    <input class="rb2" id="Ans_3" name="numericRating" type="radio" value="2" />
    <input class="rb3" id="Ans_4" name="numericRating" type="radio" value="3" />
    <input class="rb4" id="Ans_5" name="numericRating" type="radio" value="4" />
    <input class="rb5" id="Ans_6" name="numericRating" type="radio" value="5" />
    <input class="rb6" id="Ans_7" name="numericRating" type="radio" value="6" />
    <input class="rb7" id="Ans_8" name="numericRating" type="radio" value="7" />
    <input class="rb8" id="Ans_9" name="numericRating" type="radio" value="8" />
    <input class="rb9" id="Ans_10" name="numericRating" type="radio" value="9" />
    <input class="rb10" id="Ans_11" name="numericRating" type="radio" value="10" />

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

CSS
article {
    padding-left: 50px; /* arbitrary, to expose the "zero stars" area half a star to the left of the first star.*/
}

.star-rating {
    margin: 0 auto;
    display:inline-block;
}
/* radio button stars */

/* you can easily stuff the generation of these repetitive chunks of CSS into a server-side language like ASP */
.rb0:checked ~ .rating,
label.rb0l:hover ~ .rating
{
    width: 0px; /* no stars */
}

.rb1:checked ~ .rating,
label.rb1l:hover ~ .rating
{
    width: 16px; /* half a star */
}

.rb2:checked ~ .rating,
label.rb2l:hover ~ .rating
{
    width: 32px; /* a star */
}

.rb3:checked ~ .rating,
label.rb3l:hover ~ .rating
{
    width: 48px; /* 1.5 stars */
}

.rb4:checked ~ .rating,
label.rb4l:hover ~ .rating
{
    width: 64px; /* 2 stars */
}
.rb5:checked ~ .rating,
label.rb5l:hover ~ .rating
{
    width: 80px;
}
.rb6:checked ~ .rating,
label.rb6l:hover ~ .rating
{
    width: 96px;
}
.rb7:checked ~ .rating,
label.rb7l:hover ~ .rating
{
    width: 112px;
}
.rb8:checked ~ .rating,
label.rb8l:hover ~ .rating
{
    width: 128px;
}
.rb9:checked ~ .rating,
label.rb9l:hover ~ .rating
{
    width: 144px;
}
.rb10:checked ~ .rating,
label.rb10l:hover ~ .rating
{
    width: 160px; /* 5 stars */
}

.star-rating label.star {
    width: 16px; /* half star */
    left: -16px; /* half star */
    padding: 0;
    height: 40px; /* whole star + 2x padding (4px each for top and bottom) */
    position: relative;
    z-index: 3;
    float: left;
}

.star-rating label.star.last {
    width: 32px;
}

/* hide inputs (RBs and their labels) */
.star-rating input[type=radio],
.star-rating label.rb
{
    display: none;
}

/* using icons found at http://www.easyicon.cn/language.en/icondetail/523835/ */
.rating {
    background: url(http://cdn-img.easyicon.cn/png/5238/523834.gif) repeat-x top left;
    position: relative;
    z-index: 2;
    top: 4px; /* 1x padding */
    height: 32px; /* whole star */
    width:0px;
}

.rating-bg {
    background: url(http://cdn-img.easyicon.cn/png/5238/523835.gif) repeat-x top left;
    position: relative;
    z-index: 1;
    top: -28px; /* 1 whole star - 1x padding */
    height: 32px; /* whole star */
    width: 160px;
}

/* IE8 fallback to radio buttons */
.ie8 .star-rating input,
.ie8 .star-rating label.rb
 {
    display: inline-block;
}

.ie8 .rating,
.ie8 .rating-bg,
.ie8 .star-rating label.star {
    display: none;
}

DEMO


text:
Q: Contact form sends email but no email arrives I created this contact form below and everything is great up to the point where I send the message. I get the " Thank you for contacting us etc" showing the message was sent successfully but it never arrives to my email.
I'm building this form/site for a client and tested it out in my Hotmail account. I read in another post that Hotmail may be rejecting it so I changed it to send to my work email but still not getting the email. ( work email is through Blue Host ). Could there be another reason the message is not arriving? Anything wrong with my form?
Thanks for your help.
Here's my form:
<form method="post" action="emailform.php">

<fieldset>

Your Name:
<input type="text" id="name"
 class="large" required="required"
 placeholder="Enter your name"/>

Your Email:
 <input type="email"  placeholder="Enter your email"/>

    Enter Your Message Below <textarea name="label"    maxlength="800" rows="6"
cols="23"></textarea>

<input type="submit" value="Submit"/>
</fieldset>
</form>

And I'm using this script to send, I have it renamed as emailform.php on my server
http://www.bruceontheloose.com/htmlcss/examples/chapter-16/emailform.txt
PHP handler
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Emailing Form Data</title>

<?php
/* --------------------------------------------------
IMPORTANT NOTE:

The sample PHP code in this file is simple by design, but as a result, it doesn't include the security checks that a bulletproof script would include. Use caution before including it on your own site. If you do intend to use a script like this, I recommend consulting PHP books and other resources to learn how to check submitted form values for malicious data before you write the values to the screen or to a database.
---------------------------------------------------- */

/* This is a very simple PHP script that outputs the name of each bit of information (that corresponds to the name attribute for that form field) along with the value that was sent with it right in the browser window, and then sends it all to an email address (once you've added it to the script; see the comments near the end regarding yourmail@yourdomain.com).
*/

if (empty($_POST)) {
    print "
No data was submitted.
";
    print "";
    exit();
}

/* Creates function that removes magic escaping, if it's been applied, from values and then removes extra newlines and returns to foil spammers. Thanks Larry Ullman! */
function clear_user_input($value) {
    if (get_magic_quotes_gpc()) $value=stripslashes($value);
    $value= str_replace( "\n", '', trim($value));
    $value= str_replace( "\r", '', $value);
    return $value;
}

/* Create body of email message by cleaning each field and then appending each name and value to it. */

$body ="Here is the data that was submitted:\n";

// Get value for each form field
foreach ($_POST as $key => $value) {
    $key = clear_user_input($key);
    $value = clear_user_input($value);

    if ($key == 'email_signup') { // True if an Email checkbox chosen
        if (is_array($_POST['email_signup'])) {
            $body .= "$key: ";
            $counter =1;

            foreach ($_POST['email_signup'] as $value) {
                //Add comma and space until last element
                if (sizeof($_POST['email_signup']) == $counter) {
                    $body .= "$value\n";
                    break;
                } else {
                    $body .= "$value, ";
                    $counter += 1;
                }
            } // end foreach
        } else {
            $body .= "$key: $value\n";
        }
    } else { // field is not email_signup
        $body .= "$key: $value\n";
    }
} // end foreach

extract($_POST);

/* Get file upload picture name */
if(isset($_FILES['picture'])) {
    /*
        This basic script presents the name of the uploaded file only. To check the file size, file type (like JPG, GIF, or PNG), and actually upload a file to a folder, see the video tutorial at http://net.tutsplus.com/articles/news/diving-into-php/. The code explained in the video is also available for download from that URL. That page also includes links to a series of videos about using PHP.
    */

    $picture_name = $_FILES['picture']['name'];

    // make sure name isn't blank
    if ($picture_name != '') {
        // add the picture name to the email body message
        $body .= "picture: $picture_name\n";
    }
}

/* Removes newlines and returns from $email and $name so they can't smuggle extra email addresses for spammers */
$email = clear_user_input($email);
$first_name = clear_user_input($first_name);

/* Create header that puts email in From box along with name in parentheses and sends Bcc to alternate address. Change yourmail@yourdomain.com to the Bcc email address you want to include. */
$from='From: '. $email . "(" . $first_name . ")" . "\r\n" . 'Bcc: yourmail@yourdomain.com' . "\r\n";

// Creates intelligible subject line that also shows me where it came from
$subject = 'New Profile from Web Site';

/* Sends mail to the address below with the form data submitted above. Replace yourmail@yourdomain.com with the email address to which you want the data sent. */
mail ('yourmail@yourdomain.com', $subject, $body, $from);
?>

Thanks for signing up!

A: HTML :
<form method="post" action="emailform.php">
    <fieldset>

        Your Name:
        <input type="text" name="name" id="name"class="large" required="required" placeholder="Enter your name"/>

        Your Email:
        <input type="email" name="email"  placeholder="Enter your email"/>

Enter Your Message Below
            <textarea name="message" maxlength="800" rows="6"
        cols="23"></textarea>

        <input type="submit" value="Submit"/>
    </fieldset>
</form>

In emailform.php file :
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Emailing Form Data</title>

<?php
/* --------------------------------------------------
IMPORTANT NOTE:

The sample PHP code in this file is simple by design, but as a result, it doesn't include the security checks that a bulletproof script would include. Use caution before including it on your own site. If you do intend to use a script like this, I recommend consulting PHP books and other resources to learn how to check submitted form values for malicious data before you write the values to the screen or to a database.
---------------------------------------------------- */

/* This is a very simple PHP script that outputs the name of each bit of information (that corresponds to the name attribute for that form field) along with the value that was sent with it right in the browser window, and then sends it all to an email address (once you've added it to the script; see the comments near the end regarding yourmail@yourdomain.com).
*/

if (empty($_POST)) {
    print "
No data was submitted.
";
    print "";
    exit();
}

/* Creates function that removes magic escaping, if it's been applied, from values and then removes extra newlines and returns to foil spammers. Thanks Larry Ullman! */
function clear_user_input($value) {
    if (get_magic_quotes_gpc()) $value=stripslashes($value);
    $value= str_replace( "\n", '', trim($value));
    $value= str_replace( "\r", '', $value);
    return $value;
}

/* Create body of email message by cleaning each field and then appending each name and value to it. */

$body ="Here is the data that was submitted:\n";
//Fetching the form fields here
$email = $_REQUEST['email'];
$name = $_REQUEST['name'];
$message = $_REQUEST['message'];

/* Removes newlines and returns from $email and $name so they can't smuggle extra email addresses for spammers */
$email   = clear_user_input($email);
$name    = clear_user_input($name);
$body   .= clear_user_input($message);//Appending the message to the body of the email

/* Create header that puts email in From box along with name in parentheses and sends Bcc to alternate address. Change yourmail@yourdomain.com to the Bcc email address you want to include. */
$from='From: '. $email . "(" . $name . ")" . "\r\n" . 'Bcc: yourmail@yourdomain.com' . "\r\n";

// Creates intelligible subject line that also shows me where it came from
$subject = 'New Profile from Web Site';

/* Sends mail to the address below with the form data submitted above. Replace yourmail@yourdomain.com with the email address to which you want the data sent. */
mail ('yourmail@yourdomain.com', $subject, $body, $from);
?>

Thanks for signing up!

This should do it for you.


text:
Q: How does the Rune Skill work in Diablo 3 I've watched so many different videos and seen a lot of different facts about the Rune system in Diablo 3. It all keeps changing. I'm not really sure which is the correct answer. I'm hoping someone can clarify how this system works and what these runes do.

A: As of a recent beta patch, runes are no longer items that are dropped.  Instead they are basically skill modifiers that are unlocked as you level up.  Each time you level up, you will unlock new skills and/or rune choices that affect your existing skills.  You choose a certain number of skills, and a corresponding rune for each, to equip as your skill set.  Each skill can have up to 6 different rune versions of it, but you must select which one you want to have equipped at any time.  There are no longer different levels of rune abilities, it is simply a matter of having it unlocked or not.

A: The rune system allows active skills to change in behavior.  In some cases, the rune entirely replaces the original skill.  For example, the Demon Hunter's Companion skill provides a different companion with each rune.  Note however that the passive results of a long running Companion cast are always better with a rune than with no rune.  The no rune version does have a distinctive active effect when first cast that may be better for a particular situation than a runed version.
In other cases, the rune adds to the original effect.  For example, the Demon Hunter's Hungering Arrow skill has a Puncturing Arrow rune which purely increases the Pierce of the arrow.  Puncturing Arrow is strictly better than Hungering Arrow with no rune at all.
You can only select one rune per skill.  Runes may decrease some aspects to increase others.  For example, the Demon Hunter's Chakram skill has a Twin Chakrams rune which increases the number of attacks while decreasing the damage per attack.  It also demonstrates that runes can change the type of damage.  In the case of Twin Chakrams, the damage is changed from Physical to Fire.
Changing runes disengages existing casts.  For example, the Demon Hunter's Sentry skill runs for a long time (long enough to cast it multiple times).  Changing the rune will cause existing sentries to disappear.
You cannot change runes while a skill is on cooldown.
I think of runes as just part of the skill system rather than a system of their own.  They increase skill variety without having to select from entirely novel skills.


text: Q: Shiny introduces strange character during download I have tried to create Shiny application, which supposed to produce ANOVA post-hoc table with mean values followed by standard deviations and separated by plus-minus sign (±). Everything works nice in RStudio environment and when aplication is reproduced in local web-server (both, render and download). Even when I try to run application on Shiny server it renders correct table to HTML, but when I try to download table as .csv downloadHandler introduces a strange character (Â) in front of plus-minus sign. How can I override this strange sign introduction? I have tried to enforce "UTF-8" encoding in many different places in code, but with no success. Moreover, I have tries everything what is specified in Unicode characters in Shiny apps, but again with no success. The complete code is included within the application (showcase). Sample table for running application could be found here, and downloaded table with introduced Â's could be found here (special character  is not visible at GitHub view for some reason, but when you download it it becames visible).


text:
Q: xmlNewCDataBlock implicit conversion to int I'm parsing xml via libxml2 library. After updating Xcode to 5.1, I got warning that last parameter - length - is implicitly converted to int, while it's unsigned long.
Here's function declaration:
XMLPUBFUN xmlNodePtr XMLCALL
    xmlNewCDataBlock(xmlDocPtr doc,
                     const xmlChar *content,
                     int len);

Is there any similar function that takes unsigned long values, because I don't know how big my data can be, and I want to process it safely.

A: There's no such function. libxml2's string manipulation functions use ints for string lengths and offsets, so text nodes longer than INT_MAX are not supported.


text:
Q: How to configure Quarkus extension attribute? I would like to change attribute allow-non-standard-wrappers value in Quarkus undertow extension configuration.
In Wildfly, it's done in standalone.xml undertow subsystem. How do we do such configuration change in Quarkus ?
Thanks,

A: Quarkus makes a lot of choices about how things (like undertow) should work in order to optimize for build-time compilation and define things that will work well native mode.
Undertow is used for servlets, but how servlets work in quarkus is constrained. Resteasy is used for REST, and Vert.x is also used for other http traffic.
Configuration elements for http generally (where servlets are just one piece) are here: https://quarkus.io/guides/http-reference


text:
Q: Should DialogFragments have their own ViewModel or should they use the ViewModel of their containing Fragment? I am new to android and i am not sure if it is a good practice to let DialogFragments use the ViewModel of their containing Fragment, or should it have a ViewModel of its own.
I am asking this since Google recommends that each Activity/Fragment has its own ViewModel.

A: I don't see a problem with the dialog having it's own ViewModel.  This would fall into the Single Responsibility Principle, where the Fragment only handles what's relevant to it and ditto for the DialogFragment. Try and keep them uncoupled.
https://en.wikipedia.org/wiki/Single_responsibility_principle


text:
Q: How can I test/mock external code or external dependencies using moq? I'm using Moq for mocking of my code in unit testing. It's ok to mock the code without external dependencies. Below code is my last dependencies which I mocked
/// <summary>
/// Executes the request.
/// </summary>
/// <param name="booking">The booking.</param>
protected override void ExecuteRequest(BookingModel.Booking booking)
{
    var request = this.CreateRequest(this.TravelContext, booking);
    using (var proxy = this.TravelContext.CreateProxy<IMonitorBookingServiceProxy>())
    {
        var response = proxy.AutoCancelBooking(request);
        this.AddResponseInfos(response.ResponseInfos);
    }
}

I mock the above code like this
// mock the IMonitorBookingServiceProxy
Mock<IMonitorBookingServiceProxy> mockedMonitorBookingContext = new Mock<IMonitorBookingServiceProxy>() { DefaultValue = DefaultValue.Mock };
mockedMonitorBookingContext.Setup(x => x.AutoCancelBooking(It.IsAny<AutoCancelBookingRequest>())).Returns(autoCancelBookingResponse).Verifiable();
ProxyFactory.Configure<IMonitorBookingServiceProxy>(mockedMonitorBookingContext.Object);

it's return the response to me correctly.
but my problem is that there's a lot of scenarios and classes to be test inside proxy.AutoCancelBooking(request); function.
How How i can test or mocked that that classes and dependencies .

A: You say that are a lot of scenarios to be tested inside the IMonitorBookingServiceProxy.AutoCancelBooking request function. Do you want to test the functionality within IMonitorBookingServiceProxy.AutoCancelBooking or do you want to test the functionality of ExecuteRequest depending on different responses returned by IMonitorBookingServiceProxy.AutoCancelBooking?

A: Purpose of mocking is to removing the dependencies to test your code, So, in my code
/// <summary>
/// Executes the request.
/// </summary>
/// <param name="booking">The booking.</param>
protected override void ExecuteRequest(BookingModel.Booking booking)
{
    var request = this.CreateRequest(this.TravelContext, booking);
    using (var proxy = this.TravelContext.CreateProxy<IMonitorBookingServiceProxy>())
    {
        var response = proxy.AutoCancelBooking(request);
        this.AddResponseInfos(response.ResponseInfos);
    }
}

when I'm calling proxy.AutoCancelBooking(request); it calls the Web API which is dependencies which can't be mocked, Tht's why we will generate mocked response and return it from above function. I'm already doing it right.


text:
Q: How to change all the strings in an iphone application with respective selected language in settings? I need help from you, I need to display all the text, labels , strings and what ever text is showing to user in the iphone application with respective selected language in settings of iphone.
for example user selects German or French in settings of iPhone language, then my application should provide or view the details in that language.
I need sample code for localization, Is there any simple way to follow the standard steps to translate the code to different languages in iphone sdk.
please healp me, I hope that I can get efficient solution on this from you.
Thank you,
Madan Mohan.

A: See here: http://www.icanlocalize.com/site/tutorials/iphone-applications-localization-guide/

A: I think the previous link gives a pretty good idea of how to do I18N on the iPhone, but if you feel you need more info, you can try this article http://blog.federicomestrone.com/2010/05/18/internationalise-your-iphone-apps-with-xcode/ which is just slightly more code-orientated.
The point though is always the same - you have to separate code from text resources and load all your text (strings) with the NSLocalizedString macro, or a variant thereof.


text:
Q: STM32F407VG-Discovery USB Limits I'm currently in the middle of my 3rd year university project and am trying to convert the STM Discovery board into a data-logger.
I've already found this site, which demo's how to make a GPS data-logger and should be a good springboard for me.
My question is twofold:
1) Is the STM's USB port capable of 15Megabits per second (15Mbps) data transfer?
2) I've read that there is a physical limit to the size of the USB stick that the STM can read, but have not found any reliable source for this. Does this limit exist, and if so, what is it?
To clarify, the data being transferred are raw AC voltages from numerous sensors, along with the type of sensor, time of reading, and a counter value. 7 sensors are audio and sampled at 100kHz (max frequency of interest is 40kHz), 144 sensors are sampled at 3125Hz, and a further 100 sensors are sampled at 391Hz. All 16 ADC pins are in use, along with SPI2.
Thanks in advance.
Edit: Here is the full calculated aggregate of the data being transferred:
(12bits * 100kHz * 7sensors) + (12bits * 3125Hz * 144sensors) + (12bits * 390.625Hz * 32sensors) + (16bits * 390.625Hz * 63sensors) = 14343750bits per second ~= 15Mbps

A:
1) Is the STM's USB port capable of 15Megabits per second (15Mbps) data transfer?

No.
The USB OTG socket is USB Full Speed, which means a maximum of 12Megabits/second.
The other USB socket is connected to the hardware debugger, which is an STM32F103, which is only capable of USB Full Speed, 12Megabits/second, and goes via a much slower SWD interface.
EDIT:
Just to clarify how I concluded that DISCOVERY board only has USB Full-Speed on the socket:
The High-Speed-capable USB OTG port only has on-chip USB Full-Speed transcievers. To operate at High-Speed, it needs an external High-Speed PHY.
The STM32F407 datasheet says:

2.2.31 Universal serial bus on-the-go high-speed (OTG_HS)
  The STM32F405xx and STM32F407xx devices embed a USB OTG high-speed (up to
  480 Mb/s) device/host/OTG peripheral. The USB OTG HS supports both full-speed and
  high-speed operations. It integrates the transceivers for full-speed operation (12 MB/s) and features a UTMI low-pin interface (ULPI) for high-speed operation (480 MB/s). When using the USB OTG HS in HS mode, an external PHY device connected to the ULPI is required.

I looked at the STM32F4DISCOVERY datasheet for that discovery board. It has schematics for the board (section 6). Only the USB Full-Speed pins are connected to a USB socket, and there is no external High-Speed PHY. Hence it must be Full-Speed only.
However, it appears the High-Speed ULPI pins are available, so it is possible that you might be able to connect an external PHY etc. and get that to work. It might be worth digging around the st.com web site to see if they have an application note for that. However, I wouldn't automatically expect it to be easy. I don't know if the driver software is available, so unless you are very experienced and some test equipment to debug it, I'd recommend you check for driver software first.
END EDIT.
Further, USB FUll Speed's 12Mbps is a theoretical maximum which aggregates both data and control bandwidth. AFAIK, I'd be happy with 50% of that. IIRC, the software in the development kit wouldn't give 50% for 'normal' (non-lossy) transfers.

2) I've read that there is a physical limit to the size of the USB stick that the STM can read, but have not found any reliable source for this. Does this limit exist, and if so, what is it?

I am assuming you are using the USB OTG socket. I haven't experimented with this.
EDIT 2:
I don't know of any actual physical limit, but I find it easy to believe there are practical limits imposed by the USB Host 'Mass Storage class' software in the STM32 Discovery board libraries (or 3rd party libraries). They may be the limits that you have read about.
For example, if the USB stick is formatted with FAT32, then the maximum file size for one file on a FAT32 file system was 4 GiB minus 1 byte, (\$2^{32} − 1\$), or 4,294,967,295 bytes. That might be a limit you've read about, and might be a problem for your logger as your data rate is almost 2MB/second. So it could log for less than 40 minutes into one file.
(That could be fixed by using a sequence of files to log the data stream, eg write the first, say, \$2^{30}\$ bytes to eg. file 'log00001.dat', then close it and write the next \$2^{30}\$ bytes to file 'log00002.dat', etc)


text:
Q: How to do multiple assignment of vectors in MATLAB? Please I want a help from you .
I have 3 vectors with values x=[2,4] y=[5,6] z=[2,1]
I want to say that [u,v,c]=[x,y,z]
and I want to use (obligatory) this formula :
[u,v,c]=???
I can say for example : a=[x,y,z]
but this is not allowed for our assignment .
I tried many time but Matlab said (too many arguments).
please help me.

A: Use deal, which matches up input and output lists:
>> [u,v,c] = deal(x,y,z)

u =
     2     4
v =
     5     6
c =
     2     1


text:
Q: C# - Keep track of auto incrementing variable between serialization and deserialization I am working on a project and need help with regards to auto incrementing ID fields.
In terms of serialization, what is the best way to get the ID from when it was last serialized when it comes to deserialization of a static variable that you have been auto incrementing upon each instantiation of a class.
For instance...

[Serializable]
class Category
{
    private static int iCatID = 0;
    private int iCategoryID;
    private string sCategory;

    public Category(string _sCategory)
    {
        iCatID++;
        iCategoryID = iCatID;
        sCategory = _sCategory;
    }
}

I learnt the hard way that after creating 5 or so instances of this class, I serialized it, then deserialized and expected iCatID to pick up where it left off when I started creating more instances of the class, but it had of course reset back to 0.
What I want to know is how do I keep track of an auto incrementing variable in between serialization and deserialization and what would be best practice?
I've thought of two ways to possibly do it:

*

*When serializing the class, save the value of the static variable to a global setting and get that value again and set the static variable from the global setting on deserialization.

*When deserializing the class, use linq to query all instances of the class and get the highest number and then set the static variable accordingly.

I'm sure that there's a more elegant way of dealing with this.
Any help would be great, thanks.

A: Serialization is about instances... if you took a snapshot then it would be stored, i.e.
static int nextCatID;
private readonly int catID;
private string category;
...
public Category(string category)
{
    catID = Interlocked.Increment(ref nextCatID);
    this.category = category
}

here catID is the value related to the individual instance - and would be serialized and deserialized; of course, it could then lead to repeats: if you serialize item 1 and then deserialize it 5 times, you'll have 5 more "item 1"s.
If you wanted the value to be set during deserialization, you can do that too - just mark the field as non-serialized:
static int nextCatID;
[NonSerialized]
private int catID;

and set it in a post-serialization callback using the same code from the constructor (note that because the callback is not a constructor, you can't use readonly):
[OnDeserialized()]
private void OnDeserialized(StreamingContext context)
{
    catID = Interlocked.Increment(ref nextCatID);
}

A: You could:
private static long iCatID = DateTime.Utc.Ticks;

start your counter with the current time (UTC) converted in a long. So at any run of your program with a little luck (if your user hasn't changed the clock), all the new IDs will be > all the old IDs.
Note that by using UTC you are resistant to changes of Summer Time/Winter Time.
Another solution is to simply forget about Id and use Guid.
You generate it through Guid.NewGuid() and it will be unique. The only problem is that you have just lost the ordering of items. You can't simply compare two Guid and tell "this is newer, this is older". You can tell that they are equal/different.


text:
Q: MySQL processlist history maintainence I was thinking of writing a tool to maintain history of queries taking longer than 5 seconds.
Tool back end setup will look like:
Table1:QUERY_META
queryId int() (PK)
query text
regDate date

Table2: QUERY_STAT
queryId: int() (FK)
runDate: date (date of Run)
avgTimeTaken:int()
noOfRuns: int()

To make it "smart", I was hoping to maintain only unique queries. What I mean by that is, suppose I have queries like:
a) SELECT a,b,c from table1 where x='x1' and y != 'y1'; (10 seconds)
   b) SELECT a,b,c from table1 where x='x2' and y != 'y2'; (10 seconds)
Now essentially, I'll like to store query like:
SELECT a,b,c from table1 where x = <x> and y != <y>;

This'll make life easier to see how many of the same kind of queries are running.
What it means for my tool to do is: normalize the where clause.
I can split at the keyword WHERE, and that's where my problem becomes big. How can I normalize/standardize the where clause?
There are quite a few comparison operators and I don't know easy way to do string manipulations. I am not worrying about multiple where clauses as of now.
I consider myself to be proficient using Python, MySQL (but open to anything that gets the job done).
My fallback plan is banking on the select and adding a queryTag column on QUERY_META table. It'll work as a psuedo-group by column! There are complications here too, but typing that all here will lengthen the already long post.
I cannot use slow query logs for this purpose, due to audience of the tool and some system limitations.
If there is a tool that already does that, please point me towards it, because I was having hard time identifying what to google for.

A: There is an incredible tool called pt-query-digest from Percona.  It does everything you want and more.  I have always used it with the slow query logs, but it has other options.  From the help:

pt-query-digest is a sophisticated but easy to use tool for analyzing
  MySQL queries. It can analyze queries from MySQL slow, general, and
  binary logs. (Binary logs must first be converted to text, see
  --type). It can also use SHOW PROCESSLIST and MySQL protocol data from tcpdump. By default, the tool reports which queries are the slowest,
  and therefore the most important to optimize. More complex and
  custom-tailored reports can be created by using options like
  --group-by, --filter, and --embedded-attributes.

Be sure to check out the options for --group-by as they are very powerful.


text:
Q: How to Implement Search with Pagination using Ajax codigniter Controller
 function view_product()
    {
        $config = [
            'base_url'          =>  base_url('admin/view_product'),
            'per_page'          =>  10,
            'total_rows'        =>  $this->AdminModel->num_rows(NULL),
            'full_tag_open'     =>  "
",
            'full_tag_close'    =>  "
",
            'first_tag_open'    =>  '
',
            'first_tag_close'   =>  '
',
            'last_tag_open'     =>  '
',
            'last_tag_close'    =>  '
',
            'next_tag_open'     =>  '
',
            'next_tag_close'    =>  '
',
            'prev_tag_open'     =>  '
',
            'prev_tag_close'    =>  '
',
            'num_tag_open'      =>  '
',
            'num_tag_close'     =>  '
',
            'cur_tag_open'      =>  "
",
            'cur_tag_close'     =>  '
',
        ];

        $this->pagination->initialize($config);
        $data['page'] =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['product'] =$this->AdminModel->view_product(NULL,$config['per_page'],$data['page']);
        $data['pagination'] = $this->pagination->create_links();
        $this->load->view('admin/view_product',$data);

    }

 public function ajaxsearch()
     {
          $query = $this->input->post('query');
          print_r($this->AdminModel->num_rows($query));

          $config = [
            'base_url'          =>  base_url('admin/ajaxsearch'),
            'per_page'          =>  10,
            'total_rows'        =>  $this->AdminModel->num_rows($query),
            'full_tag_open'     =>  "
",
            'full_tag_close'    =>  "
",
            'first_tag_open'    =>  '
',
            'first_tag_close'   =>  '
',
            'last_tag_open'     =>  '
',
            'last_tag_close'    =>  '
',
            'next_tag_open'     =>  '
',
            'next_tag_close'    =>  '
',
            'prev_tag_open'     =>  '
',
            'prev_tag_close'    =>  '
',
            'num_tag_open'      =>  '
',
            'num_tag_close'     =>  '
',
            'cur_tag_open'      =>  "
",
            'cur_tag_close'     =>  '
',

        ];

        $this->pagination->initialize($config);
        $data['page'] =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['product'] =$this->AdminModel->view_product($query,$config['per_page'],$data['page']);
        $data['pagination'] = $this->pagination->create_links();
        $this->load->view('admin/product_search_result',$data,false);

     }

Model
public function num_rows($searchKeyword=NULL)
    {
        if ($searchKeyword == "NULL") $searchKeyword = "";

        $query = $this->db
                      ->select('*')
                      ->from('product')
                      ->like('p_name',$searchKeyword)
                      ->get();

        return $query->num_rows();

    }

 function view_product($searchKeyword=NULL,$limit,$offset)
    {
            if ($searchKeyword == "NULL") $searchKeyword = "";

            $query = $this->db->select("*")
                              ->from('product')
                              ->limit($limit, $offset )
                              ->join('product_category', 'product.p_cid = product_category.p_cid')
                              ->join('company','product.c_id = company.c_id')
                              ->order_by('p_id')
                              ->like('p_name',$searchKeyword)
                              ->get();
            return $query->result();
    }

View
function load_data(query)
      {
            $.ajax({
                      url:"<?php echo base_url();?>admin/view_product",
                      method:"POST",
                      data:{query:query},
                      success:function(data)
                      {
                          $('#showData').html(data);
                          $('#product_list').html(data);
                      }
                    });
      }

  $('#product_name').keyup(function()
      {
          var search = $(this).val();
          if(search != '')
          {
             load_data(search);
          }
        /*  else
          {
             load_data();
          }*/
      });

I am new to C.I, I am creating a Search Filter, The filter is working properly until i moved to the next Pagination link. When i am on First link the data is showing according to the filter/search keyword, but as i move to the next link everything goes off (All the data shows on page) how to solve this problem ?

A: I will suggest you to have one function for both searching & pagination in CONTROLLER and have two separate function in MODEL
function view_product()
{
    $config = [
        'base_url'          =>  base_url('admin/view_product'),
        'per_page'          =>  10,
        'total_rows'        =>  $this->AdminModel->num_rows(NULL),
        'full_tag_open'     =>  "
",
        'full_tag_close'    =>  "
",
        'first_tag_open'    =>  '
',
        'first_tag_close'   =>  '
',
        'last_tag_open'     =>  '
',
        'last_tag_close'    =>  '
',
        'next_tag_open'     =>  '
',
        'next_tag_close'    =>  '
',
        'prev_tag_open'     =>  '
',
        'prev_tag_close'    =>  '
',
        'num_tag_open'      =>  '
',
        'num_tag_close'     =>  '
',
        'cur_tag_open'      =>  "
",
        'cur_tag_close'     =>  '
',
    ];

    $this->pagination->initialize($config);
    $data['page'] =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
    if(@$this->input->post('searchKeyword')==null)
    {
    $results=$this->AdminModel->view_product($config["per_page"],$page);
    }
    else
    {
    $searchKeyword=$this->input->post('searchKeyword');
    $results=$this->AdminModel->view_product_withKey($config["per_page"],$page,$searchKeyword);
    }
    $data['product']=$results;
    $data['pagination'] = $this->pagination->create_links();
    $this->load->view('admin/view_product',$data);

}

MODEL
public function view_product($limit,$start)
{
    $this->db->from($this->table);
    $this->db->where('status',TRUE);
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    return $query->result();
}

public function view_product_withKey($limit,$start,$searchKeyword)
{
    $this->db->from($this->table);
    $this->db->like('field1', $searchKeyword);
    $this->db->or_like('fiel2', $searchKeyword);
    $this->db->or_like('field3', $searchKeyword);
    $this->db->or_like('field4', $searchKeyword);
    $this->db->where('status',TRUE);
    $this->db->limit($limit, $start);
    $query = $this->db->get();
    return $query->result();
}

Please test the code . AND do considered the variable name . please use your variable respectively.


text:
Q: Auto resize div to fit two (or more) stacked pictures in it I have a div with display: inline-block that has two or more IMGs in it. IMGs are "stacked" on top of each other (I also have script that sets z-index when necessary), so I use position: absolute; top: 0; left: 0; for these IMGs. I need to resize containing div to fit the biggest image in it. The problem is, that images are loaded dynamically and have different sizes and I need to resize containing div to fit the biggest one currently in it. When I don not use no position: absolute, containing div resizes automatically to fit the image, but in that case I cannot place images on top of each other.
So, is it possible to achieve this with css only? The goal is to have several images with unknown sizes stacked on top of each other.
Thank you.
(snippet is for illustration only)

window.onload=function()
{
  let lastPic=1;

  setInterval(function()
  {
    let pics=document.querySelectorAll(".pic");
    pics[lastPic].style.zIndex="";
    lastPic=Math.ceil(Math.random()*3);
    pics[lastPic].style.zIndex="3";
  }, 1000);

};
div#container
{
  display: inline-block;
  border: 1px solid black;
  background: black;
  padding: .5em;
}

img.pic
{
  position: absolute;
  top: 0;
  left: 0;
  opacity: .9;
}

div#container img:nth-child(1)
{
  border: 1px solid #f00;
  background: rgba(255,0,0,.5);
}
div#container img:nth-child(2)
{
  border: 1px solid #00f;
  background: rgba(0,0,255,.5);

}
div#container img:nth-child(3)
{
  border: 1px solid #0f0;
  background: rgba(0, 255,0,.5);
}
div#container img:nth-child(4)
{
  border: 1px solid #0ff;
  background: rgba(0,255,255,.5);

}
<!doctype html>

A: Instead of position:absolute, use display:grid (in this case display:inline-grid so it shrink wraps the images) and put all the images in the same row & column.

Note: older versions of Internet Explorer either do not support CSS-Grid or support an older version of the specification and will require specific -ms- grid properties.

div#container {
  display: inline-grid;
  border: 1px solid black;
  padding: 0.5em;
}

img.pic {
  grid-row: 1;
  grid-column: 1;
  opacity: 0.9;
  display: block;
}

div#container img:nth-child(1) {
  border: 1px solid #f00;
  background: rgba(255, 0, 0, 0.5);
}

div#container img:nth-child(2) {
  border: 1px solid #00f;
  background: rgba(0, 0, 255, 0.5);
}

div#container img:nth-child(3) {
  border: 1px solid #0f0;
  background: rgba(0, 255, 0, 0.5);
}

div#container img:nth-child(4) {
  border: 1px solid #0ff;
  background: rgba(0, 255, 255, 0.5);
}


text:
Q: Background-image transition not working I'm trying to do a simple fade-in fade-out transition with a background-image without events, because its like a banner. I want to set two different images so I have this:
setInterval(function() {
  var $banner = $('#banner');
  if ($banner.hasClass('background1')) {
    $banner.removeClass('background1');
    $banner.addClass('background2');
  } else {
    $banner.removeClass('background2');
    $banner.addClass('background1');
  }
}, 3000);

My CSS is:
.background1 {
  -webkit-transition: background-image 0.2s ease-in-out;
  transition: background-image 0.2s ease-in-out;
  padding: 7em 0 8.25em 0;
  margin-bottom: -6.5em;
  background-image: linear-gradient(to top, rgba(46, 49, 65, 0.8), rgba(46, 49, 65, 0.8)), url("../../images/fondo.jpg");
  background-size: auto, cover;
  background-position: center, cover;
  background-repeat: no-repeat, no-repeat;
}

.background2 {
  -webkit-transition: background-image 0.2s ease-in-out;
  transition: background-image 0.2s ease-in-out;
  padding: 7em 0 8.25em 0;
  margin-bottom: -6.5em;
  background-image: linear-gradient(to top, rgba(46, 49, 65, 0.8), rgba(46, 49, 65, 0.8)), url("../../images/fondo_.jpg");
  background-size: auto, cover;
  background-position: center, cover;
  background-repeat: no-repeat, no-repeat;
}

And the element where I want this effect is like this:

setInterval(function() {
  var $banner = $('#banner');
  if ($banner.hasClass('background1')) {
    $banner.removeClass('background1');
    $banner.addClass('background2');
  } else {
    $banner.removeClass('background2');
    $banner.addClass('background1');
  }
}, 3000);
.background1 {
  -webkit-transition: background-image 0.2s ease-in-out;
  transition: background-image 0.2s ease-in-out;
  padding: 7em 0 8.25em 0;
  margin-bottom: -6.5em;
  background-image: linear-gradient(to top, rgba(46, 49, 65, 0.8), rgba(46, 49, 65, 0.8)), url("../../images/fondo.jpg");
  background-size: auto, cover;
  background-position: center, cover;
  background-repeat: no-repeat, no-repeat;
}
.background2 {
  -webkit-transition: background-image 0.2s ease-in-out;
  transition: background-image 0.2s ease-in-out;
  padding: 7em 0 8.25em 0;
  margin-bottom: -6.5em;
  background-image: linear-gradient(to top, rgba(46, 49, 65, 0.8), rgba(46, 49, 65, 0.8)), url("../../images/fondo_.jpg");
  background-size: auto, cover;
  background-position: center, cover;
  background-repeat: no-repeat, no-repeat;
}

I dont know what I'm doing wrong so, can someone help me?

A: You can use Jquery and animate() function with easing plugin for make that.
Plugin: https://github.com/gdsmith/jquery.easing
Please try:

setInterval(function() {
  var $banner = $('#banner');
  if ($banner.hasClass('background1')) {
    $banner.animate({opacity:0},200,"easeInCirc",function(){
      $banner.removeClass('background1');
      $banner.addClass('background2');
      $banner.animate({opacity:1},200)
    })
  }else{
    $banner.animate({opacity:0},200,"easeOutCirc",function(){
      $banner.removeClass('background2');
      $banner.addClass('background1');
      $banner.animate({opacity:1},200)
    })
  }
}, 3000);
.background1 {
  padding: 7em 0 8.25em 0;
  margin-bottom: -6.5em;
  background-image: linear-gradient(to top, rgba(46, 49, 65, 0.8), rgba(46, 49, 65, 0.8)), url("http://www.activcompany.com/uploads/pictures/095-ERDF-29-05-12.jpg");
  background-size: auto, cover;
  background-position: center, cover;
  background-repeat: no-repeat;
}

.background2 {
  padding: 7em 0 8.25em 0;
  margin-bottom: -6.5em;
  background-image: linear-gradient(to top, rgba(46, 49, 65, 0.8), rgba(46, 49, 65, 0.8)), url("http://www.myfeelback.com/sites/default/files/erdf-satisfaction-riverain-OG-TC.jpg");
  background-size: auto, cover;
  background-position: center, cover;
  background-repeat: no-repeat;
}


text:
Q: Saddle point method I need to calculate the following integral
$$\int_0^\infty{ a \; b \; t^2 \; e^{-b t} e^{- a (1 - (1 + b t) e^{- b t}} \frac{a^{k - 1} (1 - (1 + b t) e^{- b t})^{k - 1}}{(k - 1)!}} dt$$
with $a = 890, b = 0.02178799631089532$, which exhibits a maximum and therefore can be calculated by the saddle point method for values of $k$ of let's say from $100$ to $300$, for values of $k$ greater than $a$ the integrad tends to zero. How can I calculate the integral using the saddle point method?

A: You can start by taking out values and rearranging:
$$\int_0^\infty{ a \; b \; t^2 \; e^{-b t} e^{- a (1 - (1 + b t) e^{- b t}} \frac{a^{k - 1} (1 - (1 + b t) e^{- b t})^{k - 1}}{(k - 1)!}} dt=\frac{a^kb}{(k-1)!}\int_0^\infty t^2e^{-bt}e^{-a(1-(1+bt)e^{-bt})}\left[1-(1+bt)e^{-bt}\right]^{k-1}dt={\frac{a^k}{b^2(k-1)!}\int_0^\infty u^2e^{-u}e^{-a(1-(1+u)e^{-u})}\left[1-(1+u)e^{-u}\right]^{k-1}dt}$$


text:
Q: Groovy JSONSlurper to reformat JSON object into array I've been spinning my wheels long enough on this so I'm hopeful for some help or pointers. I'm new to groovy and have been able to wade my way this far in, but am stuck here.
Using Groovy, given the following input JSON:
{
    "rates": {
        "USD": 3.39,
        "EUR": 1.00,
        "CAD": 1.31
    }
}

I want to convert each value within the rates object to an array, looking similar to the following. Ideally this script can handle 1-n rates. Notice that From_Curr is statically added to each array obj.
{
    "rates": [{
            "From_Curr": "GBP",
            "To_Curr": "USD",
            "Rate": 3.397
        }, {
            "From_Curr": "GBP",
            "To_Curr": "EUR",
            "Rate": 1.00
        }, {
            "From_Curr": "GBP",
            "To_Curr": "CAD",
            "Rate": 1.31
        }
    ]
}

I tried the following groovy, and I realize that because I'm not starting with a json array it isn't quite working out how I want.
def collectedRates = new JsonSlurper()
    .parseText(inputJson)
    .rates
    .collectEntries{["From_Curr":"GBP","To_Curr":it.key,"Rate":it.value]};

A: User tim_yates in comments pointed out my flaw-- use collect instead of collectEntries. Working snippet below Thanks!
def collectedRates = new JsonSlurper()
    .parseText(inputJson)
    .rates
    .collect{["From_Curr":"GBP","To_Curr":it.key,"Rate":it.value]};


text:
Q: Issues with auto updating App Store - OSX Ive got 5 or 6 Macs that I'm responsible for the security of. One of the things I want to do is keep all the macs on the latest security patch for their respective OS.
We have a mixture of 10.10.5 and 10.11.x OS across the different machines, some of the machines, need to be on 10.10.x as some mission critical software we use on them only runs on 10.10.x
I noticed there is an auto update feature for the OSX App store, but I'm concerned of two things :

*

*It will auto update the OS to Sierra or what ever is latest when it is auto updating (I only want to update to the latest version of my current OS to encompass security patches etc.)

*If a user choses to restart the machine in the middle of the day it will start trying to install software and take 30 mins to to install where as the user was only hoping to do a quick restart and get back to work
Is there a way around either of these points?

A: As far as I know and I'm using a MacBook Pro too, when you set automatic update, it will automatically download and install update.
However, for big upgrade, it always ask you do to it, such as upgrade from the current version to Sierra.


text:
Q: How to add or delete default value theme options while activate and deactivate theme I want to add & reset default value for my theme options while activate and deactivate a theme
More clearly something like this
if(theme active)
  add_option();
  // add new option to the theme and register default setting for one time only

if(theme deactivate)
   delete_option();
  // reset current option and delete default setting  for one time only

Question
How know is theme active or not? What a function or hook for this one. Let me know

A: I think what you are looking for was answered here:

*

*Theme Activate Hook


text:
Q: What is this timeformat? I want to use DateFormatter
but I don't know this time format
in Swift
let date = "2017-04-22T15:42:35.000Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd........"
print(dateFormatter.date(from: date))

2017-04-22T15:42:35.000Z
"yyyy-MM-dd...."

A: let date = "2017-04-22T15:42:35.000Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
print(dateFormatter.date(from: date))

This must be what you are looking for.


text:
Q: How Do I Set User Agent In AsyncHttpClient? In my app I am working with YouTube. I am requesting a page that I need in mobile view. Like this... http://m.youtube.com?persist_app=1&app=m
If I enter that link into a web browser I am locked in mobile view on the YouTube page (in the web browser that is). I want to do the same with AsyncHttpClient. If I was working with a webview I know I could do this..
WebSettings ws = wv.getSettings();
ws.setUserAgentString("Foo/");

Now how do I accomplish this with AsyncHttpClient?
I've tried this and it didn't work
public void myAsyncHttpClient(String url) {
    AsyncHttpClient client = new AsyncHttpClient();

    client.addHeader("User-Agent", "Foo/");
    client.setUserAgent("Foo/");

    client.get(url, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

            urlHTMLCode = new String(responseBody);

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    });
}

Any ideas? Thanks!

A: Just use
AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder().setUserAgent(UserAgentString).build();
AsyncHttpClient asyncHttpClient = new AsyncHttpClient(cf);

Example with your code >
public void myAsyncHttpClient(String url) {

    AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder().setUserAgent("User-Agent").build();
    AsyncHttpClient client = new AsyncHttpClient(cf);

    client.get(url, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            urlHTMLCode = new String(responseBody);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    });
}


text:
Q: Changing spring constants after importing robot causes issues I have to run an optimization on tendon stiffnesses in a modelled leg. Changing the spring constants manually causes no issues and the physical model seems to work well. The issue presents itself when I attempt to optimize for these values.
Since this is an optimization problem, I have to run the simulation for 1.5 seconds and then reset the robot to its initial state, with slightly different spring constants. To do this I have the robot model saved as a "Robot.wbo" file. At the end of each optimization iteration, I remove the existing robot node and use "def importMFNode" to create a new robot node, which creates the robot in the initial state. At the start of each new iteration, I then set new spring constants and setting these causes the model to behave unexpectedly. I have pinned down the issue to these two lines.
knee_spring_constant.setSFFloat(int(x[2]))
heel_spring_constant.setSFFloat(int(x[3]))

All these two lines do is change the spring constants of two slider joints. If I do it using these two commands, the model fails. If I do it manually, it works.
Instead of the model behaving normally, it just behaves erratically and not like it is supposed to. However, if I manually make a new copy of the robot node right after it is imported by the supervisor code, and delete the old one, the robot behaves as it is supposed to.

A: I'm not sure why this is not working, maybe a global physics reset is missing.
But for sure, your method to unload/reload the robot is heavy and can be simplified easily.
There are several solutions to reset a robot which are more simple and so which will potentially work better.

*

*You could reset the robot position and its physics at the end of an iteration. Changing the spring constants before calling the physics reset function seems to be a safe idea.

*You could reset the entire simulation and change the spring constants.

*You could keep your method as-is, but change the springs inside Robot.wbo before loading it (with a basic template engine, a simple search and replace could do the job).


text:
Q: Linq to EF Dynamic Search with multiple properties Given the follwing:
SQL Tables:
Names
-----
Id (int)
FirstName (varchar)
LastName (varchar)

NameProperties
----------
Id (int)
NameId (int) FK to Names Id
PropType (int)
PropValue (int)

Every Name can have multiple NameProperties
Now my searchCriteria Class is as follows
public string FirstName { get; set; }
public string LastName { get; set; }
public List<KeyValuePair<int,int>> Properties { get; set; } Corresponding to a list of PropType ProValue

How do I search using linq to EF when having multiple PropType & PropValues ?

A: Supposing that the criteria in Properties should all be met (i.e. AND and not OR) you could do this:
// c is a searchCriteria object.
var query = context.Names
    .Where(n => n.FirstName == c.FirstName && n.LastName == c.LastName);
foreach(var pair in c.Properties)
{
    query = query.Where(n => n.NameProperties.Any(np =>
        np.PropType == pair.PropType && np.PropValue == pair.PropValue;
}

(not checked for syntax, just showing the idea).
It is not very efficient to query this way, but querying an Entity–attribute–value model is always a pain. If it is even remotely possible to change the Name table in a way that it includes columns corresponding with the NameProperties then do it.


text:
Q: Generalized Zassenhaus Lemma Zassenhaus Lemma states that, if $A^* \lhd A$ and $B^* \lhd B$, then $$\frac{A^* (A\cap B)}{A^* (A\cap B^* )}\cong \frac{B^* (A\cap B)}{B^* (A^*\cap B)}.$$
I generalized this lemma, and I want to see whether my proof for the generalization is correct or not.

2nd Isomorphism Theorem: If $H \lhd G$ and $K <G$ then $HK/H \cong K/K \cap H$.

Let's generalize this theorem a little bit:
Lemma 1: If $X < N(A)$, where $N(A)$ is the normalizer of $A$, then $AX/A \cong X/(A \cap X)$.
The proof of this is similar to the 2nd Iso. Th.

Lemma 2: Suppose G is a group and $X$, $A$, and $H$ are subgroups of $G$. $X < N(A)$ implies  $$\frac{A(X \cap H)}{A} \cong \frac{(A\cap X)(X \cap H)}{(A\cap X)}.$$
Proof:
$$X < N(A) \Rightarrow X \cap H < N(A) \Rightarrow \frac{A(X \cap H)}{A} \cong \frac{X\cap H}{A \cap X \cap H}, \text{by Lemma 1}$$
Also
$$X < N(A \cap X) \Rightarrow X \cap H < N(A \cap X) \Rightarrow \frac{(A \cap X)(X \cap H)}{A\cap X} \cong \frac{X\cap H}{A \cap X \cap H}, \text{by Lemma 1}$$
Hence, the result is followed.

Lemma 3 (Edited): Suppose G is a group and $X$, $A$, and $H$ are subgroups of $G$. $X < N(A) \cap N(H)$ implies  $$\frac{AX}{A(X\cap H)} \cong \frac{X}{(A\cap X)(X \cap H)}.$$
Proof: Lemma 1 implies $\frac{AX}{A} \cong \frac{X}{A\cap X}$. This and Lemma 2 imply $$\frac{AX/A}{A(X\cap H)/A} \cong \frac{X/(A\cap X)}{(A \cap X)(X \cap H)/(A \cap X)}.$$
Moreover, $X < N(A) \cap N(H)$ implies $X\cap H \lhd X < N(A)$, which, in turn, implies $A(X \cap H) \lhd AX$. In addition, $H \cap X \lhd X$ and $A \cap X \lhd X$ imply $(A \cap X)(H \cap X) \lhd X$.
Now, the result is followed by the 3rd isomorphism theorem.

Generalized Zassenhaus: If $X < N(A) \cap N(B)$, then $$\frac{AX}{A(X\cap B)} \cong \frac{BX}{B(X \cap A)}.$$
Proof: We use Lemma 3 by considering $X < N(A)$ and $H=B$. We have $\frac{AX}{A(X\cap B)} \cong \frac{X}{(A\cap X)(X \cap B)}$. Now, we use Lemma 3 by considering $X < N(B)$ and $H=A$. We have $\frac{BX}{B(X\cap A)} \cong \frac{X}{(B\cap X)(X \cap A)}$. Hence, the result is followed.

The Zassenhaus lemma is derived with the generalized Zassenhaus by considering $X = A \cap B$, $A=A^* $, and $B=B^* $.
Is the proof correct? If it is, have you seen this generalization before? Does this generalization have a value in group theory?


text:
Q: How to update the Child component state on Updating the Parent Component state I have two components 1) Accordion Component and 2) MyCustom Component
Now I am importing Accordion Component into MyCustom Component as Below
import { Accordion } from '../../../controls/accordion';

public clickEvent = () =>{
this.setState({
  attachmentsAccordionCollapsed:!this.state.attachmentsAccordionCollapsed
});}

<Accordion title="Attachments" defaultCollapsed={this.state.attachmentsAccordionCollapsed} className={styles.itemCell} ></Accordion>

Now I am changing the state attachmentsAccordionCollapsed value on change event in the MyCustom Component but the property "defaultCollapsed" value of Accordion component does not change or update on changing the state of the MyCustom component.
Accordion Component
import * as React from 'react';
import styles from './Accordion.module.scss';
import { IAccordionProps, IAccordionState } from './index';
import { css } from "@uifabric/utilities/lib/css";
import { DefaultButton, IIconProps } from 'office-ui-fabric-react';

/**
 * Icon styles. Feel free to change them
 */
const collapsedIcon: IIconProps = { iconName: 'ChevronRight', className: styles.accordionChevron };
const expandedIcon: IIconProps = { iconName: 'ChevronDown', className: styles.accordionChevron };

export class Accordion extends React.Component<IAccordionProps, IAccordionState> {
  private _drawerDiv: HTMLDivElement = undefined;
  constructor(props: IAccordionProps) {
    super(props);

    this.state = {
      expanded: props.defaultCollapsed == null ? false : !props.defaultCollapsed
    };
  }

  public componentDidUpdate(prevProps) {
    this.state = {
      expanded: this.props.defaultCollapsed == null ? false : !this.props.defaultCollapsed
    };
  }

  public render(): React.ReactElement<IAccordionProps> {
    return (

        <DefaultButton
          toggle
          checked={this.state.expanded}
          text={this.props.title}
          iconProps={this.state.expanded ? expandedIcon : collapsedIcon}
          onClick={() => {
            this.setState({
              expanded: !this.state.expanded
            });
          }}
          aria-expanded={this.state.expanded}
          aria-controls={this._drawerDiv && this._drawerDiv.id}
        />
        {this.state.expanded &&

 { this._drawerDiv = el; }}>
            {this.props.children}

        }

    );
  }
}

A: Instead of copying props.defaultCollapsed to negated props.expanded I would suggest not having local state in the accordion and just pass the toggle function to expand from parent like any other controlled component:

class Accordion extends React.Component {
  render() {
    return (

        Is expanded: {String(this.props.expanded)}
        <button onClick={this.props.toggleExpanded}>
          toggle expanded
        </button>

    );
  }
}

class Parent extends React.PureComponent {
  state = {
    expanded: true,
  };
  toggleExpanded = () => {
    this.setState({ expanded: !this.state.expanded });
  };
  render() {
    return (

        <button onClick={this.toggleExpanded}>
          toggle from parent
        </button>
        <Accordion
          expanded={this.state.expanded}
          toggleExpanded={this.toggleExpanded}
        />

    );
  }
}
ReactDOM.render(
  <Parent />,
  document.getElementById('root')
);