text:
Q: Maximum number of objects in an array for a class I have this class:
class tree
{
public:
    int row;
    int column;
};

I want to create a total of around 1024 objects for the class tree but if I increase the value to above 90 in tree a[90] it gives a segmentation fault:
tree a[90]; //Ok
tree a[1024]; //Segmentation fault

Is there a max limit on the number of objects we can create or is there any other work around to create 1024 objects in the form of an array?

A:
Is there a max limit on the no. of objects we can create?

Well, yes. It's called the stack limit. It depends on how big your stack is. Your stack size here is:
stack_size = sizeof(int) * 2 * 90

If on your platform sizeof(int) is 4 (which it typically is), you have 4 * 2 * 90 = 720 bytes of stack, which seems very small.
Either way, the correct way of allocating large amounts of objects is on the heap, which typically has more space then the stack:
//std::vector allocates its elements on the heap
std::vector<tree> a(1024);

If you can't use std::vector for some reason, you can still use the old school style dynamic array (not recommended though):
tree* a = new tree[1024];


text:
Q: Retrieve images and text from firebase I am about create an android app. The idea of the app is very easy but I faced problems in implementation because I am new. The app name will be Food Description.
It will contain a button, when you press the button a list of images will show about each food. For example chicken, meet, etc. These imaged should be store in firebase manually. When I press any image it should give me a detailed description about the food. This description is also should save in firebase manually.
The questions are:

*

*How can I create a database contain image and description?

*How can I retrieve the stored images list with their description?

A: Steps to follow:

*

*Create a project in Firebase with the same package name as of android project you are building.

*Select the project then follow the below steps for storing Image:

*

*Go to Storage.

*Add your images in store by Clicking Upload Files.

*When you complete uploading images then you will get Download URL of each image. This is what you need to get Image.

*Go to database:

*

*Create a database, lets say food.

*Put your Food information as you want in DB, you need to give a unique value of each food.

*Then for each food, put the key-value pair as, {name, image, description}. Here name will be food name, description is food description, for Images, just put the download URL from storage.

Now in Android Project.
Make a POJO model Class for Food like below
Class Food {
   public String name;
   public String Image;
   public String description;

   public String getName() {
       return name;
   }
   public String getImage() {
       return image;
   }
   public String getDescription() {
       return description;
   }
}

Get list of Foods using following code.
Firebase db = FirebaseDatabase.getInstance().getReference("foods");

mPostReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // Get Post object and use the values to update the UI
        Food food = dataSnapshot.getValue(Food.class);
        ArrayList<Food> foodsList = new ArrayList<>();

       foodsList.add(food);
        // ...
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        // ...
    }
});

Your can set Image using Glide or picaso
like below
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);

  Glide.with(this).load(foodsList.get(index).getImage()).into(imageView);

Please follow steps from here to learn how to embed data from firebase to RecyclerView
https://www.youtube.com/watch?v=vpObpZ5MYSE

A: export your firebase datastructure from database menu exported file will comes in json. remember copy only food tree structure of that json and paste it to json to pojo convertor rest thing is same as mentioned by bhuvensh.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magento 2: Change error message on checkout "An error occurred on the server. Please try again" Preconditions
Magento 2.1.4
PHP 7
Production mode
Steps to reproduce
Wanted to change the generic "An error occurred on the server. Please try to place the order again" to "We could not place this order. Please call us to complete."
Changed the text in vendor/magento/module-checkout/Model/PaymentInformationManagement.php
vendor/magento/module-checkout/Model/GuestPaymentInformationManagement.php
Cleared the static files, re-deployed static files, cleaned and flushed the cache. Also re-compiled for good measure.
Expected result
When an error occurs in checkout the error message should read "We could not place this order. Please call us to complete."
Actual result
Same error message occurs everytime "An error occurred on the server. Please try to place the order again."
Has anyone successfully changed the error message at checkout, to their own custom message?


text:
Q: Javascript add table in html page I have an html page which includes a table. The following Javascript code a new table to my html page under the table that already exists each time I press the add new button. How can I modify this code so that the user will be able to add only 10 tables?
  <SCRIPT language="javascript">
    function addRow(tableID) {

        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var colCount = table.rows[0].cells.length;

        for(var i=0; i<colCount; i++) {

            var newcell = row.insertCell(i);

            newcell.innerHTML = table.rows[0].cells[i].innerHTML;
            //alert(newcell.childNodes);
            switch(newcell.childNodes[0].type) {
                case "text":
                        newcell.childNodes[0].value = "";
                        break;
                case "select-one":
                        newcell.childNodes[0].selectedIndex = 0;
                        break;
            }
        }

    }

</SCRIPT>


text:
Q: Sum of recipocals of number of divisors I wrote a math problem that went like this:
Alice writes out all integers from 1 to $n$ on a blackboard. Each round, if there are still numbers on the board, Alice chooses a number on the board at random and erases that number and all multiples of that number. What is the expected number of rounds until there are no numbers left on the blackboard.
I had a somewhat closed form solution of:
We do a classical double counting argument, we calculate the probability that any integer $k$ is chosen. The probability that $k$ is chosen is $\frac{1}{d(k)}$ where $d(k)$ is the number of divisors of $k$.
This is true because it is equally likely that $k$ or any of it's divisors is chosen. By linearity of expectation, we can take the sum of the expected values that each individual integer is chosen.
This evaluates to $\sum_{k=1}^{n} \frac{1}{d(k)}$
Now, I'm curious if there's a way to further condense/bound this final sum. We can use HM-AM to bound it since the sum of divisors from $1$ to $n$ is well known, however I ran a program and the ratio between the HM and AM is ~$1.9$ for $n=100,000$.
Any help is appreciated.
Thanks !

A: This response can in no way be construed as an answer.  It is posted
as such, simply for legibility.

The probability that k is chosen is $\frac{1}{d(k)}$ where $d(k)$ is the
number of divisors of k.

If by chosen, you mean erased on the first
round, then I disagree.  On the first round, the more divisors that
$k$ has, the greater the probability that $k$ is erased.
In my opinion,
asking whether a specific number $k$ will be erased on a specific round $r$,
where $r > 1$ is a very complicated question.  Certainly, this would require
that the number $k$ not be erased on any of the prior rounds.  And certainly,
the chance of $k$ being erased on one of the prior rounds would somehow
increase as $d(k)$ increases.  By "somehow", I intend that expressing the
probability as a formula involving $d(k)$ may not be easy.
Further, under the assumption that $k$ has not been erased prior to round $r$,
computing the probability that $k$ will be erased on round $r$ could be a nightmare.  On the $r$-th round, you have to ask how many other numbers there are expected to be that are not divisors of $k$.
The actual question that you are asking is

how many rounds are expected to be needed until all numbers are erased.

Suppose that you start with a set like $\{1, 2, \cdots, 100\}$ and you rank each number $k$ by its value $d(k)$.  The more top-heavy the
set is, the greater the expected number of numbers will be erased on a single round.
However, if you are asserting that the set $\{1,2, \cdots, 100\}$ is expected
to require $\left[\sum_{k=1}^{100} ~\frac{1}{d(k)}\right]~$ rounds, I would like to see a proof of this.

Start of Edit
It just occurred to me.  Perhaps what the OP was referring to by

The probability that k is chosen is $\frac{1}{d(k)}$ where $d(k)$ is the
number of divisors of k.

is that whenever a number $k$ is erased, the chance that the erasure occurred because the number $k$ itself was chosen, rather than one of its smaller divisors is
$$\frac{1}{d(k)}.$$
This is certainly true. Further, perhaps I have a blind spot here.  However, I am having trouble seeing how you can use this fact to directly compute the expected number of rounds that will be required to erase all numbers.
It also just occurred to me is that the question of how many rounds will be required is equivalent to asking what is the expected number of rounds that it will take before the number 1 is chosen.  The erasure completes when and only when the number 1 is chosen.
The problem is that not only is this sampling without replacement, but the sampling erases a variable amount of numbers on each round.
That is, if the number $k$ is chosen on a round, then
$$\left\lfloor \frac{n}{k} \right\rfloor$$
is the maximum amount of numbers that could be erased on the round.  The reason that it is the maximum is that some of the multiples of $k$ might already have been erased.
Even with this new insight, I still regard this problem as extraordinarily complicated.
End of Edit

Assuming that you agree that there is no obvious formula for the expected number of rounds that will be required, one approach to attacking this question is to start by doing simulations on a computer.  Let $n$ vary from
$10$ through $100$.  For each value of $n$, assume that you start with the set
$\{1,2,\cdots, n\}.$  For each value of $n$, run the simulation 1000 times.  This
should be safe, since a single simulation can not take more than $n$ rounds.  Naturally, you would need some sort of random number generator, to randomly pick 1 number out of a group of numbers.
Have the computer provide both the mean number of rounds of the 1000 simulations, and some sort
of display of the distribution of the number of rounds needed for each simulation.
Then, you can look for patterns, and try to reverse engineer formulas based on these patterns.
Obviously, even here, you could still be faced with a nightmare.


text:
Q: MYSQL: Error Code: 1215. Cannot add foreign key constraint basically I have an issue with creating a joined table and don't know how to fix it. I created cInfo first, then mInfo, then eInfo which all worked but then when trying to create cRented it gave me the error: Error Code: 1215. Cannot add foreign key constraint. Any help?
Here is the code:
 CREATE TABLE cInfo (
cid int(4) DEFAULT '0',
fname varchar(20) NOT NULL,
sname varchar(20) NOT NULL,
age int(4) DEFAULT '0',
gender enum('M', 'F') NOT NULL DEFAULT 'M',
telno int(10) DEFAULT '0',
email varchar(20) NOT NULL,
addr varchar(50) NOT NULL,
cowed int(4) NOT NULL DEFAULT '0',
PRIMARY KEY (cid, cowed)
);

INSERT INTO cInfo VALUES(1,'Smith', 'John', 20, 'M', 0891234567,
'smith.john@gmail.com', '1 Bishopstown Road, Cork', 10);

CREATE TABLE mInfo (
mid INT NOT NULL,
title varchar(100) NOT NULL,
director varchar(100) NOT NULL,
relyear int(4) NOT NULL,
genre enum('Thriller','Horror','Documentary','Comedy','Drama') NOT NULL
DEFAULT 'Drama',
PRIMARY KEY (mid)
);

INSERT INTO mInfo VALUES(1,'Justice League', 'Zack Snyder', 2017, 'Comedy');

CREATE TABLE eInfo (
eid int(4) DEFAULT '0',
ppsn varchar(10) NOT NULL,
fname varchar(20) NOT NULL,
sname varchar(20) NOT NULL,
gender enum('M', 'F') NOT NULL DEFAULT 'M',
telno int(10) DEFAULT '0',
email varchar(100) NOT NULL,
addr varchar(200) NOT NULL,
mid INT NOT NULL,
PRIMARY KEY (mid),

CONSTRAINT eInfo_ref1 FOREIGN KEY (mid) REFERENCES mInfo (mid)
);

INSERT INTO eInfo VALUES(1, '1234567A', 'Moyes', 'Richard', 'M', 0871234567,
'moyes.richard@gmail.com', '1 CIT Road, Cork', 1 );

CREATE TABLE cRented (
cid int(4) DEFAULT '0',
mid INT NOT NULL,
dor Date NOT NULL,
cowed int(4) NOT NULL DEFAULT '0',
PRIMARY KEY (cid, mid, cowed),

CONSTRAINT cRented_ref1 FOREIGN KEY (cid) REFERENCES cInfo (cid),
CONSTRAINT cRented_ref2 FOREIGN KEY (mid) REFERENCES mInfo (mid),
CONSTRAINT cRented_ref3 FOREIGN KEY (cowed) REFERENCES cInfo (cowed)
);

INSERT INTO cRented VALUES(1, 1, 2017-11-23, 10 );

A: In the following:
CONSTRAINT cRented_ref1 FOREIGN KEY (cid) REFERENCES cInfo (cid),
CONSTRAINT cRented_ref2 FOREIGN KEY (mid) REFERENCES mInfo (mid),
CONSTRAINT cRented_ref3 FOREIGN KEY (cowed) REFERENCES cInfo (cowed)

remove CONSTRAINT cRented_ref3 in favor of composite foreign key cRented_ref1:
CONSTRAINT cRented_ref1 FOREIGN KEY (cid, cowed) REFERENCES cInfo (cid, cowed),
CONSTRAINT cRented_ref2 FOREIGN KEY (mid) REFERENCES mInfo (mid)

That way cRented_ref1 matches the composite primary key on cInfo.
Table eInfo is not likely an issue in this case though making the primary key and foreign key constraints the same column implies a 1:1 relationship between the data in eInfo and mInfo.


text:
Q: Can a LatticeData image be displayed in a space filled fashion I'd like a FaceCenteredCubic image as in the in LatticeData
docs, but  space packed, and cropped on all the boundaries, so that it illustrates the geometry of the calculation that leads to the $\pi/\sqrt{18}$ density result.
The call that produces the plot is
LatticeData["FaceCenteredCubic", "Image"]

but this has small spheres, and probably doesn't have a way to crop on the boundaries.  I see that there's a PackingRadius listed in the documentation.  I thought it might be  possible to use the PackingRadius property, to display the spheres in the lattice in a space packed fashion (so that they touch), but that wouldn't handle the cropping part of the problem.
Is there any easy way to do this, perhaps using the lattice data to draw spheres using the Graphics drawing options, and then using the various ViewAngle type options to crop that appropriately?

A: All the information is there, but to adjust the sphere radius I had to do a replacement as follows:
spaceFilledPlot[latticeType_] :=
 LatticeData[latticeType, "Image"] /.
  Sphere[pt_, r_] :> {Opacity[.5],
    Sphere[pt, LatticeData[latticeType, "PackingRadius"]]}

spaceFilledPlot["FaceCenteredCubic"]

I added the opacity for better visibility of the underlying lattice.
Oh, and you wanted to crop at the boundaries:
Show[
 spaceFilledPlot["FaceCenteredCubic"],
 PlotRange -> {{-1, 1}, {-1, 1}, {-1, 1}}]

Edit
In response to the comment, here is how one could replace the spheres in the default plot by RegionPlot so that the cut surfaces show up in a cropped display, giving a more solid appearance:
volumetricPlot[latticeType_] := Module[
  {
   img = LatticeData[latticeType, "Image"],
   r = LatticeData[latticeType, "PackingRadius"]
   },
  Show[
   img /. Sphere[pt_, r_] :> {},
   Map[
    RegionPlot3D[(EuclideanDistance[{x, y, z}, #] < r),
      {x, -1, 1}, {y, -1, 1}, {z, -1, 1},
      Mesh -> False,
      PlotStyle -> Opacity[.5]
      ] &, Cases[img, Sphere[pos_, _] :> pos, Infinity]]
   ]
  ]

  volumetricPlot["FaceCenteredCubic"]

Edit 2
There is at least one bug in LatticeData. I just found this when thinking about how to crop a unit cell for a non-cubic lattice. So I tried the hexagonal close-packed structure, which is closely related to the previous example. But here is the plot:
volumetricPlot["HexagonalClosePacking"]

This is clearly not very closely packed! The error is in the "Image" data for this lattice. It's very easy to spot this when you use my function because it expands the spheres to where they should touch. So I'd recommend being very careful when using these data. A somewhat better-working notebook for this case can be downloaded from Mathworld.
As a temporary fix for the issue with the hcp lattice, you could use the following modification of the plotting function in the question:
volumetricPlot[latticeType_] := Module[
  {pts,
   img = LatticeData[latticeType, "Image"],
   r = LatticeData[latticeType, "PackingRadius"]},
  If[latticeType == "HexagonalClosePacking",
   pts = {{-1, 0, Sqrt[2/3]}, {-(1/2), Sqrt[3]/2, Sqrt[2/
      3]}, {-(1/2), -(Sqrt[3]/2), Sqrt[2/3]}, {0, 0, Sqrt[2/3]}, {1/2,
       Sqrt[3]/2, Sqrt[2/3]}, {1/2, -(Sqrt[3]/2), Sqrt[2/3]}, {1, 0,
      Sqrt[2/3]}, {-(1/2), 1/(2 Sqrt[3]), 0}, {0,
      1/(2 Sqrt[3]) - Sqrt[3]/2, 0}, {1/2, 1/(2 Sqrt[3]), 0}, {-1,
      0, -Sqrt[(2/3)]}, {-(1/2), Sqrt[3]/
      2, -Sqrt[(2/3)]}, {-(1/2), -(Sqrt[3]/2), -Sqrt[(2/3)]}, {0,
      0, -Sqrt[(2/3)]}, {1/2, Sqrt[3]/2, -Sqrt[(2/3)]}, {1/
      2, -(Sqrt[3]/2), -Sqrt[(2/3)]}, {1, 0, -Sqrt[(2/3)]}},
   pts = Cases[img, Sphere[pos_, _] :> pos, Infinity]];
  Show[img /. Sphere[pt_, r_] :> {},
   Map[RegionPlot3D[(EuclideanDistance[{x, y, z}, #] < r), {x, -1,
       1}, {y, -1, 1}, {z, -1, 1}, Mesh -> False,
      PlotStyle -> Opacity[.5]] &, pts]]]

volumetricPlot["HexagonalClosePacking"]

This has the gaps corrected by shifting the z coordinates appropriately to make the center lie at the origin. The function handles the hcp case separately.


text:
Q: Show the equality Let $(X, \mathcal{A}, \mu)$ space with measure, $\mu(X) = 1$, $\epsilon > 0$ and $f: X \rightarrow [\epsilon,\infty)$ a $\mathcal{A}$-measurable and bounded function, I've tried show $$\lim_{p \rightarrow 0^{+}} \left(\int_{X} f^p(x)d\mu(x) \right)^{\frac{1}{p}} = \exp\left(\int_X \ln(f(x))d\mu(x)\right)$$
My attempt: I know is true, in this case, $\displaystyle \int_X \ln(f(x))d\mu(x) \leq \ln\left(\int_Xf(x)d\mu(x)\right)$, because $\ln(t) \leq t - 1$, $\forall t > 0$, take $t = \frac{f(x)}{\int_Xf(x)d\mu(x)}$ and integrate over $X$. So $\left(\int_{X} f^p(x)d\mu(x) \right)^{\frac{1}{p}} = \exp\left(\frac{1}{p}\ln\left(\int_X f^p(x)d\mu(x)\right)\right) \geq \exp\left(\frac{1}{p}\int_X \ln(f^p(x))d\mu(x) \right) = \exp\left(\int_X \ln(f(x))d\mu(x) \right)$, then
$$\lim_{p \rightarrow 0^{+}} \left(\int_{X} f^p(x)d\mu(x) \right)^{\frac{1}{p}} \geq \exp\left(\int_X \ln(f(x))d\mu(x)\right)$$
If $\left(\int_{X} f^p(x)d\mu(x) \right)^{\frac{1}{p}}$ is decreasing, the equality it's ok, but I don't know how show this.
There is a hint in exercise, $\displaystyle \lim_{t \rightarrow 0^+} \frac{a^t - 1}{t} = \ln(a)$. I've tried use this limit for show decreasing, but it wasn't successful.
Thank you.

A: Define $G\colon \Bbb R_{\geq 0}\to \Bbb R$ by $G(p) = \int_Xf^p\,{\rm d}\mu$. We have $G(0) = \mu(X) = 1$ and so $\ln G(0) = 0$. So:
\begin{align}
\lim_{p \to 0^+}\left( \int_X f^p\,{\rm d}\mu\right)^{1/p} &= \lim_{p \to 0^+} G(p)^{1/p} = \lim_{p \to 0^+} \exp \ln G(p)^{1/p} \\ &= \exp \lim_{p \to 0^+} \frac{\ln G(p)}{p} = \exp \lim_{p \to 0^+} \frac{\ln G(p)-\ln G(0)}{p-0} \\ &= \exp \frac{{\rm d}}{{\rm d}p}\bigg|_{p=0} \ln G(p) = \exp \frac{G'(0)}{G(0)} = \exp G'(0).
\end{align}
Now we only have to check that $G'(0) = \int_X \ln f\,{\rm d}\mu$. We have:
\begin{align}
G'(0) &= \lim_{p \to 0^+}\frac{G(p)-G(0)}{p-0} = \lim_{p\to 0^+}\frac{\int_X f^p\,{\rm d}\mu - 1}{p} \\ &\stackrel{(\ast)}{=} \lim_{p \to 0^+} \int_X \frac{f^p - 1}{p}\,{\rm d}\mu \stackrel{(\ast\ast)}{=} \int_X \lim_{p \to 0^+}\frac{f^p-1}{p}\,{\rm d}\mu \\ &= \int_X \ln f\,{\rm d}
\mu,\end{align}
where in $(\ast)$ we use that $\mu(X) = 1$ and in $(\ast\ast)$ we use the bounded convergence theorem.


text:
Q: Matplotlib - _tkinter.TclError: bad screen distance "320.0" File "main.py", line 52, in <module>
    r2n(name)

  File "C:\Users\Riki\Documents\Universita\Erasmus\Personalization and Metadata modeling 02817\Final Project\friends_followers__redis_to_networkx.py", line 69, in r2n

    **nx.draw_spring(g,node_size=50,node_color='#32CD32',node_shape='o',edge_color='.1',with_labels=True,width=0.5)**

  File "C:\Python27\lib\site-packages\networkx-1.6-py2.7.egg\networkx\drawing\nx_pylab.py", line 876, in draw_spring
    draw(G,spring_layout(G),**kwargs)

  File "C:\Python27\lib\site-packages\networkx-1.6-py2.7.egg\networkx\drawing\nx_pylab.py", line 124, in draw
    cf=pylab.gcf()

  File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 369, in gcf
    return figure()

  File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 343, in figure
    **kwargs)

  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 81, in new_figure_manager
    canvas = FigureCanvasTkAgg(figure, master=window)

  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 188, in __init__
    self._tkcanvas.create_image(w/2, h/2, image=self._tkphoto)

  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2198, in create_image
    return self._create('image', args, kw)

  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2189, in _create
    *(args + self._options(cnf, kw))))

**_tkinter.TclError: bad screen distance "320.0"**

Hi, I'm working on Python 2.7 for Windows 64bit.
Suddenly that problem occurred, but my code should be ok because was working previously (without any change the plots were visible).
I think that is a problem with the library, what shall I do?

A: Try converting your coordinates to an int before creating the canvas item. For example:
self._tkcanvas.create_image(int(w/2), int(h/2), image=self._tkphoto)

I appreciate this answer very much, as it helped me a lot; I wish I could add a separate answer, but I can't as it's closed - so posting an edit:
A solution that worked for me that didn't require changing the matplotlib library files, is to simply make a new class to override a method, the two problematic methods being __init__ and resize (and strangely, all I need is to overload resize, didn't even had to put in the fix there, and it started working for me?)
Anyways, take note that the below is copied from the Python2.7 Matplotlib - you're probably better off checking for your local matplotlib version first, and copying from there:
# copy of /usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py
# with fix:
class FigureCanvasTkAggFix(FigureCanvasTkAgg):
  def __init__(self, figure, master=None, resize_callback=None):
    matplotlib.backends.backend_tkagg.FigureCanvasAgg.__init__(self, figure)
    self._idle = True
    t1,t2,w,h = self.figure.bbox.bounds
    w, h = int(w), int(h)
    self._tkcanvas = tk.Canvas(
      master=master, width=w, height=h, borderwidth=4)
    self._tkphoto = tk.PhotoImage(
      master=self._tkcanvas, width=w, height=h)
    self._tkcanvas.create_image(int(w/2), int(h/2), image=self._tkphoto) # fix
    self._resize_callback = resize_callback
    self._tkcanvas.bind("<Configure>", self.resize)
    self._tkcanvas.bind("<Key>", self.key_press)
    self._tkcanvas.bind("<Motion>", self.motion_notify_event)
    self._tkcanvas.bind("<KeyRelease>", self.key_release)
    for name in "<Button-1>", "<Button-2>", "<Button-3>":
      self._tkcanvas.bind(name, self.button_press_event)
    for name in "<ButtonRelease-1>", "<ButtonRelease-2>", "<ButtonRelease-3>":
      self._tkcanvas.bind(name, self.button_release_event)
    for name in "<Button-4>", "<Button-5>":
      self._tkcanvas.bind(name, self.scroll_event)
    root = self._tkcanvas.winfo_toplevel()
    root.bind("<MouseWheel>", self.scroll_event_windows)
    self._master = master
    self._tkcanvas.focus_set()
    self.sourced = dict()
    def on_idle(*ignore):
      self.idle_event()
      return True
  def resize(self, event):
    width, height = event.width, event.height
    printse("WH", width, height, "\n")
    if self._resize_callback is not None:
      self._resize_callback(event)
    # compute desired figure size in inches
    dpival = self.figure.dpi
    winch = width/dpival
    hinch = height/dpival
    self.figure.set_size_inches(winch, hinch)
    self._tkcanvas.delete(self._tkphoto)
    self._tkphoto = tk.PhotoImage(
      master=self._tkcanvas, width=width, height=height)
    self._tkcanvas.create_image(width/2,height/2,image=self._tkphoto)
    self.resize_event()
    self.show()


text:
Q: how to create RPM to instal openJDK JRE, PostgreSQL in Redhat linux? I need to create a rpm which install's JRE and PostgreSQL in Redhat linux.
only thing i know is i need to create a .spec file and need to mention the instruction to do this. I could do manually by installing each rpm in the linux machine , but i need to bundle this together, so that i install the rpm which inturn installs both JRE and PostGreSQL. I am new to this rpm creation. Any pointers on how to do this?

A: what it seems that you want to do is called a "metapackage".  so your package actually contains nothing, but pulls down the Postgresql and JRE from the repos.
you need to make a spec files which will have for the
Requires: line
Requires:  <package1> <package2>
the JRE and PostgreSQL (I don't have a rh machine in front of me so I don't know the actual names), then build like this
rpmbuild -ba SPECS/metatest.spec
see here for more details
http://www.linuxquestions.org/questions/linux-software-2/how-to-make-rpms-with-dependencies-meta-packages-720481/


text:
Q: How can I calculate z-value from chi-squre distribution with 2 df? I tested two models and one is nested inside another. Nested model has 2 parameters and the bigger model has 4. I got the ln likelihood of each models. I know how to calculate the P value using twice the difference of ln likelihoods, since twice the difference of ln likelihoods is following chi square distribution with degree of freedom equal to the difference in the number of parameters between the two models.
How can I calculate z-value from chi-squre distribution with 2 df?
I need z-values for further meta-analysis using METAL https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2922887/


text:
Q: mark.parametrize over same IntervalIndex and avoid repetition I want to parametrize like below but I want to avoid repetition of Interval index 3 times. Is there a better way to do it?
@pytest.mark.parametrize("arrays",
    [
        IntervalIndex.from_breaks([
                        pd.Timestamp("2018-01-02"), pd.Timestamp("2018-01-05"), pd.Timestamp("2018-01-08"), pd.Timestamp("2018-01-11")],
                        closed='both'),
        pd.array(IntervalIndex.from_breaks([
                        pd.Timestamp("2018-01-02"), pd.Timestamp("2018-01-05"), pd.Timestamp("2018-01-08"), pd.Timestamp("2018-01-11")],
                        closed='both')),
        list(IntervalIndex.from_breaks([
                        pd.Timestamp("2018-01-02"), pd.Timestamp("2018-01-05"), pd.Timestamp("2018-01-08"), pd.Timestamp("2018-01-11")],
                        closed='both')),
        ]
    )

def test_IntervalIndex_get_indexer_non_unique(self, arrays):

    int_inx = interval_range(Timestamp("2018-01-02"), freq="3D", periods=3)

    actual = int_inx.get_indexer_non_unique(arrays)
    expected = (np.array([0, 1, 2], dtype=np.int64), np.array([], dtype=np.int64))

    tm.assert_equal(actual, expected)


text:
Q: ABAddressBook normalized phone number I need to export contacts phone numbers from the user address book to a remote server.
My server expecting a normalized phone number,
for example if I get contact number: (541) 754-3010
the normalized number should be: 5417543010
my question is about the country code, I want to detect if a number already include a country code and if not to set it myself.
It would be nice if I could query the ABRecordRef to know if a country code exists, but I don't think I can.
Any ideas?

A: 1) I am guessing that you want to strip brackets and whitespace so you can store the number as  an integer instead of a string. This is a bad idea as telephone numbers are not restricted to integers and may contain letters and special characters. (Apple itself uses "1800MYAPPLE").
2) You can check whether the value in kABPersonAddressCountryCodeKey matches the first few characters of your number and, if it doesn't, add them yourself. This is a little dangerous and you should just trust the user to supply a correct number.


text:
Q: How to read settings bundle when I go back to App? I created "updateheading" in settings bundle
If user leave the app, go to setting to change value, when user go back the app, locationManager should start/stop base on the updated value.
But the app does not run viewWillAppear. How to read updated value?
private let locationManager : CLLocationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.requestWhenInUseAuthorization()
    locationManager.delegate = self
}
override func viewWillAppear(_ animated: Bool) {

    let userDefault = UserDefaults.standard
    let updateheading = userDefault.object(forKey: "updateheading") as! Bool
    if(updateheading){
        locationManager.startUpdatingHeading()
    }else{
        locationManager.stopUpdatingHeading()
    }
}

A: View controller do not responding on application state. It is responsibility of AppDelegate. But you can subscribe for notifications.
var observer: Any?

override func viewWillAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    observer = NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationDidBecomeActive, object: nil, queue: .main) { (_) in
        doUpdate()
    }
    doUpdate()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    observber = nil
}

Where doUpdate is your current code.
PS: "If you override viewWillAppear, you must call super at some point in your implementation." (c) Apple Docs


text:
Q: Local network data transfers slower than internet downloads I have two Windows 7 machines on my local network. Both use wireless LAN adapters to connect to the AP/router.
Now if I download from Internet, my speed is 1800KB/s but if I copy files from one Windows computer to the other using shared folders, my speed is 500KB/s.
Why is the local transfer so much slower? How can I fix this?

A: There's probably no problem, this is expected behavior. When both clients are wireless, the data has to be sent twice over the wireless link, halving the bandwidth. In addition, the link has to be "turned around" twice as much, increasing the dead time. If you want higher wireless speeds, upgrade your wireless hardware.
Consider these two cases. Each example shows two data packets being sent and one acknowledgement being sent in reply.
Case 1: Internet to LAN. Packets are being received over the Internet link by the access point bound for machine A.

*

*AP -> A: Here's a data packet for you.

*A: Got it.

*AP -> A: Here's a data packet for you.

*A: Got it, and here's a reply.
Notice all requests send useful data and each data packet is sent once.
Care 2: LAN to LAN. A wants to send data to B.

*

*A: I need the link.

*AP->A: It's yours.

*A: Here's some data for B.

*AP->A: Got it.

*AP->B: Here's some data for you.

*B: Got it.

*A: I need the link.

*AP->A: It's yours.

*A: Here's some data for B.

*AP->A: Got it.

*AP->B: Here's some data for you.

*B: Got it. And I have a reply for A.

*AP->A: Here's some data.
This is clearly much worse. A must frequently arbitrate with the AP to get the link to send a packet. Each bit of data must be sent twice. There are far more handoffs of control of the link. Yuck.
Upgrading to 802.11n and an access point with multiple simultaneous stream capability can make a huge difference.


text:
Q: Use different Anaconda environments on Linux Mint and Spyder I'm trying to use and install packages in more than one environment through Anaconda 4.9.2 (I use Linux Mint 20 and Spyder 4.1.5).
I created an environment called phdenv, and it seems to me that I was able to install Python 3.7, but when trying to activate the environment through the command conda activate phdenv the error that appears is the following:
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run

     $ init init <SHELL_NAME>

Currently supported shells are:
   - bash
   - fish
   - tcsh
   - xonsh
   - zsh
   - powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'.

Note: you may need to restart the kernel to use updated packages.

what am I doing wrong?


text:
Q: The Margin or space outside can't be change to 0 This is my css code
       .my-works {
         margin-top:0;
         width: 100%;
         background-color: orange;
            }

        .my-works h3 {
            text-align:center;

            }

here's my html code

 MY WORKS

My Blog

A Tambay Inspired Flappy Bird - Yotni Bird

This is the result of the site

I already change the css margin to 0 but still it has space between the two.

A: You need to set the h3 to have margin-top:0
.my-works h3 {
    margin-top:0;
}

Not the container


text:
Q: Can't reference Entity Framework Core in .NET 5 I'm using Visual Studio Code to build a class library with .NET 5 and Entity Framework Core.
However, I can't make reference to Entity Framework Core and I keep getting errors as if it doesn't exist.
This is the project file:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.7" />
  </ItemGroup>

</Project>

All the package reference were included using dotnet add package.
These are the attempts I already made:

*

*Restart Omni sharp

*Restore the packages (dotnet package restore)

*Use a lower version of Entity Framework Core (5.0.0)

The specific problem and error message is here and was here all the time, so no other intelligent editor may close this question again:
The result continues to be the same, I get an error message on the using telling the EntityFrameworkCore namespace doesn't exist in the Microsoft namespace. However, the IntelliSense shows EntityFrameworkCore.
What else could I try?
P.S.: As required for the question not get closed - I already tried all the options on the other question in stackoverflow, all the options that fit on this scenario, and they don't work. The other question: EntityFrameworkCore does not exist in the namespace Microsoft


text:
Q: Contour integral of $f(z)$ where $f(z)$ is not defined on the contour. I have a trouble in the following problem:
Let $D=\left\{z\in\mathbb{C}~:~|z|=2\right\}$, and let $f:\mathbb{C}\setminus{D}\to\mathbb{C}$ be a function defined by $$f(\theta)=\int_{|z|=2}\frac{z^{3}+3z^{2}+z+1}{-2(z-\theta)^3}\,dz.$$ Find $f(0)$ and $f'(3i)$.
Is it possible to solve the above integration?
I have never seen kinds of integration, so I have no idea how to get started.
Give some advice! Thank you!

A: You can evaluate $f(0)$ directly from the definition of the integral. However if you know that the integral of the derivative of a function over a closed path is always 0 you can easily get $f(0)$ as $\int_{|z|=2} (-3/2) \frac 1 zdz=-3 \pi i$ since the other terms integrate to $0$. For $f'(3i)$ you don't have to calculate anything! By Cauchy's Theorem $f(\theta)=0$ whenever $|\theta| >2$ which implies $f'(\theta)=0$ whenever $|\theta| >2$, so the answer is $0$.


text:
Q: Lambda function in python to copy files from S3 to On prem server I am new to AWS and have to copy a file from S3 bucket to an on-prem server.
As I understand the lambda would get triggered from S3 file upload event notification. But what could be used in lambda to send the file securely.

A: Your best bet may be to create a hybrid network so AWS lambda can talk directly to an on-prem server.  Then you could directly copy the file server-to-server over the network.  That's a big topic to cover, with lots of other considerations that probably go well beyond this simple question/answer.
You could send it via an HTTPS web request.  You could easily write code to send it like this, but that implies you have something on the other end set up to receive it--some sort of HTTPS web server/API.  Again, that could be big topic, but here's a description of how you might do that in Python.
Another option would be to use SNS to notify something on-premise whenever a file is uploaded.  Then you could write code to pull the file down from S3 on your end.  But the key thing is that this pull is initiated by code on your side.  Maybe it gets triggered in response to an SNS email or something like that, but the network flow is on-premise fetching the file from S3 versus lambda pushing it to on-premise.
There are many other options.  You probably need to do more research and decide your architectural approach before getting too deep into the implementation details.


text:
Q: Showing a one-time UIViewController via presentModalViewController upon launch Greetings! I have a working iPhone app (huzzah!) that uses a MainView.xib containing a fully-stocked UITabBar with several UINavigationController objects and views at-the-ready.
I've now been asked to add a one-time registration view to this mix. This view would appear before the UITabBar at app-launch, get some info from the user, register with a server - or check for an existing registration, then squirrel some data away in the keychain. (If the keychain already shows proof of registration, then we skip showing this particular view.)
The registration and keychain part I've got under control (thank you Erica Sadun for the latter!), but showing that initial one-time view is proving to be trickier than I expected.
I suspect I'm too close to the problem to see what's wrong. I really hope it's pilot error and doesn't require anything too Rube Goldberg!
Here's the scenario:
The app starts by loading MainView.xib, in which lies the aforementioned UITabBar controller, et. al. For the sake of argument, let's say we must show that registration view. Also, we'd like it to have a modal appearance, so it will fly in from the bottom up. Then, when we're done, we can dismiss it, call a delegate (most likely the App Delegate) and tell it to carry on with the original UITabBar.
// Normally, the Tab Bar Controller's view is added to the window ... still do this?
[window addSubview:tabBarController.view];

// We could now set up a VC like so. Mostly harmless. (I know, "mvc" is an unfortunate abbreviation in this case.)
RegistrationVC *mvc = [[RegistrationVC alloc] initWithNibName:@"RegistrationView" bundle:nil];

Note that RegistrationView.xib has a UIView inside, but no nav controller. We want to keep it decoupled so that it can be reused, say, as part of a tab bar item's nav controller (to review your registration info, for instance).
Moving on. We create a nav controller with the intent of presenting things modally:
UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:mvc];

We then present our modal VC, using the tab bar controller as the basis, and release the alloc'ed bits.
[tabBarController presentModalViewController:nc animated:YES];
[nc release];
[mvc release];

First observation. Something tells me this is just plain sloppy. You can see the first tab bar item's nav bar and view appear just as the modal view swoops in. Yeccch! Moreover, trying to set the selected VC to nil beforehand has no effect:
 tabBarController.selectedViewController = nil;

We really don't want/need to use the tab bar until after the modal VC is done (and we have the delegate to help let us know when that happens).
Why am I even bothering with the Tab Bar? Well, it looks like I need something to hang that modal VC's hat on, and I don't know what else there is to use.
Is this the only way? It just seems to tether the Registration VC and the Tab Bar unnecessarily, and it just smells ... wrong.
Clues welcome/appreciated!

A: It's hard to answer this without knowing what your Default.png shows.  Assuming you're following the HIG and it displays an empty tabBarController, I'd suggest a somewhat complicated layering:
bottom view: tabBarController.view
middle view: UIImageView: Default.png
top view: registration view positioned below the bottom of the screen
On startup, if you need to show the registration view, manually animate it upward, and once the animation is done remove the UIImageView below it.  When registration is complete, manually animate the registration view downward to reveal the tabBarController.  If on startup you don't need the registration view, just animate the UIImageView to fade away (or just remove it).
OTOH hand, if you're not following the HIG and instead showing some kind of splash screen, things get a bit easier.  Layer like this:
bottom view: tabBarController.view
top view: UIImageView: Default.png
If you need to show registration, do presentModalViewController with animated:NO and then fade out the UIImageView.  If not, just fade out the UIImageView.
That's a lengthy explanation w/o pictures, hope it makes sense.  The salient point is that I'm suggesting adding a UIImageView:Default.png to be the first thing that is seen when the app starts, and use that to guide your transition into registration or tabBarController as appropriate.


text:
Q: Increasing not initialize array value in php Hy
I have a foreach loop that adds array keys to another array. I wanted to know if it' safe to increment (with ++) and uninitialize element.
At the moment my code is:
foreach($SociBdP as $id=>$socio)
{
    if(!isset($provenienza[$option_name]))
        $provenienza[$option_name]=0;
    $provenienza[$option_name]++;
}

I wanted to know if it's safe to do
foreach($SociBdP as $id=>$socio)
{
    $provenienza[$option_name]++;
}

or if there is a risk (like in c++) that the default value of the array isn't 0

A: While it's a documented behaviour you can trust:

It is not necessary to initialize variables in PHP however it is a
  very good practice. Uninitialized variables have a default value of
  their type depending on the context in which they are used - booleans
  default to FALSE, integers and floats default to zero, strings (e.g.
  used in echo) are set as an empty string and arrays become to an empty
  array.

... it also prevents you from taking benefit of notices since you need to lower down your error reporting settings so they don't show up in the development phase:
var_dump($foo);

Notice: Undefined variable: foo in D:\tmp\borrame.php on line 3
NULL

Notices are often seen as an annoyance by newbies but they're actually a terrific tool to spot silly typos.

A: In PHP 7, we can use the "null coalescing operator" (??) :
$provenienza[$option_name] = ($provenienza[$option_name] ?? 0) + 1;

It is much simpler and with less "repetition" than using isset()

A: Nope, the correct one is:
foreach($SociBdP as $id=>$socio)
{
    if(!isset($provenienza[$option_name]))
        $provenienza[$option_name]=0;
    $provenienza[$option_name]++;
}

You have to be sure that the array contains the key before you increment it.


text:
Q: How to extract data from a Maxtor Shared Storage II backup I am just trying to salvage data from my dying Maxtor Shared Storage II enclosure. I have backed it up to an external USB drive using its onboard features and would like to restore it to a different location, using an ordinary Linux machine.
The backup disk is formatted with an ext3 filesystem, which Linux can mount. The backup seems to reside in a directory tree, with one XML file holding metadata and an archive apparently holding my backed-up data.
The archive file has a .tar.gz extension, but when I try to open it, I get an error message saying the file is not a valid gzip-compressed file. What gives?

A: Running file on the archive gives:
POSIX tar archive (GNU)
So, apparently the MSS II creates regular tar archives but gives them a .gz extension, despite not compressing them. After renaming it from .tar.gz tp .tar I was able to extract its contents.
YMMV – if this doesn't work for someone, run file on the archive to find out if and how it was compressed, then rename it giving it the correct extension.


text:
Q: determining total number of times distinct values 0 or 1 or na in each column in a data frame in R I have 15 columns and I want to group by values in each column by either 0 or 1 or na.
my dataset
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O
0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0
1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0
1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0
NA,1.0,0.0,0.0,NA,0.0,0.0,0.0,NA,NA,NA,NA,NA,NA,NA
1.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0
1.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0
1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0
1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,NA,NA,NA,NA,NA
1.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
1.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,NA,0.0,NA,NA,NA,NA,NA
1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0
1.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0
1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0
1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0
1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0
0.0,0.0,0.0,0.0,0.0,NA,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,1.0
1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0
1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0
1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0
0.0,1.0,1.0,0.0,0.0,0.0,NA,NA,NA,NA,NA,NA,NA,NA,NA
1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0
NA,NA,1.0,NA,NA,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0
0.0,1.0,0.0,0.0,0.0,0.0,0.0,NA,0.0,0.0,NA,NA,NA,NA,NA

I want output to be like:
    A  B  C  D  E  F  G  H  I  J  K  L  M  N  O
0   5  6  2  3  5  0  1  2  3  4  1  2  0  0  1
1   5  6  2  3  5  0  1  2  3  4  1  2  0  0  1
NA  5  6  2  3  5  0  1  2  3  4  1  2  0  0  1

A: We can loop through the dataset and apply the table with useNA="always"
sapply(df1, table, useNA="always")

If there are only a particular value in a column, say 1, then convert it to factor with levels specified as 0 and 1
sapply(df1, function(x) table(factor(x, levels = 0:1), useNA = "always"))
#      A  B  C  D  E  F  G  H  I  J  K  L  M  N  O
#0     4  3  8  7 17 15 14 11 14 12 12 10  8 11  9
#1    19 21 17 17  6  9 10 12  8 11  8 10 12  9 11
#<NA>  2  1  0  1  2  1  1  2  3  2  5  5  5  5  5


text:
Q: How to stitching(side by side ) more than one video using xuggler I have to stitch more than one video streams,it may be recorded file or live streams
I have seen some video on the YouTube.
can i do it with Xuggler?
Any sample code ,link, advice, idea will be highly appreciated.


text:
Q: PHP - Access Denied while passing parameters through URL I made a php script which'll echo an image if the correct password is entered; so that, nobody can access the images stored on my server directly, thus, making my server more secure. Now, for the php script I used GET method to generate a mysql_query to my database in order to check if the email and password entered by the user are associated with a relevant account and then echo the image from a folder on my server. Now, in order to pass the parameters while runtime, I'm adding them in the URL like this:
http://<mywebserver>/get_image.php/?email=<email>&password=<password>&file_name=<image-file-name>

But, something's wrong with this whole setup, and I'm getting the following error:

Warning: mysql_query() [function.mysql-query]: Access denied for user
  'uXXXXXXXXX'@'XX.XX.XX.XX' (using password: NO) in
  /home/uXXXXXXXXX/public_html/get_image.php on line 11
Warning: mysql_query() [function.mysql-query]: A link to the server
  could not be established in /home/uXXXXXXXXX/public_html/get_image.php
  on line 11 Error getting data: Access denied for user
  'uXXXXXXXXX'@'XX.XX.XX.XX' (using password: NO)

Here is my php script, get_image.php:
<?php

$file_path = "/ProfilePics/";

if(isset($_GET['email']) && isset($_GET['password']) && isset($_GET['file_name'])) {

$id = "\"" . $_GET['email'] . "\"";
$typed_password = "\"" . $_GET['password'] . "\"";
$file = $_GET['file_name'];

$result = mysql_query("SELECT * FROM students WHERE email = $id AND password = $typed_password") or die ("Error getting data: " . mysql_error()); //line 11

if(!empty($result)) {

    if (mysql_num_rows($result) > 0) {

        $result = mysql_fetch_array($result);

        $user = array();
        $user["email"] = $result["email"];
        $user["password"] = $result["password"];

        $pass = "\"" . $user["password"] . "\"";

        if($pass == $typed_password) {

        $img_path = $file_path . $file;

        echo '<img src="' . $img_path . '" name = "cover" />';

        } else {

            echo "Incorrect password";

        }
    } else {

        echo "Unable to find user";

    }

} else {

    echo "Unable to find user";

}
} else {

        echo "Required field(s) is missing";

   }
?>

I agree, that there are lots of other questions already on stackoverflow stating similar problems. But, I didn't find the solution(s) to those questions applicable for my code. So, any help on this will be highly appreciated. Thank you for your time!

A: You don't seem to be connecting to the database before you try to send queries to it.
It should like something like this:
$conn = new mysqli($servername, $username, $password, $dbname);

Taken from the example here:
http://www.w3schools.com/php/php_mysql_select.asp
Furthermore, if you care, you should consider using PDO or some other method of preventing SQL injection attacks.
SQL Injection:
https://en.wikipedia.org/wiki/SQL_injection
Information on PDO:
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059

A: This is because you have not connected your file get_image.php to your MySQL database. Do so as follows:
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="database"; // Database name
$tbl_name="students"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

Simply replace the information above with the correct information.

A: setup a database connection first:
$con = mysql_connect('server','username','password');
$rst = mysql_query('select...', $con);

remember that kind of library to access mysql is outdated.
imagine someone logging in with this password:
password = '"; DROP TABLE students;'
or something crafted better.
There are different libraries like PDO or MYSQLI that take cares of this for you.
in newer releases of php standard mysql libis deprecated and removed


text:
Q: PHP POST: Form keeps submitting when I reload the page I have this code:

    <form enctype="multipart/form-data" action="/" method="post">
        Upload Image:
        <input style="font-family: sans-serif; font-size: 14px; width: 195px;" type="file" name="file">
        <input style="font-family: Sans-serif;" type="submit" name="enter" id="enter" value="Upload" />
    </form>

<?php
if(isset($_POST['enter']))
{
    echo "

            Scan the QR code on another device

                        or:

                On another device, go to this website on another device to view your images.

    ";
}
?>

But when I reload the page I still see
"On another device, go to this website on another device to view your images."
It doesn't go away.

A: this code will solve your problem, i test it with your code (add it at the top of your code)

Good luck


text:
Q: My SQL Query for Search Box I have this table
 date      | Expedition | Destination
________________________________________
12/05/2012 |  UPS       |  New York
12/05/2012 |  DHL       |  New York
13/06/2012 |  ATLAS     |  Atlanta
14/06/2012 |  JNE       |  Chicago

I want to create search result and this my code
 <form method="post" action="sales.php?ID=expLocal">
   Pencarian <input type="text" name="KUNCI" width="300"/><input type="submit" name="CARI"        value="CARI" />
 </form>

 <?php

  if (empty($_POST[CARI]))
  {
   $sql = "SELECT * FROM tb_exp_local";//this query for open all the data
  }
   else if (isset($_POST[KUNCI]))
  {
   $kunci=$_POST[KUNCI];
   $sql="SELECT * FROM tb_exp_local WHERE MATCH (expedition,destination,date)       AGAINST ('+$kunci' IN BOOLEAN MODE)"; // this is query for serching the data
  }

   ?>

The query runs well, but if the search box is filled with date the query does not run. Can anyone tell me how to correct this?(data type of column date is varchar)

A: *

*$kunci=$_POST["KUNCI"];

*carefull with Mysql match syntax here

*try to review mysql query when something is going wrong - a simple echo $sql will do so;

A: Are CARI and KUNCI defined anywhere in your sales.php?
Otherwise you need to check their values using

*

*$_POST["CARI"]

*$_POST["KUNCI"]


text:
Q: PostgreSQL: change order of columns in query I have a huge query with about 30 columns.
I ordered the query with:
Select *
From
.
.
.
order by id,status

Now I want that in the result to present columns in certain way.
The id column will be first, followed by status column and then all the rest.
is there a way to do that (without manually specifying 30 column names in select). Something like: Select id,status, REST

A: this will give you all columns except those you don't want to
SELECT id, status,' || array_to_string(ARRAY(SELECT 'o' || '.' || c.column_name
        FROM information_schema.columns As c
            WHERE table_name = 'table_name'
            AND  c.column_name NOT IN('id', 'status')
    ), ',') || ' FROM officepark As o' As sqlstmt

A: The "select *" will return the fields in the order in which they were listed when the table was created. If you want them returned in a particular order, just be sure to create the table with that order.

A: If you have to do it repeatly, you could create a new table:
CREATE TABLE FOO as
SELECT id, status, mydesiredorder

Or just a view,don't forget to move index constraint and foreign keys. If you must do it just once, was faster specify 30 columns than ask here


text:
Q: How to pivot a data frame with two columns and several observations for each group in R? It looks like it could be easily done using pivot_wider(), however this function seems to only work where information is grouped by more than one variable. Here's my data frame:
set.seed(1)
df = data.frame(group = c(rep(c(1:3), each=3)),
                value = sample(10:20, 9, replace = T))
  group value
1     1    14
2     1    14
3     1    19
4     2    15
5     2    19
6     2    16
7     3    18
8     3    14
9     3    14

And the desired output is:
1  2  3
14 15 18
14 19 14
19 16 14

How would you do it?
Thanks in advance!
EDIT: I just realised that columns can't be named after numbers. So the column names could be something like: C1, C2, C3.

A: Try unstack like below
unstack(rev(df))

which gives
  X1 X2 X3
1 18 10 20
2 13 11 11
3 16 16 20

A: Using dcast
library(data.table)
dcast(setDT(df), rowid(group) ~ paste0("C", group))[, group := NULL][]

-output
#   C1 C2 C3
#1: 18 10 20
#2: 13 11 11
#3: 16 16 20

A: Using the tidyverse, you need to add a dummy column to tell pivot_wider which rows to use...
df %>% group_by(group) %>%
  mutate(id = row_number()) %>%       #adds id row numbers for each group
  pivot_wider(names_from = group) %>%
  select(-id)                         #remove them again

# A tibble: 3 x 3
    `1`   `2`   `3`
  <int> <int> <int>
1    14    15    18
2    14    19    14
3    19    16    14


text:
Q: How to disable effects of other power up if picked a new power ups? I'm making a game where you can pick up a power up and gives you a boost or a new perks Ex. The fire power up makes you jump higher and makes your character/ball small and when you pick up the other power ups makes a new different perks or power
BTW I'm new at C# and unity my Idea is not to have a timer for each power ups but when you pick up a new power up it disables the effect of the last power up you picked up. Can someone help me?

A: Well, you should build an own class or system to handle your powerup mechanic. The code would be really just the manifestation of your logic. If it works with enabling and disabling scripts, then write a manager class which does exactly that. Reference each script in the inspector. When the player collects something, disable all of the scripts and enable the desired target script. Make use of enums.
But there are certainly better/other ways to handle that than having one script for each mechanic. Things get quickly out of control and quite messy if you do that. I bet 90%+ of the effects can be performed by just playing around with numbers (scaling, movement speed, jump height, etc), so what if you create a class whose instances embody floats to take care of that? For example the one you described would be:
public class Powerup
{
    SpecialEffect SpecialE = SpecialEffect.Shrink; // (enum)
    float SizeMod = 0.4f;
    float JumpMod = 2.0f;
    float SpeedMod = 1.0f; // (changes nothing)
    float DamageMod = 1.0f; // (changes nothing)

    public void ApplyEffects ()
    {
        // Do the changes to the player.
    }
}

You can expose a list of these Powerups to the inspector and fill in your elements, or do it via code in form of an initiate (I do these things with many excel sheets which get parsed, allowing me to write my data properly while having a great overwiew).


text:
Q: cannot get /about vue js vue.js When I build production by "npm run build", than access it on a local server (on my machine), than switching page to localhost:5000/about  I get an error:
Cannot GET /about
Please help guys. I am on 5th hour and can[t figure this out.. Thanks in advance
webpack.dev.conf.js:
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})

My router.js has this code:
import Vue from 'vue'
import Router from 'vue-router'

const Home = () => import(`./views/Home.vue`)
const About = () => import(`./views/About.vue`)
const Contact = () => import(`./views/contact.vue`)
const NotFound = () => import(`./views/404.vue`)

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: `/`,
      name: `home`,
      component: Home
    },
    {
      path: `/about`,
      name: `about`,
      component: About
    },
    {
      path: `/contact`,
      name: `contact`,
      component: Contact
    },
    {
      path: `/404`,
      component: NotFound
    },
    {
      path: `*`,
      redirect: `/404`
    }
  ],
  mode: `history`,
  scrollBehavior: to => {
    if (to.hash) {
      return { selector: to.hash }
    } else {
      return { x: 0, y: 0 }
    }
  }
})

But when I am on a localhost "npm run dev" it works well. This issue only happens in production or local server that servs dist folder.
Please help. Thanks..


text:
Q: Android JobScheduler running way too often when using setPeriodic() I noticed my scheduled JobScheduler is executing the job way too often. I have it set to execute daily and it requires to be idle, to be on wlan and to be charging, but when those conditions are met the job executes like every 10min or even more frequently.
My code:
JobInfo.Builder builder = new JobInfo.Builder(1,
                    new ComponentName(context.getPackageName(), SyncJobService.class.getName()));

builder.setPeriodic(TimeUnit.DAYS.toMillis(1))
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
        .setRequiresCharging(true)
        .setRequiresDeviceIdle(true);

int code = jobScheduler.schedule(builder.build());
if (code <= 0) {
    Log.e(TAG, "Could not scheduled job: " + code);
    return;
}

Log.e(TAG, "Scheduled job");

The job executes a background thread to download data from the internet, and after the data download is done I call
mService.jobFinished(mParams, true);

to notify the job scheduler that the job is done and it should reschedule it. How come the job executes so often even when the period is set to one day? My android 6.0.1 device almost never enters doze mode because of the job running so often.

A:
after the data download is done I call mService.jobFinished(mParams, true); to notify the job scheduler that the job is done and it should reschedule it

That is your problem right there. Use false, not true.
false says, "the work is done for this job". true says "we had a problem, please reschedule this job again to happen soonish". For example, the criteria says that you have to have an Internet connection, but perhaps you are having difficulty connecting to your server. In that case, return true, in hopes that the problem will clear up in a bit.
You might also consider adjusting the backoff rules via setBackoffCriteria() for those cases where you really want to return true.


text:
Q: Nesting async/await as follow ,what's the best way for Run Task simultaneously with async/await functions:
private async void ProcessItem()
{
    while (true)
    {
        await this.FetchDeviceData(); //Read From Devices
        await Task.Delay(2000);   //300000
        await this.Process(); //Insert Into DataBase
    }
}

private async Task FetchDeviceData()
{
    await Task.Run(() =>
    {
        //Read From all Devices;
    }
}

private async Task Process()
{
    if (!(await RDataBase.ProcessItem(Mem,Date)))
    //Update Record;
}

public static async Task<bool> ProcessItem(int Memb, int Date)
{
    return await Task.Run(() =>
    {
        try
        {
            //Array List = Read Device Info From DataBase
            return True;
        }
        catch
        {
            return false;
        }
    });
}

A: As I understood you want to process tasks in some order. Look at How to: Chain Multiple Tasks with Continuations

A: If you want to do all three operation in parallel you should use Task.WhenAll.
var task1 = this.FetchDeviceData(); //Read From Devices
var task2 = Task.Delay(2000);   //300000
var task3 = this.Process(); //Insert Into DataBase
await Task.WhenAll(new Task[]{task1,task2,task3 });

For More detail see this post.


text:
Q: Posts/Images overlapped when clicked on filter options and display in masonry view after window resize I've created a filter to display my posts popularity wise, style wise and
country wise.
Screenshots:
Screenshot 1: Working fine when page loads it shows all the posts/images properly in masonry.
Screenshot 2: When clicking on filter menus
By default, it shows the posts/images in a masonry grid view.
When I click on popular link/button, it shows the posts popularity-wise.
The problem is when I click on popular link/button, it is showing the posts/images but all of them are overlapped. And when I resize the page/window then it shows the posts/images in masonry view.
Here is the code:
JS:
jQuery(document).ready(function($) {

  // init Masonry
  var $grid = jQuery('#images').masonry({
  // options...
  itemSelector: '.item',
  isFitWidth: true,
  columnWidth: 1
  });

  // layout Masonry after each image loads
  $grid.imagesLoaded().progress( function() {
  $grid.masonry('layout');
  });

  jQuery("span.popularFilter").click(function(){
  var popular = jQuery(this).attr('data-slug');

  jQuery.ajax({
  url : ajaxurl,
  type : 'post',
  data : {
  action : 'post_popular_filter',
  popular_attr : popular
  },
  success : function( response ) {
  jQuery("#images").html(response);
  $grid.masonry('reloadItems')
  }
  });
  });

});

Please Help

A: Got the solution:
function masonaryGrid(){
setTimeout(function(){
$grid.masonry('reloadItems')
$grid.masonry('layout');
},true)
}

// init Masonry
var $grid = jQuery('#images').masonry({
// options...
itemSelector: '.item',
isFitWidth: true,
columnWidth: 1
});

// layout Masonry after each image loads
$grid.imagesLoaded().progress( function() {
$grid.masonry('layout');
});

jQuery("span.popularFilter").click(function(){
var popular = jQuery(this).attr('data-slug');

jQuery.ajax({
url : ajaxurl,
type : 'post',
data : {
action : 'post_popular_filter',
popular_attr : popular
},
success : function( response ) {
jQuery("#images").html(response);
masonaryGrid();
}
});
});


text:
Q: Discord.py bot won't connect to a voice channel I'm trying to make some basic music commands with my discord bot, but I can't seem to get the bot to connect to the vc. Here's the code I have tried:

    @commands.command(pass_context=True)
    async def join(self, ctx):
        channel = ctx.author.voice.channel
        if channel:
            print(channel.id)
            await channel.connect(reconnect=True)
        else:
            await ctx.send('bruh you arent in a vc')

Does anyone know why this isn't working? Also, here are my imports, in case they are the problem (for whatever reason):
import asyncio
import youtube_dl
import shutil
import ffmpeg
import os
from discord.utils import get
from discord.ext import commands
import discord
import datetime

If anyone knows the problem, and how I could fix it, I would greatly appreciate it.

A: Try to install: pip install discord.py[voice]
Maybe you have this problem: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice

A: EDIT:
Full Solution:
@client.command()
async def join(ctx):
    channel = ctx.author.voice.channel
    if channel:
        print(channel.id)
        await channel.connect(reconnect=False)
    else:
        await ctx.send('bruh you arent in a vc')

quick fix
change
async def join(self, ctx):

TO:
async def join(ctx):


text:
Q: Is it possible to make fixable errors/warnings with SwiftLint? I'm using SwiftLint to make custom errors and warnings and it's working well.
However, I want to add a "fix" button to the warnings and errors just like with standard Xcode errors and warnings.
Xcode already does this for the internal warnings/errors, like this:

Here's what my current custom warning looks like:

I've scoured through the documentation, tutorials, etc. and also opened an issue here:
https://github.com/realm/SwiftLint/issues/3315
I don't think it exists with SwiftLint, but I'd love to know if anybody can be prove me wrong or know of a better alternative!
P.S. Here's a link to their repo: https://github.com/realm/SwiftLint

A: Answered here by SwiftLint owners: https://github.com/realm/SwiftLint/issues/3315


text:
Q: Is there a way to get Process Ids of other 3rd party applications in Android...? I have a requirement in my project where in i have to kill process of 3rd party application.
As i know Android can have multiple application running at a time, so can i get all those Process
Ids some how...

A: This class will help you to kill processes:
http://developer.android.com/reference/android/os/Process.html
This gives you a list of currently running processes:
ActivityManager.getRunningAppProcesses();

The list contains ActivityManager.RunningAppProcessInfo objects which store the pid. You can then kill the processes via
Process.killProcess(pid);

You need the proper permissions to do that. Android should throw an exception if you try to kill a process without the proper permissions and tell you what permission you need.

A: check this way if it solves your purpose:
 ArrayList<PackageInfo> res = new ArrayList<PackageInfo>();
            PackageManager pm = context.getApplicationContext().getPackageManager();
            List<PackageInfo> packs = pm.getInstalledPackages(0);
            packs.get(pos).gids;
            packs.get(pos).sharedUserId;

A: You can get information about all running processes using ActivityManager. Refer following code:
    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> list = am.getRunningAppProcesses();
    for (RunningAppProcessInfo proc : list) {
        Log.v("Proccess", proc.processName + " : " + proc.pid);
    }

Multiple applications can be running in the same process, so it would be better to use RunninAppProcessInfo.pkgList over RunninAppProcessInfo.processName.


text:
Q: How can I use a weight matrix created by a trained neural network to make predictions in another file? I have trained a neural network classifier using keras, and it is currently predicting with 90% accuracy. I would like to make predictions on another file without having to include the entire model. Is it possible to make the predictions using just the output weight matrix? I.e, mathematically, how can I make the same classification using the weight matrix without having to re-train the model every time i get a new data input for which I need a classification prediction?

A: Save your model or the weights of your model:
model.save(filename)
np.save(filename, model.get_weights())

For loading, in the first case:
from keras.models import load_model
model = load_model(filename)

In the second case:
#recreate the model then:
model.set_weights(np.load(filename))

Then:
results = model.predict(batch_of_data)


text:
Q: Applying an unbiased estimator by using a linear function Let $X_1,...,X_n$ by a a sample from a Uniform Distribution $(0,\theta)$ where $\theta > 0$ is an unknown parameter.
How do I construct an unbiased estimator by applying a linear function to each of the sample mean $\bar{X}$ and nth order statics $X_{(n)}$.
I have calculated the Expectation and Variance of $\bar{X}$:
$E(\bar{X})=\frac{\theta}{2}$
$Var(\bar{X})=\frac{\theta^2}{12}$
I have calculated the Expectation and Variance of $X_{(n)}$:
$E(X_{(n)})=\frac{n}{n+1}\theta$
$Var(X_{(n)})=\frac{n}{(n+1)^2}\theta^2$

A: An estimator $\hat \theta$ of some parameter $\theta$ is unbiased if $$\operatorname{E}[\hat \theta] = \theta.$$  That is to say, the expected value of the estimator is equal to the parameter.  Since you found the expectation of the sample mean $\bar X$ is $$\operatorname{E}[\bar X] = \theta/2,$$ is there a constant that you can multiply $\bar X$ by that would change the right hand side to $\theta$?  Recall that $$\operatorname{E}[cX] = c \operatorname{E}[X]$$ for some fixed constant $c$.  Once you find this constant, then this will provide an estimator for $\theta$ that is based on the sample mean.
Similarly, for the maximum order statistic $X_{(n)}$, what could you multiply by?  Note here that $n$ is still a constant--it is presumed that the sample size is fixed and known, thus with respect to the expectation of a sample statistic, it is also constant.


text:
Q: Easiest way to drop all tables to run syncdb in Django? I keep making minor changes in my Django models. I don't care about the test data I keep adding, I just want to drop all tables (models) so I can run syncdb again. manage.py flush doesn't delete table schema, it just removes data.
Is there a quicker function in Django 1.6 to drop all tables?

A: 1) Django 1.6 is an unsupported Django version https://www.djangoproject.com/download/#supported-versions
you can see that Django 1.6 was supported until April 2015. So try to migrate to 1.8 LTS or 1.9 now and have migrations in your Django project or integrate South in your old Django app to have migrations http://south.readthedocs.org/en/latest/index.html
2) No there is not a quicker function in Django 1.6 (django-admin/manage.py command) that drop all tables. The more closer thing in this old versions is:
manage.py sqlclear appname
and put the output in your sql shell, maybe can work with pipe.
manage py sqlclear appname | manage.py dbshell
at least with MySQL works well.


text:
Q: Add different sequential numbers in combobox in access bases another combobox I'm trying to add a list a sequential numbers in combobox 2 based on the choice made in combobox 1. I have a table that defines how many numbers need to be displayed in combobox2 based on the items in combobox1. What I need to do is that if the number is 3, then it should display 1,2,3 but if the number is 5, it should display 1,2,3,4,5 and so on.
Is this possible ?

A: Yes, this is possible.
The two easiest ways are probably:
1) Set the RowSourceType to Value List
Then build the string
1;2;3;...;n

in VBA and assign it to the RowSource Property.

2) Create and populate a Number Table (a single INT column, with values 1..n).
Set the RowSourceType to Table/Query
Set this RowSource:
SELECT NumCol FROM NumberTable
WHERE NumCol <= [Combobox1].Value

so it will show the first x entries.


text:
Q: AMD Raid and Dual Boot I've just upgraded my PC with a new Ryzen processor and a B550M Motherboard. I use this computer for both gaming (in a Windows-dedicated SSD) and working (in another Linux-dedicated SSD). I also have 2 1TB HDDs that I use for mass storage.
Since this new motherboard offers me the "AMD Raid" feature, I decided to combine the 2 HDDs in one RAID-0 array, for increased write/read speeds. The final disk arrangement was like this:

Array
Disks
Raid type

Array 0
Windows SSD
No raid

Array 1
Linux SSD
No raid

Array 2
HDD 0 + HDD 1
RAID 0

After a clean install, I can easily boot into the Array 0 to Windows, where I can easily use both Arrays 0 and 2.
The problem is: I want to dual-boot into Array 1, where I'd have the Linux OS and also access to the Array 2.
It seems that AMD Raid boots to the first array, but I can't find an option to change the Array order in the BIOS setup.
I couldn't find any reference to help me in this situation. Could anyone here point me to the right path, please?


text:
Q: Superlative version or synonym of "Versatile" I'm looking for comparative/superlative versions of versatile - synonyms which should mean "more versatile" and "extremely versatile"
Here's the background:
Over on meta.so, I've proposed a new 3-tiered badge for users who have high rep across multiple SE sites.
At bronze I'd call it Versatile.
Can't think of titles for Silver and Gold.
I only have "Multifaceted" and "All-rounder" right now.
Any other suggestions?

A: *

*polymath

*sage

*Da Vinci

*Renaissance Man (Person?)

*homo universalis

*swiss army knife

*protean

A: Some synonyms (positive, comparative or superlative) and related nouns:

*

*well-rounded

*multifaceted

*multitalented

*resourceful

*Jack of many trades (possibly bronze/silver)

*Master of many trades (possibly gold)

*handy

A: Beyond inventing a word like "versatilitudinous", the best ideas I can come up with are "multitalented", "well-rounded", and "Jack-of-all-trades".

A: "Jack of all trades" could be a good bronze.  Like many bronze badges, it's not an unqualified complement; it has the desired connotation of "good at a lot of things", but the implicit "…and master of none" keeps open the motivation to push on to the silver or gold.


text:
Q: SwiftUI - Regresar a una vista determinada tras realizar una acción Necesito volver a la vista inicial de mi APP tras realizar un onLongTapGesture { } en un elemento de una List{ }.
Detallo algo más, tengo una lista con información recogida mediante una petición GET a una API. Esa información la listo mediante el componente List {} de SwiftUI.
Al pulsar sobre un elemento, de la lista, la información que contiene se almacena en una base de datos y desaparece del listado.
Lo que me gustaría implementar sería una funcionalidad que volviese a una determinada vista tras el evento onLongTapGesture{ }.
Gracias

A: Solución:

*

*Dentro del struct:
@State private var goToView: Bool = false

*Dentro del View:
NavigationLink(destination: RepositoriosListView(), isActive:
   self.$goToView) { EmptyView() }

*En el evento:
onLongPressGesture {
// Agrego a la base de datos local lo que necesito
self.goToView.toggle()
}


text:
Q: How to get recyclerView getItemCount - position start from 2 instead of 0 I'm trying to connect my recyclerview two different mutableArray and one textView.
It works correctly instead of override fun getItemCount() starts from position 0 instead of 2. All data comes from firestore and is called in MainActivity class
In position 0 i have own adapter for newList and it works correctly, in position 1 i have textview and it works correctly. In position 2 i want to start this flowerList but for somereason it miss 2 first items from my flowerList.
So my question is how i can make my
override fun getItemCount(): Int {
   return flowerList.size
}

To start from position 2 instead of position 0
Here is my full code for that adapter:
class MainAdapter(val flowerList: MutableList<Flowers>, val newsList: MutableList<News>, val context: Context) : RecyclerView.Adapter<MainAdapter.ViewHolder>() {

    private val TYPE_NEWS_LAYOUT = 0
    private val TYPE_TITLE_LAYOUT = 1
    private val TYPE_FLOWERS_LAYOUT = 2

    override fun onCreateViewHolder(parent: ViewGroup, position: Int): ViewHolder {
        if (position == TYPE_NEWS_LAYOUT) {
            val newsFeed = LayoutInflater.from(parent.context).inflate(R.layout.main_horizontal_recycler, parent, false)
            return ViewHolder(newsFeed)

        } else if (position == TYPE_TITLE_LAYOUT) {
            val textView = LayoutInflater.from(parent.context).inflate(R.layout.item_main_text_recycler, parent, false)
            return ViewHolder(textView)

        } else {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_main_bottom_recycler, parent, false)
            return ViewHolder(view)
        }
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        if (position == 0) {
            holder.itemView.main_top_recycler_horizontal.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            holder.itemView.main_top_recycler_horizontal.adapter = MainHorizontalAdapter(newsList)
        } else if (position == 1) {
            holder.middleTitle.text = "Text here"
        } else {
            val flower = flowerList[position]
            holder.flowerName.text = flower.flowername
            Glide.with(context).load(flower.mainimageurl).into(holder.flowerImage)
        }
    }

    override fun getItemViewType(position: Int): Int {
        if (position == 0) {
            return TYPE_NEWS_LAYOUT
        } else if (position == 1)
            return TYPE_TITLE_LAYOUT
        else
            return TYPE_FLOWERS_LAYOUT
    }

    override fun getItemCount(): Int {
        return flowerList.size
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val flowerName = view.flower_name
        val flowerImage = view.flower_image
        val middleTitle = view.main_recycler_title
    }
}

A: Incrementing a counter is going to be a problem because onBindViewHolder gets called every time the view gets recycled. Instead, I think you want to change the line
FROM:
val flower = flowerList[position]
TO:
val flower = flowerList[position - 2] // subtracting two, to account for the first two positions, in the adapter, that are your News and Title views


text:
Q: read csv without using import csv read csv without using  import csv in python
"name","sem","math","physics","chemistry"
"devendran","1,2,3","90","90","90"
"devendran","4","99","88","77"
expected output is
{'name': 'devendran', 'sem': '1,2,3', 'math': '90', 'physics': '90', 'chemistry': '90'}
{'name': 'devendran', 'sem': '4', 'math': '99', 'physics': '88', 'chemistry': '77'}

A: Only complication is you want to split on commas except within quotes without using CSV (and I assume other external modules)

*

*You can use pure Python function tokenize from Split by comma and how to exclude comma from quotes in split
Code
def tokenize( string, separator = ',', quote = '"' ):
    """
    Split a comma separated string into a List of strings.

    Separator characters inside the quotes are ignored.

    :param string: A string to be split into chunks
    :param separator: A separator character
    :param quote: A character to define beginning and end of the quoted string
    :return: A list of strings, one element for every chunk
    """
    comma_separated_list = []

    chunk = ''
    in_quotes = False

    for character in string:
        if character == separator and not in_quotes:
            comma_separated_list.append(chunk)
            chunk = ''

        else:
            chunk += character
            if character == quote:
                in_quotes = False if in_quotes else True

    comma_separated_list.append( chunk )

    return comma_separated_list

# Read file 'test.txt'
with open('test.txt', 'r') as f:
    result = []
    for i, line in enumerate(f):
        line = line.rstrip()           # remove trailing '\n'
        line = tokenize(line)          # split on "," except for quotes
        if i == 0:
            header = line              # header row
        else:
            # Dictionary comprehension for header, value pairs
            result.append({h:l for h, l in zip(header, line)})

    print(*result, sep = "\n")

Output
{'"name"': '"devendran"', '"sem"': '"1,2,3"', '"math"': '"90"', '"physics"': '"90"', '"chemistry"': '"90"'}
{'"name"': '"devendran"', '"sem"': '"4"', '"math"': '"99"', '"physics"': '"88"', '"chemistry"': '"77"'}

File: test.txt
"name","sem","math","physics","chemistry"
"devendran","1,2,3","90","90","90"
"devendran","4","99","88","77"


text:
Q: What prevents a hacker from publishing a newer version of a package to NPM? What prevents a hacker from cloning a NodeJS repo from github, adding some malicious code, incrementing the version as a patch, and running npm publish?
It doesn't look like the NPM docs say anything about authenticating the identity of the person running npm publish.
I cloned a repo and incremented the version and ran npm publish --dry-run and it didn't complain that it wouldn't publish.

A: NPM does restrict who can push code to your published package, but that's not to say someone can't do this without your knowledge. There's been a few cases so far where stolen credentials have presumably been employed.
You could experiment by creating a package, then attempt to push to it from another computer without the necessary credentials. You'll see what measures are in place to prevent that.


text:
Q: Union of two bounded sets is bounded Suppose $(X,d)$ is a metric space, for a nonempty subset $A$ of $X$, define
$$ \delta(A) = \sup_{x, y \in A} d(x,y) $$
$A$ is bounded if $\delta(A) < \infty $. If $A$, $B$ are bounded, does it follow that $A \cup B$ is bounded ? I know that $A \cap B$ is bounded since $A \cap B \subseteq B$, and the fact that $A \subseteq B \implies \delta(A) \leq \delta(B) $. But how about the $\cup$ ?
thanks

A: Let's $a\in A$ and $b\in B$ be fixed. Take any $x\in A , y\in B$, then $$d(x,y) \leq d(x,a ) +d(a,b) +d(b,y) \leq \delta (A) +d(a,b) +\delta (B)$$
thus $A\cup B$ is bounded.

A: And, in order to prove David Mitra's answer, you should:

*

*Use the triangle inequality .

*Convince yourself of the following fact:

$$
\mathrm{sup}_{x\in A,y\in B} \left\{ x + y\right\} \leq \mathrm{sup}_{x\in A} \left\{ x \right\} + \mathrm{sup}_{y\in B} \left\{ y\right\} \ .
$$
EDIT. And the second inequality comes from the fact that, for all $x\in A$ and all $y\in B$, you have
$$
x + y \leq \mathrm{sup}_{x\in A} \left\{ x \right\} + \mathrm{sup}_{y\in B} \left\{ y\right\} \ .
$$
Now, apply $\mathrm{sup}_{x\in A,y\in B}$ to both sides of this inequality and you are done.
Exercise. Why don't you have, in general, an equality
$$
\mathrm{sup}_{x\in A,y\in B} \left\{ x + y\right\} = \mathrm{sup}_{x\in A} \left\{ x \right\} + \mathrm{sup}_{y\in B} \left\{ y\right\} \quad \text{?}
$$
:-)

A: I would reason as follows:
$$\delta(A\cup B)=\sup(\delta(A),\delta(B),\sup_{a\in A, b\in B}d(a,b))$$
Since $A$ and $B$ are bounded, then, by definition, $\delta(A) < \infty$ and $\delta(B) < \infty$. One of the axioms of metric spaces (Kreyszig, 1978, page 3, axiom (M1)) is: "$d$ [the metric] is real-valued, finite and nonnegative". Therefore, $\sup_{a\in A, b \in B}d(a,b) < \infty$, so it follows that $\delta(A \cup B) < \infty$, which means that $A\cup B$ is bounded.


text:
Q: when admin updates user profile how to access that obj in views and perform some task in django when admin updates user profile how to access that  obj in views and perform some task in django
i have user model and when user creates new account  by default his id is deactivated but when admin activate their account from admin panel by change the user model field "is_active" to True
the i want to send that user an email and some other task also
so how to get that user's object
that activated by admin


text:
Q: How to check if a foreign-key is part of a many-to-many in the same model? Here is a simplified version of my model:
class Group(models.Model):
    creator = models.ForeignKey(User, related_name='group_creator')
    members = models.ManyToManyField(User, through='Membership')

    def clean(self):
        if self.creator not in self.members.all():
            raise ValidationError('Creator should be part of this group.')

When I perform a full_clean() on an new instance of my model, it raises this Exception.
ValueError: 'Group' instance needs to have a primary key value before a many-to-many relationship can be used.

I know it comes from my clean() method, but I can't figure out why I get this error. I've seen people having the same trouble as me, but never in their own model.
Any idea how to solve this?
Apologies for my english, it's pretty poor, I know. Maybe that's why I can't figure this out.

A: You can't check self.members.all() when the object has not been saved yet. It needs a primary key before it can lookup relationships to itself in the join table.
What you should be checking is self.cleaned_data['members'].


text:
Q: Python map() function iterates over 'None' element I wrote a simple map() function that iterates over a list and prints as many '*' that are in the list. I see a small problem with my code, I see an extra 'None' in my output. Could someone help me debug this issue?
Problem Statement:
-----------------
Define a procedure histogram() that takes a list of integers and prints a
histogram to the screen. For example, histogram([4, 9, 7]) should print the
following:

****
*********
*******

Source Code
def print_asterisks(num):
    print ''.join('*' for i in xrange(num))

def histogram(s):
    map(print_asterisks, s)

def main():
    # Test inputs
    print histogram([4,7,5])

if __name__ == "__main__":
    import sys
    sys.exit(main())

Output
****
*******
*****
None

A: In this line:
print histogram([4,7,5])

You are printing the return value of the histogram function, which is None.  You only need to call the function:
histogram([4,7,5])

A: Since the function histogram isn't returning anything. print histogram([4,7,5]) prints None.
def print_asterisks(num):
    print ''.join('*' for i in xrange(num))

def histogram(s):
    map(print_asterisks, s)

def main():
    # Test inputs
    histogram([4,7,5])

if __name__ == "__main__":
    import sys
    sys.exit(main())

Output:
****
*******
*****

A: Replace
def main():
    # Test inputs
    print histogram([4,7,5])

with
def main():
    # Test inputs
    histogram([4,7,5])

Note: the function histogram doesn't have any return statement.

A: write histogram([4,7,5]) instead print histogram([4,7,5])
def print_asterisks(num):    print ''.join('*' for i in xrange(num))def histogram(s):    map(print_asterisks, s)def main():    # Test inputs    histogram([4,7,5])if __name__ == "__main__":    import sys    sys.exit(main())


text:
Q: Updating Merge Field twice but its taking merge field value updated first time
*

*Creating envelope in draft status and adding recipient while creating.

*Using embedded view for the recipient and on visit updating recipient details like name, email, title and custom merge field.
Performing API call in below sequence.

a. Update Recipient:
PUT
{
  "signers": [
    {
      "routingOrder": "1",
      "roleName": "Signer 1",
      "recipientId": "1",
      "name": "John Doe",
      "email": "test@gmail.com"
    }
  ]
}

b. Update Custom Tag
PUT
{
  "titleTabs": [],
  "textTabs": [
    {
      "value": "VP, Finance Test Updated 1",
      "tabLabel": "ContactTitle",
      "tabId": "TABID",
      "recipientId": "1"
    }
  ]
}

c. Add Custom Field
POST
{
  "textCustomFields": [
    {
      "value": "**0031a00000hi8rsAAA**",
      "show": "true",
      "required": "true",
      "name": "**Contact**",
      "errorDetails": null,
      "configurationType": "salesforce"
    }
  ]
}

d. Send Envelope (Update Status to sent if it is in draft status)
PUT
{
  "status": "sent"
}

*The user doesn't sign but just close the browser window.

*Now different user visits the DocuSign embedded URL as the signer. Then following API call takes place.
a. Update Recipient:
PUT
{
  "signers": [
    {
      "routingOrder": "1",
      "roleName": "Signer 1",
      "recipientId": "1",
      "name": "John Doe",
      "email": "test@gmail.com"
    }
  ]
}

b. Update Custom Tag
PUT
{
  "titleTabs": [],
  "textTabs": [
    {
      "value": "VP, Finance Test Updated 2",
      "tabLabel": "ContactTitle",
      "tabId": "TABID",
      "recipientId": "1"
    }
  ]
}

c. Add Custom Field
POST
{
  "textCustomFields": [
    {
      "value": "**0031a00000hixyzAAA**",
      "show": "true",
      "required": "true",
      "name": "**Contact**",
      "errorDetails": null,
      "configurationType": "salesforce"
    }
  ]
}

*This user updates the merge field present in the document which is linked with Salesforce contact's title field and sign envelope. Docusign updates record which is updated in 2.c instead of final custom field I.e when user sign which is updated in 4.c

*When I perform rest call to see the custom fields present in envelope, it shows record id updated in 4.c
Can you please let me know what would be the issue?


text:
Q: Disable prevent Dropbox from Auto updating (via BITS) on Windows & roll back to last stable bug free version(s)? https://apple.stackexchange.com/questions/173890/can-i-stop-dropbox-from-automatically-updating-itself-on-os-x
How can I disable Dropbox from updating itself and start creating sync issues (as are happening right now) on Windows 8.1?
And how do I install and rollback to last stable version (now & later as well)?

*

*PS: This time luckily I downloaded a week old version from here:
http://www.filehorse.com/download-dropbox/old-versions/

*Not sure if it will resolve the issues, but we might have to think of a way of keeping/ archiving last few downloaded releases.

Found this, Stop DropBox for Windows desktop syncing when on metered wireless connection
but Prefer something other than a 3rd party Firewall to block its auto updates.
Any local tweaks/ permissions/ Group Policy related mechanism(s) / ideas?
Bonus: Ideally, I'd like to start with my machine and then be able to scale/ implement this solution across a small network of machines on a Domain.

A: In short, there is no way to stop Dropbox from updating itself.
When it is running, it will constantly check for updates.
When it is not running, two task scheduler tasks (in Windows) will run at login and once a week to check for updates. But even if you disable these tasks, simply running the app will cause it to look for updates.
This fact, combined with the fact that Dropbox refuses to publish a changelog for updates, makes Dropbox a very suspect danger. In any other context, this behavior is more akin to malware than a legitimate application.
Yes, Dropbox is probably not doing unsavory things with your PC, but you have no control over what Dropbox does to your PC, and that is wrong.

A: Blocking in firewall the following processes might do the trick of preventing the automatic updates:

*

*the Dropbox service:
 C:\Windows\System32\DbxSvc.exe

*the update client:
 C:\Program Files(x86)\Dropbox\Update\Install{some_uuid}\DropboxClient_xx.x.xx.exe
Let pass the Dropbox.exe process for the sync to work. Probably after a while will alert you to update within a certain amount of days, to still be able to use it.

A: Windows already offers Task Scheduler, which can edit triggers and conditions for each task, including the two DropboxUpdate… tasks. Just run as Administrator and reschedule each task or alter the conditions when each starts—such as on plug-power and idle.
Using the tool Windows itself uses to schedule Tasks leaves everything more reliable, rather than install an additional tool that leaves one component on your machine fighting another.
To find "Task Scheduler", just search Windows using the onebox, and run as Administrator.


text:
Q: How to import module with ambiguous name from PYTHONPATH? I am doing
sys.path.append(dst)

where dst contains common.py and want to import it. Unfortunately, I already have common module with another code. Is there a way to solve ambiguity?

More exact question is how to allow premade module, which imports module of ambiguous name (import common) to work inside premade context, which already has another module with the same name (common).