text:
Q: The reason why these prepositions here are used and why "be" form is used in this youtube information passage

sentence A: Many YouTube videos will play using HTML5 in supported browsers.
sentence B: You can request that the HTML5 player be used if your browser doesn't use it by default.

Hello.
The above passage is from a youtube page.
I made the words bold which I am about to ask about.
I have 3 question about that passage.
Question 1)
In the sentence A, doesn't the part "using~" mean a method or a way of playing?
Then, why is "by using" not used instead of "using" there?
Question 2)
In the sentence B, why is "be" used instead of just "is"?
Is there any word omitted before "be", for example, "should" or "may"?
I wish to get an explanation about this.
Question 3)
In the sentence B, why is "by" used before "default"?
I think "as" or "for" are much more appropriate to it.
Or all of them are usuable here?
P.S.
I always thank you so much for your sincere, brilliant helps.
Even a very short, simple explanation is very helpful to me.

A: *

*Either using or by using would work here. In this case, the whole phrase "using HTML5 in supported browsers" acts as an adverb modifying play. Adverbs answer the question, "How?" In other words, this sentence is saying

"How will the video play?"
"Using HTML5 in supported browsers."

*This is an example of the (somewhat rare) subjunctive mood in English. It is often used when expressing a desire, hope, hypothetical scenario, etc.

E.g. (subjunctive in bold):

"I wish that I were taller."
"He insisted that I be quiet."

*"By default" is an idiomatic phrase. "For default" or "as default" are arguably also okay, but they sound weird because they are not idiomatic.


text:
Q: EF Core design in console application I'm having hard time wrapping my head around on how to properly design my models in a console application while still trying to take advantage of EF core. For a bit more context, in a ASP.NET project you mostly only have to deal with a single request and is more "isolated" while the console application can grow infinitely more complex by having to maintain state and keep track of data.
For example, lets have a GameInstance which represents the current state of a game with active players connected to it. When the game starts, its state is loaded from a database using GameEntity model. While the game progresses, we need to save its state.
The first thing that comes to mind is to structure the following as:
public class GameInstance
{
    private int Id { get; }
    public string Name { get; private set; }
    public string Description { get; private set; }
    public int Score { get; private set; }

    private List<NetworkConnection> connectedClients;

    public GameInstance(GameModel model)
    {
        this.Id = model.Id;
        this.Name = model.Name;
        this.Description = model.Description;
        this.Score = model.Score;
    }

    public void SetDescription(string description)
    {
        using (DbContext db = new DbContext())
        {
            GameModel model = new GameModel()
            {
                Id = this.Id,
                Description = this.Description
            };

            db.Attach(model);

            model.Description = description;

            db.SaveChanges();
        }

        this.Description = description;
    }
}

public class GameModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int Score { get; set; }
}

But the drawback is pretty clear. All changes made require the database model to be reconstructed constantly which looks clumsy. Its also not great for allocations.
The second option is to store the GameModel inside the GameInstance and redirect the properties directory to the model itself. All changes can now be done directly to the model itself. Keeping the model around sounds more appealing but feels wrong.
The third option is to just have one class, the GameInstace and then configure EF core using the fluent API to do the right thing. This simplifies this scenario a lot and all changes can be done directly to the used instance. However, now you might need to introduce some database specific fields to the instance itself and the mix of properties required to keep track of the state. It feels like the single responsibility principle starts get cracks here. Also it makes it more difficult to use domain based architecture.
When dealing with REST requests in ASP.NET the user input comes in its own model like RequestModel. Then that is used to query the database to retrieve DatabaseModel and the required changes are done with the data from the request. Then the response is send with ResponseModel and all the objects can now be discarded and the single responsibility holds. It feels like EF core fits here perfectly. I don't feel the same with my console application.
How could I apply EF core to the console application cleanly? Am I missing something obvious? Am I overthinking this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems with Sidebars and #pusher in Semantic UI Please, help me with this issue.
I have a sctructure.

...

...

...

...

...

When I am clicking on toggle button, I am having problems... Semantic-ui puts all divs to #pusher without #ls and top fixed menu.
Administration toolbar is invisible, because is inside #pusher.
I don't want #rs and toolbar inside #pusher.

...

    Skip to main content

  ...

  ...

...

How can I solve this problem?
Thanks!!!

A: I see you have two divs named "ls", I assume the second one was meant to be called "rs", that would be why it is moved into #pusher

A: We needs add class "Pusher" instead id. Thats all.


text:
Q: Solving simple decision-making model over multiple periods Consider the following model.
Each period t=0,1,..., an agent makes an effort $x\in R_+$ to solve a problem. The value from solving the problem is $V>0$. The relationship between effort and problem solving is stochastic. So for any effort $x$ the probability of solving the problem is $p(x)$ (which is strictly increasing in $x$). And there is a cost associated with effort $c(x)$ (which is a quadratic function increasing in $x$). If the effort fails in one period, the agent can try anew in the next period (effort in one period does not affect the probability of success in the next). However, there is a discount factor $\delta\in(0,1)$ such that the agent may prefer to solve the problem now to solve it later.
If so, the decision problem at each period $t$ would be:
$$ \max_{x_t \in R} U = p(x) \cdot V - c(x) + (1-p(x))\cdot \delta \cdot U $$
where $U$ denotes the present value of the future payoffs of the agent.
What the agent should do to solve this problem optimally?


text:
Q: Generating binary variables in Pig I am newbie to the world of Pig and I need to implement the following scenario.
problem:
    Input to pig script: Any arbitrary relation say as below table
    A   B   C
    a1  b1  c1
    a2  b2  c2
    a1  b1  c3

we have to generate binary columns based on B,C so my output will look something like this.
output

    A   B   C   B.b1    B.b2    C.c1    C.c2        C.c3
    a1  b1  c1  1        0       1       0       0
    a2  b2  c2  0        1       0       1       0
    a1  b1  c3  1        0       0       0       1

Can someone let me know how to achieve this in pig? i know this can be easily achieved using R script but my requirement is to achieve via PIG.
Your help will be highly appreciated.

A: Can you try this?
input
a1      b1      c1
a2      b2      c2
a1      b1      c3

PigScript:
X = LOAD 'input' USING PigStorage() AS (A:chararray,B:chararray,C:chararray);
Y = FOREACH X GENERATE A,B,C,
                       ((B=='b1')?1:0) AS Bb1,
                       ((B=='b2')?1:0) AS Bb2,
                       ((C=='c1')?1:0) AS Cc1,
                       ((C=='c2')?1:0) AS Cc2,
                       ((C=='c3')?1:0) AS Cc3;
DUMP Y;

Output:
(a1,b1,c1,1,0,1,0,0)
(a2,b2,c2,0,1,0,1,0)
(a1,b1,c3,1,0,0,0,1)


text:
Q: Expected number of cycles in random function Let f be a left-total function with a discrete domain and codomain both in the range of 0..N. The image of f is chosen randomly (with replacement). Given N, how many cycles is the function expected to contain?
Edit: Here's the code
from random import randint

def test(N):
    """Returns all cycles for a function over 0..N-1"""
    edges = [randint(0,N-1) for n in range(N)]

    cycles = []

    def cycle(start):
        """Find a cycle from a given start point"""
        current = start
        lst = []
        while True:
            if current in lst:
                lst = lst[lst.index(current):]
                break
            lst.append(current)
            current = edges[current]
        return lst

    # For every edge from domain to codomain:
    # append the cycle to the list if it isn't contained already
    for e in edges:
        c = cycle(e)
        #if c is not None:
        srt = sorted(c)
        if not srt in cycles:
            cycles.append(srt)

    #Print function
    #for i,e in enumerate(edges):
    #    print(f"{i} -> {e}")

    # Print N and the number of cycles in this function
    #print(N, cycles)

    return len(cycles)

# Get the average number of cycles for N=1..200
for n in range(1,200):
    avg = []
    # 1000 random functions of size N
    for i in range(1000):
        avg.append(test(n))
    #print(avg)
    print("%i\t%f" % (n, sum(avg)/len(avg)))

With values:
1   1.000000
10  1.966000
20  2.191000
30  2.356000
40  2.573000
50  2.635000
60  2.742000
70  2.762000
80  2.932000
90  2.851000
100 3.002000

A: Let $a_n$ denote the expected number of cycles in a random endofunction on a set of $n$ elements. Marko Riedel has already posted the derivation of the asymptotic result $a_n\sim\frac12\log n$ by P. Flajolet and A. Odlyzko in a comment. Here I'll also derive the constant term, and I'll use Prüfer sequences instead of generating functions, so you can choose the proof that's more accessible for you.
Joyal's proof of Cayley's formula for the number of labeled trees with a given number of vertices makes use of a correspondence between endofunctions and vertebrates. A vertebrate is a tree with an ordered pair of (possibly identical) vertices distinguished. The name is based on the idea that the unique path in the tree connecting the two distinguished vertices forms a sort of spine of the tree.
An endofunction can be viewed as a family of rooted trees, where the roots are the elements contained in cycles. A vertebrate can also be viewed as a family of rooted trees, where the roots are the elements along the spine. There are $k!$ possible orders of the $k$ elements along the spine, and $k!$ possible permutations specifying the endofunction on the $k$ elements contained in cycles, so there are as many endofunctions with $k$ cyclic elements as there are vertebrates with spine length $k$.
To count the vertebrates with spine length $k$, label the vertices $1$ through $n$ and fix the spine to be $n,n-1,\ldots,n-k+2,m$, in that order, with $m\lt n-k+2$ arbitrary. Then the last $k-2$ elements of the Prüfer code for the vertebrate are $n-k+2,\ldots,n-1$, and the element before that is one of the $k$ elements on the spine; the remaining $n-k-1$ elements of the Prüfer code can be chosen arbitrarily. We also need to multiply by $\frac{n!}{(n-k)!}$ because we arbitrarily fixed the $k$ elements on the spine, so the number of vertebrates with spine length $k$ (and thus the number of endofunctions with $k$ cyclic elements) is
$$
kn^{n-k-1}\frac{n!}{(n-k)!}=(n-1)!\frac{kn^{n-k}}{(n-k)!}\;.
$$
The endofunction permutes the $k$ cyclic elements with some permutation on $k$ elements. The expected number of cycles in a uniformly random permutation on $k$ elements is $H_k=\sum_{j=1}^k\frac1j$, the $k$-th harmonic number. (This is proved e.g. here.)
Thus, the expected number of cycles in a uniformly random endofunction is
$$
a_n=\frac{\sum_{k=1}^n(n-1)!\frac{kn^{n-k}}{(n-k)!}\sum_{j=1}^k\frac1j}{\sum_{k=1}^n(n-1)!\frac{kn^{n-k}}{(n-k)!}}\;.
$$
The denominator is of course simply the total number $n^n$ of endofunctions. Exchanging the summations yields:
\begin{eqnarray*}
a_n&=&n^{-n}\sum_{k=1}^n(n-1)!\frac{kn^{n-k}}{(n-k)!}\sum_{j=1}^k\frac1j
\\&=&
(n-1)!\sum_{j=1}^n\frac1j\sum_{k=j}^n\frac{kn^{-k}}{(n-k)!}
\\
&=&
n!\sum_{j=1}^n\frac1j\frac{n^{-j}}{(n-j)!}\;.
\end{eqnarray*}
The last equality is provided by Wolfram|Alpha; I haven't tried to prove it, but if you're interested I suspect there's a nice combinatorial argument for it.
I doubt this can be simplified further, but we can derive an upper bound and an asymptotic result from it.
For the upper bound, note that $\frac{n!n^{-j}}{(n-j)!}\le1$, so $a_n\le\sum_{j=1}^n\frac1j=H_n=\log n+\gamma+o(1)$, where $\gamma$ is the Euler–Mascheroni constant.
For the asymptotics, I won't rigorously derive the order of the approximations, but the result should be correct up to terms of order $o(1)$.
We have
\begin{eqnarray*}
a_n
&=&
n!\sum_{j=1}^n\frac1j\frac{n^{-j}}{(n-j)!}
\\
&=&
\sum_{j=1}^n\frac1j\prod_{k=0}^{j-1}\frac{n-k}n
\\
&=&
\sum_{j=1}^n\frac1j\prod_{k=0}^{j-1}\left(1-\frac kn\right)
\\
&=&
\sum_{j=1}^n\frac1j\exp\left(\sum_{k=0}^{j-1}\log\left(1-\frac kn\right)\right)
\\
&\approx&
\sum_{j=1}^n\frac1j\exp\left(-\sum_{k=0}^{j-1}\frac kn\right)
\\
&=&
\sum_{j=1}^n\frac1j\exp\left(-\frac{j(j-1)}{2n}\right)
\\
&\approx&
\sum_{j=1}^\infty\frac1j\exp\left(-\frac{j(j-1)}{2n}\right)\;.
\end{eqnarray*}
Thus we want to sum the harmonic series, damped by a Gaussian. This is hard to do directly because of the smooth transition from the discrete behaviour for small $j$ that we need to sum exactly to the approximately continuous behaviour for large $j$ that we could approximate with an integral. To deal with these two domains separately, we can introduce an intermediate term with a simple exponential that we can sum exactly:
\begin{eqnarray*}
a_n&\approx&\sum_{j=1}^\infty\frac1j\exp\left(-\frac{j(j-1)}{2n}\right)
\\
&=&
\sum_{j=1}^\infty\frac1j\exp\left(-\frac j{\sqrt{2n}}\right)+\sum_{j=1}^\infty\frac1j\left(\exp\left(-\frac{j(j-1)}{2n}\right)-\exp\left(-\frac j{\sqrt{2n}}\right)\right)\;.
\end{eqnarray*}
The first sum is the integral of a geometric series:
$$
\sum_{j=1}^\infty\frac{q^j}j=\int_0^1\sum_{j=1}^\infty q^{j-1}\mathrm dq=\int_0^1\frac1{1-q}\,\mathrm dq=-\log(1-q)\;,
$$
and
$$
-\log\left(1-\exp\left(-\frac1{\sqrt{2n}}\right)\right)\approx\log\sqrt{2n}=\frac12(\log n+\log2)\;.
$$
The summand in the second sum has no singularity at $j=0$ and varies smoothly, so we can approximate it by an integral over $x=\frac j{\sqrt{2n}}$:
\begin{eqnarray*}
a_n&\approx&\frac12(\log n+\log2)+\int_0^\infty\frac1x\left(\mathrm e^{-x^2}-\mathrm e^{-x}\right)\mathrm dx
\\
&=&\frac12(\log n+\log2+\gamma)\;,
\end{eqnarray*}
where the last equality is again provided by Wolfram|Alpha.
A plot of the exact values against $\log n$, compared to the linear asymptote, confirms the asymptotic result:

P.S.:
We can use the same method to obtain an asymptotic result for the expected length of the cycle that a uniformly random element in a uniformly random endofunction leads to. The element is equally likely to lead to any one of the cyclic elements, so the expected length of the cycle is the expected length $\frac{k+1}2$ of the cycle containing a random cyclic element:
$$
n^{-n}\sum_{k=1}^n(n-1)!\frac{kn^{n-k}}{(n-k)!}\cdot\frac{k+1}2=\frac12+\frac{n!}{2n}\sum_{k=1}^n\frac{k^2n^{-k}}{(n-k)!}\;.
$$
Here we don't have any complication due to a singularity at the origin, and we can directly approximate the sum by an integral over $x=\frac k{\sqrt{2n}}$ as above, yielding
$$
\frac{n!}{2n}\sum_{k=1}^n\frac{k^2n^{-k}}{(n-k)!}\approx\frac1{2n}(2n)^{\frac32}\int_0^\infty x^2\mathrm e^{-x^2}\mathrm dx=\sqrt{\frac{\pi n}8}\;.
$$
I didn't include the constant term $\frac12$ because the approximations also contribute a constant term; the correct constant term seems to be $\frac13$. Here's a log-log plot of the exact values compared to the asymptote $\sqrt{\frac{\pi n}8}$ and to $\sqrt{\frac{\pi n}8}+\frac13$:

So the expected number of cycles is of order $\log\sqrt n$, compared to $\log n$ for permutations, and the expected length of the cycle containing a random element is of order $\sqrt n$, compared to $n$ for permutations.
The number $k$ of cyclic elements is directly related to the expected length $\frac{k+1}2$ of the cycle containing a random element, so its expected value is asymptotically $\sqrt{\frac{\pi n}2}$, as also derived in the paper by Flajolet and Odlyzko.


text:
Q: Is it possible to use the same OpenGL context between top-level windows in Qt? I'm developing an editor in Qt that will have multiple GL contexts running simultaneously in multiple top-level windows. Since VAOs can't be shared between contexts, I'm trying to come up with a way to manage them on a per-context basis, which is proving to be fairly complicated.
It would be a lot simpler if I could just simply use the same context between both, but this doesn't seem to be possible with Qt 5.4. QGLWidget was able to explicitly take a QGLContext pointer as a constructor parameter, but there's no corresponding function for QOpenGLWidget. This is what the documentation says about context sharing:

When multiple QOpenGLWidgets are added as children to the same top-level widget, their contexts will share with each other. This does not apply for QOpenGLWidget instances that belong to different windows.

Is there a way around this?
I can't find too much info on the subject unfortunately, since QOpenGLWidget is relatively new - most of what I can find is talking about QGLWidget.
edit: I'm trying some different things and I've had a little bit of success creating a custom GL widget so I can manage the contexts myself, although there's some bad bugs. However it's sounding like it's actually required to have different contexts for different windows in some cases, which would mean I should just stick with QOpenGLWidget and come up with a VAO-management system. It would be cool if someone with more knowledge/experience on the subject could explain how this works though.

A: From the QOpenGLWidget documentation:

To set up sharing between QOpenGLWidget instances belonging to
  different windows, set the Qt::AA_ShareOpenGLContexts application
  attribute before instantiating QApplication. This will trigger sharing
  between all QOpenGLWidget instances without any further steps.

According to the Application Attribute documentation, this flag was introduced in version 5.4


text:
Q: Simplify $\frac{1}{1\times2\times3} + \frac{1}{2\times3\times4} +\frac{1}{3\times4\times5}+\cdots+\frac{1}{n(n+1)(n+2)}$ This is a very interesting word problem that I came across in an old textbook of mine. So I know its got something to do with sequencing and series, which yields the shortest, simplest proofs, but other than that, the textbook gave no hints really and I'm really not sure about how to approach it. Any guidance hints or help would be truly greatly appreciated. Thanks in advance :) So anyway, here the problem goes:

Simplify $$\frac{1}{1\times2\times3} + \frac{1}{2\times3\times4} +\frac{1}{3\times4\times5}+\cdots+\frac{1}{n(n+1)(n+2)}$$

A: You just need to realize that $$\frac{1}{1\times2\times3}=\frac12(\frac{1}{1\times2}-\frac{1}{2\times3})\\ \frac{1}{2\times3\times4}=\frac12(\frac{1}{2\times3}-\frac{1}{3\times4})\\$$
Now combine everything, you can have most of the terms cancelled.
$$\frac{1}{1\times2\times3} + \frac{1}{2\times3\times4} +\frac{1}{3\times4\times5}+\cdots+\frac{1}{n(n+1)(n+2)}=\frac12(\frac{1}{1\times2}-\frac{1}{2\times3}+\frac{1}{2\times3}-\frac{1}{3\times4}+\cdots-\frac{1}{(n+1)(n+2)})\\=\frac12(\frac{1}{1\times2}-\frac{1}{(n+1)(n+2)})\\=\frac12(\frac{(n+1)(n+2)-2}{2(n+1)(n+2)})\\=\frac{n(n+3)}{4(n+1)(n+2)}$$


text:
Q: Listening for button click and linking fragment with view model Im trying to learn view models and implement them in my app. I have been following a tutorial on getting me started but, I have a couple questions.

*

*How do i listen for a button click? Since all the business logic is suppose to be stored in the view model would I put an OnClick listener there? Or would i put it with my onChange method in the activity that launches the fragment?

*How to tell the fragment to use the view model?
Update was looking at this guys tutorial Location of click event in MVVM architecture . Isn't the whole point of mvvm to eliminate the need of interfaces?
Update 2: Found where you can use data binding to shove OnClick listener into button here: Handle onClick event with Databinding and MVVM and Using DataBinding library for binding events
Live data observe code from activity launching fragment
 //private BattleRhythmViewModel battleModel;
   battleModel = ViewModelProviders.of(this).get(BattleRhythmViewModel.class);

   battleModel.getEvents().observe(this, new Observer<ArrayList<Event>>() {
       @Override
       public void onChanged(@Nullable ArrayList<Event> events) {
        // Add newly created events to array/recycler view
           // Another one for pushing new platform/content to database

       }
   });
}

View model for fragment
public class BattleRhythmViewModel extends ViewModel  {
private MutableLiveData<ArrayList<Event>> battleRhythmEvents;
private MutableLiveData<ArrayList<TableData>> battleRhythmExtra;

public LiveData<ArrayList<Event>> getEvents()
{
    return battleRhythmEvents;
}

public LiveData<ArrayList<TableData>> getExtras()
{
    return battleRhythmExtra;
}

}


text:
Q: JavaFX Controller not linking to JavaFX fxml file I am attempting to create a method in my main screen controller to set a new scene in my program. When attempting to do so, I get the following error:

Error resolving onAction='#partAddButtonPushed', either the event handler is not in the Namespace or there is an error in the script.

The relevant fxml code is:
<AnchorPane id="AnchorPane" prefHeight="420.0" prefWidth="1000.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="john.Doe.View_Controller.MainController">
   <children>
        <Button id="addPartsButton" fx:id="partAdd" layoutX="190.0" layoutY="340.0" maxWidth="70.0" minWidth="70.0" mnemonicParsing="false" onAction="#partAddButtonPushed" prefWidth="70.0" text="Add">

and the relevant code in the controller is:
public class MainController implements Initializable {

@FXML
    private Button partAdd;

    @FXML
    private void partAddButtonPushed(ActionEvent event) throws IOException {
        Parent partAddParent = FXMLLoader.load(getClass().getResource("/View/AddPart.fxml"));
        Scene AddPartScene = new Scene (partAddParent);

        Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
        window.setScene(AddPartScene);
        window.show();
    }

Would anyone happen to know why they are not linking up?


text:
Q: Practical use of futures? Ie, how to kill them? Futures are very convenient, but in practice, you may need some guarantees on their execution. For example, consider:
import scala.actors.Futures._

def slowFn(time:Int) = {
    Thread.sleep(time * 1000)
    println("%d second fn done".format(time))
}

val fs = List( future(slowFn(2)), future(slowFn(10)) )
awaitAll(5000, fs:_*)
println("5 second expiration. Continuing.")

Thread.sleep(12000)      // ie more calculations
println("done with everything")

The idea is to kick off some slow running functions in parallel. But we wouldn't want to hang forever if the functions executed by the futures don't return. So we use awaitAll() to put a timeout on the futures. But if you run the code, you see that the 5 second timer expires, but the 10 second future continues to run and returns later. The timeout doesn't kill the future; it just limits the join wait.
So how do you kill a future after a timeout period? It seems like futures can't be used in practice unless you're certain that they will return in a known amount of time. Otherwise, you run the risk of losing threads in the thread pool to non-terminating futures until there are none left.
So the questions are: How do you kill futures? What are the intended usage patterns for futures given these risks?

A: Futures are intended to be used in settings where you do need to wait for the computation to complete, no matter what. That's why they are described as being used for slow running functions. You want that function's result, but you have other stuff you can be doing meanwhile. In fact, you might have many futures, all independent of each other that you may want to run in parallel, while you wait until all complete.
The timer just provides a wait to get partial results.

A: I think the reason Future can't simply be "killed" is exactly the same as why java.lang.Thread.stop() is deprecated.
While Future is running, a Thread is required.  In order to stop a Future without calling stop() on the executing Thread, application specific logic is needed: checking for an application specific flag or the interrupted status of the executing Thread periodically is one way to do it.


text:
Q: Yocto recipe python whl package I am writing a custom yocto recipe that should install a python package from a .whl file.
I tried it using a recipe that contains:
inherit pypi setuptools
PYPI_SRC_URI="http://ci.tensorflow.org/view/Nightly/job/nightly-pi-zero/lastSuccessfulBuild/artifact/output-artifacts/tensorflow-1.5.0rc1-cp27-none-any.whl"

But it does not work that way, it states, that a setup.py file is missing and when trying to write a custom do_compile task that runs pip install <PATH-TO-WHL> it says, that pip is an unkown command.
When installing .whl files directly onto the target system one would type the following:
pip install <path-to-whl-file>

Thanks for your help!

A: .whl package is just a .zip file with python sources, and precompiled binaries for certain platform.
So, you can do something like this:
COMPATIBLE_HOST = "i686.*-mingw.*"

SRC_URI = "https://files.pythonhosted.org/packages/d8/9d/7a8cad803ef73f47134ae5c3804e20b54149ce62a7d1337204f3cf2d1fa1/MarkupSafe-1.1.1-cp35-cp35m-win32.whl;downloadfilename=MarkupSafe-1.1.1-cp35-cp35m-win32.zip;subdir=${BP}"

SRC_URI[md5sum] = "a948c70a1241389d7120db90d69079ca"
SRC_URI[sha256sum] = "6dd73240d2af64df90aa7c4e7481e23825ea70af4b4922f8ede5b9e35f78a3b1"

inherit nativesdk python3-dir

LICENSE = "BSD-3-Clause"

PV = "1.1.1"
PN = "nativesdk-python3-markupsafe"

LIC_FILES_CHKSUM = "file:///${S}/MarkupSafe-1.1.1.dist-info/LICENSE.rst;md5=ffeffa59c90c9c4a033c7574f8f3fb75"

do_unpack[depends] += "unzip-native:do_populate_sysroot"

PROVIDES += "nativesdk-python3-markupsafe"
DEPENDS += "nativesdk-python3"

FILES_${PN} += "\
    ${libdir}/${PYTHON_DIR}/site-packages/* \
"

do_install() {
    install -d ${D}${libdir}/${PYTHON_DIR}/site-packages/MarkupSafe-1.1.1.dist-info
    install -d ${D}${libdir}/${PYTHON_DIR}/site-packages/markupsafe

    install -m 644 ${S}/markupsafe/* ${D}${libdir}/${PYTHON_DIR}/site-packages/markupsafe/
    install -m 644 ${S}/MarkupSafe-1.1.1.dist-info/* ${D}${libdir}/${PYTHON_DIR}/site-packages/MarkupSafe-1.1.1.dist-info/
}

I haven't tested it, yet, but it already forms proper nativesdk package.
Note downloadfilename= parameter to the SRC_URI - without it, .whl file would not be extracted.

A: Basing on https://stackoverflow.com/a/57694762/5422708 answer I would like to share working recipe for engineering_notation 0.6.0 module which also provides only .whl package:
SUMMARY = "To easily work with human-readable engineering notation."
HOMEPAGE = "https://github.com/slightlynybbled/engineering_notation"

SRC_URI = "https://files.pythonhosted.org/packages/d4/c4/4712b8020b8a3ada129581be891e2dbbd6a4cf54195ea2b80f89bbc51756/engineering_notation-${PV}-py3-none-any.whl;downloadfilename=engineering_notation-${PV}-py3-none-any.zip;subdir=${BP}"

SRC_URI[md5sum] = "5684efec41bc0738bb1fe625a71ffaf7"
SRC_URI[sha256sum] = "1ea1e450d575b4804723d0711b0609d2711dffac2f4b5548ee632c16a636d9f6"

inherit python3-dir

LICENSE = "MIT"
LIC_FILES_CHKSUM = "file:///${S}/engineering_notation-${PV}.dist-info/METADATA;md5=5a9ae92d9fbf02bbcd5e4e94e6356cd3"

do_unpack[depends] += "unzip-native:do_populate_sysroot"

DEPENDS += "python3"

FILES:${PN} += "\
    ${libdir}/${PYTHON_DIR}/site-packages/engineering_notation \
    ${libdir}/${PYTHON_DIR}/site-packages/engineering_notation-${PV}.dist-info \
"

do_install() {
    install -d ${D}${libdir}/${PYTHON_DIR}/site-packages/engineering_notation
    install -d ${D}${libdir}/${PYTHON_DIR}/site-packages/engineering_notation-${PV}.dist-info

    install -m 644 ${S}/engineering_notation/* ${D}${libdir}/${PYTHON_DIR}/site-packages/engineering_notation/
    install -m 644 ${S}/engineering_notation-${PV}.dist-info/* ${D}${libdir}/${PYTHON_DIR}/site-packages/engineering_notation-${PV}.dist-info/
}


text:
Q: fail2ban not matching xmlrpc I've added an xmlrpc jail for fail2ban to protect against a persistent attack. The apache access.log is as below...
191.96.249.80 - - [16/Dec/2016:14:54:21 +0000] "POST /xmlrpc.php HTTP/1.0" 403 469 "-" "Mozilla/4.0 (compatible: MSIE 7.0; Windows NT 6.0)"
191.96.249.80 - - [16/Dec/2016:14:54:21 +0000] "POST /xmlrpc.php HTTP/1.0" 403 469 "-" "Mozilla/4.0 (compatible: MSIE 7.0; Windows NT 6.0)"
191.96.249.80 - - [16/Dec/2016:14:54:21 +0000] "POST /xmlrpc.php HTTP/1.0" 403 469 "-" "Mozilla/4.0 (compatible: MSIE 7.0; Windows NT 6.0)"
191.96.249.80 - - [16/Dec/2016:14:54:22 +0000] "POST /xmlrpc.php HTTP/1.0" 403 469 "-" "Mozilla/4.0 (compatible: MSIE 7.0; Windows NT 6.0)"

and my fail to ban def is as below...
[Definition]
failregex = ^<HOST> .*POST .*xmlrpc\.php.*
ignoreregex =

This doesn't appear to be matching as nothing for xmlrpc appears in the fail2ban log but fail2ban does report that jail as being active.
My jail is setup like this in my jail.conf file
[xmlrpc]
enabled = true
filter = xmlrpc
action = iptables[name=xmlrpc, port=http, protocol=tcp]
logpath = /var/log/apache2/access.log
bantime = 43600
maxretry = 0

Anybody got any ideas why it might not be matching?

A: I figured this out in the end. It turns out I'd missed the port definition from the xmlrpc jail setup.
[xmlrpc]
enabled = true
filter = xmlrpc
port = http,https
action = iptables[name=xmlrpc, port=http, protocol=tcp]
logpath = /var/log/apache2/access.log
bantime = 43600
maxretry = 0

Now works perfectly


text:
Q: About pyramid web framework error, CSRF token is missing or invalid 1.jinja2 template file:
<!DOCTYPE html>
<html>
<head>
    <title>image upload demo</title>
</head>
<body>
<form action="{{ imgup_url }}" method="post" accept-charset="utf-8"
      enctype="multipart/form-data">
    <input type=hidden id="token" value="{{ token }}">
    <label for="filename">File:</label>
    <input id="pictitle" name="pictitle" type="text" value="okkk" />
    <input id="upfile" name="upfile" type="file" value="" />

    <input id="button" type="submit" value="upload" />
</form>
</body>
</html>

2.views.py file
@view_config(permission='post', route_name='imgup',
             renderer='shootout:jinja2/imgup.jinja2',
             check_csrf=False)
def ueditor_ImgUp(request):
    """ upload image """
    form = Form(request, schema=ImgUpSchema)
    token1 = request.session.new_csrf_token()
    if 'form.submitted' in request.params:
        token2 = request.session.get_csrf_token()
        if token2 != request.POST['csrf_token']:
            raise ValueError('CSRF token did not match')
        print "imgup is login begin!!!"
        source_pictitle = request.POST.get('pictitle')
        source_filename = request.POST['upfile'].filename

        response = Response()
        myresponse = __myuploadfile(fileObj, source_pictitle, source_filename, 'pic')
        response.write(myresponse)
        print "imgup is success!!!"
        return response
    else:
        return {'imgup_url':'/imgup','token':token1}

3.__init__.py file :
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)

    session_factory = UnencryptedCookieSessionFactoryConfig(
        settings['session.secret']
        )

    authn_policy = SessionAuthenticationPolicy()
    authz_policy = ACLAuthorizationPolicy()

    config = Configurator(
        settings=settings,
        root_factory=RootFactory,
        authentication_policy=authn_policy,
        authorization_policy=authz_policy,
        session_factory=session_factory
        )

    config.add_static_view('static', 'shootout:static')
    config.add_static_view('html', 'shootout:html')
    config.include(addroutes)
    config.add_route('imgup','/imgup')

when submitted upload button show:
403 Forbidden
Access was denied to this resource.
CSRF token is missing or invalid
How to solve this problem?Thanks.

A: pyramid html post method need csrf_token,so i do:
view:
csrf_token = request.session.get_csrf_token()
return {'csrf_token':csrf_token}

template(Jinja2):
<input id="_csrf" type="hidden" value="{{ csrf_token }}"/>

success~


text:
Q: Query about feature extraction and classification of EEG signal in MATLAB using wavelet transform and SVM,NN I am doing a project on EEG. For this purpose

*

*I have an excel file having around 10000 values in only 1 column..I want to convert this file into a matrix of order 512*14..I am doing it manually which is taking much time..can anyone tell me how to do this by applying window,especially hamming window or any other easy method please..?

*I have extracted features like power and entropy using wavelet transform but the differentiation in results is not seen..can anyone tell the program or tell whether this code is correct or not..

*Also anybody knows how to use SVM and NN classifier for EEG classification? Please tell as soon as possible..as I am urgently in need of it..
tic
clear all
close all
clc
subject 1 - sad..............................
a11 = xlsread('7168sub1-sad.xlsx');
[mat11] = vec2mat(a11,14)
size(mat11)
t11 = wpdec(a11,5,'db2');
cfs1s1 = wpcoef(t11,[1 0]);%..decompose into higher n lower freq...
cfs2s1 = wpcoef(t11,[1 1]);%..discard..
cfs3s1 = wpcoef(t11,[2 0]);%..decompose..
cfs4s1 = wpcoef(t11,[2 1]);%..gamma...
cfs5s1 = wpcoef(t11,[3 0]);%..decompose..
cfs6s1 = wpcoef(t11,[3 1]);%..beta..
cfs7s1 = wpcoef(t11,[4 0]);%..decompose..
cfs8s1 = wpcoef(t11,[4 1]);%..alpha..
cfs9s1 = wpcoef(t11,[5 0]);%..delta..
cfs10s1 = wpcoef(t11,[5 1]);%..theta..
fprintf('ENTROPIES of DELTA,THETA,ALPHA,BETA,GAMMA ARE :\n')
fprintf('SUBJECT 1 - SAD and ANGRY EMOTIONS :\n')
E11d = wentropy(cfs9s1,'shannon')
E11t = wentropy(cfs10s1,'shannon')
E11a = wentropy(cfs8s1,'shannon')
E11b = wentropy(cfs6s1,'shannon')
E11g = wentropy(cfs4s1,'shannon')
%.................subject 1 - angry.......................
a21 = xlsread('7168sub1-angry.xlsx')
[mat21] = vec2mat(a21,14)
size(mat21)
t21 = wpdec(a21,5,'db2');
cfs1a1 = wpcoef(t21,[1 0]);
cfs2a1 = wpcoef(t21,[1 1]);
cfs3a1 = wpcoef(t21,[2 0]);
cfs4a1 = wpcoef(t21,[2 1]);
cfs5a1 = wpcoef(t21,[3 0]);
cfs6a1 = wpcoef(t21,[3 1]);
cfs7a1 = wpcoef(t21,[4 0]);
cfs8a1 = wpcoef(t21,[4 1]);
cfs9a1 = wpcoef(t21,[5 0]);
cfs10a1 = wpcoef(t21,[5 1]);
%............Find entropy :...................
E21d = wentropy(cfs9a1,'shannon')
E21t = wentropy(cfs10a1,'shannon')
E21a = wentropy(cfs8a1,'shannon')
E21b = wentropy(cfs6a1,'shannon')
E21g = wentropy(cfs4a1,'shannon')
%...............Plot ENTROPIES...............
x = 1:1:5;
figure(1)
%================= all sad ========================
%------------------ sub-1 -------------------------
plot(1, E11d, 'b*')
hold on
plot(1, E11t, 'b*')
hold on
plot(1, E11a, 'b*')
hold on
plot(1, E11b, 'b*')
hold on
plot(1, E11g, 'b*')
hold on
%================= all angry ========================
%------------------ sub-1 -------------------------
plot(1, E21d, 'r*')
hold on
plot(1, E21t, 'r*')
hold on
plot(1, E21a, 'r*')
hold on
plot(1, E21b, 'r*')
hold on
plot(1, E21g, 'r*')
hold on
%========================================================
toc
this program is shown for 1 person,in same way i have done for 10 persons.please tell me is it correct??

A: I also work on EEG analysis using Wavelet transformation and SVM Classifier.Use 1-D or 2-D wavelet transformation in MATLAB general view. MAny research Paper give 256 Hz Sampling frequency. wavelet transformation use for decompose signal in particular band, i attach one image. feature extract before decomposition of signal, after decomposition, and after Reconstruction the signal. In MATLAB, wavedec and wavedec2 respectively used for 1-D and 2-D wavelet transformation. after decomposition extract co efficient detail and approximatw using detcoef and appcoef function according to level. then reconstruction using waverec function.
thanks


text:
Q: Simple Git Branch Switching Workflow I am working on a project using Git. Now, I am working on a feature in a branch and ran across something that I need to see some code from someone else's branch to remind myself how a function he wrote works (these two branches will get merged when I am done).
I do not really want to commit my changes right now and git checkout his branch...then switch back over.
What is a better way to deal with this problem?

A: The tool for the job is git-stash. Running git stash in a Git directory with changed files will stash away your changes, bringing the working directory back to the state of HEAD (a clean state). This allows you to checkout a different branch, as well as many other operations. When you're done and back in this branch, run git stash pop to pop the changes in the stash back onto the working directory, bringing yourself back the state you were at before stashing the changes away.
$ git branch
* develop-back
  develop-other
$ git stash
$ git checkout develop-other
$ ...
$ git co develop-back
$ git stash pop

Yes, this works perfectly well and is very convenient. But remember that you shouldn't be afraid of committing changes in Git. In fact, git-stash does exactly that: commit your changes somewhere. Committing in Git means saving your work, and in this case that's exactly what you want to do. You can always reset-mixed:
$ git commit -am 'stashing away for a moment'
$ git co develop-other
$ ...
$ git co develop-back
$ git reset HEAD~

This workflow is equivalent to stashing, and you can see that it takes no more steps. git stash is just a "wrapper" around this procedure, with a somewhat more humane interface.

A: Sounds like you want to use git stash.
First execute git stash. Then checkout the other branch. Once you've finished taking a look, go back to your own branch, and use git stash pop.


text:
Q: How to make a JTable cell (link) clickable I am making a hospital project in Java, I have made a JTable which is fetching Hospital Name and a Hospital image link i.e "Click to see more" from SQL database. My problem is that the data is successfully fetched from database to the table, but I can't click  the link which is in the table cell.
How to make the link active?

A: Consider using JXTable (a class of SwingX): it supports a hyperlink renderer which can be configured to do any action, based on the cell value
JXTable table = new JXTable(myModel);
AbstractHyperlinkAction<Object> simpleAction = new AbstractHyperlinkAction<Object>(null) {

    public void actionPerformed(ActionEvent e) {
        // here goes what you want to do on activating the hyperlink
        //LOG.info("hit: " + getTarget());
    }

};
TableCellRenderer renderer = new DefaultTableRenderer(
    new HyperlinkProvider(simpleAction));
table.getColumnExt(0).setEditable(false);
table.getColumnExt(0).setCellRenderer(renderer);

A: You can either make a TableCellEditor whose isCellEditable method could be used to activate on a single mouse click.  Frankly, this just get messy.
Or, you could attach a MouseListener to the table directly and monitor for the mouseClicked event.
On the clicked event, you could need to getSelectedColumn and getSelectedRow to determine if they've clicked on the column you want and get the link value from the selected cell, using getValueAt
You'll need to take into consideration that the table may be sorted or the columns are no longer in the order you started them in (the user may have moved them).
Then you'll need convertColumnIndexToView and convertRowIndexToModel
Simple :D

A: I think that avoiding an external library is a better way to go as MadProgrammer suggests, but I guess swingx is still pure java. Anyway, I would use the mouseClicked listener and then open uri in the way described in this question How to add hyperlink in JLabel.
JTable table = new JTable();

table.addMouseListener(new MouseAdapter() {
  public void mouseClicked(MouseEvent e) {

        int row = table.getSelectedRow();
        int col = table.getSelectedColumn();

        //build your address / link

        URI uri = new URI("http: your link here");

        //see below
        open(uri);
      }
    });

//Then elsewhere as from the McDowell answer
private static void open(URI uri) {
  if (Desktop.isDesktopSupported()) {
    try {
       Desktop.getDesktop().browse(uri);
      } catch (IOException e) { /* TODO: error handling */ }
   } else { /* TODO: error handling */ }
 }

A: I solved adding a button inside the cells clickable, I followed this tutorial Table Button Column from Rob Camick:
String[] columnNames = {"First Name", "Last Name", ""};
Object[][] data =
{
    {"Homer", "Simpson", "delete Homer"},
    {"Madge", "Simpson", "delete Madge"},
    {"Bart",  "Simpson", "delete Bart"},
    {"Lisa",  "Simpson", "delete Lisa"},
};

DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model );

Then:
Action delete = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        JTable table = (JTable)e.getSource();
        int modelRow = Integer.valueOf( e.getActionCommand() );
        ((DefaultTableModel)table.getModel()).removeRow(modelRow);
    }
};

ButtonColumn buttonColumn = new ButtonColumn(table, delete, 2);
buttonColumn.setMnemonic(KeyEvent.VK_D);

Where ButtonColumn class is:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;

/**
 *  The ButtonColumn class provides a renderer and an editor that looks like a
 *  JButton. The renderer and editor will then be used for a specified column
 *  in the table. The TableModel will contain the String to be displayed on
 *  the button.
 *
 *  The button can be invoked by a mouse click or by pressing the space bar
 *  when the cell has focus. Optionally a mnemonic can be set to invoke the
 *  button. When the button is invoked the provided Action is invoked. The
 *  source of the Action will be the table. The action command will contain
 *  the model row number of the button that was clicked.
 *
 */
public class ButtonColumn extends AbstractCellEditor
    implements TableCellRenderer, TableCellEditor, ActionListener, MouseListener
{
    private JTable table;
    private Action action;
    private int mnemonic;
    private Border originalBorder;
    private Border focusBorder;

    private JButton renderButton;
    private JButton editButton;
    private Object editorValue;
    private boolean isButtonColumnEditor;

    /**
     *  Create the ButtonColumn to be used as a renderer and editor. The
     *  renderer and editor will automatically be installed on the TableColumn
     *  of the specified column.
     *
     *  @param table the table containing the button renderer/editor
     *  @param action the Action to be invoked when the button is invoked
     *  @param column the column to which the button renderer/editor is added
     */
    public ButtonColumn(JTable table, Action action, int column)
    {
        this.table = table;
        this.action = action;

        renderButton = new JButton();
        editButton = new JButton();
        editButton.setFocusPainted( false );
        editButton.addActionListener( this );
        originalBorder = editButton.getBorder();
        setFocusBorder( new LineBorder(Color.BLUE) );

        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(column).setCellRenderer( this );
        columnModel.getColumn(column).setCellEditor( this );
        table.addMouseListener( this );
    }

    /**
     *  Get foreground color of the button when the cell has focus
     *
     *  @return the foreground color
     */
    public Border getFocusBorder()
    {
        return focusBorder;
    }

    /**
     *  The foreground color of the button when the cell has focus
     *
     *  @param focusBorder the foreground color
     */
    public void setFocusBorder(Border focusBorder)
    {
        this.focusBorder = focusBorder;
        editButton.setBorder( focusBorder );
    }

    public int getMnemonic()
    {
        return mnemonic;
    }

    /**
     *  The mnemonic to activate the button when the cell has focus
     *
     *  @param mnemonic the mnemonic
     */
    public void setMnemonic(int mnemonic)
    {
        this.mnemonic = mnemonic;
        renderButton.setMnemonic(mnemonic);
        editButton.setMnemonic(mnemonic);
    }

    @Override
    public Component getTableCellEditorComponent(
        JTable table, Object value, boolean isSelected, int row, int column)
    {
        if (value == null)
        {
            editButton.setText( "" );
            editButton.setIcon( null );
        }
        else if (value instanceof Icon)
        {
            editButton.setText( "" );
            editButton.setIcon( (Icon)value );
        }
        else
        {
            editButton.setText( value.toString() );
            editButton.setIcon( null );
        }

        this.editorValue = value;
        return editButton;
    }

    @Override
    public Object getCellEditorValue()
    {
        return editorValue;
    }

//
//  Implement TableCellRenderer interface
//
    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        if (isSelected)
        {
            renderButton.setForeground(table.getSelectionForeground());
            renderButton.setBackground(table.getSelectionBackground());
        }
        else
        {
            renderButton.setForeground(table.getForeground());
            renderButton.setBackground(UIManager.getColor("Button.background"));
        }

        if (hasFocus)
        {
            renderButton.setBorder( focusBorder );
        }
        else
        {
            renderButton.setBorder( originalBorder );
        }

//      renderButton.setText( (value == null) ? "" : value.toString() );
        if (value == null)
        {
            renderButton.setText( "" );
            renderButton.setIcon( null );
        }
        else if (value instanceof Icon)
        {
            renderButton.setText( "" );
            renderButton.setIcon( (Icon)value );
        }
        else
        {
            renderButton.setText( value.toString() );
            renderButton.setIcon( null );
        }

        return renderButton;
    }

//
//  Implement ActionListener interface
//
    /*
     *  The button has been pressed. Stop editing and invoke the custom Action
     */
    public void actionPerformed(ActionEvent e)
    {
        int row = table.convertRowIndexToModel( table.getEditingRow() );
        fireEditingStopped();

        //  Invoke the Action

        ActionEvent event = new ActionEvent(
            table,
            ActionEvent.ACTION_PERFORMED,
            "" + row);
        action.actionPerformed(event);
    }

//
//  Implement MouseListener interface
//
    /*
     *  When the mouse is pressed the editor is invoked. If you then then drag
     *  the mouse to another cell before releasing it, the editor is still
     *  active. Make sure editing is stopped when the mouse is released.
     */
    public void mousePressed(MouseEvent e)
    {
        if (table.isEditing()
        &&  table.getCellEditor() == this)
            isButtonColumnEditor = true;
    }

    public void mouseReleased(MouseEvent e)
    {
        if (isButtonColumnEditor
        &&  table.isEditing())
            table.getCellEditor().stopCellEditing();

        isButtonColumnEditor = false;
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
}


text:
Q: Even with space my AWS EC2 instance show message "No space left on device" My AWS EC2 Instance have the properties below:

As We can see, there is 6,4GB free space, but even with this space when accessing my app in this intance the message "No space left on device" is showing.
Why does it happen?

A: I guess your problem is not with EC2, but with Linux in general.
Check your inodes, you can have free disk space but saturated your inodes
Example:
$ df -i .
Filesystem                   Inodes  IUsed   IFree IUse% Mounted on
/dev/mapper/ubuntu--vg-root 3219456 330596 2888860   11% /

A: A reason why 'No space left on device' might appear, even if df suggests that there's space available, is if:

*

*A file was opened by a program

*Subsequently, the file got deleted

*The program is still running and it still has an open file handle

Linux only really deletes files when all references to the file have disappeared. This includes references such as files, but also open file handles.
If you recently deleted a particularly large file, there is probably a program on your system that still has that file open. If you have a good idea what program that is, the simplest might be to just restart that program.


text:
Q: VB.NET listview not showing all data from dataset This issue is driving me mad, I can't work out why it's happening. I'm running a query in an access db using vb.net then putting the data into a listview. Code:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim strAccessConn As String = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = T:\mydb.accdb"
    Dim cn As OleDbConnection = New OleDbConnection(strAccessConn)
    Dim ds As New DataSet
    Dim dt As DataTable

    'Note the query is entered as a string.
    Dim da As New OleDbDataAdapter("Q_LIST", cn) 'is the name of the query in Access

    'Set the CommandType of the SelectCommand to TableDirect
    da.SelectCommand.CommandType = CommandType.TableDirect
    da.Fill(ds, "mytable")
    dt = ds.Tables("mytable")

    ListViewBatchResults.MultiSelect = True
    ListViewBatchResults.View = View.Details
    ListViewBatchResults.GridLines = True
    ListViewBatchResults.Columns.Clear()
    ListViewBatchResults.Items.Clear()

    For Each col As DataColumn In dt.Columns()
        ListViewBatchResults.Columns.Add(col.ToString)
    Next

    MsgBox(dt.Rows.Count)

    For Each row As DataRow In dt.Rows()

        Dim lst As ListViewItem

        lst = ListViewBatchResults.Items.Add(row(0))

        For i As Integer = 1 To dt.Columns.Count - 1
            lst.SubItems.Add(row(i))
        Next

    Next

End Sub

This listview is not showing all the returned data though, and I can't work out why - it works on other queries in the DB but not this one for some reason. The row count shows that there are 264 rows, the listview only shows 3 of them when I run the project however. What the heck is going on?
Cheers!

A: Dim lst As ListViewItem

to
Dim lst As New ListViewItem


text:
Q: Haskell RSA Encryption Key Generator Trouble Okay so I am trying to create a basic RSA function into Haskell. It doesn't take string, only numbers. The trouble I am having right now is the key generator function. Here is what I have so far:
chooseKeys :: Integer -> Integer -> (Integer,Integer)
chooseKeys n e =
    let
      n' = (n-1)*(e-1)
      m  = (n*e)
      e' = find (e `mod` n') -- e' needs to be such that the gcd of (e',n') = 1
      d' = minv n' e'
      find x
        | g == 1 = x
        | otherwise = find ((x+1) `mod` n')
        where (g,_,_) = extGCD x n'
    in (e', d')

I know my 'minv' function is fine, but I don't think it is spiting out the right value. The program runs, but it doesn't give my the write answer. Could someone give some much appreciated help? Thanks!
EDIT: I modified the code a little bit. Hopefully it is a little clearer now.

A: If I recall my RSA correctly, you want d' * e' `mod` n' == 1.
Given this, and assuming this is the same minv as in your previous question, I think you have its arguments reversed.


text:
Q: Add padding to div, if (vertical) scrollbar is visible in another div Folks, I have the following HTML with Bootstrap classes.

some stuff aligned to main

some tabular stuff

data goes here

data goes here

data goes here

How can I add some padding to the .header div (e.g. addClass("pr-3"), if and only if the .main div has the vertical scrollbar visible (due to the amount of content that's in there.
I understand, I can determine, whether the scroll is visible on an element by comparing element.scrollHeight > element.clientHeight. I guess my question is, how do I link in an event handler that checks, when the scroll becomes visible, and when it disappears again. Obviously, the .main div isnt static or even a static  field, but dynamically made up of a number of s (".record"). Those are added by some a $(.main).append($record.clone()); statement and populated by mySQL data.
Why do I want to do that? The .header contains the labels for the fields in the .main div. When there is more data than space, the scrollbar is added automatically, reformatting the field-width as appropriate. The result is that that the labels in the .header div arent fully aligned anymore with the fields below.
Any thoughts?

A: You would need to wrap your .header and .main class into another element. Then just check for each of these wrappers, if their corrosponding main element has a scrollbar - like you suggested with scrollHeight > height() - and if so, add your class to the wrappers header element:

$('.some-wrapper-class').each(function() {
 let $header = $(this).find('.header');
  let $content = $(this).find('.main');
  console.log($content[0].scrollHeight > $content.height()) ;
  if($content[0].scrollHeight > $content.height()) {
    $header.addClass('text-danger');
  }
});
.header {
  font-size: 2em;
  font-weight: bold;
}

.header-padded {
  color: red;
}

.main {
  height: 50px;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

Header with scrollbar

    some tabular stuff

data goes here

data goes here

data goes here

Header without scrollbar

    some tabular stuff


text:
Q: How to access the current cordinate of UIButton from the super view, when occur the UIGestureRecognizerStateEnd I am new to iOS development. Now I am implementing an UIPanGestureRecognizer model application. I have one UIButton for UIPanGestureRecognizer. My question is, how can access the reside coordinate of UIButton from the super view (such as UIView, UIScrollView etc?)
if anybody know please help me.

A: You may use
CGRect rectInSuperView = [button convertRect:button.frame toView:superview];

Check the documentation


text:
Q: How to get the full url? $html = file_get_contents("any site");
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');

foreach ($images as $image) {
   echo $image->src;
}

return me nothing
$html = file_get_contents("any site");
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');

foreach ($images as $image) {
   echo $image->getAttribute('src');
}

return me relative url like "/images/example.jpg
$html = file_get_contents("any site");
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');

foreach ($images as $image) {
   echo $image.src;
}

return me:
Fatal error: Call to undefined function getElementsByTagName()

So, how can I get the absolute path ?

A: You can use parse_url to find the base URL:
$url = 'http://www.example.com/path?opt=234';
$parts = parse_url($url);
if (isset($parts['scheme'])){
    $base_url = $parts['scheme'].'://';
} else {
    $base_url = 'http://';
    $parts = parse_url($base_url.$url);
}
$base_url .= $parts['host'];
if (isset($parts['path'])){
    $base_url .= $parts['path'];
}

And then combine it with your code as follows:
$html = file_get_contents("any site");
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');

foreach ($images as $image) {
   echo $base_url.$image->getAttribute('src');
}

A: This code differentiates between src attributes with a relative URL and a full URL. It's a bit more robust than simple string concatenation and handles cases where the relative path doesn't begin with a slash. e.g. images/image.jpg vs. /images/image.jpg.
<?php
$site = 'http://example.com/some/deeply/buried/page.html';
$dir = dirname($site);

$html = file_get_contents($site);
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');

foreach ($images as $image) {
    // get the img src attribute
    $img_path = $image->getAttribute('src');

    // parse the path into its constituent parts
    $url_info = parse_url($img_path);

    // if the host part (or indeed any part other than "path") is set,
    // then we're dealing with a fully qualified URL (or possibly an error)
    if (!isset($url_info['host'])) {
        // otherwise, get the relative path
        $path = $url_info['path'];

        // and ensure it begins with a slash
        if (substr($path,0,1) !== '/') $path = '/'.$path;

        // concatenate the site directory with the relative path
        $img_path = $dir.$path;
    }

   echo $img_path;  // this should be a full URL
}
?>

A: its working for me, try it too
<?php
  echo path_to_absolute(
    "../images/example.jpg", /* image url */
    "http://php.net/manual/en/" /* current page url */,
    false /* is your url containing file name at the end like "http://server.com/file.html" */
  );

  function path_to_absolute( $src, $base = null, $has_filename = false ) {
    if ( $has_filename && !in_array( substr( $src, 0, 1 ), array( "?", "#" ) ) ) {
      $base = dirname( $base )."/";
    }
    else {
      $base = rtrim( $base, "/" )."/";
    }

    if ( parse_url( $src, PHP_URL_HOST ) ) {
      /* Its full url, so return it without modifying */
      return $src;
    }

    if ( substr( $src, 0, 1 ) == "/" ) {
      /* $src begin with a slash, find server host and, join it with $src */
      return str_replace( parse_url( $base, PHP_URL_PATH ), "", $base ).$src;
    }

    /* remove './' from $src, we dont need it */
    $src  = ( substr( $src, 0, 2 ) === "./" ) ? substr( $src, 2, strlen( $src ) ) : $src;

    /* check how many times we need to go back **/
    $path = substr_count( $src, "../" );
    $src  = str_ireplace( "../", "", $src );

    for( $i = 1; $i <= $path; $i++ ) {
      if ( parse_url( dirname( $base ), PHP_URL_HOST ) ) {
        $base = dirname( $base ) . "/";
      }
    }

    return $base . $src;
  }
?>

example usage..
here we finding links from php.net as there are so many relative links
<?php
  $url  = "http://www.php.net/manual/en/tokens.php";
  $html = file_get_contents( $url );
  $dom  = new DOMDocument;
  @$dom->loadHTML( $html );
  $dom->preserveWhiteSpace  = false;

  $links  = $dom->getElementsByTagName( 'a' );

  foreach( $links as $link ) {
    $original_url = $link->getAttribute( 'href' );
    $absolute_url = path_to_absolute( $original_url, $url, true );
    echo $original_url." - ".$absolute_url."\n";
  }

  /** prints...
   * / - http://www.php.net/
   * ...
   * control-structures.while.php     - http://www.php.net/manual/en/control-structures.while.php
   * control-structures.do.while.php  - http://www.php.net/manual/en/control-structures.do.while.php
   * ...
   * /sitemap.php - http://www.php.net/sitemap.php
   * /contact.php - http://www.php.net/contact.php
   * ...
   * http://developer.yahoo.com/ - http://developer.yahoo.com/
   * ...
   * ?setbeta=1&beta=1 - http://www.php.net/manual/en/tokens.php?setbeta=1&beta=1
   * ...
   * #85872 - http://www.php.net/manual/en/tokens.php#85872
   **/
?>

A: I think you should combine your 2nd solution with the URL of 'any site'. Because the src tag of the image may contain only relative paths. From the point of the web developer, there is no need to include the absolute path.


text:
Q: What is the inverse of $G: (x,y) \rightarrow (x, 1-ye^x+xe^y)$ How can I calculate the inverse of
$$
\begin{align*}
G: \mathbb{R}^2 &\rightarrow \mathbb{R}^2\\
(x,y) &\mapsto (x, 1-ye^x+xe^y)
\end{align*}
$$
I actually just need the inverse in a neighborhood of the point $(0,1)$, and I know that the inverse exists in that neighborhood because
$$
[D_pG] = \left(\begin{matrix}
1 & 0\\
-ye^x+e^y & xe^y-e^x
\end{matrix}\right)_p
\implies
[D_{(0,1)}G] = \left(\begin{matrix}
1 & 0\\
e-1 & -1
\end{matrix}\right)
$$
which is invertible, and by the inverse function theorem I know that there is $G^{-1}:U \subset \mathbb{R}^2 \rightarrow \mathbb{R}^2$ where $G(0,1) \in U$ open set.

Here's what I was able to achieve:
One thing to note is that when $v \rightarrow 0$ we have that
$$
G^{-1}(v) \sim D_{(0,0)}G^{-1}(v) + G^{-1}(0,0)
$$
But $G^{-1}(0,0) = G^{-1}(G(0,1)) = (0,1)$  and $D_{(0,0)}G^{-1} = D_{G(0,1)}G^{-1} = (D_{(0,1)}G)^{-1}$, therefore we can conclude that when $v \rightarrow 0$ it follows that
$$
G^{-1}((v_1,v_2)) \sim (D_{(0,1)}G)^{-1}((v_1,v_2)) + (0,1) = (v_1,-v_1-v_2+v_1e+1)
$$
Can someone please check my work and give me some directions?
Thanks!


text:
Q: Django-allauth login page is too simple I have created a project in which I provided a login system. I also want to provide a login with the google option. I have installed Django-allath and made the necessary changes to log in and retrieve the necessary data. But when I click on login with google it sends me to the simple login page and after continuing it redirects me to the google login page. I want when I click on login with google, the application should send me to the google login page.
Please help me.

A: not sure what your problem is but use django social auth.
The docs are straight forward. you van use it in combination with all auth
docs


text:
Q: Adding a new field to each array element in .lua Please tell me, if there are any errors here and how to make the code more clean.
There is a space "company". Inside it's a string "type" and "information" map. Inside this map is a "job" object and an array of "users" objects. The "users" array consists of 2 objects. Each object has 4 fields.
I need to add a new field:

status = "UPDATED"

inside each object in the "users" array, under a certain condition
"company": {
  "type" : "01",
  "information":
    {
      "job":
        {
          "job_name": "N",
          "job_address": 1670392687114,
          "job_salary": 1234567890123,
          "contacts": 0
        },
      "users":
        [
          {
            "id": 1,
            "name": "Alex",
            "rate": 4,
            "address": "bla bla bla"
          },
          {
            "id": 2,
            "name": "Jenifer",
            "rate": 5,
            "address": "bla bla bla"
          }
        ]
    }
}

My logic is next:
if tuple.type == "01" or tuple.type == "02" or tuple.type == "03" or tuple.type == "04" then
   for _, attr in pairs(users) do
      attr.status = "UPDATED"
   end
end

Is it correct to add a new status="UPDATED" field to each object in the array "users" here?
Does this entry exist?
And yet, tell me please, can I somehow make the condition in if more beautiful? For example analog in Java list.contains()

Updated:
The final version after adding new field "status" should look like this (see image)

A:
Is it correct to add a new status="UPDATED" field to each object in
the array "users" here? Does this entry exist?

If you want the table to have a status field with value "UPDATED" then attr.status = "UPDATED"is correct.
This only makes sense if you'll add more non-updated users to that table later though as you're updating the entire list. you could as well just mark the users table object as updated.

And yet, tell me please, can I somehow make the condition in if more
beautiful? For example analog in Java list.contains()

No but you could write your own function.
function table.contains(tbl, value)
  for _, v in pairs(tbl) do
    if (v == value) then return true end
  end
  return false
end

if table.contains({"01", "02", "03", "04"}, tuple.type) then
  for _, attr in pairs(users) do
    attr.status = "UPDATED"
  end
end

Alternatively you could use a lookup table
local isUpdateType = {
  ["01"] = true,
  ["02"] = true,
  ["03"] = true,
  ["04"] = true,
}

and later
if isUpdateType[tuple.type] then end

How to solve this depends very much on what you consider "beautiful" here.


text:
Q: Problema con input hidden formulario PHP Tengo que hacer que un formulario básico incluido en una tabla envíe un determinado valor para luego poder borrar la fila, pero no soy capaz de que lo haga.
Se trata de una tabla con usuarios, claves y botones borrar (que utilizo como submit). La idea es que al presionar uno de ellos me guarde la variable $cont como el número de fila en el que estoy, pero siempre me devuelve o la primera, si utilizo al principio $cont=0, o la última, si uso $cont=1. ¿Hay alguna manera de que me guarde la fila en la que está el botón en concreto?
Adjunto código.
echo "
<form action='' method='post'>

USUARIO	CLAVE ENCRIPTADA	";
    $cont=0;
    foreach ($usuarios as $clave=>$valor) {
        echo "
";
        echo "".$usuarios[$clave]."	";
        echo "".$pswds[$clave]."	";
        echo "".$cont."	";
        echo "<input type='hidden' name='cont' value='".$cont."'>";
        echo "<input type='submit' name='borrar' value='BORRAR' id='enviar'/>	";
        $cont++;
    }
    echo "</form>
";


text:
Q: iPhone: Positioning Multiple UITextFields When Keyboard is Shown and Orientation Changes I have a view that contains 10 UITextFields created programatically. I want the following behavior:

*

*When I click on a particular UITextField, the keyboard should hide all the text fields which are visually below the selected text field.

*If I have a text field selected and change the device orientation, the text field and the keyboard should both rotate to the proper orientation without the text field losing the selection focus.

*I need to control whether the return key in the keyboard is active.

How do I manage these text fields to get these behaviors.

A: Add your textfield in scrollview and set tag for all the textfield.Than put following code in you application.You must have to enter you textfield position as per your requirements.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
// Begin animations to move TextFields into view.

if (textField.tag == 1) {

    [UIView beginAnimations: @"moveField" context: nil];
    [UIView setAnimationDelegate: self];
    [UIView setAnimationDuration: 0.5];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
    self.scrlview.frame = CGRectMake(0,30,320,357);
    [UIView commitAnimations];
    textfield2.hidden=YES;
    textfield3.hidden=YES;
    textfield4.hidden=YES;

}

else if(textField.tag == 2)
{

    [UIView beginAnimations: @"moveField" context: nil];
    [UIView setAnimationDelegate: self];
    [UIView setAnimationDuration: 0.5];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
    self.scrlview.frame = CGRectMake(0,30,320,357);
    [UIView commitAnimations];
    textfield1.hidden=YES;
    textfield3.hidden=YES;
    textfield4.hidden=YES;

}

else if(textField.tag == 3)
{

    [UIView beginAnimations: @"moveField" context: nil];
    [UIView setAnimationDelegate: self];
    [UIView setAnimationDuration: 0.5];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
    self.scrlview.frame = CGRectMake(0,25,320,357);
    [UIView commitAnimations];
    textfield1.hidden=YES;
    textfield2.hidden=YES;
    textfield4.hidden=YES;

}

else if(textField.tag == 4)
{

    [UIView beginAnimations: @"moveField" context: nil];
    [UIView setAnimationDelegate: self];
    [UIView setAnimationDuration: 0.5];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
    self.scrlview.frame = CGRectMake(0,20,320,357);
    [UIView commitAnimations];
    textfield1.hidden=YES;
    textfield2.hidden=YES;
    textfield3.hidden=YES;

}

return YES;

}
//Set the objects on the view when device orientation will change.
 -(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {

if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation ==UIInterfaceOrientationLandscapeRight) {

    // set the views oreintation here for landscapemode.
}
if(interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown ||
   interfaceOrientation == UIInterfaceOrientationPortrait) {

    //set the views oreintation here for Portraitmode.
}

}
//Delegate called when orientation will change
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  {
// Return YES for supported orientations
return YES;

}


text:
Q: About React-Native index.js This day I study React Native, but one problem is too hard
react-native-cli: 2.0.1

error: index.js: Unknown option: .plugs. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.

this is my script index.js
import {AppRegistry} from 'react-native';
import App from '~/App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

What is the problem?

A: Replace import App from '~/App'; with import App from './App';


text:
Q: Include subdomain for constrained route in Rails url helper Say I have the following routes that are constrained to specific subdomains:
App::Application.routes.draw do
  constraints :subdomain => "admin" do
    scope :module => "backend", :as => "backend" do
      resources :signups
      root :to => "signups#index"
    end
  end
  constraints :subdomain => "www" do
    resources :main
    root :to => "main#landing"
  end
end

My problem is that root_url and backend_root_url both returns a url on the current subdomain: "http://current-subdomain.lvh.me/" instead the subdomain specific for the resource.
I would like root_url to return "http://www.lvh.me/" and backend_root_url to return "http://admin.lvh.me/" (the behavior should be the same for all resources under the subdomain).
I have tried to accomplish this in rails 3.2 by setting the url options in various places, one being url_options in application controller:
class ApplicationController < ActionController::Base
  def url_options
    {host: "lvh.me", only_path: false}.merge(super)
  end
end

Maybe I need to override the url helpers manually? How would I approach that (accessing the routes etc)?
Edit: I'm able to get the correct result using root_url(:subdomain => "admin") which returns "http://admin.lvh.me/" regardless of the current subdomain. However, I would prefer not having to specify this all over the code.

A: Using "defaults" as shown below will make rails url helpers output the correct subdomain.
App::Application.routes.draw do
  constraints :subdomain => "admin" do
    scope :module => "backend", :as => "backend" do
      defaults :subdomain => "admin" do
        resources :signups
        root :to => "signups#index", :subdomain => "admin"
      end
    end
  end

  constraints :subdomain => "www" do
    defaults :subdomain => "www" do
      resources :main
      root :to => "main#landing"
    end
  end
end


text:
Q: Typeerror : a bytes-like object is required ,not 'str'-python 3.6 for the code I want to make client that sends string ( 'hello') but there is that error
for tcp client :
    from socket import*
    servername ='localhost'
    serverport=12000
     while(1):
         clientsocket=socket(AF_INET,SOCK_STREAM)
         clientsocket.connect((servername,serverport))
         sentence=input("Input sentence:")
         clientsocket.send(sentence)
         ModifiedSentence = clientsocket.recv(1024)
         print ('From Server:', ModifiedSentence)
         clientsocket.close()


text:
Q: How do I execute a sub that doesn't display as a macro? I found an excellent piece of code on this site that I'd like to add to my workbook:
Trim all cells within a workbook(VBA)
The code there is:
Sub DoTrim(Wb As Workbook)
    Dim aCell As Range
    Dim wsh As Worksheet

    '~~> If you are using it in an Add-In, it is advisable
    '~~> to keep the user posted :)
    Application.StatusBar = "Processing Worksheets... Please do not disturb..."
    DoEvents

    Application.ScreenUpdating = False

    For Each wsh In Wb.Worksheets
        With wsh
            Application.StatusBar = "Processing Worksheet " & _
                                    .Name & ". Please do not disturb..."
            DoEvents

            For Each aCell In .UsedRange
                If Not aCell.Value = "" And aCell.HasFormula = False Then
                    With aCell
                        .Value = Replace(.Value, Chr(160), "")
                        .Value = Application.WorksheetFunction.Clean(.Value)
                        .Value = Trim(.Value)
                    End With
                End If
            Next aCell
        End With
    Next wsh

    Application.ScreenUpdating = True
    Application.StatusBar = "Done"
End Sub

I've tried copying and pasting this into an Excel module, but can't figure out how to execute it. I'm really new at all this, so I apologize in advance if this is a stupid question. I've searched on why the Sub won't show up as a macro, and the best possible answer I've found is that it is because it contains variables?
I realize the original poster was trying to modify an Add-In; I'm just hoping there's a way to invoke this on a workbook.
Thanks!

A: The subroutine is expecting a Workbook as a parameter Sub DoTrim(Wb As Workbook), so you won't be able to run it from the macros window
If the Excel Module is in the same Workbook you want to trim, then you can remove the parameter and use the ThisWorkbook object instead to loop through the Worksheets in the Workbook, as below:
Sub DoTrim()
    Dim aCell As Range
    Dim wsh As Worksheet

    '~~> If you are using it in an Add-In, it is advisable
    '~~> to keep the user posted :)
    Application.StatusBar = "Processing Worksheets... Please do not disturb..."
    DoEvents

    Application.ScreenUpdating = False

    For Each wsh In ThisWorkbook.Worksheets
        With wsh
            Application.StatusBar = "Processing Worksheet " & _
                                    .Name & ". Please do not disturb..."
            DoEvents

            For Each aCell In .UsedRange
                If Not aCell.Value = "" And aCell.HasFormula = False Then
                    With aCell
                        .Value = Replace(.Value, Chr(160), "")
                        .Value = Application.WorksheetFunction.Clean(.Value)
                        .Value = Trim(.Value)
                    End With
                End If
            Next aCell
        End With
    Next wsh

    Application.ScreenUpdating = True
    Application.StatusBar = "Done"
End Sub


text:
Q: JSON table data not showing after adding to innerHTML I'm trying to build a simple table using JSON data from a google sheets URL.
I have it working in another instance, using the same JSON data to populate divs in a grid.
But when I apply the same principle to building a table, I can only get the first row to appear – see here:

var url = '[json feed]';

$.getJSON(url, function appendData(data) {

  var tableContent = document.getElementById("content");

  var entries = data.feed.entry;
  console.log(entries);

  for (var i = 0; i < entries.length; i++) {

    var tableRow = document.createElement("tr");

    tableRow.innerHTML = '' + entries[i].gsx$position.$t; + '	' + entries[i].gsx$team.$t; + '	' + entries[i].gsx$weeklyscore.$t; + '	' + entries[i].gsx$totals.$t; + '	';

    tableContent.appendChild(tableRow);

  };
});
table {
  border: 1px solid black;
}

td {
  border: 1px solid black;
}

        Position
        Team
        Weekly Score
        Totals

I've been over and over it, and I cannot figure out how to get to the rest of the JSON data between the  tags after tableRow.innerHTML = to populate the rest of the table.
I'm sure it's something simple I'm not getting, but any help would be appreciated! Thanks

A: Please try this,
var tableRow = document.createElement("tr");

var str = '' + entries[i].gsx$position.$t + '	' + entries[i].gsx$team.$t + '	' + entries[i].gsx$weeklyscore.$t + '	' + entries[i].gsx$totals.$t + '	';
tableRow.innerHTML = str;
tableContent.appendChild(tableRow);

There was an extra ; in all "$t" like this "$t;" in your code.

A: Set the innerHTML of your table's tbody--not row.
Note: Using innerHTML to do this is not something I recommend, but here's an example regardless.

document.getElementById("bn_insert_body").addEventListener("click", e => {

  const rows = `
Body Column 1	Body Column 2	Body Column 3

Body Column 1	Body Column 2	Body Column 3
`;

  document.querySelector("#my_table tbody").innerHTML = rows;

});

    Column 1
    Column 2
    Column 3

<button type="button" id="bn_insert_body">Insert Data</button>


text:
Q: R count matched strings I am trying count matched items between strings:
target_str = "a,b,c"
table1 = data.frame(name = c("p1","p2","p3","p4"),
                    str = c("a,b","a","d,e,f","a,a"))

Based on target_str, count how many matches. I want my output table look like this:
name       matches
p1         2        #matches a and b
p2         1        #matches a
p3         0        #no matches
p4         1        #if has duplicate, count only once

I have about 1 million target_strs that need to calculate the matches, so speed is very important. Appreciate any suggestions. Thanks in advance!

A: target_str = "a,b,c"
split_str <- strsplit(target_str, split = ",")[[1]]
table1 = data.frame(name = c("p1","p2","p3","p4"),
                    str = c("a,b","a","d,e,f","a,a"))
data.frame(name = table1$name,
           matches = rowSums(sapply(split_str, grepl, x = table1$str)))

#   name matches
# 1   p1       2
# 2   p2       1
# 3   p3       0
# 4   p4       1

A: This should be fairly fast:
# target string modified to be a character vector:
target_str <- unlist(strsplit(c("a,b,c"), split=","))

# separate each obervations strings:
stringList <- sapply(s, strsplit, split=",")

# get counts, put into data.frame
table1$Counts <- sapply(stringList, function(i) sum(i %in% target_str))

A: This cbinds counts to the first column, preserved as a dataframe with drop=FALSE. Counts are added from successive test for "in-ness" with grepl:
cbind( table1[ ,1,drop=FALSE], counts=rowSums(sapply( scan(text=target_str, sep= ",", what=""),  function(t) { grepl( t, table1$str)})) )
Read 3 items
  name counts
a   p1      2
b   p2      1
c   p3      0


text:
Q: Feathersjs filter results I have created a node/feathers project using this chat application guide as a base. It's working great, but now I would like to filter the results the api is giving. For example, when user makes GET request to /messages I would like the response to include only the messages that the authorized user has created, not anyone else's messages. Auth is working correctly in the api and message items have the userId who created the message, but I just don't understand what and where I'm supposed to do to filter the messages according to the user id. After hours of googling I couldn't find anything related to this or anyone even asking the question, so what am I missing here?

A: You can do a manual filtering. Both on before and after hooks. How to use hooks.
In before hooks you can create a function that update your query object to only get/find data it owns.
hook.params.query = { ... , ownedBy: hook.params.user._id }

Or do result filtering in after hooks, you have the hook.result which is the only thing you can manipulate in the after hooks. Then you can use Array.prototype.filter() to filter the results the user gets.


text:
Q: Dither in Leech lattice quantization! Can you please help me how to generate a dither signal $\mathbf{U}$, where $\mathbf{U}$ is a random vector of length 24 that is uniformly distributed over the Voronoi region of the Leech lattice.
Best,
Farzad

A: Hi all,
I refer readers to the paper, "Dithering in lattice quantization"by A. Kirac, in this paper he explains how to generate dither signals to have quantization error that is uniformly distributed on the voronoi cell.
Best,
Farzad


text:
Q: C# factory - is upcast a must? Does the C# factory pattern require an upcast?
I want God in class library G to create an Adam in class library A without making G dependant on A. God produces Adams for consumption by Eve in class library E, and it's OK for Eve to know and depend on Adam.
(edit - this sample keeps getting better and better :)
The solution I could think of is having an AdamFactory in A. This way AdamFactory knows Adam and can easily create it (possibly by just calling Adam's constructor). God receives an AdamFactory and can order it to CreateAdam.
Now, because God isn't allowed to know Adam, AdamFacotry's CreateAdam must return an object, and this requires Eve to up-cast the object returned by AdamFactory to an Adam.
This will work, I think. However, I feel uneasy about up-casting as it's a no-no. Is this really a must?
P.S. - No Blasphemy intended, and I apologize if someone's feelings were hurt. It seemed better to use God and Adam instead of Creator and Created because the two latter words are too similar to each other.
Edit: Re interfaces suggestion. Let's assume Adam has two methods: ProvideLove, ProvideFood and ProvideProtection (we're keeping this sample kis-safe :). Eve uses Adam for these two purposes, but of course God doesn't. So why provide God with the knowledge that AdamFactor returns something that implements an IAdam and not just an object? I don't get it!
Edit: The working code (with everybody in the same library, which my goal is to separate to different libraries) looks something like this:
Adam God.LoadAdam(AdamID theAdamID)
       var adam = new Adam(theAdamId, this)

Adam.Adam(AdamID theAdamID, God theGod)
      _god = theGod
      _mind  = theGod.LoadMind(theAdamId, this)

Mind God.LoadMind (AdamID theAdamID, Adam theAdam)
      var mind  = new Mind (theAdam)
      var mindId = new minId(theAdamId)
      mind.DeserializeFromFile(minId)

Mind.Mind (Adam theAdam)
      _adam = theAdam

A: I am not sure I completely understand the requirements but here is a suggestion:

//in assembly G
public abstract class HumanFactory<T>
{
    public abstract T CreateHuman();
}

//in assembly A
public class Adam { }
//in assembly A
public class AdamFactory : HumanFactory<Adam>
{
    public override Adam CreateHuman()
    {
        return new Adam();
    }
}

//in assembly G
public class God
{
    public T Create<T>(HumanFactory<T> factory)
    {
        return factory.CreateHuman();
    }
}

and the usage:

//Somewhere in assembly E
Adam adam = new God().Create(new AdamFactory());

A: What about using interfaces so God knows IAdam, or something like IHuman ?

A: I think you could use dependence injection. Try with an Inversion Of Control (IoC) container like Unity 2, StructureMap, Or Castle of Windsor.

A: You're describing an abstract factory pattern, although the "child" factories (e.g. AdamFactory) normally have something in common so you'd expect them to produce something more like a common interface rather than just an object (see Davide's answer)
You're right to worry about the up-cast since that will tie Eve to the implementation of Adam which defeats the purpose of a factory (unless you're really using it as a builder).
Question is, why do you need the God class at all?

A: Well, if God is a persistence class library as you mentioned in comment, then it should not influence the class design of the rest of the system.
So, I wouldn't add unnecessary interfaces. It's Ok to return an object from deserializer and downcast afterwards (e.g. BinaryFormatter, XmlSerializer).
The better way would be to make your deserializer generic.

A: OK, what about sprinkling in some generics here?
Let's say God may accept Factories of any type T that adhere to the following interface:
interface IFactory  {
  Type CreatedType { get; }
  object Create();
}

An abstract class to implement this may look like this:
abstract class AbstractFactory<T> : IFactory {
  public Type CreatedType { get { return typeof(T); }
  public virtual object Create() {
    return innerCreate();
  }
  protected abstract override T innerCreate();
}

Now, you can register factories with God:
God.RegisterFactory(new AdamFactory());

AdamFactory inherits from AbstractFactory<Adam>
God stores its factories in a dictionary where the key is the type returned by the IFactory interface
the Create Method now looks like that:
God.Create<Adam>();

God looks into its factories, sees there is one for typeof(T) of the generic method, retrieves the factory, calls create and downcasts to T.
What do you think?


text:
Q: react zoom/pan scatter plot, data filtering vs clip I have a question in React implementation for zoom/pan function for a scatter plot.
I wonder what approach would be good and want to hear opinions of React & data visualization expert.
I am specifically interested in implementing zoom/pan function of a scatter plot that is dynamically changing data range to visualize.
(Approach 1) Given a data range (controlled by mouse wheel event), first, filter the data, and render circles () for the filtered data. In this case, each circle will be generated with new key such that
const circles = [];
filteredData.forEach( (d, index) => {
     circleProps = { /*..compute circle props... (e.g. position within a SVG) */ }
     circles.push(
          <circle key={`circle-${index}`} {...circleProps} />
     );
});

Thus, every time the data range changes, it will create new set of circles located within the range.
(Approach 2) Similar to Approach 1 but no filtering on the data. Instead, use clip path to visualize only the circles within the range. In this case, it will update entire circles according to re-calculated positions but it will only create the circles one time at the beginning.
What would better approach? Or, any other options to handle large-scale data? Also, please correct me if anything is wrong.
Thanks.


text:
Q: How can i read an unknown number of integers until space character is reached ? (C++) I need to read numbers from console separated by ; until i get to the space character. The input should look something like this: 3;1  -2;-1;1     1;1;3;2 . There can by more than one space between each set of numbers and i need to insert each set of numbers into a vector . My initial ideea was something like this:
char c;
std::vector<double> coordinates;
while(std::cin >> c){
    if(c != ' ' & c != ';'){
        double a = c - 48;
        coordinates.push_back(a);
    }
}

The problem with this is that converting a char to an integer using ASCII can't be made if I have negative numbers. If anyone could give me another method to do this type of reading or can give me some advice I would appreciate it very much!

A: here's the code to do what you want
you can get the idea you wanted from it
don't forget to read comments
i also added char 'e' to end input
#include <iostream>
#include <vector>
#include <string>
int main()
{
    std::string cnum="";
    std::vector<std::vector<long long>> mainVec;
    int pos=0;
    while (true)
    {
        std::vector<long long> cvec;
        while (true) {
             //std::cin wont get spaces
            char c=getchar();
            //we reached the space so lets parse it and go to next num
            if (c == ';') {
                int num;
                try
                {
                    //will throw if can't parse so inside of try cache
                    num=std::atoll(cnum.c_str());
                    cvec.push_back(num);
                }
                catch (const std::exception&)
                {
                    std::cout << "can't parse the number";
                }
              //make ready for next num
                cnum.clear();
            }
            else if (c == ' ') {

                int num;
                try
                {                   //will throw if can't parse so inside of try cache
                    num=std::atoll(cnum.c_str());
                    cvec.push_back(num);
                }
                catch (const std::exception&) {
                    std::cout << "can't parse the number";
                }
                //go to next vector
                mainVec.push_back(cvec);
                cvec.clear();
                //or use std::move
                break;
            }
            //end this operation
            else if (c == 'e') {
                int num;
                try
                {                   //will throw if can't parse so inside of try cache
                   num= std::atoll(cnum.c_str());
                    cvec.push_back(num);
                }
                catch (const std::exception&) {
                    std::cout << "can't parse the number";
                }
                //add last vector and break the loops
                mainVec.push_back(cvec);
                goto rest;
            }
            else
                cnum += c;
        }
    }
rest:
    std::cout << "the end";

}

you can do the optimizations yourself (reducing rapeated code in each if case)

A: What you need is a way to look ahead in the input. If you know whether the next character is a space, a semi-colon, a digit or a minus sign then you can make the correct decision on what to read.
Here's function that does this for you
int peek_char(istream& input)
{
    int ch = input.get();
    if (ch >= 0)
        input.put_back(ch);
    return ch;
}

With this function you know what the next character is going to be without reading it. If there is no next character (because of end of file) it will return a negative number.

A: You could use istream::peek:
auto read_sets(std::istream& is) {
    std::vector<std::vector<double>> sets;
    std::vector<double> current_vector;

    double number;
    while (is >> number)
    {
        current_vector.push_back(number);
        switch (is.peek())
        {
            case ';': // ignore semicolons
                is.ignore(1);
                break;

            case ' ': // move to the next set
                sets.push_back(std::move(current_vector));
                current_vector.clear();
                break;

            default: // no need to handle dots and digits. EOF is handled in while condition
                break;
        }
    }

    sets.push_back(std::move(current_vector)); // push the last set
    return sets;
}

A: Ok so i tried all the suggestions that were posted here, and i couldn't really make it work for my problem, mostly because these suggestions used advanced stuff that i haven't learn. For the getline suggestion it was almost working but i couldn't make it work perfectly. So, i remembered that i did a similar kind of reading before and i tried to use that idea and it worked very good. I don't think that it's the best idea but it's a trick that works and i wanted to post it here if anyone will have the same problem as me. The detail that i forgot to mention is that i know the dimension of the vector can be 2, 3 or 4, (because i need to treat that vector as a point in 2,3 or 4 dimension in my problem) so i can use scanf for that, like this:
double a,b,c,d;
std::vector<Point *> points;
int x = scanf("%lf;%lf;%lf;%lf ",&a,&b,&c,&d);
while(x != EOF){
    if(x == 2){
        points.emplace_back(new Point2D(a,b));
    }
    if(x == 3){
        points.emplace_back(new Point3D(a,b,c));
    }
    if(x==4){
        points.emplace_back(new Point4D(a,b,c,d));
    }
    x = scanf("%lf;%lf;%lf;%lf ", &a,&b,&c,&d);
    if(x == 0) break;   //i don't think this is necesary , but without it my debugger wouldn't work

The idea of the problem is that i have a class Point that i extended in 3 more classes, Poin2D, Point3D, Point4D. Point2D has 2 coordinates, Point3D has 3 coordinates and Point4D has 4 coordinates and each object has a constructor with the coordinates as parameters
Thanks everyone for trying to help me! :)


text:
Q: How to submit a form to 2 different url's I have a form with 4 inputs:

*

*Name

*Email

*Voucher

*Terms

This script is for authenticating into a wifi system. The system only cares about the Voucher value. But i want to record the entire form for records.
Is there any way to have the system submit the form a first time to one url via ajax and then just the voucher as a post ?
I have attached my code below:
Thanks for your help !!
<form data-validate="parsley" data-show-errors="true" data-focus="first" name="input" method="post" action="login">
      <input type="hidden" name="by" value="voucher" />
      <input type="hidden" name="page_error" value="en_.html" />

        <unifi if="has_error">

<unifi error="error" />

        <unifi else="has_error" />

<unifi txt="UseVoucher" />

        </unifi>
        <fieldset class="large-text">

          Name
            <input id="name" name="name" data-required="true" data-minlength="2" data-error-container="div#error" data-error-message="Please enter your name" type="text"  class="textinput" placeholder="John Smith" value="" autocomplete="on" />
          Email
            <input id="E-mail" name="E-mail" data-required="true" data-type="email" data-error-container="div#error" data-error-message="Please enter your E-mail adress" type="text" class="textinput" placeholder="John.Smith@me.com" value="" autocomplete="on" />

            Voucher Code
            <input id="voucher" name="voucher" data-minlength="10" data-maxlength="10" data-error-container="div#error" data-required="true" data-error-message="Please enter a correct voucher code" type="text" class="textinput" placeholder="00000-00000" value="" autocomplete="off" />

        </fieldset>

          <input type="checkbox" name="remember" value="0" data-mincheck="1" data-error-container="div#error" data-error-message="Please accept the terms and conditions before conecting"> I accept the terms and conditions

  <button type="submit" name="connect" type="submit" value="Connect" id="connect" class="btn btn-info btn-block">Connect</button>
    </form>
  </unifi>


text:
Q: What is the file encoding method being used here? Binary files are frequently attached to SEC filings (see example here) and I am writing a parser to capture this text and re-create the file.
It doesn't matter if the file is an Excel spreadsheet or PDF (which is the sample below and linked to), the encoding method looks the same.  Its not Base64; I don't recognize it.
Do you?  TIA.
<DOCUMENT>
<TYPE>LETTER
<SEQUENCE>1
<FILENAME>filename1.pdf
<TEXT>
<PDF>
begin 644 filename1.pdf
M)5!$1BTQ+C4-)>+CS],-"C,W(#`@;V)J#3P\+TQI;F5A<FEZ960@,2],(#$T
M-C0S,2]/(#,Y+T4@,30Q-S0W+TX@,2]4(#$T-C$R,R]((%L@-#8X(#$V,ET^
M/@UE;F1O8FH-("`@("`@("`@("`@("`@#0HT-R`P(&]B:@T\/"]$96-O9&50
M87)M<SP\+T-O;'5M;G,@-2]0<F5D:6-T;W(@,3(^/B]&:6QT97(O1FQA=&5$
M96-O9&4O241;/#`T-#$S,4$Q.#`Q-D,X-#!!-S$X0S-%,T$X1D5$0S!!/CQ!
M,31&,S%#,T(Y-T(T-#0P.3)"-#<P148U,D8W0C,X13Y=+TEN9&5X6S,W(#,R
....
...<snip>...
....
M``$F1B;-S0Q,#`S,"2"2-PU$,O:!2(:C0-E_QTS!;`;&H4$R/0&1C`P``08`
M_(\&40T*96YD<W1R96%M#65N9&]B:@US=&%R='AR968-"C$Q-@T*)25%3T8-
!"C\_
`
end
</PDF>
</TEXT>
</DOCUMENT>

A: The answer turned out to be old school: UUEncoding
Thanks to all who viewed the question.


text:
Q: How to navigate to a new page from within a OnFrameNavigated handler I am porting a Windows Phone 8 app to Windows Store 8.1 and I am having some trouble with navigating to a new page when Frame.Navigate(...) is called from within a OnFrameNavigated handler.
The long story:
The App manages different "Media" objects like Books or Films. To edit the properties (title, author, etc.) of such an element the WP uses a custom "MediaEditor" control that was inspired by the DatePicker from the WP ToolKit:
Instead of manually navigating to an Editor/Picker page the Editor/Picker is capsuled in its own class. This class hooks up to the ApplicationFrame and handles Navigation to the Editor/Picker page on its own. When the ApplicationFrame navigates back to the page/content that was visible before showing the Editor/Picker the result can be processed, e.g. fire an event with the picked date.
There is one difference in my MediaEditor compared to the DatePicker:
If the MediaItem that is currently edited is related to another MediaItem (e.g. Movie A is the film version of Book A) the editing of this item can directly been started from within the MediaEditor:

*

*call mediaEditor.Edit(MovieA) --> MediaEditor for MovieA is displayed

*Select to Edit BookA from within MediaEditor --> MediaEditor for MovieA is closed and MediaEditor for BoolB is displayed

This is done by calling Edit(BookA) from within OnFrameNavigated. Thus the complete Navigation is:

*

*call mediaEditor.Edit(MovieA) --> Frame.Navigate(typeof(MediaEditorPage), MovieA)

*Select to Edit BookA --> Frame.GoBack()

*Detect that BookA should be edited in OnFrameNavigated --> Frame.Navigate(typeof(MediaEditorPage), BookA)

While this works on Windows Phone this does not work on Win 8.1. Frame.Navigate(typeof(MediaEditorPage), BookA) is simply ignored. There is no OnNavigationFailed, no console output, nothing. The App navigates back to the first page (the one that original called mediaEditor.Edit(MovieA)) and nothing else happens.
What exactly is the problem here?
MediaEditor mediaEditor = new MediaEditor();
mediaEditor.Edit(bookItem);

public class MediaEditor {
    private Frame applicationFrame;
    private object frameContentWhenOpened;

    public void Edit(MediaItem item) {
        applicationFrame = Window.Current.Content as Frame;

        if (applicationFrame != null) {
            frameContentWhenOpened = applicationFrame.Content;

            applicationFrame.Navigated += OnFrameNavigated;
            applicationFrame.NavigationFailed += OnNavigationFailed;

            applicationFrame.Navigate(typeof(MediaEditorPage), item);
        }
    }

    void OnNavigationFailed(object sender, NavigationFailedEventArgs e) {
        System.Diagnostics.Debug.WriteLine(e);
    }

    MediaEditorPage editorPage;
    void OnFrameNavigated(object sender, NavigationFailedEventArgs e) {
        if (e.Content == frameContentWhenOpened) {
            applicationFrame.Navigated -= OnFrameNavigated;
            applicationFrame.NavigationFailed -= OnNavigationFailed;

            applicationFrame = null;
            frameContentWhenOpened = null;

            if (editorPage != null) {
                if (editorPage.EditOtherItem)
                   // Directly start editing another Item
                   Edit(editorPage.OtherItem);
                else
                   // Finish editing, fire Events, etc
            }
        } else {
            editorPage = e.Content as MediaEditorPage ;
        }
    }

}