Q:

xcode4:build depending on target

I have two targets for my project: one is the App, and the other is UT.I'd like to return different results for one method depending on the target.
I followed this link but failed.
I tried both:

I use TARGET_NAME. I set OTHER_CFLAGS to contain -DTARGET_NAME=${TARGET_NAME} in the project setting. And then in the code:

NSString *returnStr = nil;
#if TARGET_NAME == PhotoAPI
    returnStr = [NSString stringWithFormat:@"%@\'%@\');",EventFunStr,dataStr];
#elif TARGET_NAME == LogicTest
    returnStr = [NSString stringWithFormat:@"%@", dataStr];
#endif
return returnStr;

However it seems TARGET_NAME == PhotoAPI is always true.
 2. I also use Preprocessor Macros, and I set APP for the App targtet and UT for UT. And In the code:

NSString *returnStr = nil;
#ifdef APP
    returnStr = [NSString stringWithFormat:@"%@\'%@\');",EventFunStr,dataStr];
#elsedef UT
    returnStr = [NSString stringWithFormat:@"%@", dataStr];
#else
    returnStr = nil;
#endif
return returnStr;

And It always return nil.
I use LLVM GCC 4.2.
Can anyone help me?

A:

The problem may be i the way you define the flags
heres a good doc on using it to call NSLog only in DEBUG
http://iphoneincubator.com/blog/debugging/how-to-create-conditional-log-statements-in-xcode
it said in comments
If you’re going to use GCC_PREPROCESSOR_DEFINITIONS instead of OTHER_CFLAGS,
make sure to use the form “DEBUG=1″ instead of “-DDEBUG=1″


Q:

Dynamic table first row need to sow first

I have found javascript source code which work like stop watch and show data start time, end time length and time between two time interval in table dynamically. Here first row is going down after next click , but I need first row will remain  first after next click and next data will display at next one by one.
Thanks to all
enter code here

    <button type="button" id="action">
Start Timer</button>

                    Start Time
                    End Time
                    Length
                    Time Between

A:

Just update your $('#history').prepand() to $('#history').append() like this:
    $('#history').append(

'+formattedStart+'	'+formattedEnd+'	'+lengthFormatted+'	'+timeBetweenFormatted+'
')}

So, it will insert Table Row at the end of History Div.


Q:

How to tag a field in sql server?

I want to categorizes things in data base so that one thing can be in several categories. I have a table for categories. I want to make foreign key to them but how can I make a field have several value? is there a way to make the coulmns dynamically or have an array of an enumeration or array of another table fields?

A:

In generally, when you have a many to many relationship (one "thing" can be in many categories, one category can have many "things" in it), you have to set up a linking table to tie the two things together.
Each row in the linking table would have the ID of one row in the "thing" table, and of one row in the category table. So, many rows could be used to tie a given "thing" to its categories, and many rows could tie different "things" to a given category.
The thing_id and category_id columns in the linking table would be foreign keys to the "thing" and category tables (respectively).


Q:

ImportError: No Module named 'mt_exceptions' when using Mingus library

Forgive my ignorance in advance, I am very new to python. I am trying to use a python 3 version (https://code.google.com/r/artdent-mingus-python3/) of the Mingus library (https://pypi.python.org/pypi/mingus/) in 3.4.2. When trying to use the note module, I keep getting the ImportError listed in the title.
Based on my research on similar ImportError questions, I have tried the following things:
-I made sure there was a mt_exceptions.py file in the relevant directory
-I made sure each mingus directory in the site-packages directory has init.py file
-I deleted the .pyc files in the mingus directory
Any pointers on what I might try next?

A:

I've solved the problem by manually entering in "C:\Python34\Lib\site-packages\mingus\core" and editing the file (In my case, I had to edit notes.py from "from mt_exceptions import NoteFormatError, RangeError, FormatError" to "from mingus.core.mt_exceptions import NoteFormatError, RangeError, FormatError", and then I got a typical Python 2.x running on 3.x dict error. So that's the problem!
Solution: Use Python 2.x, or update the whole schmere to 3.x (That's what I'm doing).
As you can see here, Python 3.x has changed the import syntax a bit, and that's exactly what's happening. I had to run 2to3 through all the mingus source code and fix the imports manually from all files (Basically, porting the whole thing to Python 3.x).


Q:

Is it possible to set a cube with a snowflake schema in data.cube R?

Or, can dimensions be, in some way nested, in data.cube?
Given the following example (accessed via ?data.cube on R, having installed last branch of data.cube-oop package, by @jangorecki) for which I post code and image example.
Consider I want to expand the cube adding a new dimension which would turn the schema to snowflake, so for each geography location, I would have another set of data (data.table) which would describe demography properties (i.e. population based on gender, age, etc)
Image

dotted: possible new dimensions.
black: actual facts and dimensions from code example.
green: new dimension which turns the schema into snowflake.
Code
# multidimensional hierarchical data from fact and dimensions
X = populate_star(N = 1e3)
sales = X$fact$sales
time = X$dims$time
geography = X$dims$geography
# define hierarchies
time.hierarchies = list( # 2 hierarchies in time dimension
    "monthly" = list(
        "time_year" = character(),
        "time_quarter" = c("time_quarter_name"),
        "time_month" = c("time_month_name"),
        "time_date" = c("time_month","time_quarter","time_year")
    ),
    "weekly" = list(
        "time_year" = character(),
        "time_week" = character(),
        "time_date" = c("time_week","time_year")
    )
)
geog.hierarchies = list( # 1 hierarchy in geography dimension
    list(
        "geog_region_name" = character(),
        "geog_division_name" = c("geog_region_name"),
        "geog_abb" = c("geog_name","geog_division_name","geog_region_name")
    )
)
# create dimensions
dims = list(
    time = as.dimension(x = time,
                        id.vars = "time_date",
                        hierarchies = time.hierarchies),
    geography = as.dimension(x = geography,
                             id.vars = "geog_abb",
                             hierarchies = geog.hierarchies)
)
# create fact
ff = as.fact(
    x = sales,
    id.vars = c("geog_abb","time_date"),
    measure.vars = c("amount","value"),
    fun.aggregate = sum,
    na.rm = TRUE
)
# create data.cube
dc = as.data.cube(ff, dims)
str(dc)

other questions related to the example are:
what is the value expected for each element? why

"time_week" = character()
"time_date" = c("time_week","time_year")

instead of

"time_week" = character()
"time_date" = date()

and why this naming as in columns of data.table?

"time_quarter" = c("time_quarter_name"),
"time_month" = c("time_month_name")

A:

Cube model is underlying structure that user don't have to deal with. data.cube-oop uses the following data model.
Going precisely to your example in question. You can't add new dimensions in snowflake schema this way. New dimensions must be connected to fact table. Tables in snowflake schema that are not directly connected to fact table are just hierarchy levels in dimensions. In your example that means the customer dimension is just a higher level attributes of geography dimensions. You might eventually do the opposite, create customer dimension and on higher levels of customer hierarchy keep geography attributes.
In any way you decide to do it, you must create your dimensions from single table each (can be same wide table of course). You cannot construct dimension by providing its levels separately, this would be more confusing than just single denormalized dimension table which is something that users most often deal with.
So in order to keep geography attributes in customer dimension just lookup geography values to your customer table and supply as.dimension with new table.

As for the second part of your question, hierarchy lists defines relationship between attributes in hierarchy, not data types. Column name on LHS define a key column in hierarchy level, while RHS define dependent attributes which will be present on that particular level. You basically define which column goes on which level in hierarchy, lower levels must refer to upper level in order to create real hierarchy. This is enforced by uniqueness of data, i.e. you must have only single time_month_name for each time_month.
To see this relationship better try the following:

library(data.cube)
X = populate_star(N = 1e3)
dc = as.data.cube(X)
dc$dimensions$time$levels

It will print all hierarchy levels in time dimension, each hierarchy level is a separate table.


Q:

What is the title of the song that plays during the next episode(18) previews of Parasyte -the maxim-?

What is the title of the short insert soundtrack that plays at the end of every episode in Parasyte -the maxim-? During the next episode(18) previews (see images), a suspenseful/thriller song is being played as background music instead of the usual vague voice-overs. It really rocks and I want to know because I feel as though I have heard it being used in other anime aside from this one.

A:

Though this one sounds like a dubstep version, I think it's Hypnotik.


Q:

not able to get sever.xml port settings in jira

when i start jira in windows it starts successfully on default port 8080,
the situation is that i want another app to be started on same port,and when i search through /conf/server.xml i didnot find the connector port settings in that but when i go through GUI tool provided by jira i am able to get the port settings,
so my question is that how jira is implementing this, is there any other setting which jira is taking into consideration or something else.??
any suggetion...

A:

Jira does honor the conf/server.xml file. If you need to change the port number it should be set in the default connector (you can add this if it doesn't exist):
<Connector port="8082"
  maxThreads="150"
  minSpareThreads="25"
  maxSpareThreads="75"
  connectionTimeout="20000"

  enableLookups="false"
  maxHttpHeaderSize="8192"
  protocol="HTTP/1.1"
  useBodyEncodingForURI="true"
  redirectPort="8443"
  acceptCount="100"
  disableUploadTimeout="true"/>

There is more information on the Atlassian Confluence site for Jira: https://confluence.atlassian.com/display/JIRA/Changing+JIRA's+TCP+Ports.
Also, you may want to consider http://www.serverfault.com for future questions, stackoverflow's brother for system administration Q&A.


Q:

What is a desktop environment, session and shell?

This is how all happened. I was trying to search good screen recorder and found on some website that recordMyDesktop will work well under GNOME *Shell. So I tried searching in google "how to find whether I'm using gnome shell". The first link directed me to official gnome wesite there it showed a message as below.
 So I thought it is something to do with desktop environment and continue browsing as below.
In this question I tried first answer to find my desktop environment, but the command DESKTOP_SESSION gave me "command not found". So I tried 5th answer by Nadiw. The command and output are as below.
ls /usr/bin/*session
/usr/bin/ck-launch-session  /usr/bin/gnome-session

So it is confirmed I'm using GNOME but it is not showing as desktop environment instead its showing "session", by which I got confused.
Hence I tried third answer by Luis Alvarado from this post. The command and output are as below
echo $XDG_CURRENT_DESKTOP
Unity

Now I found this totally irrelevant. My questions are

If the desktop environment is Unity how can it use a session of GNOME and GNOME shell.
How GNOME shell is different from bourne shell, t shell and others
Or if one of the outputs I'm getting is wrong? Then how to find which DE i'm using? And which is the default DE for Ubuntu 14.04.
On which of these factors I should depend while downloading a software? Whether it is Desktop Environment or session or shell?

A:

DESKTOP_SESSION is not a command, it's a variable. You can do echo $DESKTOP_SESSION to see what the value is, just like with XDG_CURRENT_DESKTOP:
$ echo $DESKTOP_SESSION
gnome
$ echo $XDG_DESKTOP_SESSION

$ echo $XDG_CURRENT_DESKTOP
GNOME

(I'm using GNOME Shell. Yes, I did not get any output for XDG_DESKTOP_SESSION. This is a known bug.)
This output is not irrelevant:
$ echo $XDG_CURRENT_DESKTOP
Unity

It is the most relevant bit of information you have, that you are running the Unity shell.

To install Gnome Shell:
sudo apt-get install gnome-shell

See the third of the reference links for screenshots for selecting Gnome Shell.
The interface, the part that you interact with, is called a shell. The Bourne shell and other classic shells are command line shells. Gnome Shell, Unity, etc. are graphical shells.
The default Desktop Environment for Ubuntu is GNOME 3, with the Unity shell and other modifications. Because the base is GNOME, you'll see some output which is true for GNOME Shell as well, for the various tests.
Usually, none. The answer to this is very complicated and application-dependent. Have a look at the fifth linked question.

As for the browser error, if it persists after you start using Gnome Shell, see the FAQ.
Also see:

What is the relationship between Unity, Gnome, Gnome 3, Compiz, Metacity, and LightDM?
What kinds of desktop environments and shells are available?
How do I install and use the latest version of GNOME?
What is the default desktop environment for Ubuntu 13.10?
When installing packages (particularly those with graphical UIs) how do you determine which is fitting for your distribution?


Q:

Magnolia - creating new area

I read magnolia documentation, but I'm still not sure how to create new area for existing page. What I want to do is Banner area (with image and some text) above <div id="wrapper-2">. I'm using Magnolia CE 4.5.9.
What I should do is probably:
1) add new area to: [templating-kit tab]/templates/prototype/areas
2) add a line like [@cms.area name="banner" content=content/] to /templating-kit/pages/main [templating-kit/templates] tab
3) something in [configuration] tab (?)
Thanks in advance for any help.

A:

Step by step guide is at http://documentation.magnolia-cms.com/templates/introduction.html#Areas
HTH,
Jan


Q:

AnkhSVN + Visual Studio 2013 Preview cannot set up - loading hangs

Using:

Microsoft Visual Studio Ultimate 2013 Preview Version 12.0.20623.01
Update
AnkhSVN 2.5.12116

I've:

enabled the plugin in the Tools->Options
added project to svn outside of VS, using TortoiseSVN GUI.

When I start VS, go to:

File->Subversion->Open from subversion,
add the svn URL:
https://myserver.com/svn/repo/project

and then the dialog hangs, just saying:
loading    (and showing the spinner, as if it is actually loading)
No files are offered. Interestingly, if I open the URL combobox, it shows many different paths that I have in my repo, e.g.

https://myserver.com/svn/repo/projectA
https://myserver.com/svn/repo/projectB
https://myserver.com/svn/repo/projectC

but which ever I one I choose, the endless "loading" occurs.
I've tried clearing the auth cache in AnkhSVN, I've imported the certificate from the https server on my win machine and so on.
TortoiseSVN works fine, and I can see the repo from Google Chrome.
Also, View->Repository Explorer hangs, showing spinner image forever.
Thanks,
Igor

A:

What do you see when you type ping myserver.com in a command prompt. If you don't see a ping to an 12.34.56.78 like address, but to some '2001:888:0:7::77' style address your server most likely resolves to an ipv6 address before it resolves to an ipv4 address. (Note that localhost has this problem)
Subversion 1.8 switched to a new http implementation and this implementation currently doesn't try to connect to further addresses resolved by the DNS resolver.
The problem is that many Subversion servers don't listen to ipv6 connections yet, while by using the machine name as a service name you tell your http client (in this case Subversion) that your server does support ipv6.


Q:

why does snprintf() write extra characters?

In my program, I open a file and write "Hello world" in it. I am using snprintf() to populate 'fname' variable. After this I put gdb on a.out and print the string 'fname'. I see that there are lots of extra character in string 'fname' which I did not assign. Where are these extra characters coming from? Could anyone help please?
  3 int main(void)
  4 {
  5     FILE *debug_fp = NULL;
  6     char fname[100];
  7
  8     snprintf(fname, 100, "./my_debug_%d", getpid());
  9     debug_fp = fopen(fname, "w");
 10     fprintf(debug_fp, "%s", "Hello world");
 11     return 0;
 12 }

gdb output:
(gdb) b test.c:10
Breakpoint 1 at 0x4005be: file test.c, line 10.

Breakpoint 1, main () at test.c:10
10          fprintf(debug_fp, "%s", "Hello world");
(gdb) p fname
$1 = "./my_debug_16178\000\000\000\000\000\000\000\000\300\313Ab:\000\000\000\360\005@\000\000\000\000\000\063\004@\000\000\000\000\000\001\000\000\000\000\000\301\000'\006@", '\000' <repeats 13 times>"\300, \313Ab:\000\000\000\360\005@", '\000' <repeats 13 times>"\260, \343\377\377"
(gdb) q

Thank you.

A:

In this case gdb doesn't care about your 0-terminator in the string and just prints the array, i.e. the full 100 characters in fname.
You can also use printf "%s" or p /s if you want gdb to treat your array as a C-string.


Q:

How do I enable profile in vim?

I learned about using :profile here, so I just tried to install vim with profiling enabled.
I tried this:
./configure --prefix=/home/username --with-features=profile

But in the output from configure I got the message
Sorry, profile is not supported

Does that mean that profile is not an option for me at all because of my OS, or is there something that I can do to make it "supported"?

A:

I don't think you can enable the profile feature via ./configure; you either have to define FEAT_PROFILE or simply build a huge version of Vim, which then includes that feature. From src/feature.h:
/*
* +profile      Profiling for functions and scripts.
*/
#if defined(FEAT_HUGE) \
        && defined(FEAT_EVAL) \
        && ((defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)) \
                || defined(WIN3264))
# define FEAT_PROFILE
#endif

TL;DR
./configure --with-features=huge


Q:

preg_match easiest way to match text from inside html tags

Possible Duplicate:
Best methods to parse HTML with PHP

for example i have a html code like :

            Text text text:3

            Text text text

            1
            0
            2

            2.90
            3.20
            1.85

Which is best regular expression to match all data from inside  tags?

A:

I normally suggest if you need to actually express what you're looking for in a HTML document to use an xpath expression for that because it can give you the actual value whereas regex'es are not able to further parse the HTML/XML, and xpath expressions are much more fine-grained. See the output which returns the text-value for example w/o any further tags inside:
array(8) {
  [0]=>
  string(16) "Text text text:3"
  [1]=>
  string(14) "Text text text"
  [2]=>
  string(1) "1"
  [3]=>
  string(1) "0"
  [4]=>
  string(1) "2"
  [5]=>
  string(4) "2.90"
  [6]=>
  string(4) "3.20"
  [7]=>
  string(4) "1.85"
}

Code:
$html = <<<EOD

            Text text text:3

            Text text text

            1
            0
            2

            2.90
            3.20
            1.85

EOD;

// create DomDocument to operate xpath on
$doc = new DomDocument;
$doc->loadHTML($html);

// create DomXPath
$xpath = new DomXPath($doc);

// perform the XPath query
$nodes = $xpath->query('//td');

// process nodes to return their actual value
$values = array();
foreach($nodes as $node) {
    $values[] = $node->nodeValue;
}
var_dump($values);


Q:

How to write a dataset with HDF.PInvoke?

I'm trying to write arrays into an HDF5 file in C#, using HDF.PInvoke.
I've made a simple program that writes a 3x3 array into an HDF5 file, but when I opened it, the result is not the same as the array.
using HDF.PInvoke;
using System.Globalization;
using System.IO;

using System.Runtime.InteropServices;

namespace WindowsFormsApp3
{
    public unsafe partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            string currentPath = Path.GetDirectoryName(Application.ExecutablePath);
            Directory.SetCurrentDirectory(currentPath);

            long file_id = H5F.create(@"weights.h5", H5F.ACC_TRUNC, H5P.DEFAULT, H5P.DEFAULT);

            int[,] arrInt3 = { { 1, 2, 3 }, { 3, 2, 1 }, { 3, 2, 1 } };

            ulong[] dims = {3,3};

            long space_id = H5S.create_simple(2, dims, null);

            long dataset_id = H5D.create(file_id, "/dset", H5T.STD_I32BE, space_id, H5P.DEFAULT, H5P.DEFAULT, H5P.DEFAULT);

            GCHandle pinnedArray = GCHandle.Alloc(arrInt3, GCHandleType.Pinned);
            IntPtr pointer = pinnedArray.AddrOfPinnedObject();

            long write_id = H5D.write(dataset_id, H5T.NATIVE_INT32, H5S.ALL, H5S.ALL, H5P.DEFAULT, pointer);

            long status = H5D.close(dataset_id);
            long status2 = H5S.close(space_id);
            long status3 = H5F.close(file_id);
        }
    }
}

When I open the file in Python, the result is
>>> f.root.dset
/dset (Array(1, 2)) ''
  atom := Int32Atom(shape=(), dflt=0)
  maindim := 0
  flavor := 'numpy'
  byteorder := 'big'
  chunkshape := None

>>> f.root.dset[:]
array([[0, 0]])

Why is it different from the original array? I'd like know where I've made mistakes.

A:

Not sure how to do this using HDF.PInvoke but, if you are not bound to this particular library, you may want to check HDFql (as it greatly simplifies how to handle HDF5 files).
Writing an 3x3 array into an HDF5 file using HDFql in C# can be done as follows:
public Form1()
{
    InitializeComponent();

    string currentPath = Path.GetDirectoryName(Application.ExecutablePath);

    Directory.SetCurrentDirectory(currentPath);

    HDFql.Execute("CREATE TRUNCATE FILE weights.h5");

    int[,] arrInt3 = { { 1, 2, 3 }, { 3, 2, 1 }, { 3, 2, 1 } };

    HDFql.Execute("CREATE DATASET weights.h5 /dset AS INT(3, 3) VALUES FROM MEMORY " + HDFql.VariableTransientRegister(arrInt3));
}

Please check this webpage for additional examples on how to use HDFql in C#.


Q:

Por que consigo cancelar o evento onkeydown mas não consigo cancelar o onkeyup?

Abaixo tenho dois campos usando a mesma função. No primeiro campo uso o onkeydown e no segundo onkeyup:

function eventos(e){
   if(isNaN(e.key)){
      e.preventDefault();
      return;
   }
   console.log("Um número foi digitado");
}

document.getElementById("campo1").onkeydown = eventos;
document.getElementById("campo2").onkeyup = eventos;
Digite apenas números (evento keydown):

<input id="campo1">

Digite apenas números (evento keyup):

<input id="campo2">

Na função eu verifico se o que foi digitado é um número com isNaN(e.key). Se o que foi digitado não for um número, irá entrar no if, cancelar o evento e sair da função (return). Porém, apenas no evento onkeydown, caso seja digitado qualquer tecla que não seja um número, o evento é cancelado normalmente e nada acontece no input. Mas no evento onkeyup, se eu digitar uma letra, por exemplo, a letra é inserida no input.
Gostaria de saber o porquê do preventDefault() funcionar em um e não funcionar no outro evento.
Pesquisei no MDN e lá diz que o evento keyup é cancelável.

A:

Não é que o keyup não pode ser cancelado, mas quem trata que foi pressionada uma tecla é o keydown, uma vez que não cancelou o keydown isso não pode mais ser feito, e o que foi digitado já está no input.
O evento keyup é mais um evento de notificação, para avisar que a tecla que foi pressionada agora foi liberada. É executado após o keydown e keypress, e ele não pode desfazer o que foi feito nesses outros eventos.
Parece meio inútil, mas imagine um jogo, em que a tecla de tiro seja "espaço", no keypress do espaço dispara um tiro e continua atirando, até que o evento keyup aconteça, daí pode disparar uma função que faça algo, como "carregar mais tiros", só um exemplo pra pensa na funcionalidade desse evento.
Veja pelo log que o evento é cancelado, mas nada muda no input, pois o keydown não foi cancelado:

document.addEventListener('keydown', event => {
    if (typeof event.cancelable !== 'boolean' || event.cancelable) {
        event.preventDefault();
        console.log('evento cancelado, keydown');
    } else {
         console.warn('evento não pode ser cancelado, keydown');
    }
});

document.addEventListener('keyup', event => {
    if (typeof event.cancelable !== 'boolean' || event.cancelable) {
        event.preventDefault();
        console.log('evento cancelado keyup');
    } else {
        console.warn('evento não pode ser cancelado keyup');
    }
});
<input type="text" id="teste" />


Q:

Telerik ASP.NET MVC Checkbox Kendo validation

I have boolean property in my view model wit [Required] attribute.
I have
@(Html.Kendo().CheckBoxFor(m => m.AcceptTermsOfUseAndPrivacyPolicy)

$("form").kendoValidator();

in my view.
All other controls on forms validates as expected, only check box validation is not working (validation is not performed).
What I am missing?

A:

For MVC part (creating custom attribute, view and model validation)
http://blog.degree.no/2012/03/validation-of-required-checkbox-in-asp-net-mvc
For JavaScript part (custom Kendo validator):
(function($, kendo) {
    $.extend(true, kendo.ui.validator, {
        rules: {
            booleanrequired: function(input, params) {
                if ($(input).is(':checkbox')) {

                    var attr = $(input).attr('data-val-booleanrequired');
                    var req = $(input).attr('data-val-required');

                    if ((typeof req !== typeof undefined && req !== false) && (typeof attr !== typeof undefined && attr !== false)) {

                        return $(input).is(':checked');
                    }
                    return true;
                }
                return true;
            }
        },
        messages: {
            booleanrequired: function(input) {
                return input.attr("data-val-booleanrequired");
            }
        }
    });
})(jQuery, kendo);


Q:

XmlPullParserException expected end_tag

I am getting this error in android with webservice.
When i run android webservice and run android project that time this will occur
So what's problem here?
pls anyone know?
Thanks
Prashant Adesara

A:

It seems like the XML file you are trying to parse is not valid. It is missing an end tag somewhere.


Q:

Test if one of many factors improved performance

We give customer surveys and obtain millions of customer satisfaction scores every year. We have 100 measurable factors related to the scores, such as service type, date, zip code, etc. One department worked on improving one of the factors (e.g., checkout time) this year and would like to see if their work positively affected the scores. But we would like to exclude the impact of other factors. This is the method I can think of:

Create a predictive model (e.g., random forest) with the 99 factors besides the one got improved as the predictor variables, and customer satisfaction scores as the response variables.
Train the model with last year's data (before improvement), and use it to predict this year's scores.
Somehow check if the model is accurate enough (maybe hold some of last year's data to test), and check if the actual scores this year are significantly higher than the predicted ones.

Is there any standard method to do this kind of study?

A:

Your hypothesis concerns whether a particular intervention improved some performance. As stated, we need not create a prediction model necessarily. You are simply trying to estimate a conditional mean difference in the outcome under the two settings: one where the intervention is applied, and the other where it isn't. This may indeed be as simple as a plain old t-test. Controlling for other, independent determinants of the outcome, however, will increase precision (and, therefore, the power to detect if the intervention was effective).
If repeated measurements were drawn over time, then you are fitting a basic pre-post type of model using historical trends to infer the typical "intervention free" outcomes. If you implemented the intervention in an A/B setting, then there are groups of individuals representing either scenario.
In any case, there may be things influencing the observed outcome having little to do with the intervention, such as autocorrelation or secular trends. Controlling for these in a regression model allows you to make true "apples-to-apples" comparisons.
So, depending on the nature of the "influencing" factors, you can always use adjustment in a multivariate regression model.
Alternately, if there are 100s of such predictors, controlling for all of them simultaneously is impossible if the sample size is modest (perhaps, under 1000) due to multicollinearity, loss of efficiency, and other considerations. In this case, a sensible approach is using propensity score adjustment. This is a hybrid of prediction and inference. You use these 100s of predictors in a binary regression model to predict who is likely to have received the intervention and who is likely to not have, create a propensity score, and adjust for it in an analysis including the binary intervention indicator. Typically, these are still very highly collinear, so loss of power is still a consideration. The advantage of propensity score adjustment is that you may develope such scores using the machine learning techniques of feature selection to create a parsimonious model when predictors outnumber observations.


Q:

Any Framework For epub Reader

I want to make a e-book reader application for iOS. can anybody suggest me some good epub format book READER LIBRARIES?
Thanks!

A:

This might help you out for making a good ePub reader. There are many libraries as well which you can easily find out.Check this out


Q:

Combine multiple checkboxInput and checkboxgroupinput selections in a named list

I'm building a section for my app and I'm struggling to create the desired output.
I have: n checkboxInputs for my 'channels'
then i checkboxGroupInputs of parameters for each channel (identical sets)
and j checkboxGroupInputs of calculations to select for each ChannelxParameter combination.
I deliberately didn't go overboard, so I chose not to allow the user to choose different statistics per Channel * Parameter combination.
What I am looking to get as reactive output is a named list :
 1. where names are combined names of input of the Channels and Parameters: i.e. paste('Channel', 'Parameter')
 2. "values" are text strings of the selected statistics / calculations
 3. The list should only contain the names of selected channel.parameter combination
 4. Remove the list element or value from the list if the user deselects a statistic, parameter or channel
The app unit looks like this:

In this case the expected output would be a list that looks like this:
$SWS.Height
[1] "Sum" "Max"

$SWS.Total
[1] "Sum" "Max"

$FL.Red.Height
[1] "Mean"  "Stdev"

$FL.Red.Width
[1] "Mean"  "Stdev"

App:  so far only prints what is selected
library(shiny)
Channels <- c('SWS', 'FWS', 'FL.Red', 'FL.Orange', 'FL.Yellow')
Parameters <- c('Height', 'Width', 'Average', 'Total', 'Slope', 'Fill.Factor', 'Correlation.Coeff', 'Fill.Factor')
ui <- fluidPage(

  h5('Channels', style = 'font-weight:bold'),
  fluidRow(
    lapply(Channels, function(x) {
            column(2, checkboxInput(inputId = paste('Channel', x, sep = ''), label = x))
    })
 ),
 h5('Parameters', style = 'font-weight:bold'),
  fluidRow(
  lapply(Channels, function(x) {
    column(2,
           checkboxGroupInput(inputId = paste("Parameters", x, sep = ''), label = NULL, choiceValues =Parameters,
                              choiceNames = gsub('\\.', '\\ ', Parameters)) )})
  ),
 h5('Statistics', style = 'font-weight:bold'),

 fluidRow(
   lapply(Channels, function(x) {
     column(2,
  checkboxGroupInput(paste("Calculations", x, sep = ''), label = NULL, c('Sum', 'Mean', 'Stdev', 'Max', 'Coef.Var'))
 )
   })
 )
)

server <- function(input, output, session) {

  values <- reactiveValues(Statisticlist = list())
## build observer to deselect all sub category checkboxes if channel is deselected
  lapply(Channels, function(x) {
    observeEvent(input[[paste('Channel', x, sep = '')]], {
                 if(!input[[paste('Channel', x, sep = '')]]) {
                  updateCheckboxGroupInput(session, inputId = paste("Parameters", x, sep = ''), selected=character(0))
                  updateCheckboxGroupInput(session, inputId = paste("Calculations", x, sep = ''), selected=character(0))

                  }
              })
  })

   ## attempt to fill named list with selection, and remove it when deselected
  observe({
    lapply(Channels, function(x) {
     if(input[[paste('Channel', x, sep = '')]]) {
       if(!is.null(input[[paste("Parameters", x, sep = '')]])) {
         if(!is.null(input[[paste("Calculations", x, sep = '')]])) {
      print(paste(x, input[[paste("Parameters", x, sep = '')]], sep = '.'))
       print(input[[paste("Calculations", x, sep = '')]])

       # values$Statisticlist <- list(paste(x, input[[paste("Parameters", x, sep = '')]], sep = '.') = input[[paste("Calculations", x, sep = '')]])  ## what to do here....
         }
       }
     }
    })
  })
}

shinyApp(ui, server)

A:

I have come up with a solution, the NOT SO NICE part of it is, that it effectively rebuilds the entire list on ANY change. If somebody knows a cleaner way, feel free to post it.
The way I have done it is:
  lapply(Channels, function(x) {
    observe({
      if(input[[paste('Channel', x, sep = '')]] & !is.null(input[[paste("Parameters", x, sep = '')]]) & !is.null(input[[paste("Calculations", x, sep = '')]])){
        lapply(input[[paste("Parameters", x, sep = '')]], function(y) { values$Statisticlist[[paste(x, y, sep = '.')]] <- input[[paste("Calculations", x, sep = "")]]
        })
        }
    })
  })

where we loop over all the main checkboxInputs: 'Channels'
then if the Channel is selected:  if(input[[paste('Channel', x, sep = '')]])
combined with at least 1 Parameter selected: !is.null(input[[paste("Parameters", x, sep = '')]])
and at least 1 calculation selected:  !is.null(input[[paste("Calculations", x, sep = '')]]
then loop over all selected parameters lapply(input[[paste("Parameters", x, sep = '')]], function(y) {
and assign to element paste(x,y,sep= '.') of the list values$Statisticlist the selected calculations: input[[paste("Calculations", x, sep = "")]]
This basically rebuilds the entire list every time there is any change in the entire collection of checkboxes, and thus also "drops" the deselected items
P.S. I'm not sure how else to do this, but since the number of checkboxes is relatively small I don't think this will cause a problem in terms of speed.


Q:

Saving text color to a text file in python?

I am wondering, is there any way to save the color of text when printing stdout to a text file? Here is a snippet of code for example:
import sys, time, shutil

sys.stdout = open('testytest.txt', 'w')
print "\033[0;32mSome text"

time.sleep(1)

#"Some text" should still be colored when reprinted
with open('testytest.txt', 'r') as testfile:
     shutil.copyfileobj(testfile, sys.stdout)

So, once again, is there any way to save color when stdout is being saved to a text file? Or is it already saved?

A:

Well you print the escape characters as well.
So if you save the data that is printed to the stdout like:
python somescript.py > somefile

That file will contain the escape chars as well.
This to conclude: it is already saved. Instructions to modify the color actually don't exist. The program simply writes a binary stream and some shell visual programs interpret this as command to color.


Q:

Conditional Error when saving an entry in the CP cause by status

I'm experiencing a confusing problem that I've narrowed down to a custom status.
I have a status for a channel with the following options:

Open
Close
Spec
Sold

I can save an entry in this channel just fine for all statuses except for "Sold". When I save an entry with a status of Sold I get this error in the CP:
Error

You have an invalid conditional in your template. Please review your conditionals for an unclosed string, invalid operators, a missing }, or a missing {/if}.

Parser State: Invalid Condition: Not enough operands for operator ” != “.

In on line 68

Notice how the error doesn't tell me which template contains the problem.
Further, if I change the status of Sold to a lower case S as in "sold", then it works correctly and I can save the entry without getting the error.
I should also say, even though I get the error, the entry is in fact saved. I don't get any PHP errors.
To make this even stranger, I'm using MSM and I only get this error on the default site, not the other two which use the same templates and statuses. This makes me suspect the error message isn't accurate.
I'm using EE2.10.1. Thanks for you help in advance.

A:

I didn't get a complete fix for this problem, but I figured out a work around. Basically, I changed my status to a lower case "sold" and then changed this in the database for all entries with this status. Doing this eliminated the error.
I doesn't answer the question of why an uppercase S was causing this error, but I at least got it working again.


Q:

Largest solution of a linear system

Given an $n\times m$ matrix $A$ of full-column rank, and a vector $\vec b$ of size $n$.
We consider the solution of the linear system:
$$
A\vec{x}=\vec{b}
$$
Since $A$ is full-column rank, the solutions of the linear system are bounded. Is it possible to get an upper bound on the norm of these solutions ?

A:

Suppose that $A\vec{x}=\vec{b}$ is solvable.
Unless $A$ has full column rank, the system $A\vec{x}=\vec{b}$ has infinitely many solutions. The set
$$
\{\lVert\vec{x}\rVert:A\vec{x}=\vec{b}\}
$$
turns out to be bounded below, but not above. In fact, it is possible to prove that
$$
\inf\{\lVert\vec{x}\rVert:A\vec{x}=\vec{b}\}=\lVert\vec{x}^+\rVert
$$
Here, $\vec{x}^+=A^+\vec{b}$ where $A^+$ is the Moore-Penrose inverse or pseudoinverse of $A$. The vector $\vec{x}^+$ also satisfies $A\vec{x}^+=\vec{b}$.
Note that this is true regardless of the rank of $A$.
To convince yourself that $\{\lVert\vec{x}\rVert:A\vec{x}=\vec{b}\}$ is not bounded above, consider
\begin{align*}
A &= \left[\begin{array}{rrr}
1 & 0 & 0 \\
0 & 1 & 0
\end{array}\right] & \vec{b} &= \left[\begin{array}{r}
0 \\
0
\end{array}\right]
\end{align*}
The solutions to $A\vec{x}=\vec{b}$ are  of the form
$$
\vec{x}
= \left[\begin{array}{r}
0 \\
0 \\
c
\end{array}\right]
$$
for $c\in\Bbb R$.


Q:

In android: I want to check the service running or not if already running change the UI colors when i launch

In my android application have check the whether the service run or not if running i want to change the UI color. I use the following code
    if(true==util.isMyServiceRunning(getApplicationContext())){

    makeUIChangesforTurnOn(true);
    }

but it showing the error that..
09-09 00:53:26.810: E/AndroidRuntime(1106): FATAL EXCEPTION: main 09-09 00:53:26.810:
E/AndroidRuntime(1106): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.param.calltracker/com.param.calltracker.MainActivity}:java.lang.NullPointerException
09-09 00:53:26.810: E/AndroidRuntime(1106):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at android.os.Looper.loop(Looper.java:130)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at android.app.ActivityThread.main(ActivityThread.java:3687)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at java.lang.reflect.Method.invokeNative(Native Method)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at java.lang.reflect.Method.invoke(Method.java:507)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at dalvik.system.NativeStart.main(Native Method)
09-09 00:53:26.810: E/AndroidRuntime(1106): Caused by: java.lang.NullPointerException
09-09 00:53:26.810: E/AndroidRuntime(1106):     at com.param.calltracker.MainActivity.makeUIChangesforTurnOn(MainActivity.java:214)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at com.param.calltracker.MainActivity.onCreate(MainActivity.java:79)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-09 00:53:26.810: E/AndroidRuntime(1106):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)

my UI change code>
   public void makeUIChangesforTurnOn(Boolean on){
    if(on){
        trun_on_off_img.setImageResource(R.drawable.green_signal);
        buttonToggleDetect.setBackgroundResource(R.drawable.orenge_button);
        buttonToggleDetect.setText("Turn off");
        textViewDetectState.setText("Monitoring Calls");
                textViewDetectState.setTextColor(getResources().getColor(R.color.green));

    }else{
        trun_on_off_img.setImageResource(R.drawable.yellow_signal);
        buttonToggleDetect.setBackgroundResource(R.drawable.green_button);
        buttonToggleDetect.setText("Turn on");
        textViewDetectState.setText("Not Monitoring Calls");
        textViewDetectState.setTextColor(getResources().getColor(R.color.orenge));

    }
}

any one help me...

A:

Follow this code :
private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager
                .getRunningServices(Integer.MAX_VALUE)) {
            if (YourService.class.getName().equals(
                    service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

Call this method in your activity like below :
      makeChangesInUI(isMyServiceRunning())


Q:

PHP For Loop Count in While Statement

I'm trying to figure out the best solution on how to output my html with the php while counting up on a div class.
This is my function that prints news:
function post_news()
{
    $post_news = $this->mysql->Query("SELECT * FROM news ORDER BY id DESC LIMIT 4");
    while ($news_row = mysqli_fetch_array($post_news))
    {
        echo "

".$news_row['title']."

".$news_row['content']."

            Read More

";
    }
}

What I am attempting is, where it shows
 I need it to count upward to class='column4'. When I attempt For loops or a second While loop I can sometimes get it to count but it always does a new line where I want these blocks to display side by side like normal.
So what is the best way to count up on my div class without it doing a line break after every block?

A:

I assume that when you say 1 to 4 you want it to start over at 1 after 4.  Just increment a counter and reset it when it reaches 4:
$num = 0;
while ($news_row = mysqli_fetch_array($post_news))
    {
        $num++;
        echo "

".$news_row['title']."

".$news_row['content']."

            Read More

";
        if($num == 4) { $num = 0; }
    }

Or actually, you use LIMIT 4 in the query so you don't really need the if statement that resets it to 0, as the loop will only iterate 4 times.


Q:

toolbar icons are not being displayed in tinymce (4.0.1) text editor

I'm upgrading tinyMCE from 3.4.2 to 4.0.1. Everything works perfect locally. But problem started when I published everything at server. Toolbar loads fine but the icons are not showing properly. Note: I have separate projects for app and CDN. I'm guessing this is a cross-domain/url reference issue but unable to figure it out. Currently the toolbar is loading as shown in the - screencast!
    tinyMCE.init({
// General options
theme: "modern",
editor_selector: "mceDesignerEditorAutoresize",
relative_urls: false,
convert_urls: false,
toolbar1: "cut copy paste | bold italic | undo redo | bullist numlist | outdent indent blockquote | link unlink image code | inserttime preview | forecolor backcolor | imgCustom attachCustom",
toolbar_items_size: 'small',
plugins:  [
    "autoresize advlist autolink lists link image charmap print preview hr anchor pagebreak",
    "searchreplace wordcount visualblocks visualchars code fullscreen",
    "insertdatetime nonbreaking save table contextmenu directionality",
    "emoticons template paste textcolor"
],
accessibility_warnings: false,
accessibility_focus: false,
setup: function (ed) {
    ed.addButton('imgCustom', {
        title: 'Image',
        image: $("#jsTinyMCEImageUrl").val().toString(),
        onclick: function () {
            openModalPopup($("#jsTinyMCEImagePath").val(), "width=700,height=600");
        }
    });
    ed.addButton('attachCustom', {
        title: 'Attachment',
        image: $("#jsTinyMCEAttachUrl").val().toString(),
        onclick: function () {
            try {
                openModalPopup($("#jsTinyMCEAttachPath").val(), "width=400,height=200");
            }
            catch (e) {
            }
        }
    });
},
language: $('#TinyMCECurrentLanguage').val(),
paste_auto_cleanup_on_paste: true

});

A:

It is found that /js/tinymce/skin/lightgray/fonts folder was not being copied to server. This happened as Visual Studio didn't recognize the font files and marked them as 'None' in Build Action and as a result these files were not being published.
Solved it by right clicking the font files, select Properties and Set value for Build Action to 'Content'.


Q:

How to change icon on NSToolBarItem print

Is there a way to change icon on NSToolBarItem print? The setter for this is available via InterfaceBuilder but if I change it - it changes only in Interface Builder but not in working project. I tried to change it from code - but the same result. I have default print icon both cases. Thanks.

A:

If this can not be changed what you can create your own toolbar item that will work for as Print.
Set new image for the toolbar button, and give Label and Palette Label, I have used My Print.

Now you need to hook  Print menu and Toolbar item's to a method, I have a method called print in the AppDelegate.


Q:

Wordpress: Search results only in one category

I'm using this code for making sure that the search results show only results from one category. It works very well, but the side-effect is that in the back-end on the All posts page a search gives also only results from that same category. How can I make sure it works at the front-end but not the back-end?
//EXCLUDE CATEGORIES FROM SEARCH RESULTS
function SearchFilter($query) {
if ($query->is_search) {
$query->set('cat','1');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');

A:

Well, this is a common issue and the solution is simple:
To avoid this our add_filter should be executed only in frontend. A simple way to do that is using the function is_admin that is a boolean function. So:
function SearchFilter($query) {
  if ($query->is_search) {
    $query->set('cat','1');
  }
  return $query;
}
if(!is_admin())
  add_filter('pre_get_posts','SearchFilter');

Is that it?


Q:

cross apply in sql server

recently i was having a problem in my stored procedure, it was working too slow, so one of my colleague suggested cross apply, he said that cross apply work as inner join but without the need of comman key between the table.
my senario is i have three tables crossarticle_article and crossarticle_articletocategory, and crossarticle_article
now i want to retreive all the records whose categoryid is 4, categoryid are stored in crossarticle_articletocategory
as much i understood, i created below query for it:
SELECT *
FROM   crossarticle_article c
       CROSS APPLY
crossarticle_articletocategory cc1
CROSS APPLY
crossarticle_category cc2
WHERE  cc2.id = 1

this query should return only records from crossarticle_article where category id matches 1
but it returns all the records from all 3 tables.
where i am going wrong,
if this is not the way of using cross apply then how to use, and whats the advantage of it.
is it that cross apply works with same tables... if so than what could be the scenario...

A:

Assuming id is the key field in all tables, The Query should be:
SELECT c.*,
       c1.colXXX,
       c2.colYYY --ALL columns  u need
FROM   crossarticle_article c
       CROSS APPLY(
    SELECT cc1.colXXX
    FROM   crossarticle_articletocategory cc1
    WHERE  cc1.id = c.id
) c1
CROSS APPLY(
    SELECT cc2.colYYY
    FROM   crossarticle_category cc2
    WHERE  cc2.id = c.id
) c2
WHERE  c.id = 4


Q:

Does functools.wraps have the undecorated reference?

#!/usr/bin/python

from functools import wraps
def logged(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print func.__name__ + " was called"
        return func(*args, **kwargs)
    return with_logging

@logged
def f(x):
   """does some math"""
   return x + x * x

I want to know if wraps has the undecorated reference to the function f? I don't see it when I tried dir(f)

Modified version
#!/usr/bin/python

from functools import wraps
def logged(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print func.__name__ + " was called"
        return func(*args, **kwargs)
    with_logging.undecorated = func
    return with_logging

@logged
def f(x):
   """does some math"""
   return x + x * x

f.undecorated

No attribute? I was merely following what I used to do with decorator...

A:

There is a reference to the original f in there, but it's messy to get to.
>>> f
<function f at 0x023F6DF0>
>>> f.func_closure[0].cell_contents
<function f at 0x023F6E30>

The first is the wrapped f, the second is the original f, notice the hex addresses are different.
If you need access to the original f, I suggest you wrap it differently:
def f(x):
   """does some math"""
   return x + x * x
original_f = f
f = logged(f)

Now you have f and original_f, both usable.


Q:

Email subscription in android

I have a subscribe button in the about us section in my app. On pressing, a small window appears asking for email from a user. Once the user enters his email where could I store all the emails from the users? How does email subscription is implemented in Android? I'm totally new to it, so please be detailed

A:

I think you would need a server where you can store in a DB the emails the clients (i.e. the apps) send you. Or since it's such a simple thing that you have to store (a string), what you could do is get them to send an email to you, and then voila, you have the addresses you need.
EDIT:
Try parse, it's a cloud server free and easy to use.


Q:

The Ability to Hide Questions

I was wondering how hard it would be to enable a 'hiding' option that let me hide certain questions that I don't want to see. That way if it was a very active question that I have no interest in, I could simply click hide and not see it anymore.
The only foreseeable reason why this couldn't be implemented completely with a Greasemonkey script is that it would be nice to get replacement posts. As of right now, even the hide tag feature simply hides the questions after they were loaded. If I hid a lot of tags, I would end up getting very few questions on the home page.
This is, of course, due to caching.

A:

I have written a simple GreaseMonkey script which will do this for you.  Just replace the ids with the ids you wish to hide, and it will remove these questions from the questions page.  This is my first GM script, so if you find bugs in it, please let me know.  I will try to make it a bit more user friendly, but this does work (on my comp anyway).
// ==UserScript==
// @name           Hide questions
// @namespace      http://stackoverflow.com/
// @include        http://meta.stackoverflow.com/questions
// ==/UserScript==
//

//************************************
//* Replace the numbers in brackets  *
//* with the ids of the questions    *
//* That you wish to hide            *
//************************************
var hiddenQs = new Array( 7609, 7598 );

var questionDivs = "//div[@class='question-summary']";
//define a search function for arrays
Array.prototype.findIndex = function(value){
var ctr = "";
for (var i=0; i < this.length; i++) {
if (this[i] == value) {
return i;
}
}
return -1;
};

function getQuestions () {
    return document.evaluate( questionDivs, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
}

var questions = getQuestions( );
var curQuestion, qID;

for (var i=0; i < questions.snapshotLength; i++) {
    curQuestion = questions.snapshotItem( i );
    qID = curQuestion.id.split('-')[2];
    if (hiddenQs.findIndex( qID ) != -1) {
        curQuestion.parentNode.removeChild( curQuestion );
    }
}

A:

It just hit me when I first noticed that I was constantly browsing through the same question over and over on the main page. My mind had dismissed them, but the UI did not let me.
Of course I can browse further elsewhere, but I feel I should be able to hide questions with a button right on the main page if I'm not interested (anymore), and possibly end up with a higher percentage of interesting questions on my main page.
Also, I wish there was a search for "open, unread, not hidden, not ignored tags questions", to show me those slightly older questions I haven't tackled yet. I mean there are 23000 questions, and I constantly see the same 25-30 over and over because people are commenting and answering on these.


Q:

How to make Tax Category field in AP Invoice line required and still update detail total and balance

I am trying to make a field required on the line item of an AP Invoice, the Tax Category field. However when I change the field to be required I run into the problem of the detail total and the balance to no longer update on the form.
What I've tried doing is eliminating the PersistingCheck = PXPersistingCheck.Nothing of the PXDefault attribute of the TaxCategoryID. This causes the field to be required on the form, however as I've stated, it also causes the form to no longer update totals. I've tried changing the PersistingCheck to PXPersistingCheck.Null, but this also prevents the totals from being updated.
Originally the PXDefault attribute for the Tax Category field is as follows:
[PXDefault(typeof(Search<InventoryItem.taxCategoryID,
      Where<InventoryItem.inventoryID, Equal<Current<APTran.inventoryID>>>>),
      PersistingCheck = PXPersistingCheck.Nothing)]

This is what my code is:
[PXDefault(typeof(Search<InventoryItem.taxCategoryID,
     Where<InventoryItem.inventoryID, Equal<Current<APTran.inventoryID>>>>))]

What I want is to be able to have the Tax Category field required and the totals to be updated as usual, but I am not able to due to something in the code preventing the totals to be updated when the PXDefault attribute of the Tax Category field is changed.
Is there anything additional I must do in order for these issues to be resolved or am possibly going about this the wrong way?

A:

You need to correctly change the PersistenceCheck and add Required=true to PXUIFieldAttribute for showing a red asterisk symbol near the column's name. Please see the example of how to do that using PXMergeAttributesAttribute and PXCustomizeBaseAttribute:
public class APInvoiceEntry_Extension : PXGraphExtension<APInvoiceEntry>
{
    #region Event Handlers
    [PXMergeAttributes(Method = MergeMethod.Merge)]
    [PXCustomizeBaseAttribute(typeof(PXUIFieldAttribute), nameof(PXUIFieldAttribute.Required),true)]
    [PXCustomizeBaseAttribute(typeof(PXDefaultAttribute), nameof(PXDefaultAttribute.PersistingCheck), null)]
    protected virtual void APTran_TaxCategoryID_CacheAttached(PXCache cache)
    {

    }
    #endregion
}


Q:

How to setup cocos2x console tool path?

I setup cocos2d-x as outlines here: http://www.codeproject.com/Articles/801093/Writing-Games-with-Cplusplus-for-Android-on-a-Mac
Setup.py had all the expected output,

./setup.py
Setting up cocos2d-x...
  ->Check environment variable COCOS_CONSOLE_ROOT   ->Search for environment variable COCOS_CONSOLE_ROOT...
      ->COCOS_CONSOLE_ROOT is found : /Users/john/Documents/Projects/Cocos2d/cocos2d-x-3.5/tools/cocos2d-console/bin
->Check environment variable COCOS_TEMPLATES_ROOT   ->Search for environment variable COCOS_TEMPLATES_ROOT...
      ->COCOS_TEMPLATES_ROOT is found : /Users/john/Documents/Projects/Cocos2d/cocos2d-x-3.5/templates
->Configuration for Android platform only, you can also skip and manually edit "/Users/john/.bash_profile"
->Check environment variable NDK_ROOT   ->Search for environment variable NDK_ROOT...
      ->NDK_ROOT is found : /Users/john/Documents/Projects/Android/android-ndk-r9d
->Check environment variable ANDROID_SDK_ROOT   ->Search for environment variable ANDROID_SDK_ROOT...
      ->ANDROID_SDK_ROOT is found : /Users/john/Documents/Projects/Android/adt-bundle-mac-x86_64-20140321/sdk
->Check environment variable ANT_ROOT   ->Search for environment variable ANT_ROOT...
      ->ANT_ROOT is found : /Users/john/Documents/Projects/ANT/apache-ant-1.9.4/bin
Please execute command: "source /Users/john/.bash_profile" to make
  added system variables take effect

but I cannot run cocos directly:
Eg: cocos
I always have to type the full path:
Eg:
/Users/john/Documents/Projects/Cocos2d/cocos2d-x-3.5/tools/cocos2d-console/bin/cocos

As a result, I cannot run ./build_native.py etc for generating my android build because it errors out saying : sh: cocos: command not found
I ran the "source /Users/john/.bash_profile" command that setup.py said I should but it makes no difference.
How do I rectify this ?
(Cocos2dx 3.5)
EDIT:
When I type: "export" in the terminal, I cannot find any lines for setting the environment variables for:
NDK_ROOT
COCOS_CONSOLE_ROOT

How do I rectify this ?

A:

I added cocos console root to the bash_profile manually.
Here how I did :
In Terminal, type:
open ~/.bash_profile

It will be opened within TextEdit.
Add these lines :
export COCOS_CONSOLE_ROOT=/Users/barisatamer/Documents/workspace-game/Engine_Source/cocos2d-x-3.4/tools/cocos2d-console/bin
export PATH=$COCOS_CONSOLE_ROOT:$PATH


Q:

Kullback-Leibler divergence and mixture distributions

Let's say I have three probability densities, $h, g$, and $f$, where f is a weighted mixture of h and g, i.e.,
$$ f(x) = w\,h(x) + (1-w)\,g(x) $$
For simplicity, let's assume all densities share the same support.
Now, it seems reasonable to expect that if, say, $h$ is the "true" density, then the Kullback-Leibler divergence (KL) between $f$ and $h$ should be smaller than KL between $g$ and $h$, i.e.,
$$ KL(f,h) \leq KL(g,h) $$
as $|f(x) - h(x)| \leq |g(x) - h(x)|$ everywhere.
However, I have no idea how to prove this, and would be very happy about any suggestions (or suggestions why my intuition might be wrong).
Thanks in advance!

A:

It just came to my mind that this follows immediately from the convexity of KL divergence. It's hard to find info about it on the web, but page 6 here
http://camo.ici.ro/journal/vol11/v11d15.pdf
describes everything you need in terms of discrete relative entropy $D_\text{KL}$ (the very same concept).
In your case,
\begin{align*}
\text{KL}(h,f)
&= \text{KL}(w \cdot h + (1-w) \cdot h, \ w \cdot h + (1-w) \cdot g) \\
&\leq w \cdot \text{KL}(h,h) + (1-w) \cdot \text{KL}(h,g)
= (1-w) \cdot \text{KL}(h,g)
\end{align*}
and summarized
$$\text{KL}(h,f) \leq(1-w) \cdot \text{KL}(h,g)$$
which is an even stronger inequality than what you asked for.

My previous text: Not a full answer but my thoughts.
So you want to show
$$\text{KL}(h,f) \leq \text{KL}(h,g)$$
or rather
$$\int_\mathbb{R} h(x) \log \frac{h(x)}{w \ h(x) + (1-w)g(x)} dx
\leq  \int_\mathbb{R} h(x) \log \frac{h(x)}{g(x)} dx$$
\begin{align*}
0 &\leq  \int_\mathbb{R} h(x) \log \frac{w \ h(x) + (1-w)g(x)}{g(x)} dx \\
0 &\leq  \int_\mathbb{R} h(x) \log\left(1-w + w\frac{h(x)}{g(x)}\right) dx
\end{align*}
Now this cannot be easy to show directly because the proof for positivity of KL-divergence (a.k.a. relative entropy) between distributions is already quite long and tricky. You could carefully read proofs of said theorem and try to adapt them to the problem at hand.
Alternatively, you could rewrite the above to
\begin{align*}
0 &\leq  \int_\mathbb{R} h(x) \log \frac{h(x)}{a_w(x)} dx = \text{KL}(h,a_w)
\end{align*}
with
$$a_w(x) := \frac{1}{\frac{w}{g(x)} + \frac{1-w}{h(x)}} \ .$$
If you can show that $a_w(x)$ is a probability distribution $\forall w \in [0,1]$ (maybe it isn't, I don't know), then $0 \leq \text{KL}(h,a_w)$ and you're done.


Q:

Shell Scripting : Unable to scp output to log file

In My Shell Script I am trying to push the scp output to a log file.Below is the code snippet.On Command line I can see the logs but The scp logs are not pushed into the file .What can be the reason ?
FTP_LOG = "Log.txt"
scp -v ${feedFile} ${USER}@${DESTINATION}:inbox >> ${FTP_LOG}

Please help me on this as I can see that there are other people who faced the same issue when I google.
The other issue is that the last returned code after scp command doesnt really say if the file transfer was a success.Even when the file transfer fails I get the last return code as indicatng success.

A:

-v outputs to STDERR not STDOUT. You want 2>> not >>


Q:

DataContext accessed after Dispose in render pages/controls

I'm randomly getting "DataContext accessed after Dispose" errors but only on aspx and ascx pages/controls.  Is there a general rule that I shouldn't be calling methods inline on pages that use datacontexts?
I'm presuming by the time the page renders and calls the method the datacontext has already been disposed?
e.g. on default.aspx
<%= CurrentContent.GetText("Intro") %>

CurrentContent is actually a database object referred to in default.aspx.cs

A:

assuming you are using it like this
using (MyDbContext ctx = new MyDbContext())
{
    return from r in ctx.Table select r;
}

Deferred execution is what is happening to you.  That query does not execute right then and there, and is only running when the returned enumerator is finally used - which in this case, is after the using block disposes of your context.  If you want to be sure this doesn't happen, either change your query pattern to
using (MyDbContext ctx = new MyDbContext())
{
    return (from r in ctx.Table select r).ToList();
}

or change your disposal methods.  I tend to like tying the lifetime of my context to the enclosing object, which in your case would be the ASP.NET Page object.  Make the context a member variable and dispose of it in the Page.Dispose


Q:

Comma operator with typeid

I was studying A Generic Non-intrusive Smart Pointer Implementation. I have some confusion in section 4. One statement is

the expression supplied as the argument to the typeid operator is only evaluated if the result type is an lvalue of polymorphic class type.

And associated example code is:
template<typename T>
  void* startOfObject(T* p) {
  void* q=static_cast<void*>(p);
  typeid(q=dynamic_cast<void*>(p),*p); // This line
  return q;
}

AFAIU, it means q=dynamic_cast<void*>(p) will be evaluated if the result type is an lvalue of polymorphic class type. The result means the result of evaluating dynamic_cast<void*>(p) (I guess), so the dynamic_cast has to be applied in any case. The articles states (as I understand) that if p is not polymorphic then dynamic_cast will not be applied, but why? Before applying it, how can it be known whether the result is polymorphic or not? It will be helpful if someone describes in details how the full statement will be executed.
Another statement is

There is also a problem if p is NULL – the typeid will throw a std::bad cast.

The problem I see is with de-referencing if p is NULL, not with typeid (although it may throw bad_typeid, but that is not because of casting). dynamic_cast will return a NULL pointer of type void* if p is NULL, and typeid should be able to deduce the type information. Is that a typo, or am I missing something?

A:

It's a fancy trick to write essentially the following code
if (T is polymorphic)
  return dynamic_cast<void*>(p);
else
  return static_cast<void*>(p);

The trick used is that typeid(expr) is evaluated in one of two ways. If the compiler determines that expr has a non-polymorphic type, it goes ahead and uses its static type. But if expr has a dynamic type, it evaluates expr at runtime. The assignment before the comma operator is therefore evaluatad if and only if *p after the comma is polymorphic.
The null case is complex for that reason. If T is not polymorphic, then typeid(*p) is replaced by the compiler at compile time, and the runtime null pointer doesn't matter at all. If T is polymorphic, special handling of null pointer dereferences applies, and that special handling states that a std::bad_typeid exception is thrown.

A:

The comma operator has left-to-right associativity and is evaluated from left to right. That means the result of the expression q=dynamic_cast<void*>(p),*p is *p. So the dynamic cast is only evaluated if the type of *p is polymorphic.
Regarding the NULL problem the standard states:

When typeid is applied to an lvalue expression whose type is a
  polymorphic class type (10.3), the result refers to a type_info object
  representing the type of the most derived object (1.8) (that is, the
  dynamic type) to which the lvalue refers. If the lvalue expression is
  obtained by applying the unary * operator to a pointer and the pointer
  is a null pointer value (4.10), the typeid expression throws the
  bad_typeid exception (18.5.3).

A:

Explanation
Since C++ is a statically typed language the type of every expression is known at compile-time, even in cases that involves polymorphic behavior.
Whether a certain class is polymorphic or not is known at the time of compilation, this property will and cannot be changed between program executions.
If the compiler sees that the expr in typeid(expr) will not yield a value of polymorphic class type, it will simply make expr "unevaluated", which is equivalent of not executing it during run-time.

! ! !
It is important to note that the expr must still be valid, we cannot use typeid to potentially ignore a ill-formed expression; a compiler diagnostic must still be issued if the expression is ill-formed.
Just because the expr will be "unevaluated" does not mean that we can have it contain an ill-formed sub-expression.
struct A { }; // not polymorphic

...

A * ptr = ...;
typeid (dynamic_cast<void*> (ptr), *ptr); // ill-formed

Since ptr is not a pointer to a polymorphic class we cannot use it in dynamic_cast<T> where T = void*, as specified in [expr.dynamic.cast]p6.

Dereferencing a potential nullptr?
This will make typeid throw an exception, so it will not yield undefined behavior but one should be prepared to handle an exception if one uses such implementation.

5.2.8p2 Type identification [expr.typeid]

(...) If the glvalue expression is obtained by applying the unary * operator to a pointer and the pointer is a null pointer value (4.10), the typeid expression throws an exception (15.1) of a type that would match a handler of type std::bad_typeid exception (18.8.3)

Clarification

It means q=dynamic_cast(p) will be evaluated if the result type is an lvalue of polymorphic class type. The result means the result of evaluating dynamic_cast(p) (I guess).

No, what the author is saying is that if the resulting type of the entire expression is a polymorphic class type, than the expression will be evaluated.
Note: The "entire expression" refers to the ... in typeid(...), in your case; q=dynamic_cast<void*>(p),*p.

The Comma Operator
The comma operator will take two operands expr1 and expr2, it will start off by evaluating expr1 and then discard this value, after which it will evaluate expr2 and yield the value of this expression.

How does the comma operator work?

Putting it together
This means that the resulting type of using a comma operator is as if it only consisted of the right-hand-side expression, and in the following line the compiler will check so that the result of expr2 is a type which is a polymorphic class.
typeid (expr1, expr2)

typeid (q=dynamic_cast<void*>(p), *p)

// expr1 = q=dynamic_cast<void*>(p)
// expr2 = *p

Note: In C++03 the resulting type had to be a polymorphic lvalue, in C++11 this has been changed to glvalues of polymorphic class type.


Q:

$f_n$ measureable $\implies$ $m\left(\bigcap_{k=0}^\infty F_k\right)=0$

I have that $f_n$ is measurable on a finite measure space.
Define $F_k=\{\omega:|f_n|>k \}$
$F_k$ are measurable and have the property $F_1 \supseteq F_2\supseteq\cdots$
Can I then claim that $m\left(\bigcap_{n=1}^\infty F_n\right) = 0$?

A:

If $f$ is real valued, $\cap F_k$ is empty. so its measure is zero.


Q:

React cannot read setState of undefined

I am trying to update the state by making api call in componentDidMount phase .
I need to do is to display the name of users . Few names are set in initial state which are working fine . Then i need to append more users which is returned by hitting a get api .
Pseudo code:
export class UserDetails extends Component {
constructor(props) {
    super(props);
    this.state = {
        users: [
            {
              id: 1,
              name: "aditya"
            }
        ]
    };
}
componentDidMount() {
    this.jsonList();
}

jsonList() {
    axios('https://api.myjson.com/bins/1fwkrw').then(function(response) {
        this.setState((prevState) => {
            {users: users.push(response.data.userdata)};
        });
    })
}

render() {
    return (

            {this.state.users.map(user => {
              return (

{user.name}

              )
            })}

    );
}
}

But here i am getting error "Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined" . Any help where i am going wrong ?

A:

Either change jsonList to an arrow function:
jsonList = () => {
    axios('https://api.myjson.com/bins/1fwkrw').then(function(response) {
        this.setState((prevState) => {
            {users: users.push(response.data.userdata)};
        });
    })
}

Or bind the method inside the constructer :
constructor(props) {
    super(props);
    this.state = {
        users: [
            {
              id: 1,
              name: "aditya"
            }
        ]
    };
   this.jsonList = this.jsonList.bind(this);
}

The way you wrote it, jsonList is not binded correctly , therefore - you cannot use this.setState since this is undefined .


Q:

Does power bi embedded bookmarks take a snapshot of the data?

I was wondering if the bookmarks captures a snapshot of the data?  For example, if the datasource updates the data, will that be reflected in the bookmark or would it display the chart based on the dataset at the time the bookmark was created?
Thanks,
Derek

A:

Power BI Embedded bookmarks, as well as Power BI bookmarks in powerbi.com, do not capture the data itself rather the visual & report configurations that manipulate the data.
Bookmarks contain visual locations & visibility, filter state & navigation between report pages.
This way you can keep the data updated and refreshable.


Q:

inquality question

I was just asked the following question(not on this website but by a friend):

$A = 2015x^2 + 2015y^2 + 6z^2$
$ B = 2(2012xy + 3yz + 3zx)$
Which is correct?

A > B

B > A

A = B

Relationship cannot be determined

I don't understand how you can compare the two unless it was in reference to something measurable like perimeter, area or volume.  So should the answer be relationship cannot be determined?

A:

Edit : Method 2
The following expression is positive (sum of squares)
$$\frac{4027}{2}(x-y)^2+\frac{3}{2}(x+y-2z)^2$$
You can expand it and find it is equal to
$$\frac{4027}{2}(x^2+y^2) - 4027xy + \frac{3}{2}(x^2+y^2)+6z^2-6zx-6zy+3xy$$
$$ \frac{4030}{2}(x^2+y^2)-4024xy+6z^2-6zx-6zy$$
This is exactly equal to $A-B$. Hence $A\geq B$
Method 1:
Matrix of quadratic form $A-B$ is
$$\begin{pmatrix} 2015 & -2012 & -3 \\ -2012 & 2015 & -3 \\ -3 & -3 & 6\end{pmatrix}$$
It has eigenvalues $0$, $9$ and $4027$, that is to say positive. Hence $A>B$ (well actually $A\geq B$ because of $0$ eigenvalue) (matrix are symmetric)
Note 1 : writing $A>B$ makes perfect sense if $A$ and $B$ are real polynomials and if the inequality holds for all $x,y,z$. If $A$ and $B$ are symmetric matrixes, $A>B$ means $A-B$ is positive matrix.
Note 2 : if you are not familiar with quadratic forms, you can always write some equation such that $a x^2 + b y^2 + 2 c x y$ using expression $(x \quad y) \begin{pmatrix} a & c \\ c & b\end{pmatrix} (x\quad y)^T$ (same for 3 dimensions with 3x3 matrix). The polynomial is positive if the matrix in the middle is positive. Being positive for a symmetric matrix means all its eigenvalues are positive.


Q:

What exactly is a PAR type LED lamp, how does it differ from R/BR type LED & CFL lamps?

I am in the process of replacing my incandescent bulbs with more efficient alternatives. My home is about 14 years old, I've owned it for a little over three years. It seems most of the bulbs that it "came with" are original, and since I purchased the house almost every tungsten bulb in a built-in fixture ended up burning out. In particular were the R40 ceiling floods, of which I have 16 in total in the interior. I'd ignored many of them, as I rarely turned most of them on, however when three in my kitchen burned out within a weeks period, I up and replaced the whole lot with EcoSmart (made by Lighting Science) R30 CFL's that offer around 800 lumens.
The initial difference was HUGE. The 14 year old bulbs were extremely dim and VERY orange in color. The CFLs, when fully warmed up, are very nice and bright. I chose cooler colors (3500k and 5000k) which light the place much more naturally (at least to my eyes). The caveat with CFL, as I am learning, is they do not perform well in cooler temperatures. I try to use my heater as little as possible in the winter, generally only heating when the interior temperature drops below 60-64 degrees. All of the CFL R30s I purchased have a common problem, which seems to be common across brands as I've tried TCP, Phillips, and others: Very long warmup time, very low lumens during warmup, and an extreme magenta hue during warmup. The bulbs also do not seem to reach full brightness, and the way the reflectors are designed, the shape of the spiral inside the R30 "can" is clearly visible and appears rather dark.
I've decided to switch to LED, despite the cost. In trying out a few from the local store, they seem far superior to CFL. They start instantly, always produce the same color, are fully dimmable (and seem to dim smoothly unlike CFL), and don't seem to be affected by temperature. I've only ever used R or BR type, however all of the ones at the local store in the color temperatures I prefer are PAR type. The BR type LED floods seem to produce similar quality and diffused light to the CFL's, but the only color I can find are 2700K. What exactly is the difference between an R/BR type flood and a PAR type flood? Additionally, what are the differences between PAR30, PAR38, etc? Are PAR type good for indoor use (in the past, I'd only ever seen a few mentions that PAR type were required for outdoor scenarios, indicating they were better sealed against weather)?

A:

Due to the lack of adequate answers, I decided to research the differences myself and provide an answer to the benefit of the community.
PAR Type Lamps
From a build quality and light control standpoint, PAR type lamps are generally considered superior. The explicit parabolic nature of the reflector means light is more precisely reflected directly out of the bulb cavity, with less dispersion, than an R or BR type lens. PAR type lamps, thanks to the design of the lens in front of the actual light emitting element (which is usually a given with home lighting...PAR in general can referr to a very wide variety of lighting which may or may not have a front lens, including high powered stage lighting). The lens is often fresnel in nature, are often additionally capable of focusing the more accurately reflected light into a brighter, narrower spot. The fact that they have a more precisely crafted lens means they are capable of being designed to emit beams of varying angular degrees wide (anywhere from 12° to 70°), with high intensity narrow beams or more diffuse wider beams, makes them highly flexible.
PAR type lamps are also frequently designed in such a way that makes them viable for outdoor use. Not all PAR type lamps are properly sealed for use in humid climates or areas where rain or other water could intrude upon the bulb, but many PAR type lamps are. This is a key difference between PAR and R or BR type lamps.
In terms of nomenclature, PAR lamps are usually designated with a number. The number of a PAR lamp, such as PAR38, gives the diameter of the lamp in inches. In the case of a PAR38, the diameter would be 4.75" (4 3/4"), or "thirty eight eighths of an inch." Common PAR lamp sizes for home are PAR20, PAR30, PAR38, with the latter being most common.
R Type Lamps
One of the more common types of flood light lamps for use indoors, the R-type lamp is a more cheaply constructed "reflector" type lamp. They are not particularly efficient in any key respect, their design is roughly defined and there are no strict rules or guidelines regarding the reflector. As such, R-type lamps generally produce a highly diffuse light with a broad angle.
They use a similar nomenclature as PAR type bulbs. For example, an R40 is a bulb 40/8ths of an inch in diameter, or 5". The two most common R-type lamp sizes are R40 and R30.
BR Type Lamps
Preceding the CFL and LED age of high efficiency lighting, the BR-type lamp was an attempt to produce a more efficient indoor-use only replacement for R-type lamps. Standing for "bulbous reflector", the design of a BR-type lamp is more strict. The reflector is designed in such a way as to more efficiently reflect light. They still produce fairly soft, diffuse light, however it is reflected in a narrower beam, thus more efficiently utilizing light produced by the internal emitter (filament, LED, or CFL spiral.)
They too use the same eighth-inch nomenclature as PAR and R type lamps. The most common sizes are BR40 and BR30.
CFL and LED R, BR, and PAR type lamps
While the core design of these types of lamps was implemented in the days of tungsten-filament (incandescent and halogen) bulbs, the design is still used for CFL and LED lamps. In the case of CFLs, the actual reflector efficiency is likely suspect (at least in the case of a PAR type lamp), as the design of a PAR lamp, and thus it's efficiency in utilizing light, is dependent on the size and location of the internal emitters. CFL spirals are usually used in CFL-based flood lamps, and CFL spirals are a very different kind of emitter than a filament or LED. LED based flood lamps probably resemble classic filament based flood lamps better than CFLs do.
LED and CFL Light Quality
In some experimentation of my own, LED-based PAR type lamps definitely seem to direct a far greater quantity of their light downward, where as CFL spiral-based lamps still generally produce a more diffused output. Depending on the type of lens in front of the emitter, the quality and shape of the projected light for both CFL and LED PAR type lamps can vary greatly, from caustic refraction to fairly diffuse. CFL R/BR type lamps nicely simulate their incandescent predecessors. LED R/BR type lamps do not seem to diffuse quite as well as CFLs, so if you are looking for diffuse flood lighting, CFL generally has a more pleasing diffusion.
LED PAR lamps definitely produce a greater amount of directed illumination, so if you need to brightly light anything, LED is probably the best choice. LED flood lamps are also usually fully dimmable, "instant" on (sometimes "instant" really means up to a half-second delay before light is actually emitted), and produce far greater consistency of color (CFL color consistency is often rather poor, and during cooler or cold days, CFL floods will frequently brighten, dim to a deep magenta, then slowly normalize as they warm). LED lamps, of all designs, are usually fully dimmable these days as well. Dimmable LED flood lamps are usually dimmable down to 10% illumination, with some from the better manufacturers (such as Lighting Science) often dimmable down to 5%. Dimming quality, smoothness, minimum output and consistency is vastly superior on LED compared to CFL, with no flicker, popping, blinking, or inconsistent dropout as is frequent with dimmable CFL lamps.
In terms of the quality of projected light, BR-type CFL lamps definitely produce a smoothly diffuse light with little visible pattern directly underneath each bulb. PAR type lamps, either CFL or LED, but more so in the case of LED, produce visible refraction patterns under each bulb. I believe this has a lot to do with the design of the lens, and when multiple flood lamps are used along a hall or in a kitchen, diffusion improves. LED PAR type lamps can be very bright, which is nice when you need light.
My Choice and Recommendation
I have chosen to refurnish my kitchen, and eventually my hallways, with Lighting Science 5000k and 3000k (or possibly 4000k) Dimmable PAR38 LED lamps. These puppies are about $34 each, however they have twice the lifetime rating of comparable lamps from all other manufacturers (50,000 hours @ 6hrs per day vs. 25,000 hours @3-6hrs per day). The light is not as diffuse as your standard R-type incandescent, but the color quality is far superior for those who have never much liked the deep orange color of a classic incandescent (the 3000k versions are closer to a halogen in color, and the 5000k produce a nice, clean, crisp neutral white.)
For the highest quality, I recommend the following. Since LED lamps are dimmable, it is recommended to use a dimming switch wherever you use high lumen LED PAR lamps (i.e. 800 lumen or brighter). Personally I use Lutron HED-certified digital dimmers with dimming setting memory. One push of the button and the lights fade up over about a 1.5 seconds to your pre-set brightness level. Another push of the button, and the lights fade to minimum brightness then off over several seconds. With 800 lumen bulbs, setting a Lutron digital dimmer one or two notches down from maximum brightness produces very pleasing illumination, with the added bonus that if you need more light, or wish to add light during the daytime to fully illuminate areas that might generally be in shadow, you have the ability to crank up the illumination beyond that pleasing level.

A:

PAR = Parabolic Aluminized Reflector.
The number is the diameter of the bulb times 8, so divide by 8 to get its diameter. Thus, a PAR30 is a 3.75" diameter bulb.
Our last house had PAR30 floods in track lighting in the living room (a style that was all the rage when the house was built in the 1980s). You can use them indoors. The quality of light you get is entirely dependent on the bulb. A beam angle of 40 degrees or more will render close to the typical light dispersal we all grew up with. There are some LED floods available, and a few offer a greater than 30 degree beam angle with a diffusing lens at around 3000k color temperature. If you can find some, they can save you a ton of money over the years.


Q:

A question about ContourPlot

I already tried to ask this question, but it was unclear what I meant, so I will try to ask it again and explain it more carrefully.
For example I will use a toy problem. Suppose we have equation:
eq=k*x^2 + 2*x + 1

I want to use ContourPlot, to plot the curves where eq=0 for some values of x andk. If x and k are both real, this is easy to do:
ContourPlot[eq == 0, {k, 0, 2}, {x, -3, 3}]

But I want to treat x as complex variable, and k as real variable. For any real k we have 2 complex roots of the equation eq==0. I am not interested in Im[x], I only interested in Re[x]. So want I want is something like this:
ContourPlot[eq == 0, {k, 0, 2}, {Re[x], -3, 3}]

So, for each k, it should solve the equation eq==0, and plot Re[x] against k, omitting Im[x]. I want 2D plot, I don't want 3D plot. (My original problem is linear stability analythis, where x is groth rate, k is wave number).
Say it another way: basically, we have here 3 parameters (complex x + real k). I want to plot Re[x] against k, ignoring Im[x], so it is like a projection of 3D curve to 2D surface.
Note: Plotting Complex Quantity Functions doesn't solve my problem.
Note:
Manipulate[ContourPlot[k (reX + imX I)^2 + 2 (reX + imX I) + 1 == 0, {k, 0, 2}, {reX, -3, 3}], {imX, -3, 3}]

Doesn't solve it as well: I don't want to manipulate Im[x], I want to omit it, whatever it is.

A:

Here is a crude way to generate the plot:
Graphics[Point[
     Flatten[Table[ {k, #} & /@
        Re[x /. Solve[ k x^2 + 2 x + 1 == 0  , x]], {k, -3, 3, .01}],
            1]], AspectRatio -> 1]

clipping the plot range..and with Axes->True

Edit: a trick to coax ContourPlot to do the job:
f[k_, x_] := (Re[y] /.
   Solve[ k (x + y)^2 + 2 (x + y) + 1 == 0  , y] )[[1]]
g[k_, x_] := (Re[y] /.
   Solve[ k (x + y)^2 + 2 (x + y) + 1 == 0  , y] )[[2]]
ContourPlot[{ f[k, x] == 0, g[k, x] == 0}, {k, -3, 3}, {x, -10, 10}]

A:

Another way using ParametricPlot:
{k, Re[x]} /.
        Solve[k x^2 + 2 x + 1 == 0, x] //
    ParametricPlot[#, {k, -5, 5}] &


Q:

Why i get Error converting data type varchar to float error in bcp query out?

I'm new in sql server,write this bcp query for save select query result to csv file:
declare @Price as float
set @Price=1744

EXEC xp_cmdshell 'bcp "select [Telno],[Cycle],[Price] FROM [ClubEatc].[dbo].[CycleAnalysisTable] where CONVERT(float, [Price])>''CONVERT(float, @Price)''" queryout d:\F.txt -c -T'

But when i run that query,get this error:

Error = [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Error
  converting data type varchar to float.

How can i solve that problem?thanks all.

A:

You got quotes, that is why your query ran as:
select [Telno],[Cycle],[Price]
FROM [ClubEatc].[dbo].[CycleAnalysisTable]
where CONVERT(float, [Price])>'CONVERT(float, @Price)'

And SQL Server can not CONVERT CONVERT(float, @Price) to float.
Try to run it like this:
declare @Price as float,
        @Query nvarchar(max),
        @sql nvarchar(max)

SELECT  @Price=1744

SELECT @Query = 'select [Telno],[Cycle],[Price] FROM [ClubEatc].[dbo].[CycleAnalysisTable] where CONVERT(float, [Price])>' +CAST(@Price as varchar(100))

SELECT @sql= 'EXEC xp_cmdshell ''bcp "'+@Query+'" queryout d:\F.txt -c -T'''

EXEC sp_executesql @sql

EDIT
One more way:
declare @Price as float,
        @bcp varchar(max)

SELECT @Price=1744

SELECT @bcp= 'bcp "select [Telno],[Cycle],[Price] FROM [ClubEatc].[dbo].[CycleAnalysisTable] where CONVERT(float, [Price])>' +CAST(@Price as nvarchar(100))+'" queryout d:\F.txt -c -T'

EXEC master..xp_cmdshell @bcp


Q:

How to map an image in html by drawing small rectangles or squares on it?

I have a image of map of a country.I want to click on a state and go to next page .How can i make some small rectangles or squares or circles on each state so that when i click them it links to respective page using html or css ??

A:

There's a feature in HTML called Image map, which you can use like this:
<img src="image.png" alt="Website map" usemap="#mapname" />
<map name="mapname">
    <area shape="rect" coords="9,372,66,397" href="http://en.wikipedia.org/" alt="Wikipedia" title="Wikipedia" >
</map>

Look at this question if you want to add further style and functionality.


Q:

Compilation error with different file name

class First
{
public static void main(String[] args)
{
System.out.println("File found");
}
}

(File saved with First.java)
javac First.java ---(no error)
java First  --- no error

then I change name of class to "class Second"

javac First.java  --- (no error)
java Second   ---   no error

but If I add public and change the name of class to "public class Second"
then there is a compile time error that file should be saved with the same name as of public class.

A:

The name of the file only matters if the class is public, in which case the file MUST have the same name as the class (class First must be in First.java).
If the class is not public, the file name has no importance.


Q:

tetris rotation

For university we're supposed to write a game (the language is modula2 little chance you know it).
Each tetromino is defined through a central piece and 3 relative pieces,
Now when it comes to rotation i just rotate the relative blocks (linear algebra).
What i am asking myself is how to handle the rotations a user does when the piece has already "landed" because than the user has a little time left to move his pieve quickly into the desired position but in tetris versions all over the web you can "rotate over" other pieces, but i dont seem to get it with my rotation.
Over what piece do i need to rotate? are there guidelines?
Thanks

A:

The Tetris Wiki specifies one way these so-called wall kicks are done:

A wall kick happens when a player rotates a piece when no space exists in the squares where that tetromino would normally occupy after the rotation. To compensate, the game sets a certain number of alternative spaces for the tetromino to look.
  [...]
  The simplest wall kick algorithm [...] is to try moving the tetromino one space to the right, and then one space to the left, and fail if neither can be done.

There are other ways, such as the one specified by the Super Rotation System mandated by the Tetris Guideline. That system uses a set of tables to determine the possible wall kicks.

A:

If I understand your question correctly, there is no right answer.  Whether you can "move through" other pieces depends on the guidelines for your particular assignment; it's possible to write code that allows it and code that doesn't.


Q:

C++ Initialising vector after declaration through a function

As you can see in the following code, i want to allocate the size and elements of the vectors declared in main through Allocate function.
Error Msg
.\MV_Produkt.cpp: In instantiation of 'void Allocation(std::vector<std::vector<T> >&, std::vector<T>&) [with T = double]':

.\MV_Produkt.cpp:44:20:   required from here

.\MV_Produkt.cpp:11:6: error: no match for call to '(std::vector<std::vector<double> >) (int&, std::vector<double>)' -----A(r, std::vector<T>(c));

.\MV_Produkt.cpp:19:6: error: no match for call to '(std::vector<double>) (int&)'-----x(c);

#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>

template<typename T>
void Allocation(std::vector<std::vector<T>>& A,std::vector<T>& x){
    std::ifstream inA("A.txt");
    int r, c;
    inA >> r >> c;
    A(r, std::vector<T>(c));
    for(size_t i=0;i<A.size();i++)
        for(size_t j=0;j<A[i].size();j++)
            inA >> A.at(i).at(j);
    inA.close();

    std::ifstream inx("x.txt");
    inx >> c;
    x(c);
    typename std::vector<T>::iterator xi;
    for(xi=x.begin();xi!=x.end();xi++)
        inx >> *xi;
    inx.close();
}

template<typename T>
void MV_Product(const std::vector<std::vector<T>> A,const std::vector<T> x, std::vector<T>& b){
    typename std::vector<std::vector<T>>::const_iterator row;
    typename std::vector<T>::const_iterator colA;
    typename std::vector<T>::const_iterator colx;
    typename std::vector<T>::iterator colb;

    for(row=A.cbegin();row<A.cend();row++)
        for(colA=row->cbegin(),colx=x.cbegin(),colb=b.begin();colA<row->cend(),colx<x.cend(),colb<b.end();colA++,colx++,colb++)
            *colb = *colA * *colx;
}

int main(){
    std::vector<std::vector<double>> A;
    std::vector<double> x;
    std::vector<double> b;
    std::vector<double>::iterator bi;

    Allocation(A, x);
    MV_Product(A,x,b);

    std::ofstream outb("b.txt");
    outb << b.size() << " " << *min(b.begin(),b.end()) << " " << *max(b.begin(),b.end()) << std::endl;
    for(bi=b.begin();bi<b.end();bi++)
        outb << *bi << std::endl;
    outb.close();
}

Thanks for any Help in advance!
P.S. If anyone could also tell me how to better pass vectors to functions and how to use template "typename " for main would be much appreciated.

A:

in your code, you can see in the error messages here
\MV_Produkt.cpp:11:6: error: no match for call to '(std::vector<std::vector<double> >) (int&, std::vector<double>)' -----A(r, std::vector<T>(c));
\MV_Produkt.cpp:19:6: error: no match for call to '(std::vector<double>) (int&)'-----x(c);
that you use for T double in the main function, while you using it as int inside Allocation function, so it's a mismatch between what you defined and what you passed.


Q:

How to start a number column from a specific number?

I need to generate a unique incrementing number that will be part of a more complex invoice number. I would like to keep the increment logic in the app.
I must resume the numbering that is currently going on another system.
I intend to do Model.maximum(:custom_number).next
But how can I start the custom_number column from a given number?

A:

If I understand your question, you just need to reset the index of the primary key of your table (Model) to the number that you want.
If your are using MySQL or PostgreSQL then:
ALTER SEQUENCE tablename_id_seq RESTART WITH 1453;

then the next record will have for index in this case the 1453
For access the DB console just run on your console rails db
EDIT
before_filter :check_invoice_number
def check_invoice_number
  self.invoice_column = Model.last.invoice_column + 1
end


Q:

for each loop over XML elements in jquery

I am looking for a way to do a for each loop over XML that is returned from an ajax request. I have the below code which logs the value of the id attribute of the first success element.
How can I change this to go over all 20,50,70 etc success elements and print the values of their id attribute?
$.ajax({
    type: 'GET',
    url: url,
    data: {},
    dataType: "xml",
    success: function(xml) {
        var id = $(xml).find('success').attr('id');
        console.log(id);
    }
});

Example XML:
<body>
<success id="1" ></success>
<success id="2" ></success>

</body>

A:

Change:
   var id = $(xml).find('success').attr('id');
   console.log(id);

To:
   $(xml).find('success').each(function() {
       var id = $(this).attr('id');
       console.log(id);
   });

Reference:
-- jQuery.each()

var xml = '<body>\
<success id="1" ></success>\
<success id="2" ></success>\
</body>';
xml = $.parseXML(xml);
$(xml).find('success').each(function() {
  var id = $(this).attr('id');
  alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Q:

How to use custom properties in a ControlTemplate trigger

I have a class derived from slider which uses a custom control template and has a few added dependency properties.  I would like to fire triggers within the template based on the new properties.
For example, I have a new dependency property called ThumbIsVisible which when set to false I want just the thumb portion of my slider to be hiddin.  My control template looks like:
<Slider.Template>
<ControlTemplate TargetType="{x:Type Slider}">
...
<Track.Thumb>
<Thumb x:Name="m_Thumb" Style="{StaticResource SliderThumbStyle}" />
...

I would like to add in a trigger that looks like:
<ControlTempate.Trigger>
<Trigger Property="ThumbIsVisible" Value="False">
<Setter TargetName="m_Thumb" Property="Visibility" Value="Collapsed" />

Right off the bat I can see this won't work as I have the control tempate's target type set to Slider.  However, if I change that to say:
<ControlTemplate TargetType="{x:Type local:myCustomSlider}">

then I run into problems with the template type differing from the controls.  The only way around this is to create the xaml using the local:myCustomSlider as the type instead of Slider. However, doing this causes lots of problems with VisualStudio's designer and code behind.
Does anyone know if there is a standard way to get around all of this?  As a workaround I tried adding to the template's triggers via code-behind but have not been able to get that to work.

A:

Of course it only takes me 30 minutes after posting my question to find the answer when I spent two days looking for it first.  Oh well, the solution is to use DataTriggers.
<ControlTemplate.Triggers>
  <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=ThumbIsVisible}" Value="False">
    <Setter TargetName="m_Thumb" Property="Visibility" Value="Hidden" />
  </DataTrigger>
</ControlTemplate.Triggers>

The key is to use the RelativeSource={RelativeSource Self} to find the custom property.  After that it works exactly as expected.

A:

It looks like there is an even simpler way to solve this problem.
<ControlTemplate.Triggers>
  <Trigger Property=local:CustomSlider.ThumbIsVisible" Value="False">
    <Setter TargetName="m_Thumb" Property="Visibility" Value="Hidden" />
  </Trigger>
</ControlTemplate.Triggers>

where local is the namespace of the CustomSlider class.