Regression techniques similar to Kriging/Gaussian process regression

Question: I am looking for regression techniques which are similar to Kriging/Gaussian process regression, in that no explicit model needs to be specified. (Discounting the prior over functions) I have three independent variables and one dependent variable to which I want to apply such a procedure. The independent variables specify coordinates (locations in 3D), while the dependent variable specifies Wi-Fi signal strength at the given coordinates. Since it is hard to appropriately visualize such high dimensional data, techniques without explicit model dependence are of primary interest. The only similar technique I found was the somewhat unsophisticated Nearest-neighbour interpolation.
Are the above-mentioned techniques the only choices for such a problem?
Answer: I would add a more detailed description of the problem you are trying to solve as your question is very vague. What are you trying to attack with Kriging/Gaussian process regression? Any clue on the nature of your problem could really help you get a better answer. Anyway, you could basically use some of a wide array of non-parametric machine learning algorithms. For example: CART, random forest, boosted regression trees, etc. Even though you don't want to specify an explicit model, you do have a problem of the form: $Y:=X_{1}+X_{2}+X_{3}$. You can fit any of these models to your data, for example, fitting random forest in R would go something like this:
fittedmodel <- randomForest(Y~X1+X2+X3,data=yourdata, ntree=1000)

fittedmodel <- randomForest(Y=yourdata[,1],X=yourdata[,2:4], ntree=1000)

The random forest R implementation has more parameters to play with, but in general is a model that requires little tuning so just using the defaults as I am doing here can give acceptable results.
What are you doing this for? if you want to interpolate a map, you can then use this trained model on your unlabelled observations, that simply must have values for the independent variables ($X_{1}, X_{2}, X_{3}$):
interpolation <- predict(fittedmodel,unlabeleddata)

Also, if you are interpolating a map, introducing the coordinates as independent variables is sometimes quite helpful.
Comment: Thanks for the answer; I have added a line about my problem. It is basically about Wi-Fi strengths observed at different locations.
Comment: Then I definetly think this could definetly be an approach you would follow.Just train one of these models on the locations where you know the Wi-Fi strengh and predict for the rest of the locations. You might get a good model. I don't think it is all that hard to visualize this result (X1,X2,X3) would be your 3d coordinates and the Y could be a color, like a 3d contour plot. There should be some 3d kriging examples out there. In the worst case, something like this: http://stackoverflow.com/questions/3786189/r-4d-plot-x-y-z-colours.
Comment: Thanks for the guidance. When I said visualization is hard, I meant to say that I found it hard to ascertain an appropriate model from the kind of visualization you suggested; the Wi-Fi signal strengths are quite close.
Answer: You could try Locally Weighted Linear Regression (wiki article). In fact there is a connection between the two techniques (local regression and GP regression) as described in pg. 26 of the GPML book.


Postgresql not running?

Question: I installed PostgreSQL and trying to connect:
$ psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

$ ps aux | grep postg

$ sudo service postgresql start - does not result.
$ psql -U ivan -h localhost msg_proxy
psql: could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

Why? My iptables seems ok:
$ sudo iptables-save
# Generated by iptables-save v1.6.0 on Mon Feb  6 13:31:17 2017
*filter
:INPUT ACCEPT [43867:5867960]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [34820:18177695]
COMMIT
# Completed on Mon Feb  6 13:31:17 2017

Output of sudo netstat -pant | grep postgres is empty
Comment: Can you see a PostgreSQL Process running, when calling `ps aux | grep postgres`
Comment: @BenH no. empty output
Comment: which OS do you use?
Comment: "Connection refused" usually means there is no server listening on that TCP port on that IP address.  (it could also mean a firewall blocked the connection)  Probably postgresql is either not running, or not configured to listen on that address and/or port.
Comment: @BenH ubuntu 16.04
Comment: try looking at this: [link](http://manpages.ubuntu.com/manpages/trusty/en/man8/pg_ctlcluster.8.html)
Answer: Respodning to this old question maybe is not the best idea, as this question lucks of a few information like:

Operating System
PostgreSQL Version
From where are you trying to connect (same machine?)
Not well described problem and trials you performed (does not result?)

As the output indicates, either PostgeSQL is not running either not accepting connections:

If in your processes do not see the PostgreSQL, are you sure
PostgreSQL is there?
ps aux | grep postgres

If your PostgreSQL is located to another server inside same network
try the following:
psql -h db-address -d db-name -U username -W

Postgresql not running?


How to handle fragment backstack

Question: I'm having problem with fragment. Lets try to understand my issue, I have two fragment A and B. When app start with main activity,i start fragment A as you can see :
 getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new MusicFragment())
                .commit();

When i click on a button, it starts fragment B
 getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new BarFragment())
                .addToBackStack(null)
                .commit();

Main problem is after starting fragment B,when i pressed back to go back to fragment A , Fragment A Recreated with new state.
I don' want to recreate fragment A. I only want to start fragment from old state where i left. How to fix it ?
Comment: i answered -> https://stackoverflow.com/questions/62498487/fragmenttransaction-add-fragment-after-replace-old-fragment-but-ondestroyview-ca/62498976#62498976
Comment: show a example code. Answer this question
Answer: Instead of calling the replace method you should be calling the add method with a subsequent call to addToBackStack with an argument of null. The add method adds the fragement to the stack with a null tag and calling the addToBackStack with an argument of null then the current fragment is stopped upon commit. If the method is not called then the current fragment is destroyed and recreated when coming back.
getSupportFragmentManager().beginTransaction()
            .add(R.id.fragment_container,new BarFragment())
            .addToBackStack(null)
            .commit();

You can clearly find it in the documentation quote saying this:

If you don't call addToBackStack() when you perform a transaction that
removes a fragment, then that fragment is destroyed when the
transaction is committed and the user cannot navigate back to it.
Whereas, if you do call addToBackStack() when removing a fragment,
then the fragment is stopped and is later resumed if the user
navigates back.
Comment: it can be `null` no problem
Comment: try removing the line `addToBackStack` from both fragments
Comment: what means ID in addToBackStack()
Comment: Congrats bro , you got it. Problem is solved. Now it is working too good. Thanxxxx
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/216636/discussion-between-mukul-jangir-and-abhinav-chauhan).
Answer: Here are some points that need to be taken care while creating fragments.
Check the backstack if the fragment is already created.
If it was created previously pop it from the backstack and put it on top so that it is visible to the user.
If fragment is not present in backstack crate it and store it in backstack.
Create a method like below which will handle such situation.
private void openFragment(Fragment fragment_to_be_opened){
      String fragment_to_be_opened_name = fragment_to_be_opened.getClass().getName();
      FragmentManager manager = getSupportFragmentManager();
// fetching the fragment if it is present in backstack
      boolean fragment_allready_present = manager.popBackStackImmediate (fragment_to_be_opened_name, 0);
      if (!fragment_allready_present){ //fragment is not present in backstack so create it and save the name in //backstack
        FragmentTransaction fragment_trasition = manager.beginTransaction();
        fragment_trasition.replace(R.id.fragment_container, fragment_to_be_opened);
        fragment_trasition.addToBackStack(fragment_to_be_opened_name);
        fragment_trasition.commit();
      }
    }

Now call this method from the activity to open a new fragment like
// create instance of fragment and pass it to the open fragment method
Fragment myFragment = new myFragment();
 openFragment(myFragment);

How to handle fragment backstack


unable to create new site

Question: I am new to drupal. Trying to understand the possibilities of drupal, I have installed drupal8 and followed some tutorials to create a site with a custom theme, custom modules and custom blocks.
So far so good.
Now I have this first test site working (installation in public_html), I wanted to create a second site, served by the same installation. I want to try and make a drupal8 version of an existing site of my company.
Following more tutorials, I have tried several things, but I am unable to get it working. I did the following:

my first site's URL is http://localhost, I tried to get the url http://localhost/owtest working
In public_html I have created a symlink with name owtest
In sites/ I created a directory owtest, containing a settings.php and an empty directory files/

I created a database for the new site. The first site's database name was 'DRUPAL' with user 'DRUPAL', for the new site I created database 'OW' with the same user.
in owtest/settings.php, I changed the database name to OW
I ran update.php, thereby clearing the cashes.

If I now go to 'localhost/owtest', it looks the same as the 'localhost' site; if I add content to the site, the same content appears to the 'localhost' site. It seems the new site does not use the new database.
Clearly, I am missing a required step. Who can help me in getting this to work?
My sites/owtest/setting.php now contains
<code>$databases['default']['default'] = array (
'database' => 'OW',
'username' => 'drupal',
'password' => 'drupal',
'prefix' => '',
'host' => 'localhost',
'port' => '3306',
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
'driver' => 'mysql',
);
</code>
thanks for helping me, Ruud
Answer: I managed to get it working. The missing link was the sites/sites.php file.
Although I did provide that, it started working after I put the following in it:
<code>$sites = array(
   'localhost.owtest' => 'owtest',
   'localhost' => 'default',
);
</code>
I can now browse to localhost/owtest and have a completely different content collection that is used by the localhost site itself.
Now I am facing a style problem, I keep tring...
Ruud
Comment: Now the new site was accessible, it had no style: the whole content was plain text. This appeared to be a file privilege issue. I checked all the privileges. In my case, the file directory was of the wrong user/group. It was important to clear the cashed to see the effect.

unable to create new site


Evitar mensagem de demora de resposta

Question: Estou desenvolvendo um aplicativo que consome, via REST, um serviço de terceiros.
Em alguns casos o serviço demora a me responder e, como o aplicativo fica esperando resposta surge uma mensagem oferecendo ao usuário a opção de aguardar ou encerrar o aplicativo, tal qual como mostra a imagem abaixo:

Esta mensagem aparece principalmente quando uso conexão 3G para consumir o serviço.
Existe alguma forma de evitar esta mensagem ou aumentar o tempo de resposta indefinidamente?
Eu não utilizei AsyncTask. Eu tentei realizar algumas adaptações mas não obtive sucesso. Então eu gostaria de saber se, dentro destas circunstâncias, existe a possibilidade de evitar a mensagem. Se a utilização do AsyncTask for a única maneira de evitar este cenário eu apreciaria bastante a recomendação de um material (ou explicação) que seja compreensível para alguém que não possui tanta experiência com Android, como eu =)
Desde já, agradeço =)
Answer: Me supreende você sequer conseguir consumir um serviço sem utilizar AsyncTask.
De qualquer forma. As opções que você tem, que alias são as mais comuns, é utilizar Volley ou Retrofit
Tem bastantes material por ai, como este:
https://www.youtube.com/watch?v=V2nwFenaWRM
e este http://www.devmedia.com.br/android-retrofit-primeiros-passos-com-a-retrofit-api/31857
Exemplo com volley:
<code>    final TextView tvMeuTextView = (TextView) findViewById(R.id.meu_textview);

    String url = "http://www.meu.server.com/meujson";

    JsonObjectRequest jsObjRequest = new JsonObjectRequest
            (Request.Method.GET, url, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    tvMeuTextView.setText("Resposta do servidor: " + response.toString());
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // em caso de erro na requisição, trata-o aqui
                }
            });

    //Preferencialmente crie um singleton para isso
    Volley.newRequestQueue(this).add(jsObjRequest);
</code>
Comment: Olá,  @Androiderson. Você poderia incluir uma pequena demonstração de código na sua resposta? Caso algum dia esses links fiquem indisponíves, ainda existirá código aqui de backup. Além de agregar mais valor ao stackoverflow.

Evitar mensagem de demora de resposta


Failed to decode bytes - IronPython

Question: I have some files with unicode data, the following code works fine when working with CPython to read those files, whereas the code crashes on IronPython saying "failed to decode bytes at index 67"
for f in self.list_of_files:
            all_words_in_file = []

            with codecs.open(f,encoding="utf-8-sig") as file_obj:
                for line in file_obj:
                    all_words_in_file.extend(line.split(" "))

            #print "Normalising unicode strings"

            normal_list = []
            #gets all the words and remove duplicate words
            #the list will contain unique normalized words
            for l in all_words_in_file:
                    normal_list.append(normalize('NFKC',l))

            file_listing.update({f:normal_list})
        return file_listing

I cannot understand the reason, is there another way to read unicode data in ironpython?
Answer: How about this one:
def lines(filename):
    f = open(filename, "rb")
    yield f.readline()[3:].strip().decode("utf-8")
    for line in f:
        yield line.strip().decode("utf-8")
    f.close()

for line in lines("text-utf8-with-bom.txt"):
    all_words_in_file.extend(line.split(" "))

I have also filed a IronPython bug https://ironpython.codeplex.com/workitem/34951
As long as you are feeding entire lines to decode, things will be ok.
Comment: The bug can be traced back to EncoderFallbackBuffer.Fallback method in .net not following documentation in case of utf-8 encoding.

Failed to decode bytes - IronPython


Comparing non-nested GLMMs with AIC

Question: Suppose I want to compare four non-nested models:
m0 = lm(y ~ 1)

m1 = lm(y ~ x)

m2 = lmer(y ~ 1 +(1|A))

m3 = lmer(y ~ x + (1|A))

Can we use AIC to compare models, even across different model types (lm vs. lmer)?
Answer: Yes, you can compare these models with AIC. You may have to fit m2 and m3 with maximum likelihood to do so. (The default method for lmer is REML.) Be sure to inspect graphs of model fits.
Answer: First, note that these models are, in fact, nested. m2 is nested in m3 (the coefficient for x is effectively constrained to be zero in m2. m0 is nested in m1 for the same reason. m1 is nested in m3 (with the random intercept variance for Aset to zero in m1.  So they could be compared using a likelihood ratio test (with the mixed models being fitted with REML = FALSE).
That said, it is also possible to compare the models using AIC (with the same proviso that the mixed models not be fitted with restricted maximum likelihood).
Note that both AIC and likelihood ratio tests have issues concerning boundary problems imposed by estimating strictly positive quantities (that
is, variance components in mixed models) though this is discussed in detail in other questions and answers elsewhere on CV.

Comparing non-nested GLMMs with AIC


How is the Fourier transform a generalization to the Fourier series?

Question: I have taken a self-tought course on the subject of Fourier series
and Fourier transform and I got the message that the latter is a generalization of the first.
I know that the idea that the Fourier series assumes that the function
$f$ is $2\pi$ periodic (or $2L$ for some $L\in\mathbb{R}$) and
that the Fourier series approximate $f$ using a sum of $\cos$ and
$\sin$ functions that is evaluated in a continues way rather then
a discrete one at the points of $\mathbb{Z}$.
The motivation for the Fourier series is clear to me - this is just
the best approximation to $f$ is the span of a subvector space -
$\{e^{int}\}_{n=-\infty}^{n=\infty}$
I want a motivation for the definition of the Fourier transform:
$$
F(\omega)=\int_{-\infty}^{\infty}f(t)e^{-i\omega t}dt
$$

For starter - It seems that is should be the case that if I take
$f$ which is $2\pi$periodic I would get something similar to the
Fourier series of $f$, this is what I tried:

$$
F(\omega)=\int_{-\infty}^{\infty}f(t)e^{-i\omega t}dt
$$
$$
=\sum_{n=-\infty}^{\infty}\int_{2\pi n-\pi}^{2\pi(n+2)-\pi}f(t)e^{-i\omega t}dt
$$
and since $f$ is $2\pi$ and so is $e^{-i\omega t}$ it follows that
the last integral equals to
$$
=\sum_{n=-\infty}^{\infty}\int_{-\pi}^{\pi}f(t)e^{-i\omega t}dt\,\,\,\,(1)
$$
The Fourier series is
$$
f(t)\sim\sum_{n=-\infty}^{\infty}(\int_{-\pi}^{\pi}f(t)e^{-int}dt)e^{int}
$$
and if I allow myself to change the notation a bit
$$
f(\omega)\sim\sum_{n=-\infty}^{\infty}(\int_{-\pi}^{\pi}f(t)e^{-int}dt)e^{in\omega}\,\,\,\,(2)
$$
I can see that $(1)$ and $(2)$ are similar, but I couldn't get from
one to the other, I tried inserting $e^{int}e^{-int}$ into the integrand
in ($1)$, but with no success.

There is also a definition of the Fourier series of a function
defined on $[-L,L]$ which is $2L$ periodic, I want to let $L\to\infty$
and get the definition of the Fourier transform, but I didn't manage
to do this, I had trouble taking the limit of the form
$$
\frac{1}{2L}\int_{-L}^{L}...
$$

since as $L\to\infty$ we get $\frac{1}{2L}\to0$
Can someone please help me to understand the relation between the
two expression $(1)$ and $(2)$ and to take the limit above and
get to the definition of the Fourier transform ?
Comment: Under your (1) you have written $f(t)\sim\sum_{n=-\infty}^{\infty}(\int_{-\pi}^{\pi}f(t)e^{-it}dt)e^{int}$. In the integral there is not any term of $n$. This integral doesn't equal $c_n(f)$. This is a first observation.
Comment: @Mitsos - seems that I forgot the $n$, should be ok now
Comment: One way to motivate the Fourier transform (in its various incarnations) is to seek a basis of eigenvectors (or eigenfunctions) for the shift operator (in various contexts).
Answer: The Fourier inversion theorem has two different forms:
$$f(t) \sim \sum_{n=-\infty}^{\infty} \left(\int_{-\pi}^{\pi} f(x)e^{-inx}\,dx\right) e^{int}$$
and
$$f(t) \sim \int_{-\infty}^{\infty}\left(\int_{-\infty}^{\infty} f(x)e^{-i\omega x}\,dx\right)e^{i\omega t}\,d\omega.$$
You seem to be a bit mixed up on that point since at one point you're referencing the inversion theorem (writing $f$ as its Fourier series) but at another you're only referencing the Fourier transform. This explains why you're "missing" a complex exponential: you're comparing the wrong things.
If you discretized the $\omega$ you were interested in and appropriately changed the measure from the Lebesgue measure to the counting measure, then you'd get something slightly resembling Fourier series. You still need to adjust the inner integral but that can be done by assuming $f$ is band-limited (which can be thought of as the restriction to $2\pi$ periodic functions). In some sense, the Shannon sampling theorem bridges the gap between Fourier series and Fourier transforms quite naturally.
As for how to "derive" the Fourier transform from Fourier series as you'd like to in your second point, I highly suggest looking up the heuristic argument given by Boggess in the appendix in A First Course with Fourier Analysis. If you would like, I can recreate the argument here.
Answer: The way that Fourier came up with the Fourier transform and its inverse is through a contorted limiting process of the Fourier series expansion on $[-c,c]$ as $c\rightarrow\infty$. Most things that Fourier did could be fully justified once Math had evolved enough, but his arguments leading to the Fourier transform were horrible and cannot be made rigorous, even though he ended up with the correct result. The simple idea behind the arguments is that if you start with $c=\pi$, then you need terms $\cos(nx)$, $\sin(nx)$ to express $f$. If you multiply the length by a positive integer $N$ so that you are looking at $[-cN,cN]$, then you need $\cos(nx/N)$ and $\sin(nx/N)$. Finally the limit results in a continuum of modes is needed to reconstruct a function $f$ on $(-\infty,\infty)$.
One way to see what is going on is to assume $f$ is continuous and vanishes outside some interval $[-R,R]$. For $N\pi > R$, you can write
\begin{align}
              f(x) & = \sum_{n=-\infty}^{\infty}e^{inx/N}\frac{1}{2\pi N}\int_{-\infty}^{\infty}e^{-int/N}f(t)dt \\
             & = \frac{1}{2\pi}\sum_{n=-\infty}^{\infty}\left[e^{ixs}\int_{-R}^{R}f(t)e^{-ist}dt\right]_{s=n/N}\frac{1}{N}
\end{align}
That looks like a Riemann sum with $\Delta s = \frac{1}{N}$ and evaluation points $\frac{n}{N}$ for $n=0,\pm 1,\pm 2,\pm 3,\cdots$. If you assume $f$ vanishes outside $[-R,R]$ as we have done, and further assume that $f'$ and $f''$ are continuous on $\mathbb{R}$, then, for $\epsilon > 0$, you can find $R_{0}$ large enough that
$$
              \left|\frac{1}{2\pi}\sum_{|n/N| > R_{0}}...\right| < \epsilon/3.
$$
and choose $N$ large enough that
$$
               \left|\left(\frac{1}{2\pi}\sum_{|n/N| \le R_{0}} ...\right) - \frac{1}{2\pi}\int_{-R_{0}}^{R_{0}}e^{isx}\int_{-R}^{R}e^{-ist}f(t)dt ds\right| < \epsilon/3
$$
and
$$
        \left|\frac{1}{2\pi}\int_{-R_{0}}^{R_{0}}e^{isx}\int_{-R}^{R}e^{-ist}f(t)dt ds-\int_{-\infty}^{\infty}e^{isx}\int_{-R}^{R}e^{-ist}f(t)dt ds\right| < \epsilon/3
$$
So, at least for some smooth compactly supported functions, you can evaluate the limit to be what you expect:
$$
          \frac{1}{2\pi}\int_{-\infty}^{\infty}e^{isx}\int_{-R}^{R}e^{-ist}f(t)dt ds = f(x).
$$
Then you can work on removing the restriction that $f$ is compactly supported.
Comment: Thank you, I derived the quantity now, after your guidance.
Comment: I know this is an old question. But could you please tell me how the reasoning goes in "you can find R_0 large enough that | \sum....|<epsilon/3. Why is this so?
Comment: @LeastSquaresWonderer : Assuming the function is compactly supported with a couple of derivatives (which was stated,) then integration by parts can be used to prove that the coefficients fall off at a nice predictable rate as a function of $n$.


Create configuration storage programmattically for list_string

Question: On a paragraph type, I have a field I want to migrate to a new field of type "list_string". To do that in the deployment and like our automatic deployment begin by an update of the database follow by importation of configurations, I want to create the new field programmatically before to do the migration in another hook_update.
I'm using the example of this article https://www.metaltoad.com/blog/programmatically-importing-drupal-8-field-configurations which is perfect except I have a problem because my new field is of type list_string. My configuration for field.storage is:
<code>langcode: fr
status: true
dependencies:
  module:
    - options
    - paragraphs
id: paragraph.field_types_link
field_name: field_types_link
entity_type: paragraph
type: list_string
settings:
  allowed_values:
    -
      value: anchor
      label: Ancre
    -
      value: internal
      label: Interne
    -
      value: external
      label: Externe
  allowed_values_function: ''
module: options
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false
</code>
When I create my new field based on my configuration file like that:
<code>$field_storage_link = \Drupal::service('config.storage.sync')->read('field.storage.paragraph.field_types_link');

\Drupal::entityTypeManager()->getStorage('field_storage_config')
  ->create($field_storage_link)
  ->save();
</code>
I have this error.

[error]  The configuration property settings.allowed_values.0.label.0 doesn't exist.

If I remove the list of allowed_values, it works and I can add my field to paragraphes bundles but in this case, I'm not able to do my migration properly because the allowed_values of my field are empty and I don't know how to update it programmatically. Someone can explain what's is the problem in my code and how to fix it?
Answer: I finish by find what was the problem. When I read the config file, my allowed value are of format:
<code>[
  [
    'value' => 'anchor',
    'label' => 'Anchor'
  ],
  [
    'value' => 'internal',
    'label' => 'Internal'
  ],
  [
    'value' => 'external',
    'label' => 'External'
  ]
]
</code>
But the FieldStorageConfig wait a format:
<code>[
  'anchor' => 'Anchor',
  'internal' => 'Internal',
  'external' => 'External'
]
</code>
So I add a transformation before to save my new field:
<code>$field_storage_link = \Drupal::service('config.storage.sync')->read('field.storage.paragraph.field_types_link');

$allowed_values_link = [];

foreach($field_storage_link['settings']['allowed_values'] as $value) {
  $allowed_values_link[$value['value']] = $value['label'];
}

$field_storage_link['settings']['allowed_values'] = $allowed_values_link;

\Drupal::entityTypeManager()->getStorage('field_storage_config')
      ->create($field_storage_link)
      ->save();

$field_type_link = \Drupal::service('config.storage.sync')->read('field.field.paragraph.link_tdm.field_types_link');

\Drupal::entityTypeManager()->getStorage('field_config')->create($field_type_link)->save();
</code>
It works properly.
Answer: For others with the same issue, see this important comment by Berdir at https://www.drupal.org/project/drupal/issues/2944144#comment-12481021
saying:

That's not the correct way to create a config entity from config.
Here's a snippet based on what I did just today:

<code>  $module_handler = \Drupal::moduleHandler();
  $config_storage = new FileStorage($module_handler->getModule('yourmodule')->getPath() . '/config/install');

  foreach (['field.storage.user.field_name', 'field.field.user.user.field_name'] as $config_name) {
    $config_record = $config_storage->read($config_name);

    $entity_type = \Drupal::service('config.manager')->getEntityTypeIdByName($config_name);
    /** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $storage */
    $storage = \Drupal::entityTypeManager()->getStorage($entity_type);
    $entity = $storage->createFromStorageRecord($config_record);
    $entity->save();
  }
</code>

The important part is "$entity =
$storage->createFromStorageRecord($config_record);", the config
structure and config entity structure doesn't always match 1:1.

I can confirm this solved the problem for me with the same error.


Aggregating more than two RRDs in RRDGraph returns empty graph

Question: I am using rrd graph to manually generate a graph of aggregated data, based on RRDs that were collected via PNP4Nagios. My issue is that when I try and aggregate more than two sources, I get a blank graph.
I believe I have the correct CDEF format, to generate aggregated data sources, based on the following: http://oss.oetiker.ch/rrdtool/tut/cdeftutorial.en.html (See "Converting your wishes to RPN").
Based on that article, I use:
CDEF:rx=rx1,rx2,+,rx3,+,rx4,+,...,rx10,+,rx11,+

Which only works if I aggregate the first two data sources in the statement, any time I do 3 or more, I get a blank graph.
I can't figure out why this is? The only difference between a working graph and a non-working on is the CDEF statement.
Works: CDEF:rx=rx1,rx2,+
Doesn't work: CDEF:rx=rx1,rx2,+,rx3,+
Here is the full working RRD graph statement with only 2 of the sources aggregated:
rrdtool graph bw_graph.png -a PNG --start=1389348873 --end=1392096786 --step 30 -w 597 -h 188 -v "Interface Traffic (bps)" \
'DEF:rx1=/path/to/data/cust1/eth0.rrd:1:AVERAGE' \
'DEF:tx1=/path/to/data/cust1/eth0.rrd:2:AVERAGE' \
'DEF:rx2=/path/to/data/cust2/eth0.rrd:1:AVERAGE' \
'DEF:tx2=/path/to/data/cust2/eth0.rrd:2:AVERAGE' \
'DEF:rx3=/path/to/data/cust3/eth0.rrd:1:AVERAGE' \
'DEF:tx3=/path/to/data/cust3/eth0.rrd:2:AVERAGE' \
'DEF:rx4=/path/to/data/cust4/eth0.rrd:1:AVERAGE' \
'DEF:tx4=/path/to/data/cust4/eth0.rrd:2:AVERAGE' \
'CDEF:rx=rx1,rx2,+' \
'CDEF:tx=tx1,tx2,+' \
'AREA:rx#0F5BFF:RX' \
'AREA:tx#FF9933:TX' \
GPRINT:rx:MAX:"RX Max %6.2lf %s" \
GPRINT:rx:MIN:"RX Min %6.2lf %s" \
GPRINT:rx:AVERAGE:"RX Avg %6.2lf %s" \
GPRINT:rx:LAST:"RX Curr %6.2lf %s\n" \
-t bw_graph

Comment: Will above method (`CDEF:rx=rx1,rx2,+,rx3,+`) work if RRD files are added the data at different timestaps (in your example `cust1/eth0.rrd` has times a bit earlier than `cust2/eth0.rrd` and so on)?
Answer: I've found that the issue in this case was not that I was adding more than two data sources - that was fine. The issue was that one of the data sources I was adding just happened to have undefined data, and that in turn was causing the entire graph to be nulled.
I found this by experimentation - I tried adding rx3,rx4,+ and found the graph was still broken, with only those two pairs. It seemed rx3 was the cause of my issues.
Going a step further to confirm my issue, I decided to aggregate 4,5,6: rx4,rx5,+,rx6,+ worked fine, and generated a graph.
After some searching, I found an article which mentioned this issue: http://rrd-mailinglists.937164.n2.nabble.com/adding-DS-values-from-multiple-rrd-files-tp5368188p5512061.html
Then, with some addition help from this document, on how to use UN to substitute unknown data with 0: http://oss.oetiker.ch/rrdtool/tut/cdeftutorial.en.html
Basically, in my CDEF statements, rx1 would become rx1,UN,0,rx1,IF.  And rx2 becomes rx2,UN,0,rx2,IF etc...
A final CDEF might look something like:
CDEF:rx=rx1,UN,0,rx1,IF,rx2,UN,0,rx2,IF,+,rx3,UN,0,rx3,IF,+
Comment: You may wan't to be using the ADDNAN operator ... OTOH, treating NAN as 0 might return rather missleading results ... since some number you do not know plus some other number is still a number you do not know.
Answer: Try The following:
CDEF:rx=rx1,rx2,rx3,+,+
It worked for me.
Comment: While this may be correct, it would be a lot more helpful if you could explain why this change should be made.


Separating real and imaginary components of rectangular coordinates - matlab

Question: I have a rectangular Coordinate in Matlab that looks like the following:
0.0240 - 0.1680i
I'd like to split the double into it real and imaginary parts, those parts being 0.0240 and -0.1680 (Don't need the i here)
I've converted the double into a string using the following:
I=0.0240 - 0.1680*i
I_1=num2str(I)

Im not sure how to proceed here to get what i want. strsplit() just gives back the string in the form it already is. Id like to somehow split it to give me the two numbers separately. I'm not too experienced with data manipulation in Matlab so any help is appreciated.
Answer: num2str converts number to string. It is not for separating real and imaginary parts.
You can use:
I=0.0240 - 0.1680*i;
real_part=real (I)
imaginary_part=imag(I)

Comment: This does exactly what is needed, I just wasn't properly using the built in functions. Thanks


The Euler-Poisson equation

Question: $$\int_{0}^\pi (x''^2+4x^2) dt$$
$$ x(0)=x'(0)=0; x(\pi)=0;x'(\pi)=\sinh(\pi)$$
This is The Euler-Poisson equation, i found:
$$\frac {\partial f}{\partial x}-\frac {d}{dt} \frac{\partial f}{\partial x'} +\frac {d^2}{d^2t} \frac{\partial f}{\partial x''}=0$$
$$2x''''=8x$$
$$x''''(t)=4x;$$
decide which way next?
${{{}}}$
Comment: Assuming $x^{(4)} = 4x$ is correct, the way to solve it is to first write down and solve the [characteristic equation](http://en.wikipedia.org/wiki/Characteristic_equation_%28calculus%29) of this ODE. This is  $\lambda^4 = 4$ which has the four solutions $\lambda_i = \sqrt{2}, -\sqrt{2}, i\sqrt{2},-i\sqrt{2}$ giving you the solution $x = \sum_{i=1}^4 A_i e^{\lambda_i t}$. Apply BC and simplify.
Comment: btw I get $x^{(4)} + 4x = 0 \implies x^{(4)} = -4x$.
Comment: Yes, u right, i lost -
Comment: $$x(t)=C_1 e^{-t} sin(t)+C_2 e^{t} sin(t)+C_3 e^{-t} cos(t)+C_4 e^{t} cos(t)$$ it's right?
Comment: Yes that seems correct. Now just apply the boundary conditions and you are done (to simpliy the final answer you might want to use $[e^{t} - e^{-t}]/2 = \sinh(t)$).
Comment: i found $$c_1=1/2;c_2=-1/2;c_3=c_4=0;x(t)=-sin(t) sinh(t)$$
Comment: I get the same thing. If you want you can pose an answer to your own question (and you can accept it also).
Answer: $$x^{(4)}=-4x$$
$$x(t)=C_1 e^{-t} sin(t)+C_2 e^{t} sin(t)+C_3 e^{-t} cos(t)+C_4 e^{t} cos(t)$$
$$C_1=1/2; C_2=-1/2; C_3=C_4=0$$
$$x(t)=-sin(t) sinh(t)$$

The Euler-Poisson equation


Is there difference between Fusion and Hybrid?

Question: In Music Terminology is there difference between Fusion and Hybrid?
I was reading a text about Rock music. I bring it here to clarify my question.

By the late 1960s a number of distinct rock music sub-genres had emerged, including hybrids like blues rock, folk rock, country rock, ... .
Further fusion sub-genres have since emerged, including pop punk, rap rock, and rap metal, ... .
Comment: I don't understand the downvotes on this question, seems like a perfectly valid one to me...
Comment: Oh, damn, a zombie question.  Never mind then...
Answer: The issue here is that "hybrid" is not a musical term. The author is simply using it here according to its typical dictionary definition:

hy•brid <code>|ˈhīˌbrid|</code>
  noun
  a thing made by combining two different elements; a mixture

"Fusion" has extensive musical connotations, however. In general it means the same thing as hybrid, but you would use it to refer to a distinctive sub-genre that resulted from the merging of two other genres of music.
Additionally, Jazz Fusion is a topic in and of itself--the linked Wikipedia article is an excellent overview of the genesis and history of the genre, which was initially defined by such influential artists as Miles Davis, Herbie Hancock, and Jaco Pastorius.
Answer: No. This is not a meaningful question. I've never heard the term "hybrid" applied like you are using it. Perhaps you should cite your source: what is the name of the author of that text, and where is it from?
"Hybrid" is a term that comes from horticulture, or plant breeding, such as when two different varieties of rose are crossed to make a new variety of rose.
"Fusion" is a term that means taking two things and fusing them together. Although it probably goes back farther than that, it was applied by some journalists in the late 1960s and 1970s to describe music that blended the styles of jazz and rock.
Your writer is just talking about pieces of music that display characteristics of multiple styles of music combined. That is all.


When is Jacobian invertible?

Question: Let $(f,U)$ be a chart on $M$ a smooth $n$-manifold. I know the inverse function theorem by which $f$ is invertible on $U$ iff its Jacobian is. What about the other direction? Is there any theorem about conditions under which the Jabobian of a map $f$ is going to be invertible?
Comment: If both $f$ and $f^{-1}$ are  differentiable, then the Jacobian of  $f$ is invertible.
Comment: You are welcome. I don't have any reference at hand, but you may prove it easily by differentiating $f^{-1}\circ f=\mathrm{id}$ with chain rule.
Comment: In the definition of a smooth manifold, the smoothness is reflected in the change of variables between intersecting charts.  Such a change of variables is always smooth with smooth inverse, so there is nothing to worry.
Comment: @Landscape Thank you, do you have any reference?
Comment: @Landscape Right, thanks! Unfortunately, it seems that it is not part of the definition of a chart that its inverse is also differentiable/smooth, or is it?
Comment: @Landscape Thank you. I will have to think about this for some time, it's not obvious to me.
Comment: You are welcome.
Answer: Landscape already gave an answer:

If both $f$ and $f^{-1}$ are differentiable, then the Jacobian of $f$ is invertible. – Landscape Aug 2 at 13:41

I'll add a pointer to a more specialized result: for harmonic maps between open subsets of $\mathbb R^2$, being invertible implies that the Jacobian is invertible at every point. This is a theorem of H. Lewy (1936). Unfortunately it fails in higher dimensions.

When is Jacobian invertible?


Proof of the cádlág modification of a martingale.

Question: I am reading a proof about the cádlág(right regular)-modification of a martingale. There is something in the proof I do not understand. The author defines the new process in terms of some limits, but he says that the limits can be infinite. But later in the argument he seems to treat $\tilde{X}$ as it was finite. Is this proof correct? Do you see how he excludes the case that the limits are infinity?
(PS: The author only calls something a martingale if it is cádlág, if it does not have those trajectory properties it is called a martingale-structure.)
.
.
.
Comment: What author is this?
Answer: The proof as written is incomplete, for the reason you note: for the triangle inequlity estimate to be applicable, you need to know that $\tilde X(s)$ and $\tilde X(t)$ are finite. By working a little harder, one can show that there is an $\mathcal F$-set $\Omega_1\subset \Omega_0$ such that the left and right limits of $\Bbb Q\ni r\mapsto X(r,\omega)$ exist and are finite. The additional ingredient to bring to bear (on top of the downcrossing lemma) is Doob's maximal inequality for $X$ restricted to the rationals, which shows that $\sup_{0\le r\le t, r\in\Bbb Q}|X(r)|$ is finite a.s. for each $t>0$.
Comment: Great, thank you very much!


Is my eletric guitar in danger due low/no humidity applied?

Question: I bought a very expensive (for me) Dean from Hell signature which is limited to 150 pieced worldwide (in fact its the #121 of 150 of these: https://reverb.com/au/item/1390256-dean-usa-dime-from-hell-ml-limited-150). I am a huge Pantera Fan and a learning guitar player. That's why I do not want to play on it right now - I am not ready for it ;)
As you might guess I am not very proficient when it comes to guitar maintanence and technic at all.
I just heard about the issue of humidity for guitar and that low or no humidity will destroy guitar!
This is a complete horror scenario for me not only cause it's limited but also that I might lose a lot of value from it.
So this guitar is in its case for about a year and throughout this year it was stored in a storage room, cellar and lastly under my bed.
I have never applied any humidity due the lack of knowledge and just by coincidence heard about the importance.
Several questions I do have now:
1.) Is the guitar most likely to be broken by now? Or is there a chance nothing happened to it?
2.) How can I give it the humidity it needs and how do I figure out what level of humidity that might be? Are there case humidity devices or do I need to place it in a room and apply the humidity to the whole room?
Please help me before it's too late :(
Comment: Under the bed sounds o.k. What's good for humans is fine for guitar! What's the cellar and store room like - very cold, wet, dry? If it's a good quality hard flightcase, it should be alright.
Comment: yeah it is that originsl dean hard leather case brought with that model
Answer: Solid-body guitars are in general pretty forgiving, in comparison with acoustic guitars or bowed strings.Obviously avoid storing it in a car parked in the sun or in some moldy cave/cellar, but other than that you should be fine. The body of such a guitar is too bulky and well-sealed to be affected much by humidity or lack thereof (unless the wood hasn't been properly slow-dried before manufacture), and the neck, even if it should change its shape slightly, can be re-adjusted using the truss rod. The through-body neck is an argument for being a bit extra careful since it can't just be replaced.
Honestly though... a) no offense meant, but, consider if you put a bit too much emphasis into that limited edition buzz. It's just a guitar, probably not really any better than off-the-shelf ones. b) if you have a nice guitar, play it! If you like it so much, play it more! If it gets damaged, have it repaired! Shame to lock a good instrument away that could make nice music. If you don't want to play it, lend it to someone you trust.
Comment: Well, these days, they're all kiln-dried, not slow-dried, but I do get your point.
Answer: If in doubt, buy a humidity meter (hygrometer).  Comfortable levels indoors are about 30 to 55% RH.  If it's OK for a person, then it's OK for a musical instrument as well.
You don't have to "apply" humidity to an instrument, just keep it in a good environment that's not damp and not bone dry.
If you do live in a particularly damp place, consider buying a dehumidifier (or fixing whatever is causing the damp!).  If you live in a particularly dry place, consider a humidifier instead.


Which items in two ranked lists are ranked significantly different?

Question: I have 91 items ranked by different demographic groups of questionnaire participants.
The rank lists for each group are all the same length and contain identical items.
I understand that I can perform correlation measures (e.g. Kendall's Tau) or intersection measures (e.g. Rank Biased Overlap) to determine how similar two sets of rankings from two different groups are. But are there any statistical tests available to tell me which items in two lists are ranked significantly differently?
Thank you!
Comment: do you have lists for each participant or just the average?
Comment: No, a group of participants perform many pairwise comparisons (item A vs B etc). The collective output of the comparisons produces a rating and ranking of items for that group (using the Elo algorithm).
Answer: For ordinal (rank based) data, kendall concordance test holds good, as it calculates a normalized score for the number of matching or concordant rankings between the two samples.
Still you can also try other rank correlation methods like:

Spearman's Rank Correlation.
Goodman and Kruskal's Rank Correlation.
Somers' Rank Correlation.

This statistical methods quantifies the degree to which ranked variables are associated by a monotonic function, meaning an increasing or decreasing relationship.
Comment: Thanks for your help! I was more trying to determine which specific items in the lists are ranked significantly different from each other? I.e. if item A is ranked 1st by one group, but 10th by the other group, is this significantly different?


Windows uses Point sampling when stretching from a DirectX BackBuffer to the WIndow

Question: Windows7 is using point filtering to stretch from my DirectX9 back-buffer to the window client area.  When the window is resized the artifacts from the stretching look very bad.  We can avoid this by changing the back buffer size, but that requires calling IDirect3DDevice9::Reset().  This results in a black screen and a small delay while resizing is happening.
Is there any way to improve the filtering method windows uses?  Or, Is there any way to update the window from a different DirectX surface such as a Render Target?

Im using unmanaged C++ DirectX code.  Say I have a 1280 x 720 back buffer surface:
D3DPRESENT_PARAMETERS  presentParams;
presentParams.BackBufferWidth  = 1280;
presentParams.BackBufferHeight = 720;
gD3D->CreateDevice(
    0, D3DDEVTYPE_HAL, hWnd,
    D3DCREATE_HARDWARE_VERTEXPROCESSING,
    &presentParams,
    &pD3D9Device);

Yet I have a 1920 x 1080 window:
hWnd = CreateWindowExA(NULL, "WindowClass", winName,
                flags, 0, 0, 1920, 1080,
                NULL, NULL, hInstance, NULL);

When I call Present() windows will stretch my DirectX back buffer to the window.  However their stretch doesn't appear to perform any filtering.
pD3D9Device->Present(NULL, NULL, NULL, NULL);

I can resize the backbuffer, but that requires a call to Reset() and Reset() causes video memory surfaces to be lost.
Comment: The usual way is to make the back buffer and window the same size - if you can't change the buffer, change the window. I presume DirectX is using the fastest possible way to get the image to the window, which involves no filtering. You can minimize the distortion by making the buffer an integer division of the window size.
Comment: I remvoed the `windows` and `windows-7` tags, because they're meaningless. The question is about `DirectX9`, which is obviously Windows-specific, and `DirectX` is doing the sampling/rendering, not Windows itself (if Windows did it, you wouldn't need DirectX).
Comment: Windows is just doing the stretch blt (after rendering) to the window.
Comment: Yes, this makes sense.  In the case where the user is resizing the window to arbitrary sizes we were trying to handle it gracefully and quickly.
Answer: I bump to this problem when I try to play video in window, and want to resize window without the need to reset device.
I found a solution from mpc-hc source code: https://github.com/mpc-hc/mpc-hc/blob/develop/src/filters/renderer/VideoRenderers/SyncRenderer.cpp
1) Make backbuffer big (biggest size that you expect the window would be)-> I chose screen size
2) Draw only on a rectangle, that size equal to the window
3) use Device.Present(srcrect, destrect). srcrect and destrect are the same rectangle and are window size.
I am new to directX and all, but this solution works for me.
Comment: Seems like it should work!  I will have to try it out.
Answer: It would be helpful if you posted some code fragments of the specific operations you're asking about, however if you are using the GDI (Unmanaged Win32) StretchBlt function, you can get better resizing behavior with HALFTONE, as per this post: Is StretchBlt HALFTONE == BILINEAR for all scaling?
If you are using GDI+ (WinForms/C#), you can get Bilinear (or better) interpolation using g.InterpolationMode = InterpolationMode.Bilinear (look at MSDN for all options).  Be warned that GDI+ is typically slower than GDI (or DX)
(Somewhat related info in this post: Bilinear interpolation - DirectX vs. GDI+)
Comment: Thanks for the information.  However I am not using GDI, just DirectX.  Im just trying to avoid resizing my backbuffer in DirectX, but it seems this is the only way to go.
Answer: Have you tried the IDirect3DDevice9::SetSamplerState?
http://msdn.microsoft.com/en-us/library/windows/desktop/bb174698(v=vs.85).aspx
Actually I was searching around for a similar issue I had. I used D3D9 texture to render some images. On Vista, the SetSamplerState plus Linear Texture Filtering helps reducing the artifacts caused by resizing windows a lot. But this is not the case on Windows7. I'm not sure how this is handled differently in the 2 platforms.


Resultado com formatação incorreta

Question: Estou com a seguinte dificuldade:
O cálculo está fazendo certo!
R$ 0.01986 quando o correto seria R$ 19.86
Como faço para formatar esse resultado?
Codigo do resultado:
Custo (/Sc):
<?php $g  = round ($c/$result->valorsc,5)?>
<?php echo $g?>

Comment: Fabio, você precisará ser mais claro em quais são os valores das variáveis, mas já adianto que provavelmente o problema está na formatação do número. O PHP usa o formato americano, reconhecendo o ponto como separador decimal; isto é, `1.390`, no PHP, é *um vírgula 390*, não *mil e 390*, como esperado.
Comment: Se o resultado é 0.01986 quando deveria ser 19.86, o cálculo não me parece certo. O que exatamente está tentando fazer?
Comment: vou explicar para vc :
Comment: o valor total acima é R$ 1.390,76 / 70 é igual R$ 19.86 o resultado ta certo, o problema é q ta aparecendo R$ 0.01986 o que vc acha que pode estar errado ?
Comment: Antes de qualquer coisa, corrija o código na pergunta, por favor.
Comment: feito a alteração amigo , me ajuda por gentileza, será que é formatação pq o calculo ta certo :(
Comment: Quais os valores das variáveis `$c` e `$result->valorsc`? O problema esta nelas. Use `var_dump($c, $result->valorsc);` pra pegar tais valores e informa pra nós.
Comment: a variavel $c = $result->valorTotal/$result->area_id os valores vem do banco de dados ai esse resultado é R$ 1.390,76 onde ele vai ser divido por pela variavel valorsc do banco de dados que é R$ 70. e o resultado da 0.01986 onde seria o correto R$ 19.86
Comment: @FabioBarroso o problema é o formato dos numeros, vocë esta tentando calcular algo que não é numero, veja: https://pt.stackoverflow.com/a/230964/3635
Comment: guilerme me ajuda kkkk ainda sou iniciante , aquele ta muito hard kkkkkk
Comment: @FabioBarroso editei a resposta: https://pt.stackoverflow.com/a/245422/3635
Comment: isso ocorre pq o php vai pegar uma parte dessa string q possa ser interpretada como numero, ou seja, 1.390,76/70 para o php é 1.39/70 q vai dar 0.01986
Answer: Provavelmente o seu nivel de log de erro não está exibindo Warnings e/ou Notices, mas se estivesse habilitado talvez iria exibir esta notificação no meio da página:

Notice: A non well formed numeric value encountered in ... on line 34

Você tem que entender que uma coisa é um numero, mesmo que sendo string, o formato dela tem que ser um numero que a máquina entenda.
Por exemplo, se fizer isto:
<?php

$valor1 = '100foo';
$valor2 = '2';

$total = $valor1 / $valor2;

var_dump($total);

Me é retornado isto:

PHP Notice:  A non well formed numeric value encountered in C:\Users\guilherme\foo.php on line 6
int(50)

Veja que conseguiu até dividir 100 por 2 = int(50), isto porque o PHP tenta fazer o "parse" da string, mas se fizer algo mais complicado como:
<?php

$valor1 = '100.000,00';
$valor2 = '2';

$total = $valor1 / $valor2;

var_dump($total);

Vai retornar isto:

PHP Notice:  A non well formed numeric value encountered in C:\Users\guilherme\Desktop\debug.php on line 7
float(50)

O resultado que o PHP tentou fazer o "parse" e exibiu, mas só reconheceu o 100.000, que é "praticamente" a mesma coisa 100.0, ou seja um tipo float, e dividiu isto assim 100.0/2 = float(50)
Ou seja, 100.000,00 para a maquina (independente de qualquer linguagem) não é um numero, ele é apenas uma string, em outras linguagens fora o PHP (que tenta fazer o parse) é capaz de ocorrer exception ou erros fatais quando tentar algo como "100.000,00"/5

Como transformar formato de dinheiro em um numero?
Primeiro eu realmente recomendo que ao invés de usar VARCHAR ou CHAR em seu banco você prefira usar DECIMAL e trabalhar com numeros reais, porque se o seu banco esta retornando algo como isto 100.000,00 é porque concerteza é um tipo de CHAR que ele usa, por favor não use algo como:
ALTER TABLE `minha_tabela` MODIFY `minha_culuna` DECIMAL(8,2)

Antes de mudar os valores de cada uma das linhas, se fizer isto sem mudar pode ter certeza que irá quebrar todos os dados, o que será impossível reverter, primeiro converta as linhas existentes, por exemplo 100.000,00 deve virar `100000.00, manualmente ou com um script que percorra todas as linhas da tabela.
Agora se você quer realmente insistir em usar CHAR (VARCHAR ou TEXT) então paliativamente você pode experimentar usar função assim:
function reverse_number_format($str)
{
     if (is_numeric($str)) {
        return $str;
     } elseif (preg_match('#^(.*?)[.,\s](\d{2})$#', $str, $out)) {
        return preg_replace('#\D#', '', $out[1]) . '.' . $out[2];
     }

     return false;
}

E então use assim no seu script:
round(reverse_number_format($c) / reverse_number_format($result->valorsc), 5);

Nota: mas como eu disse, isso é uma solução paliativa, o recomendado é mudar a sua estrutura.
Comment: Resolvido por Guilherme Nascimento!!! Muito Obrigado!
Comment: @FabioBarroso poderia marcar a resposta como correta? Se não sabe como fazer veja se isto ajuda: [Como e por que aceitar uma resposta?](https://pt.meta.stackoverflow.com/q/1078/3635)
Answer: 1.390,76 não é um numero que se possa utilizar em cálculos matemáticos. Você não digita isso na sua maquina de calcular física ou virtual para realizar um calculo. Você digitaria 1390.76
Em programação também vale a mesma regra, os números devem ser do tipo inteiro ou, parte inteira separada por ponto seguida da parte fracionaria, parteinteira.partefracionaria ou por exemplo do tipo 271e+139
No PHP a conversão de string para numero depende do formato da string, assim o PHP avalia o formato da string e caso não possua nenhum valor numérico será convertido para 0(zero). Caso possua valor numérico em sua primeira posição o valor será considerado e caso o valor não seja na primeira posição será desconsiderado.
Exemplos:
$string = (int) 'Muitas casas';

var_dump( $string ); // int(0)

$string2 = (int) '10 casas aproximadamente';

var_dump( $string2 ); // int(10)

$string3 = (int) 'Exatamente 10 casas';

var_dump( $string3 ); // int(0)

Veja no ideone  o codigo abaixo completo executado
Errado
$numerador = '1.390,76';
var_dump( $numerador ); //string(8) "1.390,76"

$divisor = '70'; //string(2) "70"
var_dump( $divisor );

echo ($numerador /$divisor); // 1.39/70

Uma solução
//tratando string para formato válido para calculos matematicos
$numerador = '1.390,76';

//retira os pontos (.)
$numerador=str_replace(".","",$numerador);

//transforma virgula (,) em ponto (.)
$numerador=str_replace(",",".",$numerador);

var_dump( $numerador ); string(7) "1390.76"

$divisao = ($numerador/$divisor);

//formatando para 2 casas decimais
echo number_format($divisao, 2, ',', '.');

Resultado com formatação incorreta


Bash CD to directory

Question: I am trying to change the extraction_sudir to a completely unrelated path to the file location (/home/user/downloads/tcomplete/foldername/file.mp4
#!/bin/bash
formats=(zip rar)
commands=([zip]="unzip -u" [rar]="unrar -o- e")
extraction_subdir='extracted'

downloadid=$1
downloadname=$2
downloadpath=$3

log()
{
    logger -t deluge-extractarchives "$@"
}

log "Download complete: $@"
cd "${downloadpath}"
for format in "${formats[@]}"; do
    while read file; do
        log "Extracting \"$file\""
        cd "$(dirname "$file")"
        file=$(basename "$file")
        # if extraction_subdir is not empty, extract to subdirectory
        if [[ ! -z "$extraction_subdir" ]] ; then
            mkdir "$extraction_subdir"
            cd "$extraction_subdir"
            file="../$file"
        fi
        ${commands[$format]} "$file"
    done < <(find "$downloadpath/$downloadname" -iname "*.${format}" )
done

I thought it would be as simple as:
extraction_subdir='/home/user/extracted'

However that seems to just place the unrar'd file in the directory:
/home/user/downloads/tcomplete/foldername/
I am looking at:
file=$(basename "$file")
...
file="../$file"

Being the cultprit but unsure how to solve this.
Edit:
Solved this my specifying the output in the unrar command e.g.:
${commands[$format]} "$file" "$extractedpath"

became:
${commands[$format]} "$file" "/home/user/extract"

Comment: It's unclear what your question is, maybe you can improve your post?
Comment: Associative arrays must be explicitly declared with `declare -A commands='([rar]="unrar -o- e" [zip]="unzip -u" )'`.
Comment: @Akarienta Sorry i am just trying to change the extraction path that is outside of the downloadpath.
Comment: @chepner You pointed me in the right direction: i changed the unrar command to specify the output folder instead.

${commands[$format]} "$file" "/home/user/extract"
Answer: You were correct in your analysis.  The issue is that the script assumes that extraction_subdir is always within downloadpath.
I can't personally test it, but I believe the following will fix the issue:
file="${downloadpath}/${file}"

It will force the file path to be absolute instead of relative.
Comment: I originally thought this too, i even tried adding the path withouth "Downloadpath" e.g. "/home/user/extract" but i get:
Cannot open filename.rar
No such file or directory
No files to extract
Comment: @Keelan - That sounds like it's skipping the inner `if` statement entirely.  Make sure you set `extraction_subdir` *and* change the `file="../$file` to the above code and it should work.  The line `if [[ ! -z "$extraction_subdir" ]]` checks if `extraction_subdir` is *not* an empty string, so if you forget to set it, the line `file="${downloadpath}/${file}"` never executes.

Bash CD to directory


PHP interface Gráfica

Question: Gostaria de saber como construir interfaces em um sistema desenvolvido em PHP de maneira simples e eficaz.
Gostaria de saber se existe algum tipo de Framework, caso exista qual o melhor para a construção de interfaces complexas.
Comment: A sua pergunta está ampla demais, poderia explicar que tipo de interface gráfica você quer fazer? O que você já fez? Quais tecnologias você pretende utilizar?
Comment: Quando se trabalha com web a principal forma de montar telas é com html, css e javascript que é bem diferente do desenvolvimento para desktops.
Comment: Exemplos de interface: Grid com rodapés que mostram o total de cada coluna
Progressbar nas células.
Grid com auto agrupamento de colunas..
Comment: O php é apenas o backend do sistema, para comportamentos dinâmicos procure por frameworks de javascript.
Comment: Tentei te ajudar mas você não está expressando de forma correta sua dúvida, primeiro pediu de interface gráfica, agora mudou o foco para melhor linguagem para consumir recursos via webservice. Faça uma pergunta específica e completa.
Answer: Normalmente em PHP é usado como linguagem web e para tal o desenvolvimento de telas é feito usando HTML e CSS, você pode achar vários tutoriais na net a respeito disso. Se for o caso recomendo o twitter bootstrap (http://getbootstrap.com/) ou o Material design (http://www.google.com/design/)
Agora se for interface gráfica mesmo, tela de programas, tem o PHP-GTK que permite construir uma aplicação como um aplicativo desktop (http://www.php-gtk.com.br/)
Mas se for esse o caso, programação para desktop recomendo você escolher outra linguagem, utilize alguma linguagem .Net da vida, ou parta para o C/C++ que tem em sua estrutura muitas semelhanças com o PHP e vai te permitir utilizar outras bibliotecas como o Qt (http://www.qt.io/) que além de outros recursos provê bibliotecas para facilitar o desenvolvimento de interfaces.
Comment: A aplicação que pretendemos desenvolver devera conter interfaces ricas estilo desktop, gostaria de saber se php é a melhor opção para optarmos..
Comment: Se sua aplicação for web PHP pode ser considerado sim uma boa linguagem. Se for uma aplicação para desktop, como disse, utilize outra como .Net, C ou C++
Comment: Queria saber se a linguagem nos forneceria um grande suporte em:
Como realizar chamadas de webservice com autenticação com certificado digital;
Como gerar as classes php a partir de um arquivo XSD;
Como realizar assinaturas de arquivos xml digitalmente com certificado didgital;
Como converter um arquivo xml em objeto php com dados preenchidos;
Consumir serviços SOAP, JSON, automaticamente através dos WSDL fornecidos pelas SEFAZ;
Answer: Para o desenvolvimento de interface em PHP você deverá fazer a mesma utilizando tecnologias web, como html, css e javascript. Neste contexto considero interessante você dar uma olhada no Bootstrap que se trata de um framework css. Com ele é possivel construir interfaces avançadas pois o mesmo contém vários templates de painéis espalhados pela web, como este ou este outro por exemplo.
Caso seja um sistema para desktop, sugiro ver sobre C# (ou qualquer outra linguagem .NET).

PHP interface Gráfica


Is there a way to compare incidences of 2 diseases in the same cohort?

Question: I would like to compare incidences of 2 diseases in the same cohort for the past 10 years.
Eg. I want to see whether there's an association between incidence of heart disease and incidence of influenza in the same cohort of people for the past 10 years.
Is this doable? What statistical method should I use? Thank you
Comment: Make a $2 \times 2$ table with rows Flu/NoFlu and columns HD/NoHD. Use Fisher's Exact test.
Answer: Suppose you have table:
        ND  noHD
Flu     10    5
noFlu    5   10

Perhaps suggestive of association, but not significant.
Not enough data.
TBL = rbind(c(10,5), c(5,10))
fi        Fisher's Exact Test for Count Data

data:  TBL
p-value = 0.1431
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
  0.7054268 23.9214257
sample estimates:
odds ratio
  3.805039

However, if you have table:
        ND   noHD
Flu     102    53
noFlu    49   105

Roughly the same proportions as in the former example,
but with about ten times the number of subjects. Highly
significant.
TBL2 = rbind(c(102,53), c(49,105))
fisher.test(TBL2, alt="two")

        Fisher's Exact Test for Count Data

data:  TBL2
p-value = 2.445e-09
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
 2.498319 6.820386
sample estimates:
odds ratio
  4.103514


Bonferroni and Greenhouse-Geisser corrections with repeated-measures ANOVA

Question: I guess my question comes in two parts:

Following a 1x7 repeated-measures ANOVA, I carried out 3 pre-planned tests. Two were t-tests between 2 of the conditions.  The third is a 1x6 ANOVA (to test significance between conditions 2-7).  My question is:
  Do I have to apply the Bonferroni correction to all 3 tests, or just the 2 tests? I.e. should the significance level be 0.05/3 = 0.017 for all 3 tests?
As above, I carried out a 1x7 repeated-measures ANOVA, and 3 pre-planned tests (2 t-tests and a 1x6 ANOVA). In the original 1x7, sphericity was assumed, so I report the 'sphericity-assumed' statistic, and it is non-significant.  Next, despite this non-significance, I decided I should do the pre-planned tests for the sake of completeness.  When I do the 1x6 repeated measures ANOVA, sphericity is NOT assumed, so I use the Greenhouse-Geisser values, and it comes up significant (if I were to use the shericity assumed values, it would be non-significant).  My problem here is that the ANOVA using just 6 of the 1x7 conditions is coming up significant when the original 1x7 was non-significant.  Logically, this doesn't seem to make sense to me.
Is there some 'rule of thumb' whereby the use of Greenhouse-Geisser values needs to be consistent?

I hope this makes sense.  I have trawled the internet.  I have looked at more stats books than you can shake a stick at.  But nothing comes close to discussing this sort of situation.
Comment: Re: your first question, multiple comparisons is a frequently discussed topic on this site, so I'd suggest do a search of the old threads. I can't comment directly on your second question (re: sphericity), but it certainly is possible, in ANOVA, to reject the null in the first case, but not reject the null when you've added a new level - particularly if that new level has a mean equal to, say, the mean of the other 6 levels.
Comment: Re: Marco... I see your point about adding a new level bringing significance to non-significance, but in my data, removing a level turned non-significance to significance...
Comment: Maybe the level that was removed had a mean very similar to the others so, by removing it, there was more heterogeneity in the means?
Answer: Regarding Bonferroni (and multiple comparisons issues in general) Jacob Cohen, in his book on regression, said "this is a subject on which reasonable people can differ". There are arguments for not doing such corrections at all (see, e.g., this piece by Andrew Gelman). I find such arguments persuasive.
If you reduce chance of type 1 error then (other things being equal) you increase chance of type 2 error (that is, you reduce power). In many fields, the "given" values are .05 for type 1 and .8 for power (.2 for type 2). But these may or may not be sensible. Type 2 error may be much worse than type 1 error.
In my view, the important thing is not statistical significance, and certainly not whether it is below .05, but effect size and precision of effect size.
If you correct for multiple comparisons, it is really a question of what "multiple" is. Paraphrasing Cohen, should it be for one experiment? One article? One set of results? Results about one topic? All results you ever do? Or what?
From a purely practical point of view, you may be required to do some particular thing to satisfy journal editors or other supervisors.
Answer: A couple of points - too long for a comment:

If you are protecting your pre-planned tests with Bonferroni correction, than there is no need to run the original ANOVA. The "double protection" only looses power.
Most of the standard "post-hoc" tests for ANOVA do not need the protection of the original F-test. Essentially the only approach that needs it is when the post-hoc tests are not adjusted at all. This is usually not recommended, because this approach only provides weak control of the familywise type I error rate (i.e. the error rate of the pairwise comparisons is controlled only if all the means are equal)
You are doing strange things with the sphericity assumption. Approximately, it means that any pairwise differences have the same variance. If you are willing to assume that the entire design satisfies it, then any subset should as well. So if you are using GG correction for the subset, you should be using it for the entire set (the reverse does not have to be true). If the GG correction changes the results substantially (not just moving the p-value from 0.048 to 0.052), then the sphericity is probably not satisfied.
You keep confusing "not significant" with "there is no difference". While this is tempting to do, this thinking leads to all sort of apparent paradoxes.
Comment: Thank for your comments.  With regard to point 3 - the reason I did not assume sphericity for the entire design is because Mauchly's for the 1x7 is less than .05.  It is only removing one condition which then creates a subset of data where sphericity becomes assumed (Mauchly's for the 1x6 is >.05), and the p value is .039.  If G-G was used, it would be .076.  Would you advise to just report the 1x7 as non-significant, sphericity not assumed, and the 1x6 significant, sphericity assumed?  And then just try and make sense of why this happening with regards to to the experiment?
Comment: I don't know enough about the power of Mauchly's test to tell whether it is good enough at picking up deviations that affect the validity of the p-value. The difference between the corrected and uncorrected p-values are tiny, and we are only talking about it because the magic threshold got crossed. I would stick with the same assumptions for the subset as for the whole set.


How can I implement the server side pagination of mui-datatable?

Question: How can I implement the server side pagination of mui-datatable?
Problems:

I can't seem to retrieve whatever value was selected by the user in the rowsPerPage options. If the user clicks 15, then these rowsPerPage inside the useEffect should be updated as well:
const getUsers = async () => {
   const usersRef = collection(db, "users");
   const q = query(
     usersRef,
     orderBy("firstName", "asc"),
     limit(rowsPerPage)
   );
   const querySnapshot = await getDocs(q);
   const arr = [];
   querySnapshot.forEach((doc) => {
     arr.push({
       ...doc.data()
     });
   });
   if (isMounted) {
     setUsers(arr);
     setCount(arr.length);
     loading(true);
   }
 };

How does the server side pagination and filter works for mui-datatable?

Recreated codesandbox: https://codesandbox.io/s/mui-datatable-server-side-pagination-filtering-and-sorting-y8pyp7?file=/src/App.js:611-1091
Answer: It's pretty obvious that in the sandbox in your code you have state
const [rowsPerPage, setRowsPerPage] = useState(10);

and the IDE underlines setRowsPerPage showing you that it's never used, so even if the user changes the value the state is not updated.
The docs show there's onChangeRowsPerPage which you can pass a callback to in order to update the state and then use the state's value to send to the backend
Answer: I found examples from (it's from official examples):
click here
it has good example how to handle pagination
the logic is:
you should have pageSize state that handle pageSize
onPageSize change update pageSize state
Comment: hello, I'm quite confused on how to implement how the page changes for the next pages? https://codesandbox.io/s/mui-datatable-server-side-pagination-filtering-and-sorting-y8pyp7?file=/src/App.js
Comment: i will update my answer with logic explanation


Atualizar uma tabela sem refresh de pagina

Question: vi aqui várias respostas para perguntas semelhantes à minha, mas nenhuma resolveu meu problema. Estou fazendo um sistema de cadastro de itens que ao clicar no botão inserir ele vai dar o insert no banco, limpar o input e por fim mostrar esse item numa tabela abaixo desse form-inline de inserção de itens. Já consigo dar o insert no banco pelo submit, já consigo dar o reset nos campos de input. Meu único problema é que para esse item cadastrado aparecer na tabela preciso dar um refresh completo na página. Isso irá demandar muito tempo do usuário. Alguém consegue me ajudar a entender o que estou fazendo de errado?
Vou colocar os códigos HTML e JS abaixo. Muito obrigado!
<!DOCTYPE html>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css">

<title>Solicitação de Produto Indisponível</title>

    PED Peças
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#conteudoNavbarSuportado" aria-controls="conteudoNavbarSuportado" aria-expanded="false" aria-label="Alterna navegação">

    </button>

                Home (página atual)

                    Solicitações de Compra

                    Nova Solicitação
                    Solicitações Realizadas

                    Respostas dos Fornecedores

        <button class="btn btn-outline-danger my-2 my-sm-0" type="submit">Sair</button>

Solicitação de Produto Indisponível - <?php echo utf8_encode($info_solicitacoes['status_solicitacao']); ?>

        Nº Solicitação
        <input readonly name="id_solicitacao" type="number" value="<?php echo $info_solicitacoes["id_solicitacao"]; ?>" class="form-control form-control-sm" id="codcliente" placeholder="Cód. Int.">

        Cód. Cliente
        <input type="number" value="<?php echo $info_solicitacoes["cod_cliente"]; ?>" class="form-control form-control-sm" id="codcliente" placeholder="Cód. Int.">

        Cliente
        <input style="text-transform: uppercase" type="text" value="<?php echo $info_solicitacoes["cliente"]; ?>" class="form-control form-control-sm" id="cliente" placeholder="Cliente">

        Telefone
        <input type="text" value="<?php echo $info_solicitacoes["telefone"]; ?>" class="form-control-sm form-control" id="tel" placeholder="(XX) XXXX-XXXX">

        Contato
        <input style="text-transform: uppercase" value="<?php echo $info_solicitacoes["contato"]; ?>" type="text" class="form-control-sm form-control" id="contato" placeholder="Contato">

        Vendedor
        <input style="text-transform: uppercase" value="<?php echo $info_solicitacoes["vendedor"]; ?>" type="text" class="form-control-sm form-control" id="vendedor" placeholder="Vendedor">

        Observação
        <input style="text-transform: uppercase" value="<?php echo $info_solicitacoes["observacao"]; ?>" type="text" class="form-control-sm form-control" id="obs" placeholder="Observação">

    <button class="btn btn-sm btn-dark">Voltar</button>
    <button class="btn btn-sm btn-primary" hidden>Atualizar</button>

Inserir Itens Para Cotação

    <form id="insere_itens">

        <input hidden readonly name="id_solicitacao" type="number" value="<?php echo $info_solicitacoes["id_solicitacao"]; ?>" class="form-control form-control-sm" id="codcliente" placeholder="Cód. Int.">

                Cód. Int.
                <input type="number" class="form-control" name="codint" id="codint" placeholder="Cód. Int.">

                Número Original
                <input style="text-transform: uppercase" type="text" class="form-control" name="numorig" id="numorig" placeholder="Número Original">

                Código Fabricante
                <input style="text-transform: uppercase" type="text" class="form-control" name="codfabr" id="codfabr" placeholder="Código Fabricante">

                Marca
                <input style="text-transform: uppercase" type="text" class="form-control" name="marca" id="marca" placeholder="Marca">

                Descrição do Produto
                <input required style="text-transform: uppercase" type="text" class="form-control" name="produto" id="produto" placeholder="Descrição do Produto">

                Unidade
                <input required style="text-transform: uppercase" type="text" class="form-control" name="unid" id="unid" placeholder="Und.">

                Quantidade
                <input required style="text-transform: uppercase" type="number" class="form-control" name="quant" id="quant" placeholder="Qtd.">

            <input type="submit" value="Inserir" class="btn btn-sm btn-success">

    </form>

            Cód. Int.
            Núm. Orig.
            Cód. Fabr.
            Marca
            Descrição
            Und.
            Qtd.
            R$ Un.
            R$ Total
            Ações

    <?php

    $consulta_itens  = "SELECT * FROM itens_solicitacao WHERE id_solicitacao = $id_solicitacao ORDER BY id_item DESC";
    $operacao_itens = mysqli_query($conecta, $consulta_itens);

    ?>

        <?php while ($registro = mysqli_fetch_assoc($operacao_itens)) { ?>

                <?php echo $registro["cod_interno"] ?>
                <?php echo mb_strtoupper($registro["num_orig"]) ?>
                <?php echo mb_strtoupper($registro["cod_fabric"]) ?>
                <?php echo mb_strtoupper($registro["marca"]) ?>
                <?php echo mb_strtoupper($registro["descricao"]) ?>
                <?php echo mb_strtoupper($registro["und"]) ?>
                <?php echo $registro["qtd"] ?>
                <?php echo $registro["venda_unit"] ?>
                <?php echo $registro["venda_total"] ?>

                    <button type="submit" class="btn btn-sm btn-success" title="Autorizar Compra"></button>
                    <button type="submit" class="btn btn-sm btn-dark" title="Recusar"></button>

    <?php
    }
    mysqli_free_result($operacao_itens);

    ?>

E abaixo segue o script JS. Pra atualizar tive que virar com o location.reload por enquanto:

Comment: Basta fazer um `.append()` ou `.prepend()` na tabela com as informações inseridas no BD.
Comment: No javascript faz uma nova TR com as TD com os dados inseridos na BD e depois fazer um ``.append()`` à tbody da table.
Answer: Antes de tudo seria interessante você separar o trecho do código responsável por renderizar a linha da tabela, podemos fazer isso criando uma função no php:
function renderTableLine($registro) {
  return <<<HTML

      {$registro["cod_interno"]}
      {mb_strtoupper($registro["num_orig"])}
      {mb_strtoupper($registro["cod_fabric"])}
      {mb_strtoupper($registro["marca"])}
      {mb_strtoupper($registro["descricao"])}
      {mb_strtoupper($registro["und"])}
      {$registro["qtd"]}
      {$registro["venda_unit"]}
      {$registro["venda_total"]}

          <button type="submit" class="btn btn-sm btn-success" title="Autorizar Compra"></button>
          <button type="submit" class="btn btn-sm btn-dark" title="Recusar"></button>

HTML;
}

Esta função seria usada em dois lugares, primeiro para renderizar todas as linhas da tabela dentro do tbody:

    <?php while ($registro = mysqli_fetch_assoc($operacao_itens)) {
        echo renderTableLine($registro);
    ?>

Depois use a mesma função para renderizar a nova linha logo depois de inserir o registro no banco de dados no arquivo inseriritens.php inserindo o mesmo trecho de código logo depois de inserir o registro no banco:
echo renderTableLine($registro_inserido);

Por fim, faça um append do html gerado na execução do arquivo inseriritens.php no tbody da tabela
function inserirFormulario(dados) {
        $.ajax({
            type: "POST",
            data: dados.serialize(),
            url: "../conexoes/inseriritens.php",
            async: false
        }).then(sucesso, falha);

        function sucesso(data) {
            $('#insere_itens')[0].reset();
            $('#tabeladeitens tbody').append(data);
        }
    }

É provável que você tenha que fazer ajustes no código, uma dica é fazer um debug para entender o que está chegando no "data" antes de fazer o append, mas a ideia é essa.
Comment: basta no javascript fazer um ``.append()`` a um anova TR com todas as TD com os dados do AJAX. Não precisa ir ao php outra vez
Comment: Isso mesmo, no sucesso faz o append do resultado retornado do POST feito via AJAX.
Comment: Valeu pessoal! Deu certo. Muito obrigado!


Techniques for dependency injection into a domain model

Question: I have a domain model type. One of its numerous properties requires an ITranslationService to provide the ability to translate its return value into the appropriate language.
Should I inject the ITranslationService into the constructor of the domain model type (thereby having to alter everywhere the type is instantiated and having to be concerned about initialisation when  retrieved via NhIbernate), even though it is used by a tiny part of the type (one of many properties); or is there another functional pattern I can use?
Does anyone have any relevant experience they can share?
Comment: check http://techblog.bozho.net/?p=180
Answer: I would not expect the domain object to do the translation - instead, use the translation service with the domain object (or the relevant property value) as a parameter, and return the translated value. For example, you could simply do
<code>var translatedString = yourServiceInstance.Translate(theDomainObject.Property);
</code>
Comment: +1 This is better. The other design sounds like a violation of the SRP.
Comment: My understanding of your answer is that you're moving the dependency on the translationservice to the client of the method? Your code looks exactly like the code in the property as-is. My problem is supplying the dependency. One possibility might be to inject the translationservice into a new accessor method. Is it straightforward to expose accessor/mutator method pairs as nhibernate properties? ...I feel out of my depth
Comment: @Ben: Yes, move the dependency to the object that's using the domain object, rather than having it in the object itself. I'd imagine the above code to be in a controller action, or a view, if this was an ASP.NET MVC web application. The goal with this is to make your domain objects just hold data, while someone else is responsible for processing that data.
Comment: @Tomas - I understand what you are saying. There is a tension though with trying to avoid an anemic model.
Comment: Is translation required by the domain entity to perform its purpose, or is it a user interface concern?

Anaemic domain models are entities which expose all their internal state for modification and lack domain specific behaviour. An entity need not, and in my opinion should not, utilise injected services in order to provide behaviour.
Comment: Translation is required by the domain entity to perform its function. If injection of a service is to be avoided, where should the translation be performed? In another service?
Answer:
Should I inject the
  ITranslationService into the
  constructor of the domain model type

Yes, that may make sense, depending on your situation. If you would always avoid the injection of services into entities, then that might lead to an anemic domain model which is an anti-pattern.
Code which needs to instantiate entities can be shielded from the extra constructor argument by using a factory, which takes care of the dependency injection.
NHibernate can also inject services into an entity via the constructor: http://fabiomaulo.blogspot.com/2008/11/entities-behavior-injection.html
Comment: Thanks. In the end I removed the dependency cf Tomas, but I liked your factory discussion.


Adding Punctuation Marks in SQL

Question: I need to add information into my tables but there are punctuation marks.  How do I add these without closing the statement? I am using SQL SERVER 2012
Example:
INSERT INTO Song (song_id, album_id, song_name, song_length_minutes, song_length_seconds)
VALUES ( 500, 200, **'Doin' it Right'**, 3, 42)

The apostrophe after "Doin" if you enter that it closes out the song_name.  So how do you add this without closing the statement?
Also, What is the best way to do time?  In this example both are seperated so I figured it would just be a numeric value data type?  Is that correct?
Example:
CREATE TABLE Song (
song_length_minutes DECIMAL (5) NOT NULL,
song_length_seconds DECIMAL (5) NOT NULL );

Is that okay to do ? And then in the INSERT statements do as shown above?  Would you only use the UI Logic if your pulling that information?
Comment: Consider using stored procedures and parameterized queries.
Answer: The following link should help you: -
http://www.orafaq.com/faq/how_does_one_escape_special_characters_when_writing_sql_queries
I recommend reading this as it includes information on double escape sequences too.
As seen on the page: -
SELECT 'Frank''s Oracle site' AS text FROM DUAL;

You could store time as simply seconds and then use your UI logic to convert this to the value that you would like to display.
Answer: VALUES ( 500, 200, 'Doin'' it Right', 3, 42)

You need to escape the quote by doubling the single quote.
Using Sql parameters will do this for you
Answer: Not sure if that's what you meant, are you talking about escaping special characters?
INSERT INTO Song (song_id, album_id, song_name, song_length_minutes, song_length_seconds)
VALUES ( 500, 200, **'Doin'' it Right'**, 3, 42);

What language are you using to run the statement?
You should probably store time in a time field, it will be much easier to move back and forth from DB to code.

Adding Punctuation Marks in SQL


When is a local homeomorphism a covering map?

Question: if $X$ and $Y$ are Hausdorff spaces, $f:X \to Y$ is a local homeomorphism, $X$ is compact, and $Y$ is connected, is $f$ a covering map?
It seems to be, and I almost have a proof, but I'm stuck at the very end of it:
I've already proved that $f$ is surjective (using the connectedness), and that for each $y \in Y$, $f^{-1}(y)$ is finite. Because $X$ is compact, there exists a finite open cover of $X$ by $ \{ U_i \}$ such that $f(U_i)$ is open and $f |_{U_i}:U_i \to f(U_i) $ is a homeomorphism.
For each $y \in Y$, we choose the subset $ \lbrace U_{i_j} \rbrace $ such that $y \in U_{i_j}$, and then define $V = \bigcap_{j=1}^k f(U_{i_j})$, and $U'_j = U_{i_j} \bigcap f^{-1}(V)$.
... and this is were I got stuck. I really want to write that $f^{-1}(V) = \bigcup_{j=1}^k U'_j$ (more or less proving it's a covering map), but I can't justify that, and I actually think that it's not true. I think I might need an extra step, and to take an even smaller neighborhood of $y$, in order to make sure that extra sets from $ \lbrace U_i \rbrace $ didn't sneak into $f^{-1}(V)$.
Any help would be greatly appreciated as I've already spent several hours working on this problem.
Comment: If you have already shown that $f$ is surjective, why are surjectivity and local homeomorphism not enough to show that $f$ is a covering map? For $y \in Y,$ we know that there is a neighborhood $U$ around $f^{-1}(y) \in X$ on which the restriction of $f$ is a homeomorphism, so $V = f(U)$ is a neighborhood around $y$ onto which $f^{-1}(V) = U$ is mapped homeomorphically. With surjectivity, isn't this enough?
Comment: Why $f:X\rightarrow Y $ is surjective?
Answer: For $y \in Y$, let $\{x_1, \dots, x_n\}= f^{-1}(y)$ (the $x_i$ all being different points). Choose pairwise disjoint neighborhoods $U_1, \dots, U_n$ of $x_1, \dots, x_n$, respectively (using the Hausdorff property).
By shrinking the $U_i$ further, we may assume that each one is mapped homeomorphically onto some neighborhood $V_i$ of $y$.
Now let $C = X \setminus (U_1 \cup \dots \cup U_n)$ and set $$V = (V_1 \cap \dots \cap V_n)\setminus f(C)$$
If I'm not mistaken this $V$ should be an evenly covered nbh of $y$.
Comment: Seems right to me. f is a closed map (compactness+hausdoff), C is closed so f(C) is closed, so V is open, and $f^{-1}(y)\bigcap C = \emptyset$ so $y \in V$, and so it's indeed an open nbh of y. $f^{-1}(V) \subset U_1 \cup \ldots \cup U_n$ by definition, and so $f^{-1}(V) = (U_1 \cap f^{-1}(V)) \cup \ldots \cup (U_1 \cap f^{-1}(V))$ when $U_i \cap f^{-1}(V) \cong V$.
Comment: Right, looks like you finished the proof. :)
Comment: @Sam why $f^{-1}(y)$ is finite? where is the compactness is nedded to argue that?
Comment: @CityOfGod: Since $f$ is a local homeomorphism, the set $f^{-1}(y)$ consists of isolated points. Since $X$ is compact, this can only be the case, if $f^{-1}(y)$ is finite.
Comment: @evaristegd: $f^{-1}(y) \subset X$ is a closed subset, hence compact (since $X$ is compact). For each $x \in f^{-1}(y)$ there exists a homeomorphically mapped neighbourhood $U_x$ of $x$. In particular, this implies that $x' \notin U_x$ for $x' \in f^{-1}(y)$, $x'\ne x$ (since $f|_{U_x}$ is injective). But at the same time, finitely many of the $U_x$ cover $f^{-1}(y)$ by compactness, so there can be at most a finite number of points in $f^{-1}(y)$.
Comment: How can I prove that, when $f$ is a local homeomorphism, the fiber of $y$ consists only of isolated points?
Comment: @Sam thank you for your input. There is now a MathSE post addressing this:
https://math.stackexchange.com/questions/3222556/proof-that-the-inverse-image-of-a-single-element-is-a-discrete-space
Answer: Here is a complete solution, said slightly differently than, but in the same spirit as, Sam's solution.

Show that $f$ is surjective. We use the fact that $Y$ is connected and Hausdorff. Local homeomorphisms are open, so $U=f(X)$ is an open subset of $Y$. Since $X$ is compact, $f(X)$ is compact, and $Y$ Hausdorff implies that compact subsets are closed. So, $V=Y\setminus f(X)$ is also open. If $f$ were not surjective, then $V\neq \emptyset$, and $U,V$ would be separating sets for $Y$, contradicting connectedness of $Y$. We conclude that $f$ is surjective.
For each $y\in Y$, $f^{-1}(y)$ is finite. Again using $Y$ Hausdorff, $\{y\}$ is closed, so $f^{-1}(y)$ is a closed subset of the compact space $X$, hence compact. For each $x\in f^{-1}(y)$, let $U_x$ be a neighborhood of $x$ where $f$ restricts to a homeomorphism. Such neighborhoods exist by the assumption that $f$ is a local homeomorphism. Then $\{U_x : x\in f^{-1}(y)\}$ is an open cover of $f^{-1}(y)$, hence has a finite subcover which we label $\{U_i\}_{i=1}^n$. The map $f$ is injective on each $U_i$, thus only contains one pre-image of $y$. Hence $y$ has finitely many pre-images in $X$.
Get an evenly covered neighborhood of $y$. Keeping the cover $\{U_i\}$ from the previous step, $V = \bigcap_{i=1}^n{f(U_i)}$ is an open neighborhood of $y$. Then $\{f^{-1}(V)\cap U_i\}$ is a disjoint collection of open neighborhoods, each homeomorphic to $V$ under $f$ since the restriction of a homeomorphism to a subspace is a homeomorphism. Thus, $V$ is an evenly covered neighborhood of $y$.

Therefore, $f$ is a covering map.
Comment: Comment after five years ;-) There is no reason based on the construction why the $U_i$ should be pairwise disjoint. However, you can achieve this by shrinking them (using the fact that $X$ is regular). But even then I do not see why $f^{-1}(V) \subset \bigcup U_i$.
Comment: Paul is correct. The proof given in step 3 is incorrect, the same line can be used to show every surjective local homeomorphism is a covering map, which is wrong. See Sam's answer for the correct construction of $V$.
Answer: cp. Fulton, Algebraic Topology, Proposition 19.3, p.266.
He uses the compactness of X. But a problem in the John Lee's book Introduction to Topological Manifolds is this (Problem 11-9): Show that a proper local homeomorphism between connected, locally path-connected, compactly generated Hausdorff spaces is a covering map.
Comment: I think the second part of your answer would better fit as a separate question. If you ask it, just link here and say that it is related but not exactly the same.
Comment: Fulton's proof only applies when $Y$ is first countable and $X$ is sequentially compact. This is less general than the question.


deserialize object with a factory method

Question: I have an object that has an array of objects that are created with a factory method.  Serialization is working fine, I can see all of the properties on the objects, but when deserializing, the properties on the array of objects are not being set.
How can I use the factory method used to create these objects when the document deserializes back to it's original object structure?
I've tried using a MapCreator like this:
<code>BsonClassMap.RegisterClassMap<Attribute>(cm =>
            {
                cm.AutoMap();
                cm.MapCreator(a => Attribute.Create(a.Name, a.GetValue(), a.IsVisible, a.GroupName, a.Priority));
            });
</code>
But I get the following exception:
[MongoDB.Bson.BsonSerializationException] = {"The only operations allowed on the prototype parameter are accessing a field or property."}
If I need to create a custom serializer, I'm not sure how to deserialize the array of objects, how to iterate through the array data in the bson reader.
Thanks,
John
Answer: I think the problem is a.GetValue(). Each parameter has to map back to a property or field in your class and GetValue() doesn't. Name, IsVisible, GroupName, and Priority are all mappable, but not GetValue() because it's a method. Remember that this is you telling us on how to construct your Attribute class. We can use the properties because we know how they've been mapped. But it isn't possible to map a method in the current version of the driver. If you'd like to file a feature request for mapping methods, you can do that at jira.mongodb.org under the CSHARP project.
Craig


Variáveis invertendo(Python)

Question: Sei que dá pra fazer de outras maneiras, mas fiz limitado aos ifs. Desejo saber o porquê de estar invertendo os resultados na última parte do código.
from random import randint

pedra, papel, tesoura = "1", "2", "3"

print("[1] Pedra\n[2] Papel\n[3] Tesoura")
p = int(input("Pense no que vai jogar: \n"))
d, e, c = "Você perdeu!", "Empate!", "Você ganhou!"
pe, pa, te = "Pedra", "Papel", "Tesoura"

if p == 1:
    print("Você jogou:", pa)
elif p == 2:
    print("Você jogou:", pe)
elif p == 3:
    print("Você jogou:", te)

pc = randint(1, 3)

if pc == 1:
    print("PC jogou:", pa)
elif pc == 2:
    print("PC jogou:", pe)
elif pc == 3:
    print("PC jogou:", te)

if pc == p:
    print(e)
elif pc == 1 and p == 2:
    print(d)
elif pc == 2 and p == 1:
    print(c)
elif pc == 3 and p == 1:
    print(d)
elif pc == 1 and p == 3:
    print(c)
elif pc == 3 and p == 2:
    print(c)
elif pc == 2 and p == 3:
    print(d)

Comment: Falamos Pedra, Papel e Tesoura... Vc colocou 1 = papel, 2 = pedra, 3 = Tesoura. Aí vc deixou seu código confuso. Muda os valores para 1 = pedra, 2 = papel, 3 = tesoura e refaz os `if`. Vai facilitar para vc. O erro está nos outros ifs e não nos dois últimos.
Answer: elif pc == 1 and p == 2:
    print(c)
elif pc == 2 and p == 1:
    print(d)
elif pc == 3 and p == 1:
    print(c)
elif pc == 1 and p == 3:
    print(d)
elif pc == 3 and p == 2:
    print(d)
elif pc == 2 and p == 3:
    print(c)

O problema era que onde o jogador ganhava, era printado a variárel que o mostrava como perdedor. Basta susbtituir, no último if, onde tem "c" por "d" e vice-versa, conforme mostrado no código acima.

Variáveis invertendo(Python)


Get book bid to display at search results page

Question: I'm trying to tweak my search results template to include the book root title at the bottom of every search results snippet. I have several books with very similar titles and content and i'd like to be able to print title of the book below each search result snippet so users know what they're going to get when they click search result.
I tried simply print $node->book['bid'] but it didn't print any result. I think it's because i have to somehow get the bid of a snippet and i'm getting bid of search results page which has no bid.
Am i right? And how i do that? I'm using Custom Search module to display my search results.
Answer: The book id bid is nothing more then the node id nid of the parent. Therefor if you have the bid, you still need to extract the title from the parent node.
$search_hit = $variables['result']['node']->nid; // The node id of the search result item
$node = node_load($search_hit); // Load the whole node whose search result we got
$parent_id = $node->book['bid']; // Extract the parent from the found node

$node2 = node_load($parent_id); // Load the parent node.
echo $node2->title; // This is the parent title.

Comment: Yeah, that was it. Worked like a charm. I was missing loading the whole node when i was trying to get it to work. Now i have a lot of possibilities with conditions based on `$parent_id`. Also `$search_hit` can be simplified to `$result['node']->nid`. Thanks a lot for help! I was trying to get the answer on drupal.org issue page, but noone replied in 9 weeks... Here i got answer in minutes.
Comment: It seems like search results template works in a different way than regular node. I put your code into my custom_search-result.tpl.php and nothing happened. But when i put it in node.tpl.php - it works perfectly. The same piece of code. I cannot even get the node id through simple: `nid; ?>`
Comment: Maybe this helps? http://drupal.org/node/535578
Comment: So `$this_node = $variables['result']['node'];` got me nowhere, basically. I tried to do what you suggested, use this and your example and it didn't return anything.

However, i am able to extract node id from this.

With your piece of code i did something like this:

`$node_id = $variables['result']['node']->nid; //This gets me the node id of every snippet
$node2 = node_load($node_id);
echo $node2->title; // This gets me the node title`

So now i have a title of the snippet and all i have to do is to get the bid. Any ideas on how to get bid from existing nid?
Comment: You are on the right track, but you need to load also the parent node. With the `bid` of the child node (the one you display the title from). See the updated example.