Map value to type to avoid switch statement in C++

Question: Recently I faced a problem that I could not manage on my own. Let's assume that we receive some bytes from network by function:
vector<char> receive ();

When I get bytes I know precisely what are for example first 10 bytes, and how to interpret them. Rest of the message is connected with value being used in the Id (these 10 bytes). So, for example it can be expressed like this:
auto bytes = receive ();
Id id = get_id (bytes);

switch (id) {
    case Id::Message1:
    {
        Message1 message = convert_bytes<Message1> (bytes);
        notify (message);
        break;
    }

    case Id::Message2:
    {
        Message2 message = convert_bytes<Message2> (bytes);
        notify (message);
        break;
    }
    ...

    case Id::MessageN:
    {
        MessageN message = convert_bytes<MessageN> (bytes);
        notify (message);
        break;
    }
}

As you see, each case section differs from others only with Message Id and type of Message.
My question is: Is there any possibility to map Id value to the specific type of Message to make above code simpler and not to use switch statement?
auto bytes = receive ();
Id id = get_id (bytes);

// Here some magic retrieval of Message type based on Id value and invoking
// appropriate convert_bytes specialization
// auto message = convert_bytes<get_message_type(id)> (bytes); (Y)

Of course (Y) is wrong, but maybe you know some other way of doing the concept.
I know that this logic of connection Id value to the type has to be implemented somewhere, but it would be much simpler just to connect Id value to the type than writing case section for each Message type.
I know also, that I probably could do something like this:
class Base {};
class Message1 : Base {}
...
class MessageN : Base {}

vector<pair<Id, Base*>> vec;

but I don't know if this is good/efficient way since I should use dynamic_cast each time I would like to convert Base* to MessageX*.
I tried to do some wrapper class with tuple and initializer_list, something like this:
struct Message1 { int x; };
struct Message2 { double z; };

enum class Id { Message1, Message2 };

template <typename Id_type, typename ... Types>
class Wrapper {
    public:
        Wrapper (tuple<Types ...> t, const initializer_list<Id_type>& il) : tpl (t), ids (il) {

        }

       MessageType_depended_on_id get_message (Id id, vector<char> bytes); // (X)

    private:
        tuple<Types ...> tpl;
        vector<Id_type> ids;
};

tuple<Message1, Message2> tpl;
Wrapper<Id, Message1, Message2> wrapper (tpl, {Id::Message1, Id::Message2});

(X) But there is no way to specify member function type depended on the id value, or am I missing something?
My last thought was to implement each case section in template specialization, something like this:
template <Id id>
class Type_retriever {};

template <>
class Type_retriever<Id::Message1> {
    public:
        static Message1 get_msg (const vector<char>& bytes) {
            cout << "Message1" << endl;
            return convert_bytes<Message1> (bytes);
        }
};

template <>
class Type_retriever<Id::Message2> {
    public:
        static Message2 get_msg (const vector<char>& bytes) {
            cout << "Message2" << endl;
            return convert_bytes<Message2> (bytes);
        }
};

template <typename Type>
void notify (Type message) { }

auto bytes = receive ();
auto id = get_id (bytes);
notify (Type_retriever<id>::get_msg (bytes));

But this will not compile because the value of 'id' is not usable in a constant expression (gcc) which is understandable why this can not compile.
If you have any suggestion, it would be great.
Comment: You are looking for the factory pattern. You don't map values to types, but rather values to functions/objects that perform deserialization. Mapping can be done by std::map. Look at other serialization libraries/frameworks for inspiration.
Answer: You can get rid of the switch statement using a registration/plugin mechanism.
Interface for registering functions and using them:
typedef void (*MessageDispatcher)(const vector<byte>& bytes);

void registerMessageDispatcher(Id id, MessageDispatcher dispatcher);

void dispatchMessage(Id id, const vector<byte>& bytes);

In the implementation:
static std::map<Id, MessageDispatcher> messageDispatcherMap;

void registerMessageDispatcher(Id id, MessageDispatcher dispatcher)
{
   messageDispatcherMap[id] = dispatcher;
}

void dispatchMessage(Id id, const vector<byte>& bytes)
{
   std::map<Id, MessageDispatcher>::iterator iter = messageDispatcherMap.find(id);
   if ( iter == messageDispatcherMap.end() )
   {
      // Deal with the error condition.
      return;
   }

   // Dispatch the message.
   iter->second(bytes);

}

Create functions for various message types.
void dispatchMessage1(const vector<byte>& bytes)
{
   Message1 message = convert_bytes<Message1> (bytes);
   notify (message);
}

void dispatchMessage2(const vector<byte>& bytes)
{
   Message2 message = convert_bytes<Message2> (bytes);
   notify (message);
}

void dispatchMessage3(const vector<byte>& bytes)
{
   Message3 message = convert_bytes<Message3> (bytes);
   notify (message);
}

etc...
Register the functions.
registerMessageDispatcher(ID::Message1, dispatchMessage1);
registerMessageDispatcher(ID::Message2, dispatchMessage2);
registerMessageDispatcher(ID::Message3, dispatchMessage3);

Now, the code to deal with the message will be:
auto bytes = receive ();
Id id = get_id (bytes);
dispatchMessage(id, bytes);


Software for Bayesian Linear Regression

Question: What kind of software is there for Bayesian Linear Regression?
I'm trying to learn by myself, and would like something user-friendly if possible.
I've searched but there's too many options, and I have no idea which one I should choose.
Any help would be appreciated.
Comment: One to look at: the R `MCMCpack` package.
Comment: What Bayesian aspects are you looking for? Any standard linear regression analysis is a Bayesian linear regression analysis using the standard default prior.
Answer: This is a dynamically developing field, so multiple software packages are available and are being developed.
You can check arm package that accompanies Data Analysis Using Regression and Multilevel/Hierarchical Models book by Andrew Gelman and Jennifer Hill, it has bayesglm function for calculating GLM models using EM algorithm.
Recently, two new packages for regression models in R were published: brms and rstanarm. Both of the packages just provide R interface and use Stan as workhorse. There is also recent rethinking package that accompanies Statistical Rethinking book by Richard McElreath.
Generally, if you are looking for R packages for Bayesian estimation check CRAN "Bayesian" task view.
Those packages are good for start, but it is good idea to look at software dedicated to Bayesian estimation: Stan and JAGS. You would need to put a little bit more effort into learning them, but they are much more flexible than the out-of-the-box solutions. Moreover, Stan has over 500 pages long detailed user manual that provides very good introduction to both Bayesian methods and the software itself. When learning JAGS you can check The BUGS Book by David Lunn, Christopher Jackson, Nicky Best, Andrew Thomas and David Spiegelhalter that is a very nice introduction to Bayesian modelling and the software.
Comment: @Scortchi it depends... ;) If you need to learn R to use those libraries that it won't be much harder than learning Stan or JAGS. For people who are fluent in R using the libraries would be pretty obvious, but learning JAGS or Stan should also not be a problem. IMHO, Stan and JAGS are really very intuitive so it is not that hard to learn them.
Answer: The book Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan is a really gentle introduction to using the common tools for Bayesian regressions. Also, his blog has solution codes for all of the exercises. You can do most common things just by modifying the example solutions. I highly recommend this as an introductory resource.
I don't know of any "point-and-click" tools so I think no matter what you do, you have to get comfortable programming in at least one language.

Software for Bayesian Linear Regression


Converting a dictionary with lists for values into a dataframe

Question: I spent a while looking through SO and seems I have a unique problem.
I have a dictionary that looks like the following:
dict={
    123: [2,4],
    234: [6,8],
    ...
}

I want to convert this dictionary that has lists for values into a 3 column data frame like the following:
time, value1, value2
123, 2, 4
234, 6, 8
...

I can run:
pandas.DataFrame(dict)

but this generates the following:
123, 234, ...
2, 6, ...
4, 8, ...

Probably a simple fix but I'm still picking up pandas
Comment: pandas.DataFrame(dict).transpose()
Answer: You can either preprocess the data as levi suggests, or you can transpose the data frame after creating it.
testdict={
    123: [2,4],
    234: [6,8],
    456: [10, 12]
}
df = pd.DataFrame(testdict)
df = df.transpose()

print(df)
#      0  1
# 123  2  4
# 234  6  8

Answer: It may be of interest to some that Roger Fan's pandas.DataFrame(dict) method is actually pretty slow if you have a ton of indices. The faster way is to just preprocess the data into separate lists and then create a DataFrame out of these lists.
(Perhaps this was explained in levi's answer, but it is gone now.)
For example, consider this dictionary, dict1, where each value is a list. Specifically, dict1[i] = [ i*10, i*100] (for ease of checking the final dataframe).
keys = range(1000)
values = zip(np.arange(1000)*10, np.arange(1000)*100)
dict1 = dict(zip(keys, values))

It takes roughly 30 times as long with the pandas method. E.g.
t = time.time()
test1 = pd.DataFrame(dict1).transpose()
print time.time() - t

0.118762016296

versus:
t = time.time()
keys = []
list1 = []
list2 = []
for k in dict1:
    keys.append(k)
    list1.append(dict1[k][0])
    list2.append(dict1[k][1])
test2 = pd.DataFrame({'element1': list1, 'element2': list2}, index=keys)
print time.time() - t

0.00310587882996


Putting a Google Maps Marker position with a Javascript variable

Question: I'm trying to put a marker inside my map, and I'm passing the javascript variable through another php page via clicking the
, when I copy the alert result (example: {lat: -25.4025, lng: -49.2643} ) and put directly inside the 'position' field it works fine, but when I put the variable on it, it does not.
PHP
$History_Assoc = mysqli_fetch_array($HistoryQuery);

      echo '
';
      echo '
';

JAVASCRIPT
var folders = document.getElementsByClassName("repoFolder");
for (let i = 0; i < folders.length; i++) {
  folders[i].onclick = function() {rootFolder.call(this)}; // note that I am passing in the context to rootFolder.
}

function rootFolder() {

  var variable =  this.getAttribute('data-value');

  alert(variable);

  var markersHistory = new google.maps.Marker({
    position: variable,
    map: map,
    icon: iconBlue2,
  });
}

Comment: Are you variables holding the correct data? Are you able to check the result it's producing?
Comment: yes, When I "alert" the variable it shows the coordinates, when I copy the same coordinates and put inside de position field it works, but when I put the variable it does not
Answer: It looks like there is a problem parsing the JSON from the data-value attributes in your markup. There are a couple of ways you could handle this, but I think the easiest would be to embed the latitude and longitude values as two separate data attributes, then use the Google Maps LatLng object to specify the coordinates for your marker. That way you can avoid the various JSON pitfalls. Here's an example:
HTML:

Clicky

Javascript
function rootFolder()
{
    var latitude =  this.getAttribute('data-lat');
    var longitude =  this.getAttribute('data-lng');

    var latLng = new google.maps.LatLng(latitude, longitude);

    var markersHistory = new google.maps.Marker({
        position: latLng,
        map: map
    });
}


How to make tf.Transform (Apache Beam Preprocessing for TensorFlow) work?

Question: I am trying to utilize tf.Transform lib for doing data preprocessing with TensorFlow via Apache Beam (Google DataFlow).
https://github.com/tensorflow/transform
here is my setup:

conda create -n tftransform python=2.7
source activate tftransform
pip install tensorflow
pip install tensorflow-transform
pip install dill==0.2.6
git clone https://github.com/tensorflow/transform.git
cd transform/
python setup.py install    # for good measure ...

I then try to execute simple_example (https://github.com/tensorflow/transform/blob/master/examples/simple_example.py):
python examples/simple_example.py
I get the following error:
AttributeError: 'DType' object has no attribute 'dtype'
(there is also a warning on import No handlers could be found for logger "oauth2client.contrib.multistore_file")
here is the stacktrace:

Traceback (most recent call last):
  File "examples/simple_example.py", line 64, in <module>
    preprocessing_fn, tempfile.mkdtemp()))
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/apache_beam/transforms/ptransform.py", line 439, in __ror__
    result = p.apply(self, pvalueish, label)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/apache_beam/pipeline.py", line 249, in apply
    pvalueish_result = self.runner.apply(transform, pvalueish)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/apache_beam/runners/runner.py", line 162, in apply
    return m(transform, input)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/apache_beam/runners/runner.py", line 168, in apply_PTransform
    return transform.expand(input)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/tensorflow_transform/beam/impl.py", line 597, in expand
    self._output_dir)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/apache_beam/transforms/ptransform.py", line 439, in __ror__
    result = p.apply(self, pvalueish, label)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/apache_beam/pipeline.py", line 249, in apply
    pvalueish_result = self.runner.apply(transform, pvalueish)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/apache_beam/runners/runner.py", line 162, in apply
    return m(transform, input)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/apache_beam/runners/runner.py", line 168, in apply_PTransform
    return transform.expand(input)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/tensorflow_transform/beam/impl.py", line 328, in expand
    self._preprocessing_fn, input_schema)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/tensorflow_transform/impl_helper.py", line 416, in run_preprocessing_fn
    inputs = _make_input_columns(schema)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/tensorflow_transform/impl_helper.py", line 218, in _make_input_columns
    placeholders = schema.as_batched_placeholders()
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/tensorflow_transform/tf_metadata/dataset_schema.py", line 87, in as_batched_placeholders
    for key, column_schema in self.column_schemas.items()}
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/tensorflow_transform/tf_metadata/dataset_schema.py", line 87, in <dictcomp>
    for key, column_schema in self.column_schemas.items()}
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/tensorflow_transform/tf_metadata/dataset_schema.py", line 133, in as_batched_placeholder
    return self.representation.as_batched_placeholder(self)
  File "/Users/XXX/anaconda/envs/tftransform/lib/python2.7/site-packages/tensorflow_transform/tf_metadata/dataset_schema.py", line 330, in as_batched_placeholder
    return tf.placeholder(column.domain.dtype,
AttributeError: 'DType' object has no attribute 'dtype'

Is this lib production ready ?
How can I make this work ?
Answer: I ran the following:

python setup.py bdist_wheel
pip install ./dist/tensorflow_transform-0.1.6.dev0-py2-none-any.whl

this uninstalls tensorflow-transform-0.1.5 and installs tensorflow-transform-0.1.6.dev0
running python examples/simple_example.py now works - I get the following result:

[{'s_integerized': 0,
  'x_centered': -1.0,
  'x_centered_times_y_normalized': -0.0,
  'y_normalized': 0.0},
 {'s_integerized': 1,
  'x_centered': 0.0,
  'x_centered_times_y_normalized': 0.0,
  'y_normalized': 0.5},
 {'s_integerized': 0,
  'x_centered': 1.0,
  'x_centered_times_y_normalized': 1.0,
  'y_normalized': 1.0}]

thanks to @elmer-garduno
Comment: Thanks Josh, both the Github and PyPi repos are now in sync so pip install --upgrade tensorflow-transform should bring in the right version.


Binomial expansion and convergence

Question: May I ask for some help on this?
Comment: This has nothing to do with "binomial expansion" – it's just a geometric series.
Answer: Hint
$$(2x-5y)^{-1}=\frac 1{2x-5y}=\frac 1{2x(1-\frac{5y}{2x})}=\frac 1{2x}\times\frac 1{1-\frac{5y}{2x}}$$ Take care that the above steps assume $x\neq 0$.
Now, remember the expansion $$\frac 1{1-t}=1+t+t^2+\cdots+t^n+\cdots$$ which is valid if $|t|<1$. Replace $t$ by $\frac{5y}{2x}$.
I am sure that you can take it from here.

Binomial expansion and convergence


Armazenar dados da table no dispositivo.

Question: Estou desenvolvendo uma aplicação para uma empresa onde realiza pedidos de refeição, essa aplicação é em PHP, como sou novo na área queria saber se é possível ter a base de funcionários salvo no tablet, assim ao digitar a matricula do funcionário ele carregar o nome sem precisar fazer uma requisição no servidor, afim de consumir menos dados móveis.
Sei lá ter uma lista ou array que teria essa informação.
Comment: Não. O `PHP` não consegue trabalhar com arquivos ou base de dados no lado do cliente. **Talvez** a melhor solução para seu caso seja utiliza `js`.
Comment: Pode criar um JSON em JS e pesquisar o nome pela matrícula.
Comment: Só um adendo: A depender do tamanho da sua base de dados, talvez isso nem valha a pena. Só para ter ideia, uma api que retorna nome, email, id, avatar, cidade, estado, país, situação (status), datas de criação e modificação consome cerca de 800 bytes, com GZIP esse valor pode chegar a 400 bytes.
Answer: Em PHP não é possível fazer isso, afinal PHP é uma linguagem web que roda somente no lado do servidor. Uma forma de fazer isso seria o desenvolvimento de um aplicativo que pode ser em android por exemplo, e utilizar um banco SQLite no celular/tablet para armazenar os funcionários, mas mesmo com essa solução o aplicativo ainda teria que fazer algumas requisições para atualizar seus registros caso um novo funcionário fosse adicionado a base de dados.
Normalmente quando desenvolvemos alguma aplicação em PHP que sera usada por alguma empresa espera-se que a empresa forneça um pacote de dados maior para os funcionarios, ou que a aplicação seja usada internamente utilizando uma rede Wifi ( em caso da utilização ser por dispositivos móveis ).


Finding the xy values from lat lon from SSMI/S sea ice concentration data

Question: I want  to find the corresponding ice concentration values that are present at a series of lat and lon coordinates (such as lon=-74.7732772827148 and lat=-69.3250350952148). However, the dataset I am using (https://cds.climate.copernicus.eu/cdsapp#!/dataset/satellite-sea-ice-concentration?tab=form) has some of the following attributes:
double xc(xc) ;
                xc:units = "km" ;
                xc:long_name = "x coordinate of projection (eastings)" ;
                xc:standard_name = "projection_x_coordinate" ;
        double yc(yc) ;
                yc:units = "km" ;
                yc:long_name = "y coordinate of projection (northings)" ;
                yc:standard_name = "projection_y_coordinate" ;
        float lat(yc, xc) ;
                lat:units = "degrees_north" ;
                lat:long_name = "latitude coordinate" ;
                lat:standard_name = "latitude" ;
        float lon(yc, xc) ;
                lon:units = "degrees_east" ;
                lon:long_name = "longitude coordinate" ;
                lon:standard_name = "longitude" ;
        int ice_conc(time, yc, xc) ;
                ice_conc:_FillValue = -32767 ;
                ice_conc:long_name = "fully filtered concentration of sea ice using atmospheric correction of brightness temperatures and open water filters" ;
                ice_conc:standard_name = "sea_ice_area_fraction" ;
                ice_conc:units = "%" ;
                ice_conc:valid_min = 0 ;
                ice_conc:valid_max = 10000 ;
                ice_conc:grid_mapping = "Lambert_Azimuthal_Grid" ;
                ice_conc:coordinates = "time lat lon" ;
                ice_conc:ancillary_variables = "total_standard_error status_flag" ;
                ice_conc:scale_factor = 0.01 ;
                ice_conc:comment = "this field is the primary sea ice concentration estimate for this climate data record"

How do I find the corresponding x and y if lat and lon are both a function of x and y?
I have tried changing the projection using pyproj but it doesn't project correctly. As an example here is the following:
lambert_aea1 = {'proj': 'laea',
          'lat_0':-90,
          'lon_0':0,
          'ellps': 'WGS84',
          'datum': 'WGS84'}

    inProj = Proj(init = 'epsg:4326')
    outProj1 = Proj(lambert_aea1)

    x1,y1 = np.array(transform(inProj,outProj1,lat_63_1[j],lon_63_1[j]))

the results are x1 =-1586154.039780751 and
y1=598565.7767689897
but x and y values are in the range of -5387.5 and 5387.5
Is there another way to directly get the values rather than changing the projection?
Comment: Please include the code that you used to change the projection.
Comment: Have you tried using the Proj-4 string listed in the documentation with pyproj? https://osisaf-hl.met.no/sites/osisaf-hl.met.no/files/user_manuals/osisaf_cdop3_ss2_pum_sea-ice-conc-climate-data-record_v2p1.pdf
Comment: @NickODell I have tried this but it seems to change the projection incorrectly. Am I possibly missing something?
Comment: What lat/lon values did you put in to get those x/y values?
Comment: @NickODell lon= -74.7732772827148 and lat= -69.3250350952148
Answer: If you look at the metadata for x and y in your file, the units are kilometers. For most projections, the units are either meters or feet.
If you multiply your x and y by 1,000 and compare the results, it is within the range you would expect.


Logic App Standard (single tenant) - How to create additional/new workflow in existing logic app using REST API

Question: I have and existing Logic App Standard with a few workflows. The goal is to create additional workflows using REST API.
Answer: To create a new workflow in your standard logic app. You can change the kind to Stateless or Stateful as per your requirement and update the trigger/action/output in the request body as per your requirement.
POST
https://management.azure.com/subscriptions/{subscription ID}/resourceGroups/{resource group name}/providers/Microsoft.Web/sites/{logic app name}/deployWorkflowArtifacts?api-version=2018-11-01
Authorization: Bearer
Request Body:
{"files":{"<>/workflow.json":{"definition":{"$schema":https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#,"actions":{},"contentVersion":"126.96.36.199","outputs":{},"triggers":{"manual":{"inputs":{},"kind":"Http","type":"Request"}}},"kind":"Stateful"}}}
To Update the existing workflow in standard logic app
POST
https://management.azure.com/subscriptions/{subscription ID}/resourceGroups/{resource group name}/providers/Microsoft.Web/sites/{logic app name}/hostruntime/runtime/webhooks/workflow/api/management/workflows/{yourworkflowname}/validate?api-version=2018-11-01
Authorization: Bearer
Request Body:
{"properties":{"definition":{"$schema":https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#,"actions":{},"contentVersion":"22.214.171.124","outputs":{},"triggers":{"manual":{"inputs":{},"kind":"Http","type":"Request"}}},"kind":"Stateful"}}
The standard logic app is built on top of the azure function app runtime, and it uses the same REST API as azure function. Make sure to add Content-Type as application/json in the header
To get familiar with function REST API you can refer to this document. To get familiar with Azure Management API and generating token refer to this document.
Comment: Strange this gives me an OK Status code 200 but I still see no workflow in my logic app. I also copied the same request body of an existing one but still I do not see it in the list of workflows.
Answer: To Update the existing workflow in the standard logic app
After thorough investigation, I was able to find a clue to UPDATE & DELETE with Standard LogicApp; it's the same URL and payload as those for CREATE but with an additional Header value: If-Match : *


Request Access To Contacts in Swift 3

Question: I want to access the user's Contacts and am planning to do so using the Contacts and ContactsUI framework that Apple supplies.
First, though, I need to ask permission to access the user's contacts and am having trouble doing so. In Swift 2, one could ask permission like so:
func requestForAccess(completionHandler: (accessGranted: Bool) -> Void) {
    let authorizationStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)

    switch authorizationStatus {
    case .Authorized:
        completionHandler(accessGranted: true)

    case .Denied, .NotDetermined:
        self.contactStore.requestAccessForEntityType(CNEntityType.Contacts, completionHandler: { (access, accessError) -> Void in
            if access {
                completionHandler(accessGranted: access)
            }
            else {
                if authorizationStatus == CNAuthorizationStatus.Denied {
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
                        self.showMessage(message)
                    })
                }
            }
        })

    default:
        completionHandler(accessGranted: false)
    }
}

I tried to convert it to Swift 3 like so, but am still coming up with errors. The error is "Instance member 'async' cannot be used on type 'DispatchQueue'; did you mean to use a value of this type instead?":
func requestForAccess(completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
    let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)

    switch authorizationStatus {
    case .authorized:
        completionHandler(true)

    case .denied, .notDetermined:
        self.contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
            if access {
                completionHandler(access)
            }
            else {
                if authorizationStatus == CNAuthorizationStatus.denied {
                    DispatchQueue.async(group: DispatchQueue.main, execute: { () -> Void in //error here
                        let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
                        self.showMessage(message)
                    })
                }
            }
        })

    default:
        completionHandler(false)
    }
}

Can anyone help out to try to fix this? Any help would be immensely appreciated. Thanks a ton in advance.
Cheers,
Theo
Comment: "am still coming up with errors" Is not a question. Say clearly what the "errors" are and on what line(s). Also, do you really imagine that no one has ever discussed how to authorize Contacts access in Swift 3 before on Stack Overflow? Try searching before asking. Save bandwidth.
Comment: @matt I dont think that kind of aggression is needed on stack overflow. i added the error, but just chill out
Comment: https://stackoverflow.com/questions/37801370/how-do-i-dispatch-sync-dispatch-async-dispatch-after-etc-in-swift-3
Comment: Which error are getting ?
Comment: @GIJOW added above. "Instance member 'async' cannot be used on type 'DispatchQueue'; did you mean to use a value of this type instead?"
Comment: I don't agree. There's a right way to ask a question. It turns out that this one has nothing to do with Contacts, requesting access, or anything else. It's just that you're trying to use an instance method as if it were a class method. And that would have been quite obvious if you had just cited that one line and shown the error message, and asked about it, right at the start, instead of wasting time and bandwidth with irrelevancies and making us beg for the information you should have provided to start with.
Comment: @matt not only did i ask this question politely and with plenty of information, it absolutely does have to with Contacts *and* requesting access. If you look at the question, you'll see I tried to adapt a Swift 2 function to Swift 3 and there was an error. You could have just answered the question with an answer of "oh this is how you solve that problem, now you know how to do that" or not have commented at all. I appreciate your love for this platform and you striving to make it a better place, but i recommend you contribute positively, or not at all.
Comment: There is someone with Stack's God syndrome. @TheoStrauss glad you could solve your problem.
Answer: Instead of
DispatchQueue.async(group: DispatchQueue.main, execute: { ... }

do
DispatchQueue.main.async { ... }

By the way, if permission had previously been denied, there's no point in requesting authorization again, because the OS will not present any "grant access" UI to the end user. It only does that if the user had not previously denied access.
If access to Contacts is truly essential for successful operation of the app, you can show them an alert that gives them the option of going to Settings directly from your app:
func requestAccess(completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
    switch CNContactStore.authorizationStatus(for: .contacts) {
    case .authorized:
        completionHandler(true)
    case .denied:
        showSettingsAlert(completionHandler)
    case .restricted, .notDetermined:
        store.requestAccess(for: .contacts) { granted, error in
            if granted {
                completionHandler(true)
            } else {
                DispatchQueue.main.async {
                    self.showSettingsAlert(completionHandler)
                }
            }
        }
    }
}

private func showSettingsAlert(_ completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
    let alert = UIAlertController(title: nil, message: "This app requires access to Contacts to proceed. Go to Settings to grant access.", preferredStyle: .alert)
    if
        let settings = URL(string: UIApplication.openSettingsURLString),
        UIApplication.shared.canOpenURL(settings) {
            alert.addAction(UIAlertAction(title: "Open Settings", style: .default) { action in
                completionHandler(false)
                UIApplication.shared.open(settings)
            })
    }
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { action in
        completionHandler(false)
    })
    present(alert, animated: true)
}

Comment: thanks so much! would you recommend deleting the entire function i had and replacing it with this? or adding the showFunctionsAlert() on top of it.
Comment: I'm not sure if I follow your question. But this does the requesting of access as well as presenting an alert if denied, so I'm not sure what else you'd need.
Comment: By the way, I tweaked my answer to take closure parameter, like your original example. My original example was requesting authorization when the view appeared, but it's better to defer this question until the point that the user really needs access (it might be when the view appears, but more likely, it's when they tap on something that obviously requires contacts; if you defer it to the latest possible moment, the user is more likely engaged with your app and more likely to grant permission.
Comment: hey, sorry commented before i saw your edit. i was asking should i include the function i had in my initial question *and* the two functions above. or do the functions you provided in your answer sufficient to ask the user for permission. thanks so much for all the help
Comment: i see what you were aiming to do now. im just about ready to click the checkmark, but one more question. should i call those two functions in the viewdidload or is that not needed. thanks a ton
Comment: First, `viewDidLoad` is not a good place to do something that could present some UI. Perhaps `viewDidAppear` is better. But, again, only do that if the view being presented requires contacts. But if the request for contacts is needed later (e.g. when they tap on a button to do something with contacts), then don't put this in `viewDidAppear`, but rather in the `@IBAction` for that button (or what have you).
Comment: Phenomenal answer, the second part of your answer saved me a ton of time.
Comment: How would you go about calling this when the user selects the button?
Comment: Er, just call `requestAccess` in your `@IBAction` method.
Answer: Same thing, really but it treats no as a no, as opposed to maybe, not now or anything like that. Did you see any fuzzy logic in Apple privacy prompts? I did not.
fileprivate func requestForAccess(completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
    let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)

    switch authorizationStatus {
    case .authorized:
        completionHandler(true)

    case .notDetermined:
        self.contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
            if access {
                completionHandler(access)
            }
            else {
                completionHandler(false)
            }
        })

    default:
        completionHandler(false)
    }
}

Request Access To Contacts in Swift 3


How do I customize a Superfish Menu for Drupal 7?

Question: I have successfully installed Superfish by installing the Libraries module, downloading the Superfish library and putting it in /sites/all/libraries, and installing the Superfish module.
Now I would like to customize the look of it. The pre-built styles that show up in the drop-down in the Superfish Configuration could be a decent starting point, but I really would like to get into the details and get the measurements and colors just right.
How can I do this?
Answer: You need to overwrite the styles in your own custom stylesheet.  Use firebug to find which styles you would like to adjust.
Keeping it in your custom stylesheet will keep the styles from being lost when you update the module.
Comment: So do I copy the "simple" style, and rename it? I tried copying one of the color styles - the blue.css, and renaming it, but it didn't show up in the dropdown list of styles to select in the configuration.
Comment: Just use the preset that gets you closest to what you need, and then override the styles in your main stylesheet.  It won't generate a custom dropdown item.


SQL Server 2019 - add day in date with time component

Question: I want to add 1 day to date with time component.
My date is say for eg.
2020-09-10 18:30:00.000'

and I want to add 24 hours i.e expected output is
2020-09-11 18:30:00.000

I wrote SELECT DATEADD(day, DATEDIFF(day, 0, '2020-09-10 18:30:00.000'), 1) but this does not show the time component.
How to add date with time component?
Answer: SQL Server is really flexible about recognizing date formats, and will happily understand your string as a date if you put in within a date function. So, no need for explicit conversion from string to date, you can just do:
dateadd(day, 1, '2020-09-10 18:30:00.000')

Answer: Drop the datediff() in your attempt. And according to the documentation, the date is the third argument of the dateadd() function.
select dateadd(day, 1, convert(datetime, '2020-09-10 18:30:00.000') );

Output:
2020-09-11 18:30:00.000

Comment: . . The conversion to `datetime` is probably unnecessary.


Given a p.d.f. of $X$, find the p.d.f. of $Y=4-3X$

Question: The probability density function of a random variable $X$ is given by
$$f_X (x) =\begin{cases}
\frac{5}{x^2} & x > 5\\
0 & \text{otherwise}\\
\end{cases}
$$
Find the probability density function of $Y = 4-3X $. Don't forget to state the support of the p.d.f (set of values $y$ for which $y > 0$).

Going to solve this using this formula from my textbook
$$f_Y(y)\frac{f_X(h^{-1}(y))}{|h'(h^{-1}(y))|}$$
Let $h^{-1}(y) = 4 - 3y$.
Then $h(y) = \dfrac{4-y}{3}$ and $h'(h^{-1}(y)) = 0-3y^{1-1} = -3$
$$\dfrac{\dfrac{5}{(4-3y)^2}}{|-3|} = \dfrac{5/3}{(4-3y)^2}$$
with support
$$\frac{4-y}{3} > 5 \iff4 - y > 15 \iff y < -11$$
Answer is
$$\dfrac{15}{(4-y)^2}$$
which is different from mine. Why?
If I let $h^{-1}(y) = \frac{4-y}{3}$,
then
$$\frac{5 \cdot 9}{(4-y)^2} \cdot \frac{1}{\left|h'\left(\frac{4-y}{3}\right)\right|} = \frac{45}{(4-y)^2} \cdot \frac{1}{\frac{1}{3}} = \frac{45 \cdot 3}{(4-y)^3}$$
which is again, not the same as the solution.

I understand it for the most part except I don't get the answer.
I still don't get how $$h'(h^{-1}(y)) = h'\left(\frac{4-y}{3}\right) = -3$$
Comment: $\frac{5}{\frac{(4-y)^2}{3^2}} = \frac{5 \cdot 9}{(4-y)^2}$
Answer: You're given $y = 4-3x$. Let this $y=h(x)=4-3x$. Then  $x=h^{-1}(y)=\dfrac{4-y}{3}$. So by the given formula,$$f_Y(y)=\frac{f_X(h^{-1}(y))}{|h'(h^{-1}(y))|}=\frac{\dfrac{5}{\left(\frac{4-y}{3}\right)^2}}{|-3|}=\frac{15}{(4-y)^2}.$$
Note that $h'$ is constant, since $Y$ is linear: $$h'(\color{blue}{x})=-3\,\,\forall x\implies h'(\color{blue}{h^{-1}(y)})=-3.$$ On the other hand, if you've noticed, a shorthand for this when $Y=\alpha X+\beta$, $$f_Y(y)=\dfrac{f_X(\dfrac{y-\beta}{\alpha})}{|\alpha|}$$ for $\alpha\ne0.$
Comment: how does $h'(h^{-1}(y)) = -3$ ?
Comment: @Basbas I'd try to view $h'$ as another function. $h'$ is a constant function, so wherever the value you pick, the "output" is still that constant.
Comment: yeah I got it, thank you.


Importing nodes directly into database

Question: I have created a custom content type and fields.
i want to import data into content type.
best solution for import data ?
i can export of database for example .CSV .XML
i don't know best solution for import data into drupal
Answer: Just use Node Export.

Create one example node from your content-type
Export it to e.g. CSV
add your other nodes
re-import CSV
Answer: Use the feeds module it has CSV importer which works well. If you need to transform the data consider using the migrate module which is more time consuming but gives more flexibility

Importing nodes directly into database


SimpleCursorAdapter java exibir imagens

Question: Como eu faço para exibir a imagens no layout com SimpleCursorAdapter?
Meu código .java:
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.listarordens);

    SQLiteDatabase db   = openOrCreateDatabase("ordens.db", Context.MODE_PRIVATE, null);
    ListView ltwLocais  = (ListView)findViewById(R.id.listHist);
    Cursor cursor       = db.rawQuery("SELECT * FROM ordens ORDER BY _id ASC",null);

    String[] from = {"_id","numero","descricao","datahora","foto"};
    int[] to = {R.id.textId, R.id.textNumero, R.id.textDescricao,R.id.textDatahora,R.id.textFoto};

    @SuppressWarnings("deprecation")
    SimpleCursorAdapter ad = new SimpleCursorAdapter(getBaseContext(), R.layout.model_listar, cursor, from, to);

    ltwLocais.setAdapter(ad);
    db.close();

}

e meu .xml:
<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/textNumero"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/textDescricao"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textNumero"
        android:layout_marginTop="14dp"
        android:layout_weight="0.77"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

<TextView
    android:id="@+id/textDatahora"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Small Text"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView
    android:id="@+id/textFoto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textDatahora"
    android:layout_toLeftOf="@+id/textNumero"
    android:text="Medium Text"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textFoto"
    android:layout_below="@+id/textFoto"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:visibility="gone" />

Comment: Especifica mais um bocado o que queres, eu não vou olhar para o teu código a não ser que saiba o que é para fazer e qual é o teu problema.
Comment: Você teve algum erro? O que aconteceu quando implementou o código ai a cima? Encontrou alguma dificuldade?
Comment: eu quero exibir a imagem a partir da url (foto), do bd
Comment: No TextView textFoto queres que apareça a URL da imagem e ao clicares nela apareça a imagem
Answer: Para aparecer a foto, você precisa trocar o TextView por uma ImageView.
Se o Bitmap da imagem estiver salvo no banco, acredito que irá funcionar. O layout ficaria assim:
//Restante do layout...
<TextView
android:id="@+id/textDatahora"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />

<ImageView
android:id="@+id/imageFoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textDatahora"
android:layout_toLeftOf="@+id/textNumero"
android:textAppearance="?android:attr/textAppearanceMedium" />

E na sua classe, altere o id do elemento:
int[] to = {R.id.textId, R.id.textNumero, R.id.textDescricao,R.id.textDatahora,R.id.imageFoto};

Outra alternativa é usar o SimpleCursorAdapter.ViewBinder, o link a seguir pode ajudar: https://stackoverflow.com/questions/8510335/simplecursoradapter-with-imageview-and-textview

SimpleCursorAdapter java exibir imagens


Interpretation of MDS factor plot

Question: Suppose I run Multidimensional Scaling and I got the resulting plot. Can anybody suggest me how to interpret the plot. Please find one of my result below. Here I've 5 concepts which I run the MDS based on 10 variables. I'll be grateful if somebody can help me out.

Regards,
Ari
Comment: Can you provide more information on your design: what are 'concepts', how many subjects, context, etc. Also, shall we assume that this is standard 'metric'-scaling (equivalent to PCA for the first two PCs), or did you rely on non-metric multidimensional scaling?
Comment: What dissimilarity is used in the analysis? Also, are you the same person I helped on SO recently: http://stackoverflow.com/q/6613046/429846 ?? If so, it is important to let people know what software you used to do the analysis.
Comment: Hi Chl: I did metric scaling to get the plot. The data set has 100 respondent who are shown different ads capturing certain concepts. These concepts are reflected in the variables mentioned. Then they were asked to rank the variables from 1(dissatisfactory) to 4 (satisfactory).We need to create the "perceptual map" from it.
Comment: Hi @Gavin, I'm the same guy you helped. I've gone through the entire doc of vegan package as well as relevant literatures. But unfortunately didn't get any material on how to interpret the result. We can do it just by reading the data points. But is there any more methodical way to do it?
Comment: In MDS, can I rotate the principal components for loading across the variables & then try to interpret it? Just like we do in Principle Component Analysis. Can anybody help me to give the code. The "vegan" tutorial doesn't have that.
Comment: Can anybody tells me how to do Property Fitting (PROFIT) using R?
Answer: I'm answering my own question for 2 reason:1) I want to be clear what I've understood is correct or not. 2) If somebody is looking for the same reason he/she should find it here.I hardly found book that gives a clear explanation of interpretation of MDS biplots. I'll also give few references where people can read more about interpretation of MDS ploting to better understand it.
This answer is divided in few parts:
Part 1: The axis of the biplot are the principal components. x-axis has the PC 1, which reflect the max variance in the dataset. y-axis has the PC 2, whichreflect 2nd most variance. E.g. in my example x-axis represent 72% of the variance, while y-axis represent 16% of the variance in the data.
<code> PC1      PC2      PC3      PC4
0.727891 0.166721 0.070320 0.003048
</code>
Part 2: The arrows reflect how the variables are loaded in each PCs. E.g. in my example "uncluttered" & "visualization" is highly negatively loaded to PC 2, hence y-axis. Similarly, "no water","fast relief" & "convinient" is highly plositively loaded to PC 2, hence x-axis.This gives us a visualization about how variables are loaded in different PCs.
<code>                    NMDS1     NMDS2
Safe                      0.616967 -0.786989
Highly.efficacious       -0.135565  0.990768
Same.side.effect.profile  0.822707 -0.568466
Fast.Relief               0.988621 -0.150428
No.Water                  0.990893  0.134648
Convenient                0.989206  0.146534
Convincing                0.763225 -0.646133
Visually.appealing        0.154414 -0.988006
Very.novel                0.900984  0.433853
Noticeable                0.691596  0.722284
Likely.to.be.read         0.887028 -0.461715
Uncluttered               0.031498 -0.999504
Interesting               0.872584 -0.488465
Credible                  0.620556 -0.784162
Prescribe.Recommend       0.809955 -0.586492
</code>
part 3: Concept points tells us how dissimilar they are from the each other. So, in my example Concept 1 & Concept 2 are very different from rest of them. Concept 2 is both bad in terms of visual appeal as well as convenience. Whereas concept 3 & 4 are more alike. They are also good in terms of visualization as well as convenience.
<code>Reference: 1) Greenacre, M. (2010). Biplots in Practice
           2) Everitt & Hothorn: An Introduction to Multivariate Analysis with R(Chapter 4).
           3) Hair: Multivariate Data Analysis
</code>
Comment: Thank you for this useful post. Hi what do you mean by highly plositively loaded to PC 2 hence x axis?
Highly negatively loaded to PC-2 hence Y axis? Can you please elaborate on this?

Interpretation of MDS factor plot


Best bayesian network program for mac?

Question: Does anyone know which is the best bayesian network program for mac that has a graphical interface and is free?
Comment: What do you mean by bayesian network program?
Comment: As a software recommendation question, I think this would now be considered off-topic here.
Comment: @mbq a program where you can specify bayesian networks as directed acyclic graphs representing the probabilistic relations between variables and can do inference from those relations. programs like AgenaRisk or Genie for mac and for free
Answer: SAMIAM software is recommended by prof. Daphne Koller at her Stanford's class "Probabilistic graphical models". It has a version for MACs as well.
Comment: (+1) Well done. (32-bit only Mac version)

Best bayesian network program for mac?


For $x$ a random real with $-1\leq x \leq1$, what is the probability that $x^2>0.5$?

Question: Let x be a random real number where -1$\le$x$\le$1 what is the probability that $x^2$>0.5.
I've tried to use integral to solve it but I'm not sure about it , If there is any book or article would help me to figure out the function to solve any similar problem I'd be pleased.
my solution is :
$$2 \cdot \frac{1-\frac{1}{\sqrt 2}}{2} \cdot
\int_{1/\sqrt 2}^1 (1-x^2)~dx$$
Comment: Welcome to MathSE.  Please edit your question to show your attempt since that makes it easier for readers to detect any errors you may have made.  This [MathJax tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: Hi! It looks like you computed an expectation, not probability! Check my answer for the correct computation!
Comment: You should specify the distribution. When none is given, it is natural to assume a uniform distribution (like Snared did), but even so, as the asker, you should make it clear. If a non-uniform density is prescribed, then you also need to integrate. With a uniform distribution all you need to do is to calculate the length of the favorable interval(s).
Comment: thank for the tutorial, do you think my answer is correct?
Comment: Please check whether I interpreted your expression correctly.
Comment: No it is what I wanted to write,thanks
Comment: I believe that integral is useful to compute spaces for unpleasant shapes ,please correct me if I'm wrong
Comment: also if you support your solution by any book or blog it would be great,thanks for your help and I'm looking forward if you have any general way to solve this kind of problems
Comment: you're right ,now I understand that it each y has exactly one x I thought it was a shape not curve please excuse me for being stubborn. thanks a lot.
Answer: $x^2 = 1/2 \iff x = \pm \sqrt2 / 2$. Due to the shape of $x^2$ near the origin, $x^2 < 1/2$ whenever $x \in [-\sqrt 2 / 2, +\sqrt 2 /  2]$. So that leaves the space for greater being $2(1-\sqrt 2/2)$ by symmetry. Dividing by the total mass of the line segment of length $2$ we get out answer $p(x^2>1/2) = 1-\sqrt 2/2 \approx 0.29$.


assigning values to input array

Question: if I have this:

function add(){
  var val = document.getElementById("item").value;

  document.getElementById("items").value = val;

}

    <input type="text" name="item" id="item" value="" >
    <input type="hidden" name="items[]" id="items[]" value="" >

    <button onclick="add()" type="button"> Add</button>

so I just want add some values to input items[], It's possible? in javascript I use push(), but in this case I don't know what to do.
Comment: The ID is `item[]`, not `items`.
Comment: `items` is not the same as `items[]`.
Comment: The input's value will be a string, so you could potentially use a `+=` and include a comma with your appended value.
However, personally, I would probably split `items`' existing value into an array, push the new value into that array, then join the array back into a string before assigning it to the value again.
Comment: I updated code, but I have this "message": "Uncaught TypeError: Cannot set properties of null (setting 'value')
Comment: I do not understand
Answer: You should create a new items[] element for each value that you're adding. Then the middleware on the server should automatically create an array with all these values.

function add(){
  var val = document.getElementById("item").value;

  var item = document.createElement("input");
  item.type = "hidden";
  item.name = "items[]";
  item.value = val;
  document.getElementById("form").appendChild(item);
}
<form id="form">
    <input type="text" name="item" id="item" value="">

    <button onclick="add()" type="button"> Add</button>

</form>
Comment: if I send it to control the input items[], it will arrive??
Comment: Yes, that's exactly what I said.
Comment: it's work, but only one value, If I added 10 item in array items only saved last  item.
Comment: That sounds like a problem with the controller script. In PHP it needs to loop over the array `$_POST['items']`, there should be something similar in other languages.

assigning values to input array


Mini-Batch Gradient Descent - Why does sampling with replacement work?

Question: When sampling the data, either one at a time (as in online learning), or in mini-batches, there exist gradient descent methods which sample with replacement and without replacement.
For Mini-Batch Gradient Descent, why do the methods that sample with replacement work? Why don't we care, for example, that the same data point could be sampled multiple times, or that some data points from the training set may never get sampled at all?
Comment: Very good question (+1). Asking for a friend: could you provide a reference for mini-batch with replacement?
Answer: It works (and we don't care about sampling points multiple times) because it's an unbiased estimator of the full gradient.
Gradient distributes over summation (and expectation). The expected value of the gradient of a mini-batch, over all possible mini-batches, is the full gradient.
More details are in Leon Bottou's paper Stochastic Gradient Descent Tricks. Section 2 talks about SGD as an unbiased estimator, and the same argument holds for the minibatch estimator.
Comment: But usually, if we implement minibatch gd we just shuffle the entire data set once at each epoch. This means, that one sample can appear at a batch only one time. Does this approach lead to a biased estimator?


Views Exposed Filters - position each filter independently

Question: I am working on a drupal 7 project and have a view (v3) over 6,000 product items with 4 exposed filters.  This all works fine - I can put the "filter form" in a block - that is fine.
But I can't figure out how to separate out the individual filter drop downs for nicer positioning.  Say I want two dropdowns on the top of the result area and 2 with the apply button stacked on the left...
Is my only option to play with absolute positioning in the css?
Answer: you can add more functionalities to Exposed Filters forms, or control his style/layout, touching template views-exposed-form.tpl.php. try this resource http://drupal.org/node/320992 or this http://ykyuen.wordpress.com/2011/07/25/drupal-theme-the-exposed-filter-in-views/ to see guides about how to implement it.


How to get bounding shape for wrapped text in p5.js

Question: I'm creating a p5 project in which I create text from a string, wrap it using the 'WORD' option and add it to the canvas. As an example:
let font;

function preload() {
  font = loadFont('SomeFont.otf');
}

function setup() {
  createCanvas(400, 400);
  background(220);
  enteredText = 'This is an exmple of a long text that should split';
  textWrap(WORD);
  textSize(30);
  textAlign(CENTER, CENTER);
  textFont(font);
  textLeading(0.83 * 30);
  rectMode(CENTER);
  fill(0);
  noStroke();

  text(enteredText, width / 2, height / 2, 20 , 20);
}

I'd like to get a bounding shape for the text, in order to add some images on the frame.
How can I get this shape?
I thought about using textBounds(), but I also don't have the multiline string since textWrap() is doing it for me.
Any ideas? Re-writing textWrap() by myself feels like an overkill since there are so many properties for it.
Thanks!
Answer: That was a long time ago.  Maybe you know the answer already... In your code
enteredText, width / 2, height / 2, 20 , 20);
Since your chara ter size is 39, with 20,20 ^ here you will not be be able to prin even one letter. Instead of 20, 20 it should be 390, 400, for example.  You would adjust the numbers to your taste.  بنللي
Comment: Use code block to separate out the code change suggestions listed by you. Also please correct some typos


Squared distance from the mean monotonicity

Question: Let $S = \{ x_1,\ldots,x_n\}$ be a set of say real numbers and $\mu(S) = \sum_{x \in S} x/|S|$ be the average of numbers in $S$. We define the total squared distance of each element in $S$ to $\mu(S)$ as follows:
$$L(S) = \sum_{x \in S} (x - \mu(S))^2$$.
Now, for any $S' \subset S$, is it always true that
$$L(S') \leq L(S).$$
I think this is quite intuitive but I wonder if that's the case. If so, I wonder if there is a simple proof.
Answer: It is indeed true. Suppose that $n\ge 1$ and $m\ge 0$ and $S_{1} = \left(x_{1},\ldots,x_{n}\right)$ and $S_{2} = \left(x_{1},\ldots,x_{n},x_{n+1},\ldots, x_{n+m}\right)$, with $\mu_{i}$ being the mean of $S_{i}$ for $i=1,2$. We want to show that $L(S_{2})\ge L(S_{1})$.
We have
$$
\begin{align*}
L(S_{2}) &= \sum\limits_{k=1}^{n+m}\left(x_{k} - \mu_{2}\right)^{2} \\
&= \sum\limits_{k=1}^{n}\left(x_{k} - \mu_{2}\right)^{2} + \sum\limits_{k=n+1}^{n+m}\left(x_{k} - \mu_{2}\right)^{2}.
\end{align*}
$$
Now, observe that $\left(x_{k}-\mu_{2}\right)^{2} = \left(x_{k}-\mu_{1} + \mu_{1}-\mu_{2}\right)^{2} = \left(x_{k}-\mu_{1}\right)^{2} + 2\left(x_{k} - \mu_{1}\right)\left(\mu_{1}-\mu_{2}\right) + \left(\mu_{1}-\mu_{2}\right)^{2}$. Putting this into the above, we have
$$
\begin{align*}
L(S_{2}) &= \sum\limits_{k=1}^{n}\left(\left(x_{k}-\mu_{1}\right)^{2} + 2\left(x_{k} - \mu_{1}\right)\left(\mu_{1}-\mu_{2}\right) + \left(\mu_{1}-\mu_{2}\right)^{2}\right) + \sum\limits_{k=n+1}^{n+m}\left(x_{k} - \mu_{2}\right)^{2}\\
&= \underbrace{\sum\limits_{k=1}^{n}\left(x_{k}-\mu_{1}\right)^{2}}_{L(S_{1})} + 2\left(\mu_{1}-\mu_{2}\right)\underbrace{\sum\limits_{k=1}^{n}\left(x_{k}-\mu_{1}\right)}_{=0} + n\left(\mu_{1}-\mu_{2}\right)^{2}+ \sum\limits_{k=n+1}^{n+m}\left(x_{k} - \mu_{2}\right)^{2}\\
&= L(S_{1}) + n\left(\mu_{1}-\mu_{2}\right)^{2} + \sum\limits_{k=n+1}^{n+m}\left(x_{k} - \mu_{2}\right)^{2}\\
&\ge L(S_{1}),
\end{align*}
$$
as required.
Comment: Splendid. Seems correct to me. Many thanks!


Newton-Raphson Method

Question: just want somebody to help me verify if I'm doing using Newton-Raphson method correctly by checking the result of an equation.
$f(x) = e^{x-1} + x^2 - 7$
I'm trying to find the zero of f(x) with initial guess $x_0 = 1.5$, and by applying the method TWICE, I got result 2.0466.
Could somebody please help me verify my answer is correct?
Thanks in advance.
Comment: I'd run the process once more to see if the new value of $f(x)$ is really tiny, as it should be.
Comment: I agree, but did you get 2.0466 after 2 iterations as well?
Comment: @Stefan4024: Thanks for the beautification:)
Comment: Sorry, I just substituted into $f$ to see that the value was moderately small. I did not run the process (too lazy!).
Comment: No worries, point taken!
Answer: Your answer is almost correct. You have a rounding error. Try not to round the previous approximations. Use the "answer-key" on your calculator to store the exact answer. Only round at the very end. The correct answer is $2.0467$ to three decimal places.
The recurrence relation is given by
$$x_{n+1} = x_n - \frac{\operatorname{f}(x_n)}{\operatorname{f}'(x_n)}$$
In your case $\operatorname{f}'(x) = \operatorname{e}^{x-1}+2x$ and so
$$x_{n+1} = x_n - \frac{\operatorname{e}^{x_n-1}+x_n^2-7}{\operatorname{e}^{x_n-1}+2x_n}$$
If $x_0 = 1.5$ then
$$x_1 = 1.5 - \frac{\operatorname{e}^{0.5}+1.5^2-7}{\operatorname{e}^{0.5}+3} \approx 2.167$$
If $x_1 = 2.167...$ then
$$x_2 = 2.167... - \frac{\operatorname{e}^{1.167...}+(2.167...)^2-7}{\operatorname{e}^{1.167...}+3} \approx 2.0466567$$
Comment: great, that's exactly what I have on my board,thanks a lot!
Comment: @Vol_Smile No worries. I'm glad I could help.

Newton-Raphson Method


facets not showing all the options drupal commerce

Question: Go to this page if you take a look to the facets at the sidebar you will notice that they are not displaying all the available options.
When I search 1 word at the search bar for example "tract" then the facets work as expected, but when I use 1 or more words the facets does not display all the options... Does any body have had this issue before with Facets of Drupal commerce?
Any suggestions?
Comment: _Does any body have had this issue before with Facets of Drupal commerce?_ is a poll. Also, a question should not depend from an external link to be understood. Questions are also for future readers, not just the user who asks them; if the linked page changes, the question is not anymore understandable.
Answer: you should probably set the filter in the view like this


javascript eval intrinsic restrictions?

Question: I have a situation in which I have to use eval in Javascript. Yes, I know it is evil, but in this case it is required, because two requisites:

The Javascript code is big.
It has to be evaluated (and downloaded) only in a few situations, so I don't want the script to be downloaded always, but on demand.

With these requisites, I have written an XMLHttpRequest to request the code (600+K), and I want to eval that code to take place immediately. As I'll show later, the script contains just data to be inserted in two variables. The problem is that evaluating this javascript fails always with syntax error. If I put the code verbatim (without eval), the code executes fine. This is the minimal example. I have a search.js file like this:
// search.js for functional mind. Generated statically
// from the set of posts.
posts = { 'postlist' : ['YYY', 'other link...' ] };
posts_for_word = { 'word1' : [0,1], 'word2' : [Z,K] };

The last variable, posts_for_word includes indexes of posts containing that word. The problem comes when I evaluate that Javascript inside eval:
// global environment
var posts = {}; // Initial value, empty
var posts_for_word = {}; // same

function() {
var request = // create XMLHTTPREQUEST request
var response = // obtain response (the javascript)
eval( response ); // <- syntax error
// access posts or posts_for_word
posts.postlist[ posts_for_word['word1'][0] ]
....
}

The problems:

When I evaluate the javascript shown above with eval, firefox tells me that it is bad formed in the first line.
I then removed the comments. I supposed that eval would evaluate it as if it was a normal Javascript program, but it doesn't seem to accept comments (why?).
After removing the comments, the code works, but still the Javascript console of Firefox tells me that there is a syntax error in the first line (that defining the JSON first variable). Why?
Comment: The usual way to load javascript when needed is to insert a new script tag into the DOM. Is there a reason why this won't work in your case?
Comment: @cobbal, I tried that first. I may have done something wrong at that moment. I'll try it again, but it didn't work (I inserted the script, but the variables could not be found in the next javascript line). Anyway, the questions for `eval` are still open.
Answer: You shouldn't use AJAX and eval() to make a script happen on your website, instead, create a

javascript eval intrinsic restrictions?


How can I show the trefoil group is torsion-free

Question: I would like to show the trefoil group is torsion-free. The trefoil group has the presentation
\begin{equation}
G = \langle a, b \mid a^3 = b^2\rangle.
\end{equation}
I tried to map this to a simpler torsion-free group, for instance, if $h: G\to \mathbb{Z}$ by
\begin{equation}
a\to 2, b\to 3,
\end{equation}
then the torsion of $G$ must be in the kernel of $h$. However, the kernel is still pretty complicated.
Any ideas will be greatly appreciated!
Comment: In general, an open subset of $R^3$ has no torsion in the fundamental group, see [here](https://math.stackexchange.com/questions/680998/is-there-a-domain-in-mathbbr3-with-finite-non-trivial-pi-1-but-h-1-0). Perhaps there is a more direct approach though.
Comment: @MikePierce I think you mean there no way to reduce a word to length _zero_.
Comment: One way to see torsion-free-ness is to realise that this is a free product with amalgamation of two torsion-free groups (namely two copies of $\mathbb{Z}$). The result from here is pretty standard (e.g. via Bass-Serre theory, or I think in Magnus, Karrass and Solitar's book *Combinatorial Group Theory*). Alternatively, the group is a one-relator group whose relator is not a proper power, and so is torsion-free (this is definitely proven in Magnus, Karrass and Solitar, although better proofs exist now).
Comment: You could talk about the group elements in terms of words consisting of 'a's and 'b's and their inverses, and talk about their length after resolving a letter with its inverse, and frame the relation $aaa \to bb$ as a "rewrite rule" for those words, and prove that with that one rewrite rule there is now way to get a word of length one. ... This would all have to be made rigorous though, but I think approaching the task with that mindset helps.
Comment: The trefoil group is isomorphic to $ B_3 $, the braid group on 3 strands. And all braid groups are known to be torsion-free. Not self contained but maybe convincing for someone who thinks about braid groups a lot?
Answer: I'll try to rewrite  user1729's comment in more detail.
The theorem used is the following and can be found for example in Serre's Trees (Thm 8)

Every finite subgroup of $G=G_1\ast_A G_2$ is contained in a conjugate of $G_1$ or $G_2$.

Now, the trefoil group can be writen in the form $G=\mathbb{Z}\ast_A \mathbb{Z}$ where $A=\mathbb{Z}=\langle a \rangle$ and the two homomorphisms $f_2:A\to \mathbb{Z}=\langle x \rangle,\ f_3:A\to \mathbb{Z}=\langle y \rangle$ are $f_2(a)=x^2,\ f_3(a)=y^3$.
Therefore, if $g\in G$ is a torsion element then it should be an element of one of the two $\mathbb{Z}$'s. Since $\mathbb{Z}$ has no torsion elements it has to be $g=1$.
Comment: +1 Nice profile picture! (Also, it is maybe worth pointing out that the proof of Serre's Theorem 8 is not difficult, and is a nice introductory proof on groups acting on trees.)


Best statistical test for a particular biological experiment

Question: I have run an experiment in which I measure the expression of a particular gene under three different medium conditions (neutral,ATPlo,ATPhi). We took samples who have two different genotypes for a particular SNP (AA,AG).
What I would like to show is that for samples with the AA genotypes the medium has an effect on the expression of the gene while for samples with the AG genotype there is no effect.
Which is the best test to prove this?
If I do an Anova for samples with genotype AA considering the medium as a factor I get a significant pvalue. If I do Anova for samples with genotype AG the pvalue is not significant. If I do a two-way Anova(medium/genotype) with interaction effects the genotype is the only variable that comes up significant.
What can I conclude about my hypothesis? Are there other tests which are more appropriate?
Comment: Is the outcome whether or not the gene is expressed? Does the medium have an effect in the sense that the probability of expression differ between the two genotypes?
Comment: I forgot to mention that mediums are applied to cells coming from the same sample (so for every sample we have three measurements)
Comment: what kind of variable is expression of gene? (binary? presence/absence or continuous?)- as stated by @MichaelChernick this is important. Regarding your research question, i think you are looking for an interaction effect between genotype and medium. Do not test the genotypes separately since your hypothesis rely on factorial design. How many replicates do you have? Three measurements is TOO LOW for testing hypothesis, this is one of the reasons of your failure with testing. Try to get more data
Comment: My point was that if expression of gene is binary logistic regression might be a better model.
Comment: Gene expression is a continuous variable. For each combination genotype/medium I have 3 samples. I plan to get more data but only if at least there is a trend for significance (experiments are very expensive and you need to convince people to give you blood). The test I tried yesterday is two-way anova where Medium is a within-subject factor and genotype is a between-subject factor...in that case the pvalue for interaction is 0.054, that gives me some hope that it will get significant when I get more samples
Answer: Assuming you have sufficient biological and technical replicates that you have not mentioned, a regression analysis should be sufficient. If you have a one-off experiment you are unlikely to get any robust results due to the natural variance associated with this type of experiment.
There are 2 ways I would go about this, given enough statistical power. The second option will require a larger sample size, but will give 'better' results (the exact size will be specific to your experiment and methods).
Option 1: Stratified Linear Regression
Perform a stratified analysis - first analyze the cells with genotype AA, then with genotype AG, with expression of your gene as the outcome and the type of media as a factor variable. In this way you can see the effect of the 2 ATP media compared to the 'neutral' media, assuming that the neutral media is coded as the bottom, or lowest, category.
By then comparing the associations between the expression and media in the separate genotypes you could determine if the expression was more associated with the media type in the AA or AG cells.
Option 2: Instrumental Variable Analysis
Again using a linear regression, you can determine the variance in the gene expression data that is determined by the genotype. To do this simply use a linear regression with the expression as the outcome, and the genotype as the only independent variable. Extracting the 'fitted values' from the model gives the predicted expression using only the genotype.
This variable you have now extracted can be used as the new outcome in a linear model, again with the media-type as an explanatory factor variable. This model shows you the association between each ATP media-type (compared to the neutral media) and the expression variance caused by the genotype. If this association is significant, there is a causal association between the genotype and the expression, in the context of the different media.


Using a Variable as an Array Parameter in C++

Question: I am trying to write code that will compare a 10 sequence piece of DNA to that of a relative's 10 sequence DNA.  The user inputs their name, how many relatives they want to compare, and their DNA.  The computer outputs the percentage of a match.  ATTAGACGCA compared to ATAAGACGCA would match 90%.  The number of relatives is a constant after the user states how many relatives.  I have tried using const, but it doesn't seem to want to use the number.
/**********************************************************************
 * Get DNA Sequence
 ***********************************************************************/
void getMyDNA(char myDNA[])
{
   cout << "Enter your DNA sequence: ";
   cin >> myDNA;
}

/**********************************************************************
 * Get Potential Relatives
 ***********************************************************************/
int getRelatives()
{
   int relatives = 0;
   cout << "Enter the number of potential relatives: ";
   cin >> relatives;

   return relatives;
}

/**********************************************************************
 * Get Potential Relatives Names
 ***********************************************************************/
void getRelativeName(string relativeNames[], int relatives)
{
   string name;
   for (int i = 0; i < relatives; i++)
   {
      cout << "Please enter the name of relative #" << i + 1 << ": ";
      cin >> name;
      relativeNames[i] = name;
   }
}

/**********************************************************************
 * Get Potential Relatives DNA Sequence
 ***********************************************************************/
void getRelativeDNA(char relativeDNA[][10], string relativeNames[], int relatives)
{
   for (int i = 0; i < relatives; i++)
   {
      cout << "Please enter the DNA sequence for " << relativeNames[i] << ": ";
      cin >> relativeDNA[i];
   }
}

/**********************************************************************
 * Display Potential Relatives Match
 ***********************************************************************/
void displayMatch(string relativeNames, char relativeDNA[][10], int relatives, char myDNA[])
{
   const int family = relatives;
   int count[family] = 0;
   for (int r = 0; r < 3; r++) //relative number r
   {
      for (int d = 0; d < 10; d++) //dna piece number d
      {
         if (relativeDNA[r][d] == myDNA[d])
            count[r]++;
      }
   }
}

/**********************************************************************
 * Main
 ***********************************************************************/
int main()
{
   char myDNA[10];
   string relativeNames[50];
   char relativeDNA[50][10];

   // My DNA
   getMyDNA(myDNA);

   //# of relatives
   int relatives = getRelatives();
   cout << endl;

   //thier names
   getRelativeName(relativeNames,relatives);
   cout << endl;

   //their dna
   getRelativeDNA(relativeDNA,relativeNames,relatives);
   cout << endl;

   //display
   displayMatch(relativeNames,relativeDNA,relatives,myDNA);

   return 0;
}

Comment: C++ doesn't have [variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array) so technically that's not valid C++. If you want a variable-length array use [`std::vector`](http://en.cppreference.com/w/cpp/container/vector).
Comment: Also, what is `count` supposed to do? Is it an array or not?
Comment: I updated my question to include my entire code.  Count is supposed to count how many letters in the sequence of DNA between me and my relative are the same.
Answer: If count is a new array create a new array dynamically as follows...
int *count = new int[relatives];

I noticed you're using the following later...
count++;

Are you trying to increment an integer or move a pointer? This code might help make it clearer...
#include <assert.h>
#include <iostream>
#include <typeinfo>

int main(void) {
  const int x = 500;
  int* a = new int[x];
  size_t i = 0;
  for(i = 0; i < x;i++) {
    a[i] = i;
  }

  for(i = 0; i < x;i++) {
    //Print numbers without moving pointer
    std::cout << a[i] << std::endl;
  }
  for(i = 0; i < x;i++) {
    //Print numbers moving pointer
    std::cout << a[0] << std::endl;
    a++;
  }
  a = a - x;
  delete[] a;
  return 0;
}

Comment: Advising a beginner to use `new` for array is diabolic.
Comment: And no mention of using `delete[ ]`.
Comment: I'll fix it up in a tick
Answer: Even if the parameter is passed as const it won't work. You can try with an array created dynamically
int *count = new int[relatives];

Comment: Please do not use the term `vector` to describe what you're advising the OP.
Comment: I'm not sure `"dynamic array"` is a good term for this. Its size is variable, but the array is in no way dynamic.
Answer: Instead of
int count[relatives] = 0;

which is invalid as standard C++ when relatives can vary at run-time, use
std::vector<int> count( relatives );

Include the <vector> header.
Comment: @MatthewCliatt: Yes, the initializer would have to be fixed, like `{0}` (or just `{}`).
Comment: Even if `relatives` couldn't vary, wouldn't it still be invalid code? You can't assign an entire array to an integer.


How to schedule cron4j on Tomcat startup?

Question: I want my web server (Tomcat 8.5) to send emails automatically once every day while it's running. So I configured a StartUp-Servlet in web.xml to run on server startup. When I test it in eclipse, I get the error Starting Tomcat v8.5 Server at Localhost has encountered a problem. Server Tomcat was unable to start within 45 seconds...
I know, this is something happening in eclipse, but it seems, that the startup doesn't finish, and my server will never be able to to other tasks as it's busy starting up... I want it to instantiate the scheduler, but then finish start up and run the scheduler 'in background'.
What is the right way to trigger the scheduler during server start?
Answer: I found a way to do this. I implement a ServletContextListener instead. web.xml looks like this:
<listener>
    <listener-class>servlets.SendEmailJob</listener-class>
</listener>

and the Class:
public class SendEmailJob implements ServletContextListener {
    Scheduler scheduler = new Scheduler();

    public void contextInitialized(ServletContextEvent event) {
        scheduler.schedule("* * * * *", new Runnable() {
            public void run() {
                //sendEmail() - time pattern not specified yet
            }
        });
        // Starts the scheduler.
        scheduler.start();
    }

    public void contextDestroyed(ServletContextEvent event) {
        scheduler.stop();
        scheduler = null;
    }
}


What is the difference between 'String' and 'Text' in Angular 2?

Question: I have following code which takes both string and text as datatype; but I am confused as to what exactly differs them?
 export class Owner {
    CompanyName: string;
    Description: Text;
}

I am using Visual Studio 2015 Community Edition Update 3 and Typescript 1.8+.
Answer: The types are not something specific to Angular 2 - it's TypeScript. That code would compile without the Angular 2 dependency.
To answer your question, there is no Text basic type in TypeScript. You can see them all here. Text would then likely be an interface or class, which can be used as types.
string on the other hand, refers to the string primitive type in JavaScript (and TypeScript).

To further elaborate, Text is an interface describing the capabilities of an HTMLElement (or TextNode) without markup content. Like you mention in your comment, it is include in lib.d.ts, which is described here as

A special declaration file (that) ships with every installation of TypeScript. This file contains the ambient declarations for various common JavaScript constructs present in JavaScript runtimes and the DOM.
Comment: Yes, you are right,Thanks. it is an interface; By peeking its definition in visual studio-I figured that It is located in node_modules/typescript/lib/lib.d.ts.I could declare a variable using it without any warning or error but I am not sure whether any values can be attached to it or not.
Comment: @KaranDesai see my update above for further clarification


Plot a fitted curve on percentage histogram (not the actual data)

Question: I first try to draw my data as percentage as follows:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
plt.hist(data, weights=np.ones(len(data)) / len(data), bins=5)
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
plt.grid()
plt.show()

This will give me this.

Now I used this line to fit a curve on the "percentage data" as follows :
import seaborn as sns
p=sns.displot(data=data, x="Dist",kde=True, bins=5)

Which gives me this:

But this curve was fitted according to the data not the percent per 5 bins. If for example you had 10 bins you could understand why there was a bump at the end. That bump we don't want to see. What I really want is a curve as this
Comment: You forgot to include reproducible data.  You could try to increase the bandwidth of the kde, e.g. `sns.histplot(data=data, x="Dist", kde=True, stat='percent', bins=5, kde_kws={'bw_adjust': 3})`
Comment: @JohanC Thank you for your comment. I added the data at the end. Even though changing the bandwidth would make the end more smoother but it will make the beginning incorrect: the summit is much lower than the actual data.
Comment: @JohanC I was wondering if there is any other way? Say fitting data while using plt.hist
Answer: The kde plot approximates the data as a sum of guassian bell curves.
An idea could be to regroup the data and place them at the centers of each bar.
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

z = [1.83E-05,2.03E-05,3.19E-05,3.39E-05,3.46E-05,3.56E-05,3.63E-05,3.66E-05,4.13E-05,4.29E-05,4.29E-05,4.79E-05,5.01E-05,5.07E-05,5.08E-05,5.21E-05,5.39E-05,5.75E-05,5.91E-05,5.95E-05,5.98E-05,6.00E-05,6.40E-05,6.41E-05,6.67E-05,6.79E-05,6.79E-05,6.92E-05,7.03E-05,7.17E-05,7.45E-05,7.75E-05,7.99E-05,8.03E-05,8.31E-05,8.74E-05,9.69E-05,9.80E-05,9.86E-05,0.000108267,0.000108961,0.000109634,0.000111083,0.000111933,0.00011491,0.000126831,0.000135493,0.000138174,0.000141792,0.000150507,0.000155346,0.000155516,0.000202407,0.000243149,0.000248106,0.00025259,0.000254496,0.000258372,0.000258929,0.000265318,0.000293665,0.000312719,0.000430077]

counts, bin_edges = np.histogram(z, 5)
centers = (bin_edges[:-1] + bin_edges[1:]) / 2
regrouped_data = np.repeat(centers, counts)

sns.histplot(data=regrouped_data, kde=True, bins=bin_edges)

Normally, a kdeplot can be extended via the clip= parameter, but unfortunately kde_kws={'clip':bin_edges[[0,-1]]} doesn't work here.
To extend the kde, a trick could be to keep the highest and lowest value of the original data.  So, subtracting one of the counts of the first and last bin, and append the lowest and highest value to the regrouped data.
counts, bin_edges = np.histogram(z, 5)
centers = (bin_edges[:-1] + bin_edges[1:]) / 2
counts[[0, -1]] -= 1
regrouped_data = np.concatenate([np.repeat(centers, counts), bin_edges[[0, -1]]])

sns.histplot(data=regrouped_data, kde=True, bins=bin_edges, stat='percent')

Comment: Thank you for your time. I marked it as correct but still it would not be 100 percent correct as it is changing the actual percentage. For example the true percentage for the first bin is 60 percent but what you did would make it as 40 percent. What I wanted is to fit a beta distribution or something to the "percent data"
Comment: You can use `sns.histplot(..., stat='percent')` if you want to see percentages instead of counts.
Comment: Thank you! Is there any way to have the curve fully fit the first bin?
Comment: Adding the minimum of `z` to the regrouped data extends the kde, but also lowers the first peek a bit. Drawing the kde separately doesn't scale the kde to the height of the percentage histogram.


Mysql_query SQL command check

Question: Good day guys.
Can you check this line of code if it is right i can't find any answer.
<code>$comments_query = mysql_query("SELECT * FROM comments ORDER BY commentsID DESC WHERE postID=".$_GET['blog']);
</code>
And I know that this is old and unsafe way to reach mysql. But this is all that i can learn from old books.
Comment: please read it from http://www.w3schools.com/sql/ or some other good tutorial sites..`where` needs to be put first then comes the `order by`..
Answer: The clauses of a SQL statement come in this order:

SELECT
FROM
JOIN (if any)
WHERE
GROUP BY (if any)
ORDER BY
LIMIT

You have your WHERE after your ORDER BY.  You Can't Do That™.
Comment: So this is the right code?
$comments_query = mysql_query("SELECT * FROM comments WHERE postID=".$_GET['blog']." ORDER BY commentsID DESC");
Comment: It looks right to me. Does it work?
Comment: No It doesn't work. And Sublime text is not even coloring it right.
Comment: It's right but i had problem with something else... Thank you a lot
Comment: Be careful with IDE text color-coding in mixed-language environments (yours is sql/php). They often cause confusion.
Comment: I know. Now it is coloring right... Like before... Thanks again

Mysql_query SQL command check


Apache Camel MDC UnitOfWork

Question: We are currently using Apache Camel's (within Spring Boot Application) MDC logging functionality to log custom correlation ID. With Camel 2.x we've implemented a custom UnitOfWork which extends MDCUnitOfWork which sets additional MDC properties based on the Exchange provided. Since Camel 3 MDCUnitOfWork's constructor changed from
public MDCUnitOfWork(Exchange exchange) to
public MDCUnitOfWork(Exchange exchange, InflightRepository inflightRepository, String pattern, boolean allowUseOriginalMessage, boolean useBreadcrumb)
Do you have an idea, where to get all the additional constructor parameters from, when configuring the custom MDCUnitOfWork as a Spring bean?
Answer: super(exchange, exchange.getContext().getInflightRepository(), "", false, false);

Why don't you try this?
Comment: Thanks, that should do the job! Sadly, the whole idea of logging of custom properties is not working well with MDC.
Comment: Maybe @clausIbsen could help you if he sees this question.

Apache Camel MDC UnitOfWork


Let $H$ be a normal subgroup of index $n$ in a group $G$. Show that for all $g \in G, g^n \in H$

Question: I am having a lot of trouble understanding the solution to this problem.
$(gH)^n = g^nH \implies g^n \in H$
Why does $H^n$ just turn into the identity? I am very confused, any help is appreciated.
Comment: It should say $g^nH$ rather than $g^nH^n$.
Comment: See also: [Prove that if a normal subgroup $H$ of $ G$ has index $n$, then $g^n \in H$ for all $g \in G$](https://math.stackexchange.com/q/472672)
Answer: The index of $H$ in $G$ is the order of the quotient group $G/H$. Since $[G:H] = |G/H| = n$, by Lagrange, every element of $G/H$ has order dividing $n$. Hence, every coset $gH \in G/H$ has order dividing $n$, i.e. $(gH)^{n} = g^{n}H = eH =H$, the identity coset. Thus, $g^{n} \in H$, since if $aH=bH$, then $a^{-1}b \in H$ (here $a=e, b=g^{n}$).
Answer: The multiplication in the quotient group is defined this way: $$(aH)(bH) = (ab)H$$
no need to multiply $H$ by it self.
Answer: I'm not sure what you mean by the identity, but if you're asking why $H^n=H$, then the reason is because $H^n = \{ h_1\cdot\ldots\cdot h_n \,|\, h_i\in H \, \forall i\} $, and since $H$ is a subgroup, we get that $e\in H$ ( this gives us $H \subset H^n$ ) and that $H$ is closed under the group operation ( this gives us $H^n \subset H$ ).
Answer: A basic result on finite groups is that if $|G|=n$, then $g^n=1_G$ (the identity element in $G$), for all $g\in G$. Consider the projection homomorphism
$$
\pi\colon G\to G/H.
$$
Since $|G/H|=n$ by assumption, we have, for all $g\in G$,
$$
\pi(g^n)=(\pi(g))^n=1_{G/H}
$$
which means that $g^n\in\ker\pi=H$.
Comment: @Hristmar Because $\pi$ is the canonical projection, so by definition its kernel is $H$.
Comment: Why is the kernel H?
Answer: We have $gH = \{ gh \mid h \in H\}$, so in particular, if $gH = H$, then $e = gh$ for some $h \in H$ - i.e. $g^{-1}\in H$ and hence $g \in H$.
The converse is also true, so $$gH = H \iff g \in H$$
The proof is saying that since $H$ has index $n$, if $gH \in G/H$, then by Lagrange, $$H = (gH)^n = g^nH$$ so by the above, $g^n \in H$


Como funciona a remoção de árvore Binária em C

Question: Estou com diversas dúvidas no funcionamento de arvore binária em C.
Estou com um código e estou com dúvida de como funciona a remoção na árvore. Alguém poderia me explicar melhor o que está acontecendo em cada linha na parte da remoção?
Struct
struct No{
    int numero;
    struct No *esquerda;
    struct No *direita;
};
typedef struct No No;

Inserção
void inserir(No **pRaiz, int numero){
    if(*pRaiz == NULL){
        *pRaiz = (No *) malloc(sizeof(No));
        (*pRaiz)->esquerda = NULL;
        (*pRaiz)->direita = NULL;
        (*pRaiz)->numero = numero;
    }else{
        if(numero < (*pRaiz)->numero)
            inserir(&(*pRaiz)->esquerda, numero);
        if(numero > (*pRaiz)->numero)
            inserir(&(*pRaiz)->direita, numero);
    }
}

Remoção
No *MaiorDireita(No **no){
    if((*no)->direita != NULL)
       return MaiorDireita(&(*no)->direita);
    else{
       No *aux = *no;
       if((*no)->esquerda != NULL) // se nao houver essa verificacao, esse nó vai perder todos os seus filhos da esquerda!
          *no = (*no)->esquerda;
       else
          *no = NULL;
       return aux;
       }
}

No *MenorEsquerda(No **no){
    if((*no)->esquerda != NULL)
       return MenorEsquerda(&(*no)->esquerda);
    else{
       No *aux = *no;
       if((*no)->direita != NULL) // se nao houver essa verificacao, esse nó vai perder todos os seus filhos da direita!
          *no = (*no)->direita;
       else
          *no = NULL;
       return aux;
       }
}

void remover(No **pRaiz, int numero){
    if(*pRaiz == NULL){   // esta verificacao serve para caso o numero nao exista na arvore.
       printf("Numero nao existe na arvore!");
       getch();
       return;
    }
    if(numero < (*pRaiz)->numero)
       remover(&(*pRaiz)->esquerda, numero);
    else
       if(numero > (*pRaiz)->numero)
          remover(&(*pRaiz)->direita, numero);
       else{    // se nao eh menor nem maior, logo, eh o numero que estou procurando! :)
          No *pAux = *pRaiz;     // quem programar no Embarcadero vai ter que declarar o pAux no inicio do void! :[
          if (((*pRaiz)->esquerda == NULL) && ((*pRaiz)->direita == NULL)){         // se nao houver filhos...
                free(pAux);
                (*pRaiz) = NULL;
               }
          else{     // so tem o filho da direita
             if ((*pRaiz)->esquerda == NULL){
                (*pRaiz) = (*pRaiz)->direita;
                pAux->direita = NULL;
                free(pAux); pAux = NULL;
                }
             else{            //so tem filho da esquerda
                if ((*pRaiz)->direita == NULL){
                    (*pRaiz) = (*pRaiz)->esquerda;
                    pAux->esquerda = NULL;
                    free(pAux); pAux = NULL;
                    }
                else{       //Escolhi fazer o maior filho direito da subarvore esquerda.
                   pAux = MaiorDireita(&(*pRaiz)->esquerda); //se vc quiser usar o Menor da esquerda, so o que mudaria seria isso:
                   pAux->esquerda = (*pRaiz)->esquerda;          //        pAux = MenorEsquerda(&(*pRaiz)->direita);
                   pAux->direita = (*pRaiz)->direita;
                   (*pRaiz)->esquerda = (*pRaiz)->direita = NULL;
                   free((*pRaiz));  *pRaiz = pAux;  pAux = NULL;
                   }
                }
             }
          }
}

Answer: Essa é uma árvore binária que guarda inteiros em nós intermediários, além das folhas, e com a propriedade de que todos os números na subárvore esquerda de um determinado nó são estritamente menores que o número do nó. Números iguais ou maiores ficam na subárvore direita.
Então vamos lá:
void remover(No **pRaiz, int numero){

A função de remoção recebe um ponteiro para um ponteiro para um nó; isto é necessário caso o número a ser removido (listado no segundo parâmetro) seja encontrado no próprio nó raiz: neste caso, o endereço de pRaiz tem que mudar para a função que chama remover().
A primeira coisa que se faz é testar para ver se a árvore está vazia, e se estiver, terminar:
    if(*pRaiz == NULL){   // esta verificacao serve para caso o numero nao exista na arvore.
       printf("Numero nao existe na arvore!");
       getch(); // getch() é fogo, mas tudo bem
       return;
    }

Apesar de ele escrever uma mensagem de "erro", isto é um comportamento correto. Se você manda remover um elemento que não existe de uma estrutura, ele não faz nada, e você pode assumir que aquele elemento não existe mais na estrutura. Se ele existia antes ou não, não faz diferença.
Em seguida, ele compara o número para saber em que sub-árvore ele está. Para isto, ele testa um conjunto de condições em ordem, e vai descartando as possibilidades metodicamente. Pessoalmente, eu não faria este tipo de indentação e manteria tudo no mesmo nível, mas vamos explicar o código que existe, não o que eu escreveria:
O primeiro caso é se o número procurado é menor que o número do nó atual:
    if(numero < (*pRaiz)->numero)
       remover(&(*pRaiz)->esquerda, numero);

Se for, ele deve estar, por construção, na subárvore esquerda. Executamos, então, o mesmo algoritmo recursivamente na subárvore esquerda.
Se não for, então verificamos se o número procurado é maior que o número atual. Se for, ele estará na subárvore direita, e executamos o algoritmo recursivamente na subárvore direita.
    else
        if(numero > (*pRaiz)->numero)
            remover(&(*pRaiz)->direita, numero);

Finalmente, tendo eliminado a possibilidade de o número ser maior ou menor, concluímos que o número está localizado na raiz desta árvore. Então pRaiz é o nó a ser removido! Procedemos, portanto, com o processo de remoção:
        else{    // se nao eh menor nem maior, logo, eh o numero que estou procurando! :)

Primeiro criamos uma variável auxiliar para manipular os nós. O comentário se refere ao fato de compiladores que não atendem ao padrão C99 exigirem que todas as variáveis locais sejam declaradas no princípio das funções. É o que eu normalmente faço por portabilidade, mas outros não gostam...
            No *pAux = *pRaiz;     // quem programar no Embarcadero vai ter que declarar o pAux no inicio do void! :[

Agora tratamos o caso de pRaiz ser uma folha, isto é, não tem filhos nem à esquerda, nem à direita. Neste caso, é só apagar o nó e correr para o abraço:
            if (((*pRaiz)->esquerda == NULL) && ((*pRaiz)->direita == NULL)){         // se nao houver filhos...
                free(pAux);
                (*pRaiz) = NULL;
            }

É claro, a probabilidade de o nó ser uma folha é baixa; neste caso, você tem que lidar com as subárvores. Um dos nós vai ter que substituir esse nó que você está apagando, e as subárvores vão ficar penduradas nesse novo nó.
Esse novo nó tem que ser ou o maior número da subárvore esquerda, ou o menor número da subárvore direita. Ele começa tratando os casos em que ou um, ou outro é nulo: neste caso, basta substituir o nó com a subárvore que existe.
            else{     // so tem o filho da direita
                if ((*pRaiz)->esquerda == NULL){
                    (*pRaiz) = (*pRaiz)->direita;
                    pAux->direita = NULL;
                    free(pAux); pAux = NULL;
                }
                else{            //so tem filho da esquerda
                    if ((*pRaiz)->direita == NULL){
                        (*pRaiz) = (*pRaiz)->esquerda;
                        pAux->esquerda = NULL;
                        free(pAux); pAux = NULL;
                    }

Neste caso, o final e mais complicado, o item tem filhos em ambos os lados. Aí não basta simplesmente substituir o nó por uma das duas árvores, você tem que escolher ou o maior nó à esquerda ou o menor nó à direita do cara que você quer apagar. No caso, o autor escolheu o maior nó à esquerda. Ele então "dá um passo à esquerda" e vai descendo a árvore à direita até encontrar um nó que não tenha subárvore direita. Isso foi encapsulado na função MaiorDireita().
Depois disso, ele pega a subárvore direita do nó e pendura na direita da nova raiz; e o mesmo com a subárvore esquerda. Depois é só destruir a antiga raiz e retornar.
                    else{       //Escolhi fazer o maior filho direito da subarvore esquerda.
                        pAux = MaiorDireita(&(*pRaiz)->esquerda); //se vc quiser usar o Menor da esquerda, so o que mudaria seria isso:
                        pAux->esquerda = (*pRaiz)->esquerda;          //        pAux = MenorEsquerda(&(*pRaiz)->direita);
                        pAux->direita = (*pRaiz)->direita;
                        (*pRaiz)->esquerda = (*pRaiz)->direita = NULL;
                        free((*pRaiz));  *pRaiz = pAux;  pAux = NULL;
                     }
                 }
             }
         }
     }

No caso do MaiorDireita(), o que ele tem que fazer é pegar uma árvore (que vai ser a subárvore esquerda de um nó que queremos apagar), e ir descendo para a direita até não conseguir mais. O nó onde pararmos é o nó que queremos retornar, mas antes precisamos removê-lo da árvore.
Note que ele, por construção, não tem uma subárvore direita, mas pode ter esquerda. Neste caso, vamos fazer como fizemos no caso análogo na remover() e substituí-lo pelo seu filho esquerdo. Agora que ele está fora da subárvore e não tem mais filhos pendurados nele, pode ser retornado para substituir o raiz acima:
No *MaiorDireita(No **no){

Começamos andando recursivamente à direita até não podermos mais;
    if((*no)->direita != NULL)
       return MaiorDireita(&(*no)->direita);
    else{

Não podendo andar mais à direita, guardamos uma referência ao nó que vamos retornar;
        No *aux = *no;

Pegamos a subárvore esquerda do nó, se houver, e a colamos no lugar do nó atual;
        if((*no)->esquerda != NULL) // se nao houver essa verificacao, esse nó vai perder todos os seus filhos da esquerda!
           *no = (*no)->esquerda;
        else
           *no = NULL;

E retornamos o nó.
        return aux;
    }
}

A MenorDireita() é igual, mutatis mutandis.
Comment: você teria algum código com explicação mais fácil?
Comment: Qualquer código que faça o que esse código faz não será _muito_ mais simples que isso. Existe um limite mínimo de complexidade para uma dada tarefa. Mas talvez a explicação seja muito verborrágica, aí você poderia apontar as partes que estão confusas para eu tentar melhorar...
Answer: Você está a remover um valor dentro de uma árvore binária de busca (ele sempre mantém a ordenação após a remoção, então necessariamente ela está ordenada). Dê uma lida no artigo de árvore binária de busca da Wikipédia, vai ajudar seu entendimento.
Esses diversos ifs e elses aí estão para testar como será feita a reinserção dos valores filhos do nó. Por exemplo, ele verifica se é uma folha (caso Remoção na folha):  não precisa reinserir nada; se ele possui apenas um único filho (caso Remoção de nó com um filho): reinsere a subárvore no lugar do nó removido; se ele possui dois filhos (caso Remoção de nó com dois filhos): nesse caso, ele coloca o menor elemento filho do nó removido em seu lugar (igual ao exemplo da Wikipédia).
A estrutura de dados árvore binária funciona igual em toda e qualquer linguagem de programação escolhida. Em algumas, você terá de adaptar o conceito de objeto e métodos de acesso para o paradigma procedural (C), enquanto outras você pode manter perfeitamente o uso como tipo abstrato de dado (Java, Python, C++). Dependendo do paradigma, você pode escrever mais ou menos, pode ser mais ou menos flexível, mas a ideia central é a mesma em todas elas.