Should you use multi-site or multiple Drupal instances to host different content for subpath sites?

Question: I want to host a Drupal 7 site that effectively has four different silos of information. The architecture will look like this:

example.com - Blog site with content about the parent company
example.com/foo - Informational site about sub-company "foo"
example.com/bar - Informational site about sub-company "bar"
example.com/fubar - Informational site about sub-company "fubar"

The top site will pretty much be a blog with navigational elements directing people to the sub-sites. The three sub-sites will essentially be the same structure, but have slightly different CSS (different color schemes) and have different information. Logins can be separate, because we actually want to be able to peel away one of the subsites to sell as an asset, if need be.
I'm wondering what the best way to do this would be. Multi-site should keep it easy to update, because the modules and core should be upgraded in lockstep. However, I can't seem to get multi-site to work for these subpaths.
Is multi-site the best way to go here? Or should I just host four different instances of Drupal, one for each site?
(Note, I saw a question about subsites just after I posted this, but it seems that subsites is only available for Drupal 6. Please correct me if that is wrong!)
Comment: nmc's answer helped me get going with subsites (you don't need the subsite module). If anyone has any input as to whether this is the best way to do things, I'm still looking for that.
Answer: Subsites should work for Drupal 7 as well (assuming this is what you're working with).  I've found these instructions helpful in the past: http://drupal.org/documentation/install/multi-site
If the company subsites you are running are under one parent company where there is one body of management (a common decision maker), then subsites makes sense.  If they are different companies which may want very different functionalities for their sites, then it may not be wise to combine them into subsites which rely on the same code.
Comment: There seems to be a lot of mix-up with nomenclature. What I saw that was only available for Drupal 6 is the subsites module. I'm giving the multi-site information you linked another try; I somehow never stumbled upon that particular page!
Answer: The Domain Access module may fit your bill, but it is more geared towards subdomains and not subdirectories.  It is worth looking into, though, if you want to have a common database.
If I were you, I would try to use subdomains instead of subdirectories regardless of the approach you take.  In the long run it will probably make life easier for you when you want to split a site off.
Comment: That sounds like a nice module that makes subdomains easier without fiddling with Apache. Unfortunately, I don't have that option; the client is adamant on having the sites be subdirectories.
Answer: Did you ever get the answer to your questions about which to use?  I'm looking at it the other way.  I have multiple sites, all in the same hosting account, and in separate folders.  Each has it's own domain name and it's own install of Drupal.  I'm considering whether I should consolidate them to a multi-site installation.
What did you wind up doing?  I did find a good article that discusses how to take a multi-site to a standalone site (which you would need of you used multi-site and then sold one of the sites):  http://technopoetic.com/2012/04/convert-a-drupal-multi-site-installation-to-a-single-site/
As far and when to use which?  I still don't know.  I hate having to install and update the same modules over and over.  I've never done a multi-site install before and I'm sure that I'm torturing the web server with all of the instances of Drupal (however, they are just php files).
If you have a single admin for all, I suppose multisite is the way to go.  With multiple instances of Drupal, I can easily move any of then indepenantly.
Let me know what you decided and how it went.
Comment: It's been a while since I dealt with the client, so I don't recall all the reasoning. I went with multisite so I only have to have one copy of the Drupal code to update. However, I still have to manually update modules for each individual site, so it only saves me a small amount of effort. I think if you're doing sub-sites (/sitename vs. sitename.domain) this method works the best, as it was the least troublesome to set up. Hope that helps!
Comment: I thought that the whole point of having an  "all" folder under sites (in addition to "default" for a single site and site-specific folders for multi-site) was that common modules would be in the "all" folder and would only need to be updated once?  Is that not accurate?
Comment: You're right. Ironically, I'm doing more work for this client currently. It looks like I misspoke in my original comment. I *had* to go with multiple installations due to the web hosting the client uses. So I have sub-folders each for each individual site. It's a bit kludgey, I admit, but it works!
Answer: If you go with multi-site and then break the site...every site is broken.  At least if you have multiple installs of drupal and then screw one up, then only one is gone.
People like me have to consider the mistakes we make.


Como exibir dados de três tabelas numa view?

Question: Possuo três tabelas: Processo, Andamento e Custas:
como faço para exibir os dados das três em uma  View, sendo que as tabelas Andamento e Custas possuem como chave estrangeira, a chave primária de Processo?
Fiz um foreach para cada tabela, mas não deu certo, fica duplicando os dados.

            Sentença/Acórdão:
            <?php echo $processo[0]->sentenca; ?>

Andamentos

                <button type="submit" class="btn btn-primary hidden-print" data-toggle="modal" data-target=".addandamento"></button>

                    <?php foreach ($processo as $proc) { ?>

                            <?= $proc->dtandamento; ?>
                            <?= $proc->descricao; ?>

                    <?php } ?>

            <button type="submit" class="btn btn-primary hidden-print" data-toggle="modal" data-target=".addandamento"></button>

                <?php foreach ($processo as $proc) { ?>

                        <?= $proc->dtcustas; ?>
                        <?= $proc->descricao_custas; ?>

                <?php } ?>

Comment: Como você passou os dados pra view? Insira seu código!
Comment: @AndréBaill coloquei na pergunta o código da view.
Comment: Ok e o codigo de controller e model?
Answer: Não sei se entendi certo, mas isso você resolve com as models, fazendo um select que faça os JOINS entre as três tabelas, algo como:
SELECT * FROM Processo INNER JOIN Andamento ON Andamento.id_processo = Processo.id INNER JOIN Custas ON Custas.id_processo = Processo.id ...;
Isso usando as funções do $this->db do codeigniter, como:
    $this->db->from('Processo');
    $this->db->join('Andamento', 'Andamento.id_processo=Processo.id');
    $this->db->join('Custas', 'Custas.id_processo=Custas.id');

Que retornará um array, o qual você deve iterar em sua view.
Comment: @IpFranz eu já tinha feito os joins, o problema é que a view mostra os dados de ambas as tabelas (Andamento e Custas) de forma duplicada. Acho que tem a haver com os foreach, mas ainda não enxerguei o problema.
Comment: Isso parece que pode ser resolvido com um `GROUP BY`, não?
Comment: @IpFranz o group_by resolveu para a tabela Andamento, mas agora a tabela Custas só exibi o primeiro registro :(
Comment: Como são os relacionamentos entre essas tabelas? Há Vários Andamentos/Custas para cada processo? Precisaria ver o banco pra conseguir ajudar melhor
Comment: vou postar o print das tabelas na pergunta, pode ser?
Comment: Código do Model:

function get_processos_like() {
        $termo = $this->input->post('pesquisar');
        $this->db->join('andamento', 'fkcodprocesso=codprocesso', 'left');
        $this->db->join('custas', 'fkcodproc=codprocesso', 'left');
        $this->db->select('*');
        $this->db->where('nprocesso', $termo);
        $this->db->order_by ("str_to_date(andamento.dtandamento, '%d-%m-%Y')", 'DESC', FALSE);
        $this->db->group_by ('andamento.dtandamento');
        return $this->db->get('processo')->result();
}


Confusion in Hartshorne exercise IV.2.7

Question: In page 306 of Hartshorne's book Algebraic Geometry, the exercise 2.7 asks me to show that,
for a given curve (in Hartshrone's sense, i.e., an irreducible complete nonsingular curve over an algebraically closed field) $Y$, there is a 1-1 correspondence between finite étale morphism $f\colon X\to Y$ of degree $2$, and $2$-torsion elements of $\mathrm{Pic}(Y)$.
However, in the text Hartshorne does not assume $X$ is connected (hence also a curve). If it is indeed not assumed to be connected, then

How to define the degree of a finite étale morphism $f\colon X\to Y$? Maybe a reasonable way is to define $\deg f$ by the rank of $f_*\mathscr{O}_X$ as a locally free $\mathscr{O}_Y$-module via $f_\flat\colon\mathscr{O}_Y\to f_*\mathscr{O}_X$.
In (a) of this exercise, Hartshorne uses the previous exercise IV.2.6(d) to show that $(\det f_*\mathscr{O}_X)^2\simeq\mathscr{O}_Y$. But exercise IV.2.6 only states for finite morphism $f$ of curves, how to solve this problem?

But if we assume $X$ is indeed a curve, then we just take $\mathscr{L}=\mathscr{O}_Y$ in (b) of this exercise, then it seems that $\mathrm{Spec}(\mathscr{O}_Y\oplus\mathscr{L})$ is not integral, because the multiplication
\begin{equation}
(a,b)\cdot(a',b')=(aa'+bb',ab'+a'b),
\end{equation}
on $\mathscr{O}_Y\oplus\mathscr{L}$ always satisfies that $(1,1)\cdot(1,-1)=(0,0)$.
Do I miss anything?
Edit: It seems that, if $X$ is not connected, then the étale morphism $f$ can be identified with the codiagonal $\nabla\colon Y\sqcup Y\to Y$, which is a trivial "étale covering". So we WLOG just consider the case $X$ is connected.
Answer: (1) You can define the degree to be the number of points (with multiplicity) in the preimage of a closed point of $Y$. You could also probably reduce to the connected case.
(2) If $f:X\to Y$ is an étale morphism of varieties, then $f$ is smooth of relative dimension $0$ (by definition). Consequently, if $Y$ is smooth then so is $X$. Hence, $X$ is smooth and $\Omega_{X|Y} = \Omega_X/f^*\Omega_Y$ is a locally free sheaf of rank $0$, i.e. the $0$ sheaf. However, for a smooth morphism $\dim X - \dim Y = \mathrm{rk}\:\Omega_{X|Y}$. In particular, $\dim X = \dim Y = 1$ here. Hence, $X$ and $Y$ are both curves.
Intuition: an étale morphism corresponds to a covering map in topology. A covering map (of manifolds) preserves dimension.
Comment: In Hartshorne's sense, a variety (in particularly, a curve) is irreducible. If $f\colon X\to Y$ is a finite étale morphism, then $X$ is not irreducible in general (for example, the codiagonal $\nabla\colon X\sqcup X\to X$).

Confusion in Hartshorne exercise IV.2.7


Why does Snowflake not read certain values?

Question: I'm having trouble with our Snowflake database.  I'm simply trying to multiply a value by a constant (for certain rows) such as:
 select *,
 case when code = 'C' then answer *0.39
 else answer end as answer_iu
 from rawheight
 where country in ('US')

The error I get is:

Numeric value '171240156932559' is not recognized

It works fine when country is not 'US'.  It also works fine when the "case when" is eliminated ie:
 select *
 from rawheight
 where country in ('US')

I get the same error when I try to filter the table as well:
select *
from rawheight
where answer>1000

Any ideas of a workaround?
Comment: Try casting the answer column as integer or appropriate data type in your case expression and/or where statement.
Comment: Please update your question with the ddl for your table and some sample data
Answer: Sometimes snowflake moves the order operations for VARAINT/JSON around, so while this code "should be safe" and actually does run correctly:
with raw_json as (
    select
        parse_json('[
        {"code":"A", "answer":"171240156932559", "country":"US"},\
        {"code":"C", "answer":1000, "country":"NZ"},\
        {"code":"C", "answer":2000, "country":"US"}\
        ]') as json
), rawheight(code, country, answer) as (
    select
        j.value:code,
        j.value:country,
        j.value:answer
    from raw_json as rj,
    table(flatten(input=>rj.json)) as j
)
select *,
 case
     when code = 'C' then answer * 0.39
     else answer
end as answer_iu
from rawheight
where country in ('US')

The optimizer can push the math/cast prior to filters that would remove rows that "do not apply", thus explosion's.
The standard way around this is to wrap data that is of many types number/float/string in VARIANT data with a TRY_TO_DOBULE or TRY_TO_FLOAT like:
TRY_TO_DOUBLE(answer) * 0.39

but that then gets upset, as that is not a text, so you have to cast to ::TEXT
when code = 'C' then TRY_TO_DOUBLE(answer::TEXT) * 0.39

This now works safely for the class of processing I am describing.


How can I determine if double stops are playable?

Question: inspired by Are these double stops playable on violin? :
I have never had the opportunity to play a fretless string instrument. When writing music for violins or other string instruments, what rules can I follow to ensure that I don't write double stops that are impossible/impractical, whether in isolation or due to their relation to adjacent notes?
Comment: This specifically answers your question for violins : https://music.stackexchange.com/questions/81500/is-this-double-stop-playable-on-violin
Answer: Answer for cello
I'll defer to others to answer for violin and viola.
Quite obviously, most double stops where one note is an open string are easy.
Apart from that, the safest double stops are generally major and minor sixths; you can use these in almost any context provided both individual notes are in the range of the cello – i.e. the lower note at least C2, the higher one at most ≈A5.
Fifths are extremely easy in the non-thumb positions (simply use a barré across two strings), though they are not always intonation-safe. In the higher positions (upper note >G4), fifths are actually quite tricky.
While relatively less interesting musically, tritones, fourths and minor sevenths are almost as easy to finger as the sixths and can be used in any position too. Fourths can be surprisingly hard to get the intonation right though.
Major thirds can usually be played ok, but may be difficult in some contexts. Minor thirds likewise, but always a bit more difficult because they require an extended position. Runs in thirds require a position shift at every note change, which makes them much more difficult than runs in sixths. Also note that the higher note in the double stop must be playable on the G-string, i.e. not lower than G2.
Octaves require an over-extended position unless the lower note is on an open string. Over-extended is doable, but hard for players with small hands. Octaves are significantly easier in high positions, specifically in thumb positions (lower note >C4).In any case, intonation problems in octaves will be very obvious (both to the player and audience).
Seconds and Major sevenths are neither easy nor typically musically useful in the cello's register, so only use them if you really mean it.
Comment: One example I remember from my first conducting class, where we had an orchestration exercise: The player can only play one note on each string; there can't be more than one note below the open G on a cello or viola or below the open D on a violin.  So, for example, a violin cannot play the A below middle C and the C# a major third above that at the same time.
Answer: First, there are physically impossible double stops. The notes below the open next-to-lowest string can only be played on the lowest string, so you can't play two notes at a time in that range. For example, a low G-B double stop on violin would be impossible.
Next, understand how the instrument is tuned. Viola, violin, and cello are tuned in fifths, while the bass is tuned in fourths. This means that those intervals require zero reach, and as the interval grows or shrinks from there it requires the player to stretch further.
The limitation then comes from the scale of the instrument, and that the notes are furthest apart in the lowest positions (closest to the nut). On violin and viola, reaching up to an interval of a fourth (on one string) is basic technique in any position, meaning that double stops from a major second to an octave are natural. There are solo violin excerpts stretching up to a tenth, but that should be considered advanced.
On cello, as another commenter explained in more detail, the reach is more limited so you should stick to thirds and sixths more. The span involved in reaching minor or major sevenths is the same as for major or minor thirds (respectively), but the seventh is a dissonant interval so it's rarely seen. Seconds and octaves should be considered advanced.
On contrabass, the scale is so large that you can't reach very far at all. To give you an idea: on a 3/4 size bass I can barely span a whole step in first position, and I can easily reach a tenth on piano. Remembering that the strings are tuned in fourths, the limit for double stops in low positions is merely from thirds to fifths. Considering that small intervals sound muddy in the bass register, you should probably only ever write fifths, if even that.
When writing phrases containing consecutive double stops, it's always easiest when the span is comfortable and the notes move in parallel. For violins and violas, consecutive thirds and sixths (even mixing major/minor) are very common. Consecutive octaves are a bit more advanced but still considered standard. Of course, the other intervals are also possible but compositionally questionable. You won't see runs like this on cello as much, but consecutive sixths are very playable.
When writing phrases consisting of consecutive double stops of varying intervals, there are all sorts of pitfalls you can fall into, and it's hard to summarize them in a post like this. I might suggest that such writing is best left to advanced players of these instruments, or at least you should check the parts with a player rather than trying to apply some general rule.
Answer: Make certain they are not separated by more than EA,AD,GD.
Comment: Could you elaborate and say why? Otherwise your answer is of limited utility.
Comment: Those two notes can be played as a double stop with ease - G=open G, A = 4th finger (in first position) on the D string.
Comment: Yeah, so, a bowed instrument's double stop cannot be separated by more than the string next to it, because you cannot physically play, say, a double stopped G and A, open, because to do so, you would have to flatten the bridge to avoid playing the D.
Comment: That is why I elaborated "open" G and A. It was purely to illustrate the string crossing.


WCF - remote service without using IIS - base address?

Question: I'm trying to get my head around the addressing of WCF services.
We have a client-server setup where the server occasionally (maybe once a day) needs to push data to each client. I want to have a lightweight WCF listener service on each client hosted in an NT service to receive that data. We already have such an NT service setup hosting some local WCF services for other tasks so the overhead of this is minimal.
Because of existing legacy code on the server I believe the service needs to be exposed as ASMX and use basicHttpBinding to allow it to connect.
Each client is registered on the server by the user (they need to configure them individually) so discovery is not the issue.
My question is, how does the addressing work? I imagine the user entering the client's address on the server in the form
http://0.0.0.0/MyService

or even
http://hostname/MyService

If so, how do I configure the client service in its App.config? Do I use localhost?
If not then what is the reccommended way of exposing the service to the server?
Note:

I don't want to host in IIS as that adds extra requirements to the hardware required for the client.
The clients will be almost certainly located on LANs, not over the public internet
Answer: You configure the base address of the service like so:
<system.serviceModel>
  <services>
    <service name="Ns.FooService">
      <host>
        <baseAddresses>
          <add baseAddress="http://localhost:9999" />
        </baseAddresses>
      </host>
      <endpoint
          address="/foo"
          binding="basicHttpBinding"
          contract="Ns.IFooContract" />
     </service>
  </services>
</system.serviceModel>

And then your service could be accessible through http://servename:9999/foo. You may take a look at this article for more information.
Comment: Thanks Darin, that's exactly what I needed to know.


RuntimeException ao usar colorbar() IDE Spyder

Question: Estou um código para mostrar o uso de mapas auto organizáveis e aparece erro de execução ao usar a função colorbar.
O erro acontece na linha colorbar(). Antes disso a saída era:

Então, quando eu executo a linha colorbar(). Aparece o seguinte erro:
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-14-dffe8fcb3a04> in <module>
----> 1 colorbar()

~/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in colorbar(mappable, cax, ax, **kw)
   2091         mappable = gci()
   2092         if mappable is None:
-> 2093             raise RuntimeError('No mappable was found to use for colorbar '
   2094                                'creation. First define a mappable such as '
   2095                                'an image (with imshow) or a contour set ('

RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).

# Self Organizing Map

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Credit_Card_Applications.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values

# Feature Scaling
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
X = sc.fit_transform(X)

# Training the SOM
from minisom import MiniSom
som = MiniSom(x = 10, y = 10, input_len = 15, sigma = 1.0, learning_rate = 0.5)
som.random_weights_init(X)
som.train_random(data = X, num_iteration = 100)

# Visualizing the results
from pylab import bone, pcolor, colorbar, plot, show
bone()
pcolor(som.distance_map().T)
colorbar()
markers = ['o', 's']
colors = ['r', 'g']
for i, x in enumerate(X):
    w = som.winner(x)
    plot(w[0] + 0.5,
         w[1] + 0.5,
         markers[y[i]],
         markeredgecolor = colors[y[i]],
         markerfacecolor = 'None',
         markersize = 10,
         markeredgewidth = 2)
show()

Answer: Desconfio que haja uma chamada à show logo após pcolor pois:

Um gráfico é exibido
A função show "consome" os gráficos feitos anteriormente - e portanto é natural que a chamada à colorbar falhe, visto que não há mais gráficos para aplicar o gráfico de barras
O seguinte trecho de código também causa a mesma exceção que lhe ocorreu:

from pylab import bone, pcolor, colorbar, show
import matplotlib.pyplot as plt
import numpy as np

dados = np.clip(np.random.randn(20, 20), -1, 1)
bone()
pcolor(dados)
show()
colorbar()

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-1-9f16f12cc15b> in <module>()
      7 pcolor(dados)
      8 show()
----> 9 colorbar()

/usr/lib/python3.6/site-packages/matplotlib/pyplot.py in colorbar(mappable, cax, ax, **kw)
   2319         mappable = gci()
   2320         if mappable is None:
-> 2321             raise RuntimeError('No mappable was found to use for colorbar '
   2322                                'creation. First define a mappable such as '
   2323                                'an image (with imshow) or a contour set ('

RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).

Se esse for o caso, vejo algumas possibilidades:

Durante o desenvolvimento, você acrescentou temporariamente uma chamada à show após a chamada à pcolor para testar o andamento do programa? Se sim, basta retirá-la - em outras palavras, o código que você compartilhou, com apenas um show, já deve estar funcionando.
Sua IDE pode fazer chamada implícita à função show. Para verificar, você pode salvar o código que você fez em um arquivo .py, e rodar diretamente via console.
Answer: Eu estava usando o Jupyter Notebook, e estava usando instruções separadas para fazer a parte de mostrar o mapa. O problema desapareceu quando executei todo esse trecho de uma só vez, ao invés de fragmentar a execução do mesmo.
from pylab import bone, pcolor, colorbar, plot, show

# Initializing the figure that contains the map
bone()
pcolor(som.distance_map().T)
colorbar()
markers = ['o', 's'] # circles and squares
colors = ['r', 'g'] # red and green

# i for lines and X for vector that represents the customer
for i, x in enumerate(X):
    w = som.winner(x) # the winning node of customer x
    plot(w[0] + 0.5,
         w[1] + 0.5,
         markers[Y[i]],
         markeredgecolor = colors[Y[i]],
         markerfacecolor = 'None',
         markersize=10,
         markeredgewidth=2) # +0.5 to plot on the center of square on the map

show()


The partitioning of a big disk is necessary for LVM's vg space expansion

Question: I am maintaining a LVM's vg as users' /home directory's storage space. But now I need to add a new 2T sized disk for extending the /home space. I wonder if the partitioning is necessary or not and then I use the several partitions as physical volumes. I prefer to use the entire disk as a physical volume member of the existing vg group for /home. Anyway I have known that multi-partition will make a disaster within a partition. By the way I must mention that both the /home space thant is existing and the 2T space I am adding are on the LSI raid raid-1 mirrored disks.
I know that the decision is really depending on the quality of disks, raid arrangement and experiences. I only hope experienced engineers can review this case and see how other engineer are doing for this case.
Cheers!
Comment: You appear to be considering only "use `/dev/sda`" and "use `/dev/sda[123...]`".  HBrujin, below, adds the middle ground of "use `/dev/sda1`" (ie, a single partition that covers the whole HDD), and that's what I'd suggest, too (+1 from me, HBrujin!).
Answer: LVM supports using the whole disk , without a partition table, for use as LVM physical volume. (The same holds true for SAN and iSCSI LUN's etc.)
Normally I still recommend creating the partition table because:

a partition table prevents other (non-Linux) systems from seeing the disk volume as raw/un-partitioned free space.

That may not be a risk in your environment, but since there's no penalty in doing so, I think it's a good habit to maintain.
Then I would simply create 1 large partition (with label 8e for Linux LVM) spanning the whole disk when the additional new space will be assigned to a single volume group. When two different volume groups need expanding, then you'll need (at least) two partitions.

In your case you have a RAID controller with two mirrored drives.
If you circumvent the RAID controller and add the single drive to the volume group providing space for /home you're losing redundancy, if that single disk fails, you'll lose all data on /home/.
Typically, it easier and better to get two new drives, set up mirroring for those two in your RAID controller and only then add the space to your volume group.
If you can't get two  new disks, you can still change the RAID level in your controller, effectively going from RAID1 to RAID5, maintaining redundancy,  but most controllers don't have that as an online non-destructive option. Doing so means backing up all data, rebuilding the RAID volume and then restore everything.
Comment: Thanks! I will give the two partitions to the mirrored disk and then assigned them to the vg group  in which /home lg is staying. The partitioning here is only providing flexibility to future space reallocation. For data safty, I must be depending on the raid setup and baking up more than 2 times in differenct places


Symfony2 - Catchable Fatal Error - Fixtures

Question: I am trying to load some fixtures in my database and I am going to become crazy due to doctrine error. This is it:

[Symfony\Component\Debug\Exception\ContextErrorExce ption]  Catchable
  Fatal Error: Argument 1 passed to
  TuzonaBundle\Entity\Ciudades::setProvincias() must be an instance of
  TuzonaBundle\Entity\Provincias, string given, called in
  /httpdocs/src/TuzonaBundle/DataFixtures/ORM/Ciudad.php on line 141 and
  defined

As you can see, the problem is specific enough. The problem is that I am not given to 'setProvincias()' the right datatype. I guess the right datatype is an integer, but it doesn't work like that... I tried with a string, with the same result.
The code is as follow
TuzonaBundle\Entity\Ciudades.php
class Ciudades
{
    /**
    * @ORM\ManyToOne(targetEntity="Provincias", inversedBy="ciudades")
    * @ORM\JoinColumn(name="id_provincia", referencedColumnName="id")
    */
    protected $provincias;

    /**
    * Set provincias
    *
    * @param \TuzonaBundle\Entity\Provincias $provincias
    * @return Ciudades
    */
    public function setProvincias(\TuzonaBundle\Entity\Provincias $provincias = null)
    {
    $this->provincias = $provincias;

    return $this;
    }

}

TuzonaBundle\Entity\Provincias
class Provincias
{

    /**
    * @ORM\OneToMany(targetEntity="ciudades", mappedBy="provincias")
    */
    protected $ciudades;

    /**
    * @var integer
    *
    * @ORM\Column(name="id", type="integer")
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    private $id;

}

Answer: Looks like the key of problem is about your words:

I guess the right datatype is an integer, but it doesn't work like
  that... I tried with a string, with the same result

No, it is not integer.
You should to call "setProvincias" with an object of Provincias datatype.
So if you are loads data via fixtures, you should to create some Provincias fixtures, like
ProvinciasData.php
public function load(ObjectManager $manager)
    {
        $province = new \YourApp\TuzonaBundle\Entity\Provincias();
        $this->addReference('YourApp\TuzonaBundle\Entity\Provincias-1', $province);
        $manager->persist($province);
        $manager->flush();
}

CiudadesData.php
public function load(ObjectManager $manager)
    {
        $ciudade = new \YourApp\TuzonaBundle\Entity\Ciudades();
        $ciudade->setProvincias($this->getReference('YourApp\TuzonaBundle\Entity\Provincias-1'));
        $manager->persist($ciudade);

        $manager->flush();
}


C++: how to access a multidimensional array with pointers?

Question: Given: (In C++)
int main () {

    int* ptr;
    int ary [10][2];
    ptr = ary;

    return 0;
}

How would I access ary[0][1] with ptr?
Comment: alas, I was making this too complicated....
Answer: You can't, because the type of ptr is wrong. The variable should be declared as int(*)[2] (pointer to an array of size 2 of integers). Then you could just use ptr[0][1].
#include <cstdio>

int main () {

    int (* ptr) [2];   // <--
    int ary [10][2];
    ptr = ary;

    ary[0][1] = 5;
    printf("%d\n", ptr[0][1]);

    return 0;
}

If you must use an int*, you need to introduce a reinterpret_cast. The array indices are laid out like:
    0       1        2         3              2*n      2*n+1
[0][0]  [0][1]   [1][0]    [1][1]    ...    [n][0]    [n][1]

so you could use ptr[1] to get ary[0][1].
#include <cstdio>

int main () {

    int* ptr;
    int ary [10][2];
    ptr = reinterpret_cast<int*>(ary);  // <--

    ary[0][1] = 5;
    printf("%d\n", ptr[1]);

    return 0;
}

Comment: I am coming from python... this explains my lack of understanding of pointers. The second concept is intriguing but seems like more work than is necessary - just goes to prove how much there is to learn in programing and how many ways there are to do everything. thanks!
Comment: Alternativly, `int* ptr = ary[0]` is fine, too. Though, In theory, you're only allowed to access `ptr[0]` and `ptr[1]` in this case.
Comment: If you are really anal, you can do `ptr+2+1` to access `ary[1][1]` and `ptr + 2 + 2 + 1` to access `ary[2][1]` and so on. That this is guaranteed to work in theory probably shows that one shoudn't worry too much (so although in theory `ptr + 3` is different (UB) than `ptr + 2 + 1` (well defined), in practice it's the same anyway) :)
Answer: typedef int tenints[10];  // tenints is an array of 10 ints

int main () {

 tenints  ary[2];       // array of 2 tenints, same as your int ary[10][2];
 tenints* ptr = ary

 // ptr[0] or *ptr is the first row
 // ptr[1] or *(ptr+1)is the second row

int* ptr2 = ptr[0];
// ptr2[1] or *(ptr2+1) is ary[0][1]

// if you don't want do use as intermediate variable,
// just substitute "*ptr" for "ptr2" in "*(ptr2+1)"
int val = *((*ptr)+1);

return 0;

}
Answer: What you want only works when the data is on block which it might not be in all cases. In the context of image processing, you mostly do something like this:
int width = 1024;
int height = 768;
char* img = new char[width*height];
char** img2d = new char*[height];
for (int y = 0; y < height; ++y){
  img2d[y] = img + y*width;
}
//set pixel at x=50, y=100
img2d[100][50] = 1;
//does the same
img2d[100*width+50] = 1;
delete[] img;

Comment: Wow, I've never thought of images in that fine of detail before. thanks!
Answer: it is possible, just look at this example ( these are dynamic arrays, but works with static too ):
void bla ( void )
{
    const int32_t sx = 50, sy = 30, sz = 50;
    uint64_t *** n = NULL;
    n = ( uint64_t*** )malloc( sizeof( uint64_t** ) * sx );
    for ( int32_t x = 0; x < sx; x++ )
    {
        *( n + x ) = ( uint64_t** )malloc( sizeof( uint64_t* ) * sy );
        for ( int32_t y = 0; y < sy; y++ )
            *( *( n + x ) + y ) = ( uint64_t* )malloc( sizeof( uint64_t ) * sz );
    }

    for ( int32_t x = 0; x < sx; x++ )
        for( int32_t y = 0; y < sy; y++ )
            for( int32_t z = 0; z < sz; z++ )
                *( *( *( n + x ) + y ) + z ) = 1024 * 1024;
}


How to use pgtype.Numeric with gorm and sqlite3?

Question: I need to store very large and high precision numbers with gORM, and using a pgtype.Numeric seems like the best bet. However, I cannot because I get an error: sql: Scan error on column index 4, name "foo": cannot scan int64
My model looks something like this:
type Model struct {
    gorm.Model
    Foo *pgtype.Numeric `gorm:"not null"`
}

Not sure if using pgtype.Numeric is the best (that's what i've seen everyone else use), or I'm doing something wrong. Thanks!
The code that caused the error:
package main

import (
  "gorm.io/driver/sqlite"
  "gorm.io/gorm"
  "math/big"

  "github.com/jackc/pgtype"
)

type Model struct {
  gorm.Model
  Foo *pgtype.Numeric `gorm:"not null"`
}

func main() {
  db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
  if err != nil {
    panic("failed to connect database")
  }
  // Migrate the schema
  db.AutoMigrate(&Model{})

  // Create
  db.Create(&Model{Foo: &pgtype.Numeric{Int: big.NewInt(10000000), Status: pgtype.Present}})

  var m Model
  db.First(&m) // this line causes the error
}

Comment: Show the code that produced the error.
Comment: Please also note on which line the error occurs. Also, that does not appear to be the complete error message. Omit sensitive information if really necessary, but please provide the full context of the error so that we can understand.
Comment: What is the type of the `foo` column in the database? Does the `db.Create` function return any kind of error? If not, what does the value stored in the database look like?
Answer: Sqlite3 does not support big integer so there is no way you can accomplish that directly. I run the code and foo column is create as:
`foo` numeric NOT NULL

Which in sqlite https://www.sqlite.org/datatype3.html means

A column with NUMERIC affinity may contain values using all five storage classes... If the TEXT value is a well-formed integer literal that is too large to fit in a 64-bit signed integer, it is converted to REAL.

So your big int will turn into float64. Good thing it paniced instead of losing accuracy silently.
What you can do is convert the big int to string or bytes first and store that.
Answer: When debugging the sql.Scanner interface for database deserialization, it is noticeable that the value from the database arrives either as int64 or float64. This then leads to the corresponding error message.
A possible solution is to use a text data type in the database, by adding the type text to the field tag:
`gorm: "type:text;"`

Using the github.com/shopspring/decimal package, you can conveniently create a decimal number using the NewString function.
The adapted code to insert the data:
num, err := decimal.NewFromString("123456789012345.12345678901")
if err != nil {
    panic(err)
}
db.Create(&Model{Foo: &num})

The model structure might then look something like this:
type Model struct {
    gorm.Model
    Foo *decimal.Decimal `gorm: "not null;type:text;"`
}

This would result in the following schema:

Test
If one inserts a breakpoint in decimal.Scan, one can see that the value comes from the database as expected as a string, resulting in the creation of a decimal with NewFromString (see Decimal's scan method).
If you add this line of code to the end of the main function
fmt.Println(m.Foo)

it would result in the following output in the debug console:
123456789012345.12345678901

Complete Program
Your complete program, slightly adapted to the above points, would then look something like this:
package main

import (
    "fmt"
    "github.com/shopspring/decimal"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type Model struct {
    gorm.Model
    Foo *decimal.Decimal `gorm:"not null;type:text;"`
}

func main() {
    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }
    // Migrate the schema
    db.AutoMigrate(&Model{})

    // Create
    num, err := decimal.NewFromString("123456789012345.12345678901")
    if err != nil {
        panic(err)
    }
    db.Create(&Model{Foo: &num})

    var m Model
    db.First(&m)
    fmt.Println(m.Foo)
}

pgtype.Numeric and SQLite
If a PostgreSQL database is used, gorm can be used together with pgtype.Numeric to handle decimal numbers like 123456789012345.12345678901. You just need to use the numeric data type on the Postgres side with the appropriate desired precision (e.g. numeric(50,15)).
After all, this is exactly what pgtype is for, see the pgtype readme where it says:

pgtype is the type system underlying the https://github.com/jackc/pgx PostgreSQL driver.

However, if you use a text data type in SQLite for the reasons mentioned above, pgtype.Numeric will not work with SQLite. An attempt with the above number writes 12345678901234512345678901e-11 to the DB and when reading it out the following error occurs:
sql: Scan error on column index 4, name "foo": 12345678901234512345678901e-11 is not a number


Como ativar o Java EE no Apache Netbeans IDE 10

Question: Eu baixei a versão final do Apache Netbeans 10.0 no site oficial, no entanto o Java EE não vem ativado, eu vou para o próprio Plugin IDE, mas a opção de download não aparece.
Answer: Vá em instalar plugins, aba installed (ou instalados), botão direito em Java Web and EE e escolha Check All. Depois clique no botão active (ou ativar).


Fixed position element contained inside of container div of variable height

Question: I am trying to make an element(social links) 'fixed' inside of a container div(blog post) that varies in height and doesn't continue past the container. So relative to the container div, not the window itself. If the Footer/Header are 500px in height, the social links span can overflow the blog container div. I would like it to snap to the top or bottom of the container div, only scrolling within.
example: https://jsfiddle.net/j8ayod1v/6/

Comment: Could you add an image of how it should look like? Because I don't understand what you're trying to explain.
Comment: I created an Example: https://jsfiddle.net/j8ayod1v/6/

I want the green to stay within the grey. Not overflow onto red.
Comment: you can change th the `positon: fixed;` into `position: absolute;` - is that what you mean?
Comment: No, I need it to scroll like fixed, just stay within the grey container div.
Answer: You could try setting the position as sticky or absolute on the element you want to remain "fixed" within the grey container depending on the behavior you're looking for.
I added both below:

header {
  background: red;
  height: 100px;
}

footer {
  background: red;
height: 300px;
}
article {
  position: relative;
  background: grey;

}
h1 {
  padding: 10px 40px;
}
p {
  padding: 10px 40px;
}

span {
  background: green;
  top: 0;
}

.sticky {
  position: -webkit-sticky;
  position: sticky;
  float: left;
}

.absolute {
  position: absolute;
  right: 0;
}

Fixed (sticky)
Fixed (absolute)

Blog Post

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean pulvinar finibus dolor, quis commodo lacus tristique in. Donec mattis massa volutpat, tristique lacus id, aliquam dolor. Mauris sed imperdiet lacus. Sed vitae cursus enim. Mauris lacinia lectus commodo nunc sodales pellentesque. Proin luctus commodo mi, vestibulum tempor elit. Praesent in dolor eleifend ante rutrum ultrices in eu nibh.

Nullam scelerisque lobortis diam, lobortis accumsan nunc molestie ac. Curabitur quis lorem id neque egestas scelerisque vitae id tellus. Morbi convallis, ante id viverra sagittis, lorem neque viverra eros, in finibus lorem purus id velit. Vivamus vitae nunc id nunc condimentum fringilla. Vivamus elementum semper mattis. Sed et porttitor lorem. Vivamus egestas hendrerit nisi, vitae sodales turpis molestie eget. Aliquam erat volutpat. Proin augue ante, dignissim ac nisi ac, blandit laoreet elit.

Donec feugiat leo suscipit diam pharetra efficitur. Curabitur augue sapien, pretium eu congue a, iaculis in tortor. Morbi nec sapien et elit venenatis pulvinar. Ut nec arcu egestas, dignissim enim sit amet, condimentum nulla. Morbi nisi nunc, interdum quis elementum id, vehicula vel risus. Sed eu sem ut eros euismod condimentum ac vel arcu. Duis gravida mattis sem, in porttitor ligula.

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Donec maximus augue at nunc hendrerit, nec lobortis libero tincidunt. Mauris at viverra dolor. Praesent sed dolor ut nibh ultrices rutrum. Vestibulum aliquam, quam nec euismod dignissim, ipsum neque semper arcu, eu fringilla nibh velit ut tortor. Curabitur molestie enim vitae accumsan venenatis. Nullam sit amet turpis enim. In tincidunt nisl et nisi posuere, in semper massa fermentum. Phasellus sodales justo ac mauris malesuada, non aliquam mauris ultricies. Curabitur vel neque non augue pulvinar consequat. Duis quis elit sodales, tincidunt ipsum sed, ullamcorper tellus. Fusce sed felis euismod, aliquam lacus eget, blandit turpis. Vivamus sapien elit, gravida ac rhoncus eget, interdum nec velit. Praesent quis velit in ex aliquet cursus vitae sit amet metus. Aliquam molestie enim vitae mauris ornare, non ullamcorper augue lacinia.

Donec consectetur id justo quis aliquam. Fusce sollicitudin turpis ligula. Etiam vel viverra tellus. Curabitur eu cursus nisi. Morbi euismod maximus malesuada. Donec condimentum, orci quis fermentum tempor, turpis enim tincidunt enim, ac posuere nisl nisl non ipsum. Aliquam iaculis risus a urna molestie auctor. Suspendisse ac lorem dui. In hac habitasse platea dictumst. Quisque risus nisl, tempus et nunc id, dictum mattis erat. Nulla pulvinar lectus ac turpis sagittis porttitor. Duis sed bibendum est, ut tincidunt eros. Donec eleifend rutrum turpis nec luctus. Maecenas auctor, libero quis dictum dictum, odio lorem cursus metus, sed viverra nulla tortor ut lorem. Ut at mattis augue, sit amet consequat elit. Quisque vehicula nulla et suscipit facilisis.

Comment: Sticky works well, thank you. The only issue is would like it to not occupy the space( like absolute). Thanks.
Comment: For removing the space taken up, does this help at all: https://stackoverflow.com/questions/56200160/remove-unwanted-space-with-position-sticky
Comment: Edit to the above, I added `float: left` and it looks good.
Answer: Is this what you need?

header {
  background: red;
  height: 500px;
}

footer {
  background: red;
height: 500px;
}
article {
  position: relative;
  background: grey;

}
h1 {
  padding: 10px 40px;
}
p {
  padding: 10px 40px;
}

span {
  background: green;
  position: sticky;
  top:0;
}

Fixed

Blog Post

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean pulvinar finibus dolor, quis commodo lacus tristique in. Donec mattis massa volutpat, tristique lacus id, aliquam dolor. Mauris sed imperdiet lacus. Sed vitae cursus enim. Mauris lacinia lectus commodo nunc sodales pellentesque. Proin luctus commodo mi, vestibulum tempor elit. Praesent in dolor eleifend ante rutrum ultrices in eu nibh.

Nullam scelerisque lobortis diam, lobortis accumsan nunc molestie ac. Curabitur quis lorem id neque egestas scelerisque vitae id tellus. Morbi convallis, ante id viverra sagittis, lorem neque viverra eros, in finibus lorem purus id velit. Vivamus vitae nunc id nunc condimentum fringilla. Vivamus elementum semper mattis. Sed et porttitor lorem. Vivamus egestas hendrerit nisi, vitae sodales turpis molestie eget. Aliquam erat volutpat. Proin augue ante, dignissim ac nisi ac, blandit laoreet elit.

Donec feugiat leo suscipit diam pharetra efficitur. Curabitur augue sapien, pretium eu congue a, iaculis in tortor. Morbi nec sapien et elit venenatis pulvinar. Ut nec arcu egestas, dignissim enim sit amet, condimentum nulla. Morbi nisi nunc, interdum quis elementum id, vehicula vel risus. Sed eu sem ut eros euismod condimentum ac vel arcu. Duis gravida mattis sem, in porttitor ligula.

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Donec maximus augue at nunc hendrerit, nec lobortis libero tincidunt. Mauris at viverra dolor. Praesent sed dolor ut nibh ultrices rutrum. Vestibulum aliquam, quam nec euismod dignissim, ipsum neque semper arcu, eu fringilla nibh velit ut tortor. Curabitur molestie enim vitae accumsan venenatis. Nullam sit amet turpis enim. In tincidunt nisl et nisi posuere, in semper massa fermentum. Phasellus sodales justo ac mauris malesuada, non aliquam mauris ultricies. Curabitur vel neque non augue pulvinar consequat. Duis quis elit sodales, tincidunt ipsum sed, ullamcorper tellus. Fusce sed felis euismod, aliquam lacus eget, blandit turpis. Vivamus sapien elit, gravida ac rhoncus eget, interdum nec velit. Praesent quis velit in ex aliquet cursus vitae sit amet metus. Aliquam molestie enim vitae mauris ornare, non ullamcorper augue lacinia.

Donec consectetur id justo quis aliquam. Fusce sollicitudin turpis ligula. Etiam vel viverra tellus. Curabitur eu cursus nisi. Morbi euismod maximus malesuada. Donec condimentum, orci quis fermentum tempor, turpis enim tincidunt enim, ac posuere nisl nisl non ipsum. Aliquam iaculis risus a urna molestie auctor. Suspendisse ac lorem dui. In hac habitasse platea dictumst. Quisque risus nisl, tempus et nunc id, dictum mattis erat. Nulla pulvinar lectus ac turpis sagittis porttitor. Duis sed bibendum est, ut tincidunt eros. Donec eleifend rutrum turpis nec luctus. Maecenas auctor, libero quis dictum dictum, odio lorem cursus metus, sed viverra nulla tortor ut lorem. Ut at mattis augue, sit amet consequat elit. Quisque vehicula nulla et suscipit facilisis.


Are Maximum Likelihood Estimators asymptotically unbiased?

Question: I can follow the proofs in which the asymptotic normal-distribution of a maximum likelihood estimator $\tilde{\theta}_n$ is derived.
however, does this already imply that the maximum likelihood estimates are asymptotically unbiased, i.e. do we have $$E(\tilde{\theta}_n) \to \theta \text{ as } n \to \infty?$$
Since I am aware that in general it is not true that convergence in distribution implies convergence in moments, an explanation would be nice.
The result is often stated e.g. in Wikipedia as "...it means that the bias of the maximum likelihood estimator is equal to zero up to the order $n^{-1/2}$")
1.) Are  some kind of regularity conditions from the mle theory used to establish this result?
2.) Or is a $\sqrt{n}$-convergence of an estimator (to a normal distribution) in general already enough to establish convergence of its moments?
Note: the Wikipedia article mentions Cox, David R.; Snell, E. Joyce (1968). A general definition of residuals , as a source where the order of the bias is derived (formula (12) or (20)).
However in this paper I can't follow the arguments 100%, since their Taylor approximation of $L'(\widehat{\beta})$ is lacking the remainder term. What is the argument used here to discard it completely?
Comment: Heuristically, I am inclined to say yes, as the counterexamples where convergence in distribution does not imply convergence of moments usually rely on cases where some probability mass "escapes". Now, if something is (asymptotically) normal, all moments (asymptotically) exist. But a more rigorous argument would certainly be helpful here.
Comment: See also Shao, Mathematical Statistics, Section 2.5.2, whose answer to your question seems to be "yes".
Answer: I have presented in this answer the issues surrounding the concept of "asymptotic unbiasedness". In short, the issue is whether it is defined as "convergence of the sequence of first moments to the true value", or as "asymptotic distribution having expected value equal to the true value" (of the parameter under estimation).
Under the second approach (which is the more intuitive in my view, while the first and the one the OP discusses can be called "unbiased in the limit"), we have that asymptotic consistency of an estimator is sufficient also for asymptotic unbiasedness. Then, when the MLE is consistent (and it usually is), it will also be asymptotically unbiased.
And no, asymptotic unbiasedness as I use the term, does not guarantee "unbiasedness in the limit" (i.e. convergence of the sequence of first moments).
The conditions for the limit of the sequence of moments to equal the corresponding moment of the asymptotic distribution can be found here, and here.


Which theories and concepts exist where one calculates with sets?

Question: Recently I thought about concepts for calculating with sets instead of numbers. There you might have axioms like:

For every $a\in\mathbb{R}$ (or $a\in\mathbb{C}$) we identify the term $a$ with $\{a\}$.
For any operator $\circ$ we define $A\circ B := \{a\circ b : a\in A\land b\in B\}$.
For any function $f$ we define $f(A) := \{ f(a) : a\in A \}$. (More general: For a function $f(x_1,\ldots, x_n)$ we define $f(A_1,\ldots, A_n):= \{f(a_1,\ldots, a_n): a_1\in A_1 \land \dots \land a_n\in A_n \}$).
One has to find a good definition for $f^{-1}(A)$ which might be the inverse image of $A$.

((3.) is just the normal definition of the image and (2.) is a special case of (3.))
Now I am interested to learn about theories and concepts where one actually calculates with sets (similar to the above axioms).
After a while I found interval arithmetic. What theories or approaches do you know?
Because there will not be just one answer to my question, I will accept the answer with the most upvotes.
Update: The theories do not have to follow the above axioms. It's okay when they make there own definitions how a function shall act on sets. It is just important that you calculate with sets in the theory, concept or approach.
Comment: Are you sure that $x^2 = 4 \Rightarrow x = \{ 2, -2 \}$? Looks like $x$ could be $\{2\}$ or $\{-2\}$, according to your item 3.
Comment: You could simply write $x\in \{2,-2\}$ instead of $x=\{2,-2\}$.  This holds without changing any axioms or creating any new ones.  For the second example $x\in [-1,1]$ will suffice.
Comment: You are right. I will delete my examples because they might be confusing...
Comment: Monoid of subsets of a group have been mentioned at MSE a few times, e.g. [here](http://math.stackexchange.com/questions/101045/what-can-we-learn-about-a-group-by-studying-its-monoid-of-subsets). [Proofwiki](http://www.proofwiki.org/wiki/Category:Subset_Products) mentions some basic properties.
Comment: @MartinSleziak thx for the links ;-)
Answer: I like Minkowski addition, aka vector addition. It is a basic operation in the geometry of convex sets. See: zonotopes & zonoids, Brunn-Minkowski inequality, polar sets... and here's a neat inequality for an arbitrary convex set $A\subset\mathbb R^n$:
$$
\mathrm{volume}\,(A-A)\le \binom{2n}{n}\mathrm{volume}\,(A)
$$
with equality when $A$ is a simplex. (Due to Rogers and Shepard, see here)
The case $n=1$ isn't nearly as exciting.


O nome do arquivo Laravel

Question: Estou salvando um arquivo no AWS s3 da amazon, o arquivo está sendo salvo mas ele coloca um underline e um número na frente, conforme a imagem abaixo:

E isso está me atraplando na hora de pegar a url do pdf pra mostrar o pdf pro usuário, teria como tirar esse número, ou uma função que pega a URL do objeto?
Tentei essa mas não traz a URL do Objeto:
$Url=Storage::disk('s3')->url($filename);

Código que está salvando o arquivo no servidor:
 $filenamewithextension = $request->file('doc')->getClientOriginalName();

        $dia=date('d/m/Y');
        $horario=date("H.i.s");
        $id=Auth::user()->id;
        $filename ='teste';

        $extension = $request->file('doc')->getClientOriginalExtension();

        $filenametostore = $filename.'_'.time().'.'.$extension;

        Storage::disk('s3')->put($filenametostore, fopen($request->file('doc'), 'r+'), 'public');

Answer: na linha
$filenametostore = $filename.'_'.time().'.'.$extension;

é onde é inserido o numero, remova o '_'.time().'.' e este número não ira aparecer (deverá ficar assim: $filename.$extension) mas tome cuidado, alguém criou este código desta maneira porque podem haver conflitos de nomes.

O nome do arquivo Laravel


Is there a way to detect if an image has been dragged and dropped into a div without moving image?

Question: I am making a survival game using javascript, and right now I'm setting up all the functions. I have made an inventory system where you can go onto the next and previous items, and it shows the description, number, image and name of the item. Right now I have two buttons that allow you to get and drop the item, but I would like to be able to drag the image of the item from the description onto the main game screen and drop it, without actually moving the image.
I have tried detecting the position of the image when it is being dragged, and check if it's in the game screen div, but what ends up happening is that the function that is called when the image is in the right place happens even if the image is not dropped.
var img = document.getElementById('img');
      var div = document.getElementById('div');
      var divLocation = div.getBoundingClientRect();
      var p = document.getElementsByTagName('p');
      var time = 0;

      img.addEventListener('drag', function() {

        p[0].innerHTML = event.clientX;
        p[1].innerHTML = event.clientY;
        p[2].innerHTML = divLocation.left;
        p[3].innerHTML = divLocation.top;

        if (event.clientX - divLocation.left >= 0 && event.clientX - divLocation.left <= 200) {
          if (event.clientY - divLocation.top >= 0 && event.clientY - divLocation.top <= 200) {

            if (time == 1) {
              alert("test");
              time = 0;
              setTimeout(1000);
            }

          }
        }

      });

      setInterval(function() {
        time++;
        if (time > 1) {
          time = 0;
        }
      }, 1000);

I want the variable for the number of item to decrease by 1, when you drop the image into the game screen div, without moving the image, but right now when the image hovered on the div the function happens.
Comment: Read [this](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations) - and implement `dragOver`.
Answer: Here is a simple, but complete, drag-and-drop implementation.
Note the image is dragged, dropped, collected, but not moved.
You will want to click the "Full page" link in the preview. Drag the image to the dashed-bordered dropzone.

document.querySelector('img').addEventListener('dragstart', dragstart_handler);
document.querySelector('img').addEventListener('dragend', dragend_handler);
document.getElementById('dropzone').addEventListener('drop', drop_handler);
document.getElementById('dropzone').addEventListener('dragover', dragover_handler);
document.getElementById('dropzone').addEventListener('dragleave', dragleave_handler);

const collectedItems = [];

function dragstart_handler(ev) {
  ev.currentTarget.style.border = "dashed";
  ev.dataTransfer.setData("text", ev.target.dataset.item);
  ev.effectAllowed = "none";
}

function dragover_handler(ev) {
  ev.currentTarget.style.backgroundColor = "lightblue";
  ev.preventDefault();
}

function dragleave_handler(ev) {
  ev.currentTarget.style.backgroundColor = "white";
  ev.preventDefault();
}

function drop_handler(ev) {
  ev.currentTarget.style.backgroundColor = "white";
  collectedItems.push(ev.dataTransfer.getData("text"));
  console.log(collectedItems);
  document.getElementById('items').textContent = `Number of items collected: ${collectedItems.length}`;
  ev.preventDefault();
}

function dragend_handler(ev) {
  ev.target.style.border = "solid black";
  ev.dataTransfer.clearData();
}
#dropzone {
  position: fixed;
  right: 0;
  bottom: 0;
  width: 200px;
  height: 200px;
  border: 1px dashed blue;
}
<!DOCTYPE html>


How can I block all IPv6 Adresses starting like this 2a01:598:xxx in my .htaccess file?

Question: How Can I block all IP Adresses that start like this 2a01:598: in my htaccess file?
I tried:
Deny from 2a01:598::/28

and i also tried it like this:
Deny from 2a01:598::

But it doesnt work? What am I doing wrong?
My wordpress website is running on shared Hosting.
Looking forward to your answers.
Comment: We could and should assume 2.4, as 2.2 has been EOL since January 2018.
Comment: What version of Apache are you on?
Answer: As described in Apache 2.4 Access Control:

The Allow, Deny, and Order directives, provided by mod_access_compat,
  are deprecated and will go away in a future version. You should avoid
  using them, and avoid outdated tutorials recommending their use.

Use Require, instead:
Require not ip 2a01:598::/28

This should work in the .htaccess context, unless limited by an AllowOverride in the server configuration.
Comment: Are you sure the connection is made over IPv6?
Comment: I just tried it to block my own ipv6 adress. But even if i use the described code i can access my website.

If I block my own ipv4 range it is working just fine. BUt not with my Ipv6?
Comment: Yes if i go to whatismyip.com my ipv6 and my ipv4 adress is shown. And if block my exact ipv6 adress i cant connect. But if i only block like this 2a01:598::/28 im still able to visit my site?
Comment: Is there a way to block all ipv6 connections to my website and only allow ipv4 adresses?
Comment: The `2a01:598::/28` refers to range from
`2a01:590:0:0:0:0:0:0` to `2a01:59f:ffff:ffff:ffff:ffff:ffff:ffff`. Are you positive your IP is on that range?
Comment: Im not sure what you mean. I have  list of ips that visited my site. All of the ips started with 2a01:598:xxxx? Maybe I can send  you the list?
Comment: That's not necessary. Just trying to rule some obvious reasons out.


Problemas visualização dos Dados Laravel 5.1

Question: Sou iniciante no Laravel e estou tentando trazer dados de um BD com multiplos schemas do Postgresql com Laravel 5.1 e está me trazendo um erro
Qual configuração deve fazer para o model acessar corretamente a tabela daquele schema?
Diretamente pelo postgres escreveria a consulta dessa forma:
 SELECT * FROM cadastro.escolaridade
 SELECT * FROM schema.tabela

ErrorException in TesteController.php line 13: Use of undefined
  constant cadastro - assumed 'cadastro'

Database.php
'pgsql' => [
'driver'   => 'pgsql',
'host'     => env('DB_HOST', '127.0.0.1'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset'  => 'utf8',
'prefix'   => '',
'schema'   => 'public',
],

Model
<?php

namespace App\Models\Programas;

use Illuminate\Database\Eloquent\Model;

class Cadastro extends Model
{

}

Controller
<?php
 namespace App\Http\Controllers;
 use App\Models\Programas\Cadastro;

 class TesteController extends Controller
 {

public function getIndex()
{
    $escolaridade = cadastro.escolaridade::all();

    return view('programas.escrituras.index', compact('escolaridade'));

}

View
@forelse($escolaridade as $descricao)

Grau de Escolaridade:{{$descricao->descricao}}

@empty

Nenhum Grau Cadastrado!

    @endforelse

Comment: `Cadastro::all()` retorna algo? `cadastro.escolaridade::all();` não se refere a classe nem a um schema. Talvez `Cadastro` tenha uma propriedade chamada `$escolaridade`.
Comment: Tirei o negativo que eu tinha dado. Mas acho que a pergunta deve ser reelaborada.
Comment: Talvez [essa resposta](http://pt.stackoverflow.com/q/82557/91) possa ajudar.
Comment: Vou dar minha opnião marcando a pergunta dele. (Esse erro não pode ser reproduzido, tal tal e tal)
Comment: O erro não faz parte desses arquivos, vc está recebendo a mensagem, mas o problema vem de outro lugar... é melhor você descobrir o problema, use xdebug ou PHPUnit para testar suas classes. Ou algo mais simples, como `die();` `var_dump()` e `print_r()`.
Comment: @IvanFerrer a sintaxe `cadastro.escolaridade::all();` que está no `TesteController` é inválida, me parece que ele quer saber como fazer model consultar um banco em um ou multiplos schemas.
Comment: Pela lógica do erro, ele não está encontrando a constante, dê uma [olhada aqui](http://www.codedungeon.org/2013/09/10/getting-started-with-laravel-and-postgresql/).
Comment: Já verificou no [site do laravel](https://laravel.com/docs/5.2/database#running-queries) ?
Comment: No PHP não existe essa sintaxe com ponto no PHP, pelo menos não que eu saiba: `cadastro.escolaridade::all()` o que é existe é isso: `{string1.string2}` ou isso `$cadastro->escolaridade::all()`.
Comment: Talvez o que ele queira fazer seja alguma coisa assim:
  `$escolaridade = Cadastro->escolaridade::all();`
Answer: Segundo essa resposta, você deve definir o schema no atributo $table do seu model.
class Cadastro extends Model
{
    protected $table = 'cadastro.escolaridade';
}

Depois pode chamar normalmente,
$escolaridade = Cadastro::all();

Comment: Assim também dá. Do jeito que eu fiz você pode usar tanto dois bancos, como também bancos de outras conexões, como também banco de outras SQL. O Laravel 4 já é top, o 5 então nem se fale. +1. Essa daí eu não sabia :)
Comment: A Forma que o @rray declarou deu certo!
Answer: Esse trecho do código está errado
$escolaridade = cadastro.escolaridade::all();

Por acaso você vem de outra linguagem e está tentando acessar membros de classes ou objetos?
O seu código indica que você está tentando concatenar uma constante cadastro com o resultado trazido por escolaridade::all() (que por usa vez é convertido para Json, já que está concatenando). Como a constante não existe, o erro é gerado.
É assim que o PHP está entendendo seu código. Então, se não é o resultado desejado, vocÊ tem que alterá-lo.
Múltiplos Schemas
No Laravel você poderia utilizar mais de uma conexão para resolver esse problema.
Por exemplo, você pode definir sua configuração assim:
return [

    'default' => 'pgsql',

    'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', '127.0.0.1'),
        'database' => 'schema_1',
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ],

    'pgsql_2' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', '127.0.0.1'),
        'database' => 'schema_2',
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ]
];

E no model que quer usar outro schema (diferente do que está em default), você pode defini-lo no model.
Exemplo com schema padrão definido na configuração:
namespace App\Model\Schema1;

class Pessoa {}

Exmeplo com schema padrão definido no model
namespace App\Model\Schema2;

class TabelaQualquer
{
       protected $connection = 'pgsql_2';
}

Assim, você está informando ao model que estará utilizando outra configuração de conexão com o banco de dados para ele. No caso, você utiliza os mesmos dados de conexão, alterando apenas o banco.
Comment: A pergunta é valida, nos postgres uma banco de dados pode ter varias 'divisões' logicas, que são chamadas de schemas, no sql para fazer uma consulta fica, `select * from schema.tabela` ou `select * from cadastro.escolaridade`. Como laravel resolve esse problema(acesso a multiplos schemas?
Comment: @rray, mas tem um erro de sintaxe sim. Isso é que causa o erro. E o laravel aceita pg sim
Comment: Não precisa nenhuma configuração extra?o schema onde ficam as tabelas geralmente é o `public` mas algumas pessoas criam outros, outro dia vi essa mesma(ou quase) pergunta, achei curioso.
Comment: @rray, atualizado. Vi o que ele precisava. No laravel você pode usar quantas conexões diferentes quiser (5 por exemplo). Basta configurar cada uma e definir quais models vão fazer isso. No laravel 5, como foi implementado os  namespaces, achei justo fazer como fiz no meu exemplo, colocando um namespace pra cada schema.
Comment: Se entendeu o ponto da questão blz :), um schema não é uma conexão :P mas se é assim que o framework resolve o problema, bola pra frente. Me pergunto como fica o relacionamento entre uma tabela de um schema com outra de outra através do orm :P. +1 pela resposta e pelo comentário de cima.
Comment: @rray se eu falei alguma besteira, por favor, corriga minha resposta :D rsrsrsrsrs
Comment: @rray dá pra fazer uma foreign key de um banco para o outro (claro, na mesma conexão). Não sei se é gambiarra :#
Comment: @WallaceMaxters No meu BD Postgres tenho 17 Schemas não sei se essa forma criando varias conexões seria muito viável
Comment: Então não faça assim. Apenas guarde o conhecimento ;). É melhor fazer igual  o @rray


Customizing a graph with gray regions

Question: I'd like to do a graph similar to this one with the gray regions to point the recessions in my graph. I have R and Excel and Stata, I'm simply trying to make it easy to distinguish the recessions by putting them in gray color, just like the picture here:

You don't really have to tell me every step for it, just lead  me to where I can learn.
Comment: Are you asking for code for some software? What software are you using? If that is representative of the data you want to show, you should be able to get such graphs, w/ recessions shaded automatically, from [FRED](http://research.stlouisfed.org/fred2/). I suspect this question is almost certainly off-topic.
Comment: You're going to have to give more details. It's easy enough to do such displays in a variety of software... but if for some reason you can't use that software, the solution's not much help to you -- [here's an example](http://i.imgur.com/85xf9Ml.png) I just generated. But if you don't use R, what good is that?
Comment: I have R, ms excel and stata. I'm simply trying to plot the growth rate of my country, but I'd like to put the recessions in gray highlight. So people who read my work can easily distinguish them. That's pretty much what I need Glen_b.
Comment: This is a strictly coding question, not a statistics question. Please add a [reproducible example](http://stackoverflow.com/q/5963269/1217536) & we can migrate it for you.
Answer: You can do this in Stata like this using US recessions:
<code>ssc install nbercycles
ssc install freduse
freduse GDP, clear
gen ym = mofd(daten)
tsset ym, monthly
nbercycles GDP if tin(1947m1,2014m7), file(graph.do) replace
</code>
The file graph.do will include detailed code about how to build such a graph by hand if you want to use a different country.
The graph will look like this:

Customizing a graph with gray regions


7 allow cross-origin framing CORS module

Question: I am embedding content in my article that are from the same domain. when I am opening my url with HTTP the embedded HTTPS content won't open and when I am opening my url with HTTPS the embedded HTTP content won't open. Same thing happen when i try to open content with localhost. I am getting this error in Firefox and Chrome:
<code>Load denied by X-Frame-Options: http://mywebsite.com/embed/clips/sandy does not permit cross-origin framing.
</code>
OR
<code> Refused to display 'https://mywebsite.com/embed/clips/sandy' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
</code>
I installed the CORS module but it does not seems to help. In Domains (/admin/config/services/cors) I added:
<code>*|<mirror>,https://mywebsite.com
*|<mirror>,https://mediamatters.org
</code>
without success. Any insight is apreciated.
Answer: https and http -- even if the host is the same -- are considered different domains.
The way you can deal with that when your site can be viewed with both https and http, is instead of referencing files
https:// or http://
just use //
It will defer to the protocol that you are on.
The only time this would cause problems would be if a certain resource only got served up under secure or insecure. But this does not sound like it would be a problem for you in this instance.
EDIT:
In order to change existing content, which it sounds like doing by hand is impossible. You could try a module like https://www.drupal.org/project/scanner -- being careful to backup, test, and make sure you are only looking at the correct URLs (you don't want to change the urls where changing the protocol would be).
One other possible way to make it work is to just make your path references root relative -- strip out http://yourdomain.com - and just leave /your/path/to/file
The other thing to do is just cherry pick the content that people are looking at most.
Comment: very helpful, thanks. but how will I deal with existing content (over 10K of articles with embedded content).


Telnet does not give a response

Question: Some wireless access points are acting a little weird, so I want to reboot them every couple of hours. Luckily there exists a security flaw which lets me login as root through telnet when using port 1111 (without username and password).
Now I want to use that to let my QNAP NAS execute the reboot command through telnet every now and then. The problem is however that that telnet version doesn't give any response if I connect to the AP. The telnet I use on OSX works just fine but the one on the NAS not.
BusyBox v1.01 (2012.06.14-18:35+0000) multi-call binary
Usage: telnet [-a] [-l USER] HOST [PORT]

When I execute telnet <HOST> 1111 nothing happens. I can send the escape character ^] which gives me the following options:
Console escape. Commands are:

 l  go to line mode
 c  go to character mode
 z  suspend telnet
 e  exit telnet

The only way to get some commands executed is by suspending telnet with z followed by some random command which isn't recognized. Then the prompt shows this:
# telnet 192.168.1.5 1111
^]

Console escape. Commands are:

 l  go to line mode
 c  go to character mode
 z  suspend telnet
 e  exit telnet
z
continuing...

asdf
Illegal command.
00>

After that I am able to communicate with the AP, but when I exit the telnet session and try the same again, the AP refuses to connect at all and it must be manually rebooted (looks like the telnet session isn't shut down properly on the AP).
So the question is what commands should I execute in order to communicate with the AP using the Busybox telnet version of the QNAP?
(No, can't use ssh unfortunately)
Comment: Are you seriously asking why you're having trouble getting a particular class A exploit (unauthorized remote access, and as root, no less) to work?  What happens when you try to telnet in on port 23?  Regardless of the answer, flaky equipment with an unaddressed remote-access-as-root-exploit has only three uses I know of.  As anonymous gifts to enemies, fuel for dumpster fires or as a source of scrap metal.
Comment: @HopelessN00b I thought so that was coming ;) The problem is with the version of telnet on the QNAP, not with the exploit which has actually nothing to do with it, since it works with other telnet clients. It is just an open port. The connection is of course only accessible within our local network, which has a firewall to the outside. And I can restrict connection to that port to certain ip addresses, so don't worry about that. Port 23 is not open, so no connection is possible.
Answer: It has to do with some line feeds and carriage returns being mixed up.
I installed netcat on the QNAP through IPKG to get some better feedback:
ipkg install netcat

And used that to connect to the access point and echo the commands with \r\n
(sleep 1; echo -e "system id\r\n";) | nc -q 5 192.168.1.6 1111

Telnet does not give a response


Statistical model for quantities that add up to 1

Question: I want to create a model for quantities $z$ that live in a probability simplex, that is, they are nonnegative and always add up to 1:
$$ S = \left\{z \in \mathbb{R}^{k} : z_1 + \dots + z_{k} = 1, z_i \ge 0 \text{ for } i = 1, \dots, k \right\},$$  where $k$ is relatively small, let's say $k \leq 5$.
Additionally, I know these values come from a black box process where I only know some details about it, e.g. an input array of the form: $(x_1,  \ldots, x_k)$ with additional features $(\theta_1,  \ldots, \theta_k)$ where again, $(x_1,  \ldots, x_k)$ are nonnegative and add up to one (notice it's also of dimension $k$).
For modelling purposes let's assume we got samples of all these arrays ($x$, $z$ and $\theta$) as time series (always all values measured at the same time), and additionally we know that:

There's a dependence of the $z$ array from the $x$'s and $\theta$'s, but with a lag, that is, $z_t$ depends on the previous time values of $x$ and $\theta$. This lag is not constant over time but it can't grow indefinitely either, let's say it's a maximum of $N$ previous timestamps where $N$ < 10

The $z$ and $x$ quantities are relative rates, not really probabilities

The output $z$ is somehow a mixture of the input $x$ of previous timestamps, e.g. $z_i^T$ will depend strongly on the respective $x_i^{t}$ for recent values $T-N \leq t \leq T-1$, and their associated parameters inside $\theta_i^{t}$ (that correspond to the $i$t-h quantity). But it won't be necessarily inside their convex combination, i.e. it could happen that the $z_i^{T}$ lies outside the minimum and maximum values of the recent $x_i^{t}$ values

I think that taking ideas from the following fields can be useful:

Graphical models - with $k$ (or $k-1$) output nodes
Neural networks - use a multilayer perceptron using an idea similar to the softmax activation function
Generalized additive models (create something similar to the multinomial logit model but with a response variable that isn't a classification response but probabilities)
Multivariate time series - but I'm not familiar with ways to impose the bounds that the series are between 0 and 1 and also the add-up-to-1 condition into the modelling framework

And I wonder if there's already some literature or known model for this kind of processes (nonnegative continuous variables that add up to a fixed quantity), but my search hasn't brought results yet. Do you have any pointers to relevant modelling approaches?
Comment: Have you come across [compositional data analysis](https://en.wikipedia.org/wiki/Compositional_data)?
Comment: Dirichlet Regression?
Comment: As @awhug, your response data is on a simplex.
Comment: Hi @awhug thanks for the suggestion, yes, had found that same wikipedia article earlier and it looked promising. I see there are several R and Python libraries, will dig further into that field
Answer: As others have written, this is compositional data analysis. We have a compositional-data tag, so searching for threads carrying, e.g., this tag and the "time-series" one may be helpful.
One paper on forecasting compositional time series is Snyder et al. (2017, IJF). Essentially, the idea is to transform the original compositional time series, then forecast the transformed data, and finally back-transform the forecasts in a way that respects the compositional nature. Thus, this approach should also work with other forecasting methods, like neural networks, or anything that uses lags or causal effects.
Comment: Thanks Stephan. That paper's quite interesting


Getting values in my Java class from velocity (Jira plugin webwork module )

Question: I am creating a Jira plugin which provides a version tab panel. In the velocity of this version tab panel i am providing a select list . the code of select list is as below
                    <form name="input" action="AddParent" method="post">
        <select name="parentVersion">
        <option value="-1">--select Parent--</option>
        #foreach($version in $versions )
            <option value="$version" selected="true">$version</option>
        <input type="submit" value="Add Parent"/>
        </form>

Now in my plugin i have included a webwork module to handle this action . when i click the "Add Parent" button nothing is happening. I need the value which i have selected in my java action class . I am surely missing something . can someone please help me with this ?
Thanks in advance .
Answer: As an alternative, you can declare a local variable named same as your select list, create getter and setter and the variable will get the selected value.
Also, yo can specify the form action as action="YourClass!yourMethod.jspa"
private String parentVersion;

public String getParentVersion() {
    return parentVersion;
}
public void setParentVersion(String parentVersion) {
    this.parentVersion = parentVersion;
}

Answer: I'm not sure what's missing in your code, but the WebWork Sample Plugin has more information about this.
Comment: Hi Matt ,i referred Webwork sample and was able to get the values by using the request.getParameter("parentVersion") method i made these changes in the velocity template  . The tutorials helped alot . Thanx :)
Comment: @mdoar: Could you link to that WebWork Sample Plugin?


em R, dec="," não funciona em read.csv2

Question: Boa tarde...
Estou tentando importar csv onde os decimais estão separados por ponto... ou seja algo assim 2.5
Eu quero que na hora de importar ele apareça com virgula, algo tipo assim, 2,5
 uo_14<- read.csv2("csv\\uo_2014.csv", as.is = FALSE , header = TRUE,
                     sep = ",", dec=",", encoding='UTF-8' )

 uo_14
    nome   valor1  valor 2
    nome1   3.5      3.6
    nome2   5.4      1.7

Não sei qual é problema!
Comment: Acho que vc nao pode usar o mesmo separador de colunas e de casas decimais
Answer: Se o objetivo for somente mudar a forma como o output do R apresenta o separador decimal, você pode usar:
options(OutDec = ",")

Veja a descrição da opção Outdec na help page da função options (?options) para mais informações.
Além disso, se o seu arquivo csv usa ponto como separador decimal, então você deveria usar dec = "." na função read.csv2:
uo_14 <- read.csv2("csv\\uo_2014.csv", as.is = FALSE, header = TRUE,
                 sep = ",", dec = ".", encoding='UTF-8')

em R, dec="," não funciona em read.csv2


Why are blank lines being added in CSV file when running python script multiple times?

Question: I am currently trying to build a python 3 script that will take a csv file, read it, and then copy the rows and add them to the end of a file. This script is going to run daily as the data dump from the application will run daily.
I have the code "working" to get the file and copy it and it does work on each run, but it is adding several blank lines to the end of the file each time. so for instance the first time i run it, it is on lines 1-101, but the next time it might be lines 9000-9101.
<code>newest = r'C:\Users\me\downloads\Test2.csv'
with open(r'C:\Users\me\downloads\out.csv', 'a', newline='') as repository:
    fileWriter = csv.writer(repository, delimiter=',')
    with open(newest, 'r', newline='') as newData:
        fileReader = csv.reader(newData, delimiter=',')
        next(fileReader)
        for row in fileReader:
            fileWriter.writerow(row)

print("Copy Complete")
</code>
I would like for it to not have the blank lines between it. as it may cause issues with the app I am trying to use to view the data.
Comment: It sounds like you have empty lines at the end of `Test2.csv` file
Comment: Are the number of blank lines that get written to the file random?
Answer: Sounds like the csv that you're using as the input contains blank lines. I'd add a check in your for row loop to make sure that you're only adding lines with data in them to your output file. This thread may be helpful to checking on if the lines in your input file are blank or not.
Comment: you know... sometimes you do something to try to shrink your data set so that it is easier to test, and you end up causing more issues than you would like lol.

thanks for this.. i tried with another CSV and it worked fine.


Python pandas dataframes - trying to access/print certain fields from read_csv causes a type error - how to fix?

Question: Whenever I try to run a simple print operation on a variable within my data frame, it displays the following errors:

TypeError: 'str' object cannot be interpreted as an integer

During handling of the above exception, another exception occurred:

and then:

KeyError: 'Value'

I know this field exists in my dataframe because I have printed the results of it
This is my code:
import pandas as pd

iColumns = 7

szTransactionFile = 'Exports/example03.csv'

df = pd.read_csv(szTransactionFile, index_col=None, skiprows=1, usecols=range(iColumns), escapechar='\'', lineterminator='\n')
df.drop(index=0, inplace=True)
df.rename(columns={list(df)[6]: 'Account Number'}, inplace=True)

for index, row in df.iterrows():
     print("Value: " + row['Value'])

These are the contents of the csv:

Date, Type, Description, Value, Balance, Account Name, Account Number
,,,,,,
05/08/2020,POS,"1234 03AUG20 , PAY *NAME, 2135655",-20,28.4,bobsley bobbington,1234
04/08/2020,POS,"1234 03AUG20 , WWW.AMAZON.COM, 123 123 132 42 GG",-15.99,48.4,bobsley bobbington,1234
03/08/2020,POS,"1234 29JUL20 C , STORE, CHINA GG",-3.3,64.39,bobsley bobbington,1234
03/08/2020,POS,"1234 24JUL20 C , IZ *KING , NORWAY GG",-5.3,67.69,bobsley bobbington,1234
30/07/2020,D/D,'PAYPAL PAYMENT,-1.99,72.99,bobsley bobbington,1234

Please could someone help me with this one? I am confused because I can access row['Date'] and row['Account Number] in the iterator, but none of the other fields.
Answer: You have leading space in column names
data = '''Date, Type, Description, Value, Balance, Account Name, Account Number,,
05/08/2020,POS,"1234 03AUG20 , PAY *NAME, 2135655",-20,28.4,bobsley bobbington,1234
04/08/2020,POS,"1234 03AUG20 , WWW.AMAZON.COM, 123 123 132 42 GG",-15.99,48.4,bobsley bobbington,1234
03/08/2020,POS,"1234 29JUL20 C , STORE, CHINA GG",-3.3,64.39,bobsley bobbington,1234
03/08/2020,POS,"1234 24JUL20 C , IZ *KING , NORWAY GG",-5.3,67.69,bobsley bobbington,1234
30/07/2020,D/D,'PAYPAL PAYMENT,-1.99,72.99,bobsley bobbington,1234'''
a = [[i for i in l.split(",")] for l in data.split("\n")]
df = pd.DataFrame(a[1:], columns=a[0])
df.loc[:, ['Date', ' Type', ' Description', ' Value', ' Balance', ' Account Name',
       ' Account Number', '', '']]
df.columns = [c.strip() for c in df.columns]
df.loc[:, ['Date', 'Type', 'Description', 'Value', 'Balance', 'Account Name',
       'Account Number', '', '']]

Comment: Thank you very much! Can't believe I missed it. Do you think it could be possible to solve this using regex in the seperator/delimiter parameter in read_csv using regex? Or would it be too complicated given sometimes there is a leading space and sometimes there isn't?
Comment: You could make your column rename smarter of use what I did with list comprehension
Answer: Python cannot convert int value to str automatically.
You can do :
   for index, row in df.iterrows():
     print("Value: " + str(row['Value']))


Compact set on $\mathbb{R}$ with this topology generated from the basis set $B=\{(–a,a)\ s.t.\ a \in \mathbb{R}\}$

Question:
Let A be a subset of a topological space $X$, and let $O$ be a collection of subsets of $X$.
  (i) The collection $O$ is said to cover $A$ or to be a cover of $A$ if $A$ is contained in the union of the sets in $O$.
  (ii) If $O$ covers $A$, and each set in $O$ is open, then we call $O$an open cover of $A$.
  (iii) If $O$ covers $A$, and $O'$ is a subcollection of $O$ that also covers A, then $O'$ is called a subcover of $O$.(Topology: Pure and Applied, Adams 206)

In the example/question I am asking, the topological is being generated by $B=\{(–a,a)\  s.t.\  a \in \mathbb{R}\}$. Thus, $(-1,1)$ would have a finite subcover as would a closed interval, say $[-3,3]$.
But what about a half open interval like $(1,4]$ or $[–3,1)$? Would they be compact and have a finite subcover?
Comment: For $(-1,4]$: 4 needs to be covered, and the set that does this covers the whole set. Similarly for $-3$ in $[-3,1)$.
Comment: So the open interval $(-1,1)$ has a cover just no finite subcover. Like the other two you commented on, $(–2,1]$ needs -2 to be covered, and these 3 all have finite subcovers?
Comment: $(-1,1)$ has a cover without a finite subcover, so is not compact
Comment: @HennoBrandsma, thank you!
Answer: Supppose a set $A$ has a maximum $M$ and a minumum $m$, and $O_i , i \in I$ is a cover for $A$. Then $m \in O_i = (-a_i,a_i)$ for some $a_i \in \mathbb{R}$,as it is in $A$ so needs to be covered. SO $m < a_i$. Similary $M \in (-a_j,a_j)$ for some $a_j$. One of these is the bigger set, say $a_j < a_i$, then $ A \subseteq(-a_i, a_i)$, because $x \in A$ implies  $x \le M < a_i$, and $x \ge m > -a_j > -a_i$.
So all such $A$ with max and min are compact in this topology, but this kind of argument also works for more sets.
If however $A$ is unbounded below and unbounded above, then $(-n,n), n \in \mathbb{N}$ is a cover for $A$ that has no finite subcover (note that a finite subcover can be reduced to one element). So a compact $A$ needs to be bounded, and so $M=\sup(A)$ and $m =\inf(A)$ exist both. If the larger one of these (in absolute value)is not in $A$, we can also find a cover without a finite subcover. Mull this over a bit...
Comment: "..so $ m=\min A$ exist(s)...". That is incorrect The interval $(0,1]$ is compact in this topology but it has no $\min.$ If $C$ is an open cover of $(0,1]$ then there exists $s\in C$ with $1 \in  s,$ so there exists $(-a,a)\in B$ with $1\in (-a,a)\subset s \in C.$ This implies $a>1$ so $(-a,a)\supset (0,1$] so the one-element family $\{s\}$ covers $(0,1]$.
Comment: @user254665 I meant the infimum of course, and then you need to consider which of these two is the larger one in absolute value, and that one needs to be a min or max, as I said.
Answer: Necessary and sufficient conditions for non-empty $A$ to be compact in this topology: $$(1).\;A \text { is bounded, and}$$  $$(2).\; |\inf A|\geq\sup A\implies \inf A=\min A ,\quad \text   {and}$$  $$(3).\;  |\inf A|\leq \sup A \implies \sup A=\max A.$$
For example: $A=[-1,2)$ then $\{(-2+2^{-n}, 2-2^{-n}): n\in \mathbb N\}$ is an open cover of $A$ with no finite sub-cover so $A$ is not compact.
Another example: $A=(-1,2]$ or $A=(0,2] . $ If $C$ is an open cover of $A,$ there exist $s\in C$ with $2\in s$,and there exists $(-b,b)\in B$ with $2\in (-b,b)\subset s\in C.$ This requires $b>2$ so the one-member sub-family $\{s\}$ covers $A$, because $s\supset (-b,b)\supset [-2,2]\supset A.$ So $A$ is compact.
Comment: A curious feature of this topology is that if $A$ is non-empty and compact, and $C$ is an open cover of $A,$  then $A\subset  s$ for some $s\in C.$


Unable to like media in instagram from any access token

Question: Since 3 or 4 days ago i'm not able to like any photos from any token, I think they blocked me to like. I still can follow/unfollow users via my application. I also can like photos via instagram iOS app.
This is the error i have:
<code>"meta": {
    "error_type":"APINotAllowedError",
    "code": 400,
    "error_message":"you cannot like this media"}
</code>
Do you know if they will unlock me or it's permanently?
Comment: I'm voting to close this question as off-topic because it is a vendor support question related to a specific account that can only be answered by Instagram support staff who can access that account's information.
Comment: Instagram suggests that we use StackOverflow for questions about API and other stuff. https://instagram.com/developer/support/
Answer: See API Terms of Use:
<code>Do not abuse the API. Too many requests too quickly will get your access turned off
</code>
Wait for some days and see if they will free you... If you are still having trouble, i would suggest to create a new client and see what happens.
Answer: Instagram changed the terms for using POST and DELETE requests. You can read more about it here http://developers.instagram.com/post/116410697261/publishing-guidelines-and-signed-requests
If you want to request access to those endpoints you can do it here, if your app is qualified.
https://www.facebook.com/help/instagram/contact/185819881608116#=


Loading jsTree Children from JSON

Question: I'm fairly new to JavaScript coding, specifically on using jQuery. I'm trying to use jsTree trying to populate it through JSON. Now I believe my question had been answered on related questions but I can't seem to find a specific answer to what I'm doing. I have referred to the jsTree documentation as well, but I still can't figure it out.
below is the code I'm trying out
<code>buildTree : function(name, url, nodeRef) {

     $("#"+name).jstree({
      "json_data" : {
    "ajax" : {
     "url" : url + nodeRef,
     "data" : function(n) {
      return { id : n.attr ? n.attr("id") : 0 };
     }
    }
   },

   "plugins" : [ "themes", "json_data" ]
  });
    }
</code>
this is basically a copy of the code in the jsTree documentation for JSON. What's happening here is I am able to populate the root folder of the tree of it's contents. Below is the response of the JSON I'm getting.
<code>[
 {
 "attr":{"id":"a3e6a1f0-ec50-4215-a6df-2065eb09115e","rel":"file"},
 "data":"File 1","state":""
 },
 {
 "attr":{"id":"b38e4a72-875b-4d69-95d3-5437f7e65575","rel":"folder"},
 "data":"Folder 1","state":"closed"
 }
]
</code>
But when I click the the node of the folder, It is being populated by the same JSON request, having the same values.
I know the culprit is
<code>"url" : url + nodeRef,
</code>
but I am lost on how I'm going to pass the ID I'm getting from the response, replacing the initial nodeRef value. I have tried using the callbacks but nothing is happening.
Any help is very much appreciated.
Answer: The following part in your code already takes care of appending an "id" querystring parameter to the ajax url. The function returns an object with key/value pairs that will be used for querystring parameters for the url to be requested.
<code>"data" : function(n) {       return { id : n.attr ? n.attr("id") : 0 };      }
</code>
I am not sure what the purpose of the nodeRef variable is in your code. Is it to find the root node? If so, could you not use a different querystring parameter for that?
Use fiddler to confirm the urls constructed by jsTree are what you expect it to be. Perhaps it's currently creating a url with two id querystring parameters and it always uses the one provided by your nodeRef variable?

Loading jsTree Children from JSON