text:
Q: how to unfreeze X I'm having a bit of instability lately, and while I've given up on fixing it (I thought I'd broken something irreparably in Quantal so I wound up upgrading to Raring for lack of any better ideas, so I have to live with a little bit of instability for now), it occasionally (once a week, often when I'm on a Skype call) happens that X stops refreshing, but all process continue to run properly in the background (music will keep playing until it reaches the end of a file, Skype continues to work, ssh processes keep going).
Is there any way for me to get X to start responding again at times like this? Normally I'd just let everything run out as best I can and then hard reboot, but I'm wondering if there's any way I can save it. Ctrl+Alt+F1 doesn't seem to have any useful effect -- it gets rid of X on one display, but I never get an interactive shell back.
Thanks!

A: Well, I managed to address my primary disincentive for hard rebooting -- I had a (long) ssh process running on that machine which I'd failed to nohup, but I needed a file from the machine to work on. Managed to take control of the process via an ssh connection from a different machine, and scp'ed the relevant file off meanwhile. Whee! Not the best solution, but at least I got to use my Linux brain.


text:
Q: Logic error in my Longest Common Subsequence python I have implemented solution of Longest Common Subsequence using Dynamic programming in python. For those who don't know LCS here's the link.
https://www.tutorialspoint.com/design_and_analysis_of_algorithms/design_and_analysis_of_algorithms_longest_common_subsequence.htm
My code is not returning the the most optimal answer. What is wrong in my logic ?
import enum

class LCS:

    class Dir(enum.Enum):
        up = 1
        diagonal = 2
        left = 3
        none = 0

    def LCS(self, x, y):
        self.DP = {}
        m = len(x) - 1
        n = len(y) - 1
        self.recursion(x, y, m, n)
        print(self.DP)
        self.printLCS(x, m, n)

    def recursion(self, x, y, i, j):
        if i == 0 or j == 0:
            return [0, self.Dir.none]
        else:
            if (i, j) not in self.DP:
                if x[i] == y[j]:
                    cost = self.recursion(x, y, i - 1, j - 1)[0] + 1
                    dir = self.Dir.diagonal
                else:
                    first = self.recursion(x, y, i - 1, j)
                    second = self.recursion(x, y, i, j - 1)
                    if first[0] >= second[0]:
                        cost = first[0]
                        dir = self.Dir.up
                    else:
                        cost = second[0]
                        dir = self.Dir.left

                self.DP[(i, j)] = [cost, dir]

        return self.DP[(i, j)]

    def printLCS(self, string, i, j):
        if i == 0 or j == 0:
            return
        elif self.DP[(i, j)][1] == self.Dir.diagonal:
            self.printLCS(string, i - 1, j - 1)
            print(string[i], end="")
        elif self.DP[(i, j)][1] == self.Dir.up:
            self.printLCS(string, i - 1, j)
        else:
            self.printLCS(string, i, j - 1)

x = "BDCABA"
y = "ABCBDAB"
sol = LCS()
sol.LCS(x, y)

Expected = "BCBA", Actual = "DAB"

A: the problem is your base states.
the string in python is 0-base, cause of this the first character of string s is not s[1] its s[0] and you must end your recursion when you reach before first element not at first element.
just replace if i == 0 or j == 0: with if i == -1 or j == -1: in function printLCS and recursion then you will get output BDAB which is the one of correct answers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update weight vector regardless of correctness for perceptron algorithm For the perceptron algorithm, what will happen if I update weight vector for both correct and wrong prediction instead of just for wrong predictions? What will be the plot of number of wrong predictions look like w.r.t. number of passes? The algorithm of perceptron is the one proposed by Rosenblatt (1958) as below:

My question is that what will happen if we remove if condition and execute update for all instances in each pass.

A: In the learning algorithm of the perceptron, the weights are not updated after a correct response.
The learning rule says that the weight vector $\mathbf{w}=(w_i,...w_n)$ is updated according to $w_i(t+1)=w_i(t)+(d_j-y_j(t))x_{ji}$ (see wikipedia). So if the output $y_j$ (obtained applying the $j$th input vector $x_j$) is equal to the desired output $d_j$, that is $d_j=y_j(t)$, the rule becomes $w_i(t+1)=w_i(t)+0$, hence there is no change to the weight.

A: First, the algorithm you cite is not from Rosenblatt (1958). Second, the cited algorithm is, at best, unclear, if not incorrect.  What is s.t. supposed to mean? "subject to", as in constrained optimisation? What happens if there is more then one $i$ for which the if condition is satisfied? Does the algorithm ever stop?
I'll try to answer your question under the assumptions:

*

*that we are actually talking about the following algorithm:

and

*that you want to know what happens if the if condition (line 5) is removed, so that the lines 6 and 7 are executed unconditionally:

In that case, the algorithm obviously never converges. But, as in each pass through the while loop exactly the same things happen, $\vec{w}$ changes by the same amount in each pass. Thus, in pass $t$, $\vec{w}(t) = t \cdot \vec{w}(1)$.
Note:

*

*The direction of $\vec{w}$ never changes after the first pass, only its size. Consequently, the number of wrong predictions w.r.t. number of passes will be flat (i.e. constant) after the first pass.

*In each pass, you add to $\vec{w}$ all elements $\vec{x}_i : y_i = +1$ and subtract all $\vec{x}_i : y_i = -1$. In other words:
$$
  \vec{w}(t+1) = \vec{w}(t) + \sum_{i : y_i = +1} \vec{x}_i - \sum_{i : y_i = -1} \vec{x}_i
$$
Now, the first sum is obviously the mean of all $\vec{x}_i : y_i = +1$, weighted by the number of such $\vec{x}_i$. The same, but with $y_i = -1$, holds for the second sum. Consequently, $\vec{w}$ is the weighted difference between the means of the two classes.

The figure below shows two classes, the line (blue) connecting their means and the direction of $\vec{w}$ (dashed, orange):


text:
Q: Any Syntactical error I found source of an application of adt and i imported in android studio, after the Gradle build there shown an single error in java code....i dont know whether it is syntactical or symantic...can u please rectify
    String str2;
    if (arrayOfString[i].contains("%")) {
        str2 = arrayOfString[i].split("%")[1];
    }
    String str1;
    for (Settingss.this.setnum = (Settingss.this.setnum + str2 + ","); ; Settingss.this.setnum = (Settingss.this.setnum + str1 + ","))
    {
            i++;
            break;
            str1 = arrayOfString[i];
    }

The error occured at 6th line at "str2"..android studio quoted that "str2" may not have been initialized.
This is not the full code, it is just at the error part.

A: change String str2 to String str2 = null;
the reason Android Studio is throwing the error is because the variable could be declared but never initialized i.e. str2 = XXX;


text:
Q: Error-invalid length for a base-64 char array I have silverlight app that post some data to another web application ,the data to post is converted to base 64 using code
byte[] byteArray = Encoding.UTF8.GetBytes(sDataToPost);
sDataToPost = Convert.ToBase64String(byteArray);

Another webapplication
get the data using the code
strText = System.Text.Encoding.ASCII.GetString(System.Convert.FromBase64String(postedData));

But it gives the exception invalid length for a base-64 char array
Thanks in Advance
DNM

A: Depending on how you post the data its quite possible that the Base64 string is being munged a little more.  For example URL encoders may do odd things with the + and = symbols in the Base64 string.


text:
Q: ModuleNotFoundError: No module named 'display' in python I have already installed 'display' module for python using the following code:
pip3 install display
However,
when I try to import a module with the code given below,
from display import Displayable
I get the following error:
ModuleNotFoundError: No module named 'display'
Any help will be greatly appreciated. Thanks.

A: This module is not widely used and does not have proper documentation.
I suggest using pprint to display data nicely.
Start by pip installing pprint:
Windows:
pip install pprint36
Mac:
pip3 install pprint36
Code
import pprint
stuff = [['apple', 'bannana'],'spam', 'eggs', 'lumberjack', 'knights', 'ni']
stuff.insert(0, stuff[:])
pp = pprint.PrettyPrinter(indent=4,compact=False)
pp.pprint(stuff)

From pprint docs


text:
Q: "two-thirds (of) (a) teaspoon(s) of salt" How should I say it?

Add two-thirds (of) (a) teaspoon(s) of salt and knead the dough for five minutes.

A: I would prefer "two thirds of a teaspoon" in speech and formal writing. In the context of a recipe, however, the measurement can probably be omitted since it was probably given above in the list of ingredients:

Ingredients:

*

*⅔tsp. Salt

*... other ingredients

Instructions:
... Add salt and knead the dough for five minutes.


text:
Q: How do we show that photons generated by a constant electric current are distributed according to a Poisson distribution? I saw the answer sometimes ago in a book "Quantum Electronics" or similar title. I don't remember the author since I lost the book. The book sets ( I believe so ) a constant electric current $I$ in a cable along the $z$ axis. Then, after a long ( but not straightforward ) calculation it arrives to the result I mentioned above.
Edit: A possible analogous calculation that OP refered to, Klein-Gordon particles generated by a classical source: problem 4.1  in these notes(In fact a solution manual to Peskin and Schroeder). If this is not what OP refered to, please delete it.


text:
Q: Неадекватно ведет себя tcp клиент для чата Добрый день. В целях обучения пишу чат на протоколе TCP. В консольной версии все хорошо, чат нормально отправляет сообщения серверу, а сервер рассылает всем клиентам. Но стоит только мне перенести этот же код на WPF - все. Клиент начинает слать серверу пустые запросы. В итоге сервер забивается этим

А в консольном варианте все хорошо

Сервер - http://pastebin.com/c2Ru2j30
Консольный рабочий вариант - http://pastebin.com/0707wqKu
Не работающий WPF - http://pastebin.com/CLpRUGKG

A: Решение оказалось банальная невнимательность.
Всего-то надо убрать из кода:
    try
    {
        client.Connect(HOST, PORT); //подключение клиента
        stream = client.GetStream(); // получаем поток

        string message = userName;
        byte[] data = Encoding.Unicode.GetBytes(message);
        stream.Write(data, 0, data.Length);

        // запускаем новый поток для получения данных
        Thread receiveThread = new Thread(new ThreadStart(receiveMessage));
        receiveThread.Start(); //старт потока прослушивания входящих сообщений
        textBoxChat.AppendText("Добро пожаловать, " + userName);
    }
    catch (Exception ex)
    {
        textBoxChat.AppendText(ex.Message);
    }
    finally
    {
        disconnect();
    }

Это:
    finally
{
    disconnect();
}


text:
Q: Arrays Simplexml accessing attributes different ways Sorry, if I missed the answer here, but I really couldn't find it between all the attribute-questions.
I used SimpleXML to parse an rss-feed and that works great in dev (xampp)
var_dump:
object(SimpleXMLElement)[672]
  public '@attributes' =>
    array (size=2)
      'name' => string 'A name' (length=11)
      'description' => string 'A very long desc' (length=12)

That worked well for me on dev:
$desc = (string) $xml->attributes()['description'];

...but not on my web-server. I found a solution, that works in both cases:
$v = 'description';
$desc = (string) $xml->attributes()->$v;

Can someone please tell me why. Is this version-related?
Again: Sorry the question has been asked before.
Edit:
I just found out, that this works also:
$a = $xml->attributes();
$desc = (string) $a['description'];

Same question :-)

A: This has nothing to do with SimpleXML directly – accessing an element inside an array that is returned by a function by using functioncall()['key'] is only possible since PHP version 5.4.
http://www.php.net/manual/en/language.types.array.php:

"As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable."


text:
Q: Issues with getting Selected values from drop down list I am trying to get the value from a drop down list in JavaScript and HTML which are two dates ( the format is just year), but I have an error of say " TypeError: "#sortDateFrom".val is not a function "
I want to check if the beginning is smaller then the end.
MY HTML code:

    <select class="form-control" id="sortDateFrom">
        <option selected disabled>-Date From-</option>
        <option>1900</option>
        <option>1910</option>
        <option>1920</option>
        <option>1930</option>
        <option>1940</option>
        <option>1950</option>
        <option>1960</option>
        <option>1970</option>
        <option>1980</option>
        <option>1990</option>
        <option>2000</option>
        <option>2010</option>
    </select>

    <select class="form-control" id="sortDateTo">
        <option selected disabled>-Date To-</option>
        <option>1900</option>
        <option>1910</option>
        <option>1920</option>
        <option>1930</option>
        <option>1940</option>
        <option>1950</option>
        <option>1960</option>
        <option>1970</option>
        <option>1980</option>
        <option>1990</option>
        <option>2000</option>
        <option>2010</option>
    </select>

And my Function in Javascript:

A: You forgot the jquery $
You also need to check when the value changes not when the page is ready

A: Look this:
You not pass $ in $('#sortDateFrom option:selected').text()
Is necessary pass option:selected too. Please look you not use value in options. For this you use .text() not .val().

$(function() {

    $('#sortDateFrom, #sortDateTo').change(function() {

        var startDate = $('#sortDateFrom option:selected').text();
        var endDate = $('#sortDateTo option:selected').text();

        if (startDate < endDate) {
            console.log("The beginning date must be smaller then the end date ");
        }
    });
});

  <select class="form-control" id="sortDateFrom">
    <option selected disabled>-Date From-</option>
    <option>1900</option>
    <option>1910</option>
    <option>1920</option>
    <option>1930</option>
    <option>1940</option>
    <option>1950</option>
    <option>1960</option>
    <option>1970</option>
    <option>1980</option>
    <option>1990</option>
    <option>2000</option>
    <option>2010</option>
  </select>

  <select class="form-control" id="sortDateTo">
    <option selected disabled>-Date To-</option>
    <option>1900</option>
    <option>1910</option>
    <option>1920</option>
    <option>1930</option>
    <option>1940</option>
    <option>1950</option>
    <option>1960</option>
    <option>1970</option>
    <option>1980</option>
    <option>1990</option>
    <option>2000</option>
    <option>2010</option>
  </select>


text:
Q: How to find specific text on the screen and its location? C# I wanted to be able to check if specific text is displayed somewhere on the screen and, if possible, determine its location so that the program could display a popup above the specific text.
I tried to use OCR (Tesseract) to scan screenshots but it correctly sees the text about 20% of the time, even after trying multiple image formats. Is this a common problem, is Tesseract not a great OCR, or are there any ways to improve the quality of the screenshots for the OCR to work better?
I capture and save the screenshots this way:
Bitmap captureBitmap = new Bitmap(1920, 1080, PixelFormat.Format32bppPArgb);
Rectangle captureRectangle = Screen.AllScreens[0].Bounds;
Graphics captureGraphics = Graphics.FromImage(captureBitmap);
captureGraphics.CopyFromScreen(captureRectangle.Left, captureRectangle.Top, 0, 0, captureRectangle.Size);
captureBitmap.Save(@"./Capture.png", System.Drawing.Imaging.ImageFormat.Png);

The OCR (Tesseract) is implemented this way:
var ImagePath = "./Capture.png";

using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
{
     using (var img = Pix.LoadFromFile(ImagePath))
     {
          using (var page = engine.Process(img))
          {
                var text = page.GetText();
                if (text.Contains(selectedword))
                {
                      MessageBox.Show("This word is here");
                }
          }
     }
 }

Are there any better ways to scan the screen / screenshots for specific text?


text:
Q: Flask MongoDB - prevent multiple concurrent calls to an endpoint by the same user We have a Flask + MongoDB web application based on MongoEngine. We are trying to enforce a user-level limit in a thread safe manner, meaning we need to prevent multiple concurrent calls to an endpoint by the same user.
Looking at older threads and MongoEngine reference, we came up with this solutions. Relevant threads we found: It's not possible to lock a mongodb document. What if I need to?
https://www.mongodb.com/community/forums/t/locking-documents-in-mongo/6865/2
Our solution is based on a boolean field in the user document which is used as a mutex. The lock field is set to True with an atomic modify, operations are performed by the endpoint and then the lock is released (False).
To enforce this we have a lock attribute in the User model:
User
  - ...
  - plans
      - execution_plan
          - ...
          - lock (bool)

The following code decorates the endpoint.
def execution_plans_decorator(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user: User = User.objects.get(_id=get_jwt_identity())
        execution_plan = user.plans.execution_plan

        timeout = time.time() + current_app.config['PLAN_LOCK_TIMEOUT']
        modified = False
        while time.time() < timeout:
            # acquire lock with an atomic query
            modified = user.modify(
                query={f'plans__execution_plan__lock': False},
                **{f'set__plans__execution_plan__lock': True}
            )
            if modified:
                logger.info(f'lock acquired for execution_plan')
                break
            time.sleep(0.5)
        if not modified:
            logger.info(f'could not acquire lock for execution_plan')
            return jsonify({'msg': 'Too many concurrent requests'}), 429

        # if a condition is not met, block the endpoint
        if not condition:
            execution_plan.lock = False
            user.save()
            return jsonify({
                'msg': f'Max number of executions reached. Upgrade execution plan'
            }), 402

        # execute the decorated function
        try:
            rv = f(*args, **kwargs)
        except Exception:
            # re-raise exception
            raise
        finally:
            # always release lock
            execution_plan.lock = False
            user.save()
        return rv

    return decorated_function

We believe the code is formally correct and proved to work without any issue.
However, on rare occasions in production (once every ~10.000 requests), the lock is not released and is marked as true.
This locks all subsequent requests to the endpoint for a particular user, requiring manual intervention.


text:
Q: Can i avoid warning of Google Font - GDPR-compliant? Im using this website Link to check if my website is Google Fonts GDPR-compliant it says:
IMG.
How can i solve this and not have this warning.
I tried to remove all my font-family locally, same result.
Im not using link to get fonts from google, im using it locally.


text:
Q: signal only works in main thread, no encoding declared I get the following error for encoding when I activate DEBUG mode:
    set FLASK_DEBUG=1
For some reason, the debug mode does not get activated by app.debug=True. Here is the error:
Non-UTF-8 code starting with '\x90' in file
C:\Users\mypc\Anaconda3\envs\fenv\Scrip
ts\flask.exe on line 1, but no encoding declared; see
http://python.org/dev/peps/pep-0263/ for de
tails

I tried the solution in the this link but it didn't help!
Working with utf-8 encoding in Python source
Then I tried the following command:
    python -m flask run
And I got the following error:
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread

This is my code :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, url_for, request, render_template, jsonify
import requests, json
from urllib.request import quote
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] =
'postgresql://postgres:password@localhost/flask'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

def __init__(self, username, email):
    self.username = username
    self.email = email

def __repr__(self):
    return '<User %r>' % self.username
@app.route('/')
def Index():
    return render_template('add_user.html')

@app.route('/postuser', methods=['POST'])
def post_user():
    user = User(request.form['username'], request.form['email'])
    db.session.add(user)
    db.session.commit()


text:
Q: Measure space $(\Omega ,\mathcal F)$ and $\mathbb P:\mathcal F\to [0,1]$ that is finite additive but not $\sigma -$additive I'm looking for a space $(\Omega ,\mathcal F)$ and a function $\mathbb P:\mathcal F\to [0,1]$ s.t. $\mathbb P(\Omega )=1$ and $\mathbb P$ is addtitive but not $\sigma -$additive.
Of course I got inspired but several post on mathstack exchange by $\Omega =\mathbb R$, $$\mathcal F=\{A\subset \mathbb R\mid A\text{ or $A^c$ is countable}\},$$
and $\mathbb P(A)=0$ if $A$ is countable an $\mathbb P(A)=1$ if $A$ is not countable. But unfortunately this is a probability measure. Any example ?

My question is not a duplicate of this post (as several thought) because the answers don't provide probability spaces.

A: This answer will show only that such a set function must exist. The reason that it is difficult to write one down explicitly is that the existence of an example on $\mathbb{N}$ requires something more than ZF. I suspect that the existence of any example will require more than just ZF but I am not sure of this. I will use the ultrafilter lemma$^*$.
Let $\Omega = \mathbb{N}$ and let $\mathcal{F} = \mathcal{P}(\Omega)$. Let $\mathcal{G}$ be a non-principal ultrafilter on $\mathbb{N}$ (recall that an ultrafilter on $\mathbb{N}$ is called principal if it is of the form $\mathcal{G} = \{A \subseteq \mathbb{N} : a \in A\}$ for some fixed $a$).
Define
$$\mathbb{P}(A) = \begin{cases} 1 \qquad A \in \mathcal{G} \\ 0 \qquad \text{otherwise} \end{cases}$$
Then $\mathbb{P}$ is a finitely additive set function (see this question). However since $\mathcal{G}$ is non-principal, it cannot contain any finite set. In particular, $\mathbb{P}(\{i\}) = 0$ for every $i \in \mathbb{N}$. Hence $\mathbb{P}$ is not countably additive since
$$1 = \mathbb{P}(\mathbb{N}) \neq \sum_{i=0}^\infty \mathbb{P}(\{i\}) = 0$$

$^*$ which is equivalent to the Boolean Prime ideal theorem and hence strictly weaker than choice. I need the ultrafilter lemma to see that a non-principal ultrafilter exists on $\mathbb{N}$. One way to get this is to use the ultrafilter lemma to get an ultrafilter extending the cofinite filter. This ultrafilter then cannot be principal.
As pointed out in the answer here and the references therein, it is consistent with ZF+DC that there are no "non-principal measures" on $\mathbb{N}$. A non-principal measure on the powerset of a set $X$ is a set function $\mu: \mathcal{P}(X) \to [0,1]$ such that $\mu$ is finitely additive, $\mu(X) = 1$ and $\mu(\{x\}) = 0$ for all $x$. The $\mathbb{P}$ in this answer is exactly an example of a non-principal measure on $\mathbb{N}$. The answer to my follow up question here then shows that it is consistent with ZF+DC that you cannot construct an example on $\mathbb{N}$.


text:
Q: Using TensorFlow 2.0 keras: NotFoundError FetchOutputs node : not found [Op:AutoShardDataset] I am trying to make use of TPU on Google Colab. I have followed the guide official tensorflow guide to use tpu
as follows:
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.config.experimental_connect_to_host(resolver.master())
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.experimental.TPUStrategy(resolver)

def SuperResolution(input_dim):
  layers = []
  layers.append(tf.keras.layers.Conv3DTranspose(filters = 64, kernel_size = (4, 4, 4), strides = 2, padding = 'same', input_shape = input_dim+(1,)))
  layers.append(tf.keras.layers.BatchNormalization())
  layers.append(tf.keras.layers.LeakyReLU())
  for i in range(5):
    layers.append(tf.keras.layers.Conv3D(filters = 64, kernel_size = (3, 3, 3), padding = 'same'))
    layers.append(tf.keras.layers.BatchNormalization())
    layers.append(tf.keras.layers.LeakyReLU())
  layers.append(tf.keras.layers.Conv3D(filters = 1, kernel_size = 3, padding = 'same', activation = 'tanh'))
  model = tf.keras.models.Sequential(layers)
  return model

with strategy.scope():
  superres = SuperResolution((44, 64, 64))
  superres.compile(loss = tf.keras.losses.MeanSquaredError(), optimizer = tf.keras.optimizers.Adam())

dataset = tf.data.Dataset.from_tensor_slices((Dataset64.reshape(len(Dataset64), 44, 64, 64, 1), Dataset128.reshape(len(Dataset128), 88, 128, 128, 1)))

dataset = dataset.shuffle(10).batch(1)
superres.fit(dataset, epochs = 10)

When I run superres.fit(dataset, epochs = 10) I get following error
NotFoundError: FetchOutputs node : not found [Op:AutoShardDataset]

Please help
Link to colab: Colab


text:
Q: returning a link with onclick embeded within a php function I am trying to return a link with an onclick function but I think I am getting my quotations confused because the link wont work.
here is the code:
return "$item_name";

A: You can always escape quotes by putting an escape character \ before them.
return "$item_name";

A: You should escape inner single quote.
    return "
           $item_name
   ";


text:
Q: AnimeJS path animate Я анимирую движение блока по кругу с помощью animejs

let a = anime.path('svg circle')

let b = anime({
  targets: 'p',
  translateX: a('x'),
  translateY: a('y'),
  easing: 'linear',
  duration: 2000,
  loop: true,
})

text

<svg viewBox="0 0 400 400" fill="none" xmlns="http://www.w3.org/2000/svg">
  <circle class="circleAnime" cx="123.945" cy="123.945" r="75.445" transform="rotate(-90 123.945 123.945)" stroke="#5FE4BF" stroke-width="73"/>

</svg>

Однако я бы хотел останавливать в любом месте по пути
при этом анимация должна заканчиваться тоесть pause() не подходит


text:
Q: Counting the numbers between $1$ and $1,000,000$ whose digits sum to $30$
What's the number of numbers between $1$ and $1,000,000$ whose digits sum is $30$?

So I thought of this as a stars and sticks problem, so in the case you have $35\choose 5$ numbers whose sum is $30$. But obviously this number of numbers includes many overlaps (if for instance the requested sum was $8$, then $80=800=8000=134=143=431$ etc.). How do I get rid of the overlaps (inclusion-exclusion)?
Thanks in advance for any assistance!

A: One looks for the number $N$ of integer solutions of
$$
\sum_{i=1}^6n_i=30,\qquad 0\leqslant n_i\leqslant9.
$$
Thus, $N$ is the coefficient of $x^{30}$ in the polynomial
$$
\prod_{i=1}^6\sum_{n_i=0}^9x^{n_i}=\left(\frac{1-x^{10}}{1-x}\right)^6.
$$
To compute $N$, note that
$$
(1-x^{10})^6=\color{red}{1}-\color{red}{6}x^{10}+\color{red}{15}x^{20}-\color{red}{20}x^{30}+o(30),
$$
and that
$$
\frac{1}{(1-x)^6}=\sum_{k=0}^{30}\color{green}{{5+k\choose5}}x^k+o(30),
$$
where $o(30)$ denotes terms of order at least $31$, hence
$$
N=\color{red}{1}\cdot\color{green}{{5+30\choose5}}-\color{red}{6}\cdot\color{green}{{5+20\choose5}}+\color{red}{15}\cdot\color{green}{{5+10\choose5}}-\color{red}{20}\cdot\color{green}{{5+0\choose5}}=50877.
$$

A: The problem isn't overlaps: it's restricting the values to the range from $0$ through $9$. You're looking for the number of solutions in non-negative integers to the equation
$$x_1+x_2+x_3+x_4+x_5+x_6=30\tag{1}$$
with the added requirement that $x_k\le 9$ for $k=1,\dots,6$: each of those solutions defines one of the numbers that you're trying to count, and vice versa. The number of solutions without the upper bound restriction is, as you say,
$$\binom{30+6-1}{6-1}=\binom{35}5\;.$$
However, some of those solutions require 'digits' greater than $9$. Start by counting the solutions in non-negative integers to $(1)$ that have $x_1\ge 10$. Those are clearly in one-to-one correspondence with solutions in non-negative integers to
$$y_1+x_2+x_3+x_4+x_5+x_6=20\;,$$
where $y_1=x_1-10$, and you know how to compute their number. Call that number $n_1$. There are just as many solutions to $(1)$ that violate the upper bound on $x_2$, just as many again that violate the upper bound on $x_3$, and so on, so a better approximation to the solution to the original problem is
$$\binom{35}5-6n_1\;.$$
Of course this overcorrects, since it's possible for a solution to $(1)$ to violate two of the upper bound constraints at once. You'll have to calculate the number $n_2$ of solutions that have $x_1\ge 10$ and $x_2\ge 10$ and then add back the appropriate multiple of $n_2$. And since it's actually possible to violate as many as three of the constraints at once, you'll have to make one further inclusion-exclusion correction.

A: HINT: Can you find the number of integer soloutions of the equation $$x_1+x_2+x_3+x_4+x_5+x_6=30$$ such that  $0\leq x_i\leq 9$ for all $i$. Use generating functions!


text:
Q: Octave sample code failing to compile in g++? I'm attempting to get the Octave C++ code here to compile in g++ (Ubuntu/Linaro 4.6.4-1ubuntu1~12.04) 4.6.4).
This trimmed version of the above will compile in g++:
#include <iostream>
#include <octave/oct.h>
using namespace std;

int main() {
//  Matrix L=Matrix(2,2);

  return 0;
}

but if I unremark out the line Matrix L=Matrix(2,2); then compile with g++ temp.cpp it gives the error message:
/tmp/ccTa3Am5.o: In function `Array2<double>::~Array2()':
temp.cpp:(.text._ZN6Array2IdED2Ev[_ZN6Array2IdED5Ev]+0x1f): undefined reference to `Array<double>::~Array()'
/tmp/ccTa3Am5.o: In function `Array<double>::Array(dim_vector const&)':
temp.cpp:(.text._ZN5ArrayIdEC2ERK10dim_vector[_ZN5ArrayIdEC5ERK10dim_vector]+0x26): undefined reference to `Array<double>::get_size(dim_vector const&)'
/tmp/ccTa3Am5.o:(.rodata._ZTV5ArrayIdE[vtable for Array<double>]+0x10): undefined reference to `Array<double>::~Array()'
/tmp/ccTa3Am5.o:(.rodata._ZTV5ArrayIdE[vtable for Array<double>]+0x18): undefined reference to `Array<double>::~Array()'
collect2: ld returned 1 exit status

I'm unsure why.  Perhaps I'm missing an #include, perhaps I don't have an appropriate file installed, perhaps I'm not linking to the appropriate library, or perhaps I'm misusing Octave in some way.

Question:  Why is this failing to compile?  How can I fix it?

It compiles fine if I use mkoctfile --link-stand-alone temp.cpp as indicated at the above site, however, I'd like to use g++ if possible, since I eventually want to be able to call Octave functions from another program I've written in C++.

A: You need to link to the octave library. If the library is octave.a:
g++ -loctave temp.cpp

A: As indicated in my comment a simple example can be found in this Howto. So in your case a simple way to achieve compilation will be creating a makefile as follows:
makefile:
all: temp

clean:
    -rm temp.o temp

temp: temp.o
      mkoctfile --link-stand-alone -o temp temp.o

temp.o: temp.cpp
        g++ -c -I$(OCTAVE_INCLUDE)
        -I$(OCTAVE_INCLUDE)octave -o temp.o temp.cpp

$(OCTAVE_INCLUDE) is an environment variable that should be set to your octave include path (e.g. /usr/include/octave-x.x.xx). Then you can simply compile and link your test application using the command make all.

A: Add the library directories to your link command:

*

*your-local-path\octave-x.x.xx\lib\

*your-local-path\octave-x.x.xx\lib\octave\x.x.xx\

mkoctfile -L"\your-path\octave-x.x.xx\lib" -L"\your-path\octave-x.x.x\lib\octave\x.x.xx" --link-stand-alone temp.cpp
For cxx11 linker errors:
Converting std::__cxx11::string to std::string
"If you get linker errors about undefined references to symbols that involve types in the std::__cxx11 namespace or the tag [abi:cxx11] then it probably indicates that you are trying to link together object files that were compiled with different values for the _GLIBCXX_USE_CXX11_ABI macro. This commonly happens when linking to a third-party library that was compiled with an older version of GCC."
Defining the following macro before including any standard library headers should fix your problem:
#define _GLIBCXX_USE_CXX11_ABI 0


text:
Q: Setting viewport width when the container is smaller than the device-width I have a small webview (with approx 75px height) that displays html content with the following metadata in the head:
<meta name="viewport" content="width=device-width, initial-scale=1" />

This html will be displayed on webviews across Android Phone, Android
Tablet, iPhone and iPad.
On phone devices (Android Phone/iPhone), the webview container width is the same as the device width,  so the above viewport meta data tag appears to work fine.
But on tablet devices (Android Tablet/iPad), the webview container width will be dynamic, so sometimes the webview container width will be smaller than the device width.
This means on tablet, whenever the webview container width is smaller than the device width, the html content should be cropped.
However after altering the metadata to have either
<meta name="viewport" content="width=50, initial-scale=1" />

or
<meta name="viewport" content="width=500, initial-scale=1" />

I found that the metadata seems to actually be ignored on Android and  iPhones/iPads with iOS9. This means the content will adjust and appear as expected on all of these devices. I can only see this issue on iPads pre iOS9.
I've tried removing the viewport metadata tag, and I've also tried using the following metadata tag
<meta name="viewport" content="width=100%, initial-scale=1" />

and both work fine, but I was wondering if there was any cleaner solution  as I've been recommended not to alter or remove the viewport metadata that I am currently using.


text:
Q: Error building Player because scripts have compile errors in the editor I am having problem with building a game. it keep saying 'Error building Player because scripts have compile errors in the editor'
I followed tips from this and still got nothing on working.
a friend suggested me to add
public static class EditorUtil

{
#if UNITY_EDITOR
    //Editr code here
    #endif
}

and it still continues with same error.
this is the full code:
 using UnityEngine;

 using System.Collections.Generic;

#if UNITY_EDITOR
using UnityEditor;
#endif

public static class EditorUtil
 {

#if UNITY_EDITOR
    //Editr code here

    static string m_EditorResourcesPath = string.Empty;
    private static string path = string.Empty;

    internal static string editorResourcesPath
    {

        get
        {
            if (string.IsNullOrEmpty(m_EditorResourcesPath))
            {
                string path;

                if (SearchForEditorResourcesPath(out path))
                    m_EditorResourcesPath = path;
                else
                    Debug.LogError("Unable to locate editor resources. Make sure the PostProcessing package has been installed correctly.");
            }

            return m_EditorResourcesPath;
        }
    }

    static bool SearchForEditorResourcesPath(out string path)
    {
        path = string.Empty;

        string searchStr = EditorUtil.path;
        string str = null;

        foreach (var assetPath in AssetDatabase.GetAllAssetPaths())
        {
            if (assetPath.Contains(searchStr))
            {
                str = assetPath;
                break;
            }
        }

        if (str == null)
            return false;

        path = str.Substring(0, str.LastIndexOf(searchStr) + searchStr.Length);
        return true;
    }

    internal static T Load<T>(string path, string name) where T : Object
    {
        EditorUtil.path = path;
        return AssetDatabase.LoadAssetAtPath<T>(editorResourcesPath + name);
    }

    private static List<string> layers;
    private static string[] layerNames;

    public static LayerMask LayerMaskField(string label, LayerMask selected)
    {
        if (layers == null)
        {
            layers = new List<string>();
            layerNames = new string[4];
        }
        else
        {
            layers.Clear ();
        }

        int emptyLayers = 0;
        for (int i = 0; i < 32; i++)
        {
            string layerName = LayerMask.LayerToName (i);

            if (layerName != "")
            {
                layers.Add (layerName);
            }
            else
            {
                emptyLayers++;
            }
        }

        if (layerNames.Length != layers.Count)
        {
            layerNames = new string[layers.Count];
        }

        for (int i=0; i < layerNames.Length; i++)
            layerNames[i] = layers[i];

        selected.value =  EditorGUILayout.MaskField (label, selected.value, layerNames);
        return selected;
    }

    public static Rect GetCurrentRect (float fieldSize = 18)
    {
        return GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.Height(fieldSize));
    }

    public static GameObject GetSelectedGameObject ()
    {
        return Selection.activeGameObject;
    }

    public static AnimationClip GetAnimationClipFromAnimator(Animator animator, string name)
    {
        if (animator == null)
            return null;

        foreach (AnimationClip animClip in animator.runtimeAnimatorController.animationClips)
        {
            if (animClip.name == name)
                return animClip;
        }
        return null;
    }

#endif
}

whats a solution for this? I've searched many posts in here and other forums and yet I keep getting the same error.
example error
Edit: second pic

A: Judging from from your screenshot, you put the script into
Assets/Renegades/Scripts/Utils
However, an Editor script must be put into the Editor folder, not into the Assets folder.
See: https://docs.unity3d.com/Manual/SpecialFolders.html
The UnityEditor Assembly is not accessible to scripts outside the Editor folder. The #if UNITY_EDITOR preprocessor directive does not solve this, because it evaluates to true when the script is run inside the Unity Editor.

A: Since above script is using UnityEditor, either u have to put this script inside folder named Editor or you have to use defines #if UNITY_Editor. What you have done is also correct but i figured that you might be calling those methods from somewhere, maybe that's why it is still giving compile error. What it does is it will make those methods to exist in Editor only, it won't be there in build. So instead of whole methods, i just used #if UNITY_EDITOR for block of code.
using UnityEngine;

using System.Collections.Generic;

#if UNITY_EDITOR
using UnityEditor;
#endif

public static class EditorUtil
{

    static string m_EditorResourcesPath = string.Empty;
    private static string path = string.Empty;

    internal static string editorResourcesPath {

        get {
            if (string.IsNullOrEmpty (m_EditorResourcesPath)) {
                string path;

                if (SearchForEditorResourcesPath (out path))
                    m_EditorResourcesPath = path;
                else
                    Debug.LogError ("Unable to locate editor resources. Make sure the PostProcessing package has been installed correctly.");
            }

            return m_EditorResourcesPath;
        }
    }

    static bool SearchForEditorResourcesPath (out string path)
    {
        path = string.Empty;

        string searchStr = EditorUtil.path;
        string str = null;
        #if UNITY_EDITOR
        foreach (var assetPath in AssetDatabase.GetAllAssetPaths()) {
            if (assetPath.Contains (searchStr)) {
                str = assetPath;
                break;
            }
        }
        #endif
        if (str == null)
            return false;

        path = str.Substring (0, str.LastIndexOf (searchStr) + searchStr.Length);
        return true;
    }

    internal static T Load<T> (string path, string name) where T : Object
    {
        #if UNITY_EDITOR
        EditorUtil.path = path;
        return AssetDatabase.LoadAssetAtPath<T> (editorResourcesPath + name);
        #else
    return null
        #endif
    }

    private static List<string> layers;
    private static string[] layerNames;

    public static LayerMask LayerMaskField (string label, LayerMask selected)
    {
        if (layers == null) {
            layers = new List<string> ();
            layerNames = new string[4];
        } else {
            layers.Clear ();
        }

        int emptyLayers = 0;
        for (int i = 0; i < 32; i++) {
            string layerName = LayerMask.LayerToName (i);

            if (layerName != "") {
                layers.Add (layerName);
            } else {
                emptyLayers++;
            }
        }

        if (layerNames.Length != layers.Count) {
            layerNames = new string[layers.Count];
        }

        for (int i = 0; i < layerNames.Length; i++)
            layerNames [i] = layers [i];
        #if UNITY_EDITOR
        selected.value = EditorGUILayout.MaskField (label, selected.value, layerNames);
        #endif
        return selected;
    }

    public static Rect GetCurrentRect (float fieldSize = 18)
    {
        return GUILayoutUtility.GetRect (GUIContent.none, GUIStyle.none, GUILayout.Height (fieldSize));
    }

    public static GameObject GetSelectedGameObject ()
    {
        #if UNITY_EDITOR
        return Selection.activeGameObject;
        #else
    return null
        #endif
    }

    public static AnimationClip GetAnimationClipFromAnimator (Animator animator, string name)
    {
        if (animator == null)
            return null;

        foreach (AnimationClip animClip in animator.runtimeAnimatorController.animationClips) {
            if (animClip.name == name)
                return animClip;
        }
        return null;
    }

}


text:
Q: c# RSA extract public key from private key Is there a way to extract public key from private key in c#? Becouse if i do ToXMLString() then i can set if i want public key information saved with the private key. So now im thinking that is there a way to extract public key from private?

A: The normal private key format for RSA includes the public key (the "public exponent" is useful for implementation of private key operations in a way which resists timing attacks). Therefore, it is possible to extract the public key from the private key.
(It is theoretically possible to have a "pure RSA private key" which does NOT include the public exponent, but it has drawbacks, such as much harder protection against side-channel attacks, and reduced performance. Therefore nobody in their right mind does that. You can assume that when you have the private key you actually have the complete key pair.)
In the C#/.NET standard library, public and private RSA keys can be represented as XML strings (ToXmlString() and FromXmlString()) or a custom RSAParameters structure (ExportParameters() and ImportParameters()). If you can obtain the complete private key then you just have to pick the public fields (modulus and public exponent), which constitute together the public key. Note that RSACryptoServiceProvider may be an interface to an underlying RSA implementation which could refuse to export the private key (but will usually accept to export the public key).

A: Take the modulus from the private key, and the public exponent is - most likely - 65537. All Microsoft cryptosystems I've seen so far produce public keys with that exponent. The combination of public exponent and modulus is the public key.

A: If you can save it, and include the private key, then what you're saving is not just the private key.
However, if you really do have only the private key, then no, you can't "extract" the public key from it. If you could do that, you would render most of todays security obsolete.
So basically, I don't believe you have only the private key, you have a key pair, and you should be able to extract the public key from that.
Whether that is easily doable in C# or .NET, I have no idea.


text: Q: PhoneGap is not opening I have recently downloaded PhoneGap Desktop on my Windows 7, but unfortunately when I try to open it first time ( after installing ) it stuck on Loading screen it shows only loading circle and nothing happens. Any idea what to do?


text:
Q: Cycling through lines obtained by vim's :g I'm using the :g command in vim. Is there a way to directly jump (one after another, similar to :cn) to the lines found by :g?
:h :g does not seem to contain such facilities.

A: it depends on what did you do with the :g.
if your :g command didn't change the matched pattern, you could press n to go to next matched line.
but if you changed the pattern, e.g. you did :g/foo/d or :g/foo/s/foo/bar/g, those lines won't be there after you fire your :g command. then there is no way to reach those line again.

A: The usual way of jumping successively to the matches of a pattern would be to use normal search , not the global command. This is, /<pattern>, and then n for successive matches.
The global command :g is used to run another command on a non-contiguous set of lines. For a contiguous set of lines, a range is enough. Ex: :1,5<command>.
But, if for some reason you need to use the global command, or just for the record, there's a way to do what you want using :g.
From Vim's help:
When using "global" in Ex mode, a special case is using ":visual" as a
command.  This will move to a matching line, go to Normal mode to let you
execute commands there until you use |Q| to return to Ex mode.  This will be
repeated for each matching line.  While doing this you cannot use ":global".
To abort this type CTRL-C twice.

To see the full story, :h multi-repeat.
So, step by step, it would be:

*

*Enter ex mode (Press Q).
This is like command-line mode, but you don't go back to normal mode after command execution, and you don't  have to type the leading :. To go back to normal mode from here, :visual is used.

*Run global command executing :visual subcommand. This is, :g/<pattern>/visual.
That will send you into normal mode for each match. Each time, you can use all vim's power to do whatever you want with that match and, when finished, going back to ex mode (pressing Q again) continues with the next match.

*When you're finished with last match, you will be left in ex mode again. Enter :visual to go back to normal mode then.

A: Depending on what you want, you could simply use :grep or :vimgrep instead of :g, which will put the matching lines into the quickfix list. (use the l variations of the commands for filling the location list).


text:
Q: Changing json file format The script scrapes prices, addresses, suburbs and postcodes of houses and then writes them to a csv file.
The csv file is imported into panda (only postcode and price) and groupby the mean price of the postcode.
This groupby list is written to a json.
The csv file looks like this in excel
    ________________________
    |Postcode|Price        |
    ________________________
    |5061    | 205000      |
    ________________________
    |5063    | 930000      |
    ________________________

The code looks like this
import pandas as pd
from pandas import DataFrame
df = pd.read_csv('House_Prices.csv', usecols=[ 'Postcode' , ' Price' ], index_col=False)

grouped = df.groupby(['Postcode']).mean()

grouped.to_json('average_house_price.json')

The code above outputs the json file as
{" Price":{"5061":2025000.0,"5063":930000.0}}

I want the json file to be outputted like this
{"5061":2025000.0,"5063":930000.0}

Is there a way with the panda library (or other) to remove the starting Price index?

A: Add column name for aggregate "Price" or " Price" for Series:
grouped = df.groupby(['Postcode'])["Price"].mean()
#grouped = df.groupby(['Postcode'])[" Price"].mean()

grouped.to_json('average_house_price.json')

A: Why don't take the field before saving as JSON, like this:
grouped[" Price"].to_json('average_house_price.json')

A: Try passing header=None
Look here:
df = pd.read_csv('t.csv', usecols=[ 'Postcode' , ' Price' ], index_col=False, header=None)


text:
Q: C++ Should an abstract class provide implementation for a (virtual) destructor? I have a class which is abstract in that it defines common behaviour for concrete classes. As such, there is going to be no memory to clean up because the class cannot be instantiated. However, I am aware that you need a virtual destructor in order for the derived destructors to get called if their static type is the Base class.
Does this mean I should declare a virtual destructor for an abstract class always, but just leave the implementation empty?

A: You must provide a definition of every destructor in a class hierarchy, since all destructors up the inheritance graph do get called when a derived class is destroyed, even if some of the destructors are trivial.
Typically, you achieve this by putting virtual ~Base() { } (or some exception-specified variation thereof) in your base class. However, if the destructor is the only virtual member function and you want to make the base abstract, you can make the destructor pure-virtual, but you still have to define it:
struct Base
{
    virtual ~Base() = 0;
};

Base::~Base() { }


text:
Q: Indy, How to know size of buffer needed? I have some problem when using Indy (idTCPServer component) to read data send by client, the data itself was a hex formatted so i can't use AThread.Connection.ReadLn(); for that...
Here my sample data sended by client
24 24 00 11 12 34 56 FF FF FF FF 50 00 8B 9B 0D 0A

or
24 24 00 13 12 34 56 FF FF FF FF 90 02 00 0A 8F D4 0D 0A

PS: it's in bytes hexadecimal (data length may vary depend on command, at maximum 160 bytes) which i can't get string representation since $00 translated to null (which mean i can't use ReadLn)
Here my sample code
procedure TfrmMain.IdTCPServerExecute(AThread: TIdPeerThread);
var
  Msg : Array[0..255] of Byte;
begin
  AThread.connection.ReadBuffer(Msg,SizeOf(Msg));
  AThread.connection.WriteBuffer(Msg,MsgSize,true);
end;

this code will not work if client not send 255 byte data, while in my case data length can be vary, i have tried this, but no response outputted
procedure TfrmMain.IdTCPServerExecute(AThread: TIdPeerThread);
var
  Msg : Array of Byte;
  MsgSize : integer;
begin
  MsgSize := AThread.connection.ReadInteger; //doesn't actually get packet length?
  SetLength(Msg, MsgSize);
  AThread.connection.ReadBuffer(Msg,MsgSize);
  AThread.connection.WriteBuffer(Msg,MsgSize,true);
end;

so how exactly i can count how many byte data sended by client (packet length)? or could someone tell me the right code to read the data?

A: The simple answer is: you can't. TCP is a stream protocol, so there is no concept of a message. The data is received in chunks, whose sizes may (and will) differ from the actually sent buffers (the network stack is free to slice or merge the stream at will).
You may built a message protocol on top of TCP, e.g. by starting the transmission, and every consequent message, by a "size field" and then waiting only for the bytes needed; you still need to check the actual size received and re-reading the rest if applicable.
The point is: packet length in the TCP world has nothing to do with the length of the sent messages.
What TIdTCPConnection does behind all the Read-methods  is:
reading all available data from the network stack, appending it into an internal input buffer and returning the requested N bytes from the beginning of the buffer, if available (waiting for next chunk, if not).

A: The 3rd and 4th bytes in the data you have shown specify the total size of the data being sent.  You were close to try ReadInteger(), but the way you used it includes the 1st and 2nd bytes, which is wrong. Try this instead:
procedure TfrmMain.IdTCPServerExecute(AThread: TIdPeerThread);
var
  Unknown: Smallint; // maybe a msg type?
  DataSize: Smallint;
  Data: Array of Byte;
begin
  Unknown := AThread.Connection.ReadSmallInt;
  DataSize := AThread.Connection.ReadSmallInt - 4;
  SetLength(Data, DataSize);
  AThread.Connection.ReadBuffer(Data[0], DataSize);
  //...
end;


text:
Q: How to allow URLs in robots.txt but disallow other ones similar to allowed This is what I'm using now:
User-agent: *
Allow: /
Allow: /video/funny-dogs/index.html
Allow: /video/funny-cats/index.html
Allow: /video/funny-dolphins/index.html
Disallow: /video/

But seems like all others "/video/" URLs are also being crawled.
What's wrong with that?

A: You robots.txt file should definitely work for Google, and I believe it will work for Bing. However, for many other robots it probably won't work, because not all robots prioritize competing Allows & Disallows the same way. Also, some robots don't support Allow at all.
For robots other than Google/Bing, you can increase the chances of success by removing the "Allow: /" line. Many older robots look for the first directive that can be applied to the current URL and then stop looking. For these robots, the allow will always be applied, and the other directives will always be ignored. Removing the "Allow: /" should fix this.
If Google or Bing are not obeying your robots.txt file, then something may be broken. You might check for the following things:

*

*Was the robots.txt file added/changed very recently? Google can often take as much as a week to notice a new robots.txt file.

*Is the robots.txt in the site's root directory? (e.g. in http://somesite.com/robots.txt, NOT http://somesite.com/subdir/robots.txt)

*Do requests for the robots.txt file return anything funny in the response headers, like X-Robots-Tag:noindex, or a status code other than 200?

A: The original robots.txt specification said that the bot should read robots.txt and take the first rule that applies. When Allow was added, that wasn't changed, and many bots still use that rule. Other bots use the most permissive rule.
In the first case, Allow: / on the first line of the file will cause the bot to think that it can crawl. In the second case, the existence of Allow: / anywhere in the file will cause the bot to assume that it can crawl anything.
There is never a good reason to include Allow: /. The assumption in robots.txt is that if a file isn't specifically disallowed, then crawling is allowed. Allow is intended to be an override or exception to a Disallow.
Remove the Allow: /. Things should work then.


text:
Q: linearlayout/textviews scrollable? Any easy to make a simple linearlayout with a buncha textviews scrollable? Right now, the last textview gets cut off...
(I don't really wanna use a listview)

A: Use ScrollView
An example here:
http://www.androidpeople.com/android-scrollview-example/
You can find many more examples using Google.


text:
Q: How to add an event to a UserControl in C#? I have a UserControl which contains 3 labels. I want to add an event for it, which occurs when the text of one of the labels changed.
I am using Visual Studio 2010

A: First, you need to declare the event within your class (alongside your methods and constructors):
public event EventHandler LabelsTextChanged;

Then you need to create a method to handle the individual labels' TextChanged events.
private void HandleLabelTextChanged(object sender, EventArgs e)
{
    // we'll explain this in a minute
    this.OnLabelsTextChanged(EventArgs.Empty);
}

Somewhere, probably in your control's constructor, you need to subscribe to the label's TextChanged events.
myLabel1.TextChanged += this.HandleLabelTextChanged;
myLabel2.TextChanged += this.HandleLabelTextChanged;
myLabel3.TextChanged += this.HandleLabelTextChanged;

Now for the HandleLabelsTextChanged method.  We could raise LabelsTextChanged directly; however, the .NET framework design guidelines say that is it a best practice to create an OnEventName protected virtual method to raise the event for us.  That way, inheriting classes can "handle" the event by overriding the OnEventName method, which turns out to have a little better performance than subscribing to the event.  Even if you think you will never override the OnEventName method, it is a good idea to get in the habit of doing it anyway, as it simplifies the event raising process.
Here's our OnLabelsTextChanged:
protected virtual void OnLabelsTextChanged(EventArgs e)
{
    EventHandler handler = this.LabelsTextChanged;
    if (handler != null)
    {
        handler(this, e);
    }
}

We have to check for null because an event without subscribers is null.  If we attempted to raise a null event, we would get a NullReferenceException.  Note that we copy the event's EventHandler to a local variable before checking it for null and raising the event.  If we had instead done it like this:
if (this.LabelsTextChanged != null)
{
    this.LabelsTextChanged(this, e);
}

We would have a race condition between the nullity check and the event raising.  If it just so happened that the subscribers to the event unsubscribed themselves just before we raised the event but after we checked for null, an exception would be thrown.  You won't normally encounter this issue, but it is best to get in the habit of writing it the safe way.
Edit: Here is how the public event EventHandler LabelsTextChanged; line should be placed:
namespace YourNamespace
{
    class MyUserControl : UserControl
    {
        // it needs to be here:
        public event EventHandler LabelsTextChanged;

        ...
    }
}

Here are the framework design guidelines on event design for further reading.

A: First you should declare an event in your usercontrol for example:
public event EventHandler TextOfLabelChanged;

then you have to call the call back function that is bound to your event(if there's any) in runtime.You can do this by handling the TextChanged event of a label like this:
public void LabelTextChanged(object sender,EventArgs e)
{
if(TextOfLabelChanged!=null)
TextOfLabelChanged(sender,e);
}

You can have your own EventArgs object if you like.
somewhere in your code you should bound your label TextChanged event to this method like this:
_myLabel.TextChanged+=LabelTextChanged;

A: public delegate void TextChangedEventHandler(object sender, EventArgs e);
public event TextChangedEventHandler LabelTextChanged;

// ...

protected void MyTextBox_TextChanged(object sender, EventArgs e)
{
    if (LabelTextChanged != null) {
        LabelTextChanged(this, e);
    }
}

A: compile error, which says: "Expected class, delegate, enum, interface, or struct" on the second line it seems to have a problem with "event...

These 2 lines need to be INSIDE the class declaration.
public delegate void TextChangedEventHandler(object sender, EventArgs e);
public event TextChangedEventHandler LabelTextChanged;

A: There is a very simple way to do that!
On the UserControl Form :

*

*change properties to public to access everywhere

on the main form , where you are using UserControl:
.5: in the using region add using userControl1=UserControl.userControl1
1.Add 'Laod' event to your UserControl :
this.userControl1.Load += new System.EventHandler(this.userControl1_Load);

2.In the userControl1_Load :
private void userControl1_Load(object sender, EventArgs e)
{
     (sender as UserControl1).label1.TextChanged += label1_TextChanged;
     //add a 'TextChanged' event to the label1 of UserControl1
     OR use direct cast:
     ((UserControl1) sender).label1.TextChanged += label1_TextChanged;

}

3.In th label1_TextChanged:
 private void label1_TextChanged(object sender, EventArgs e)
 {
     //do whatever you want
 }

A: You must be declaring the event and delegate within the Namespace. Try to bring the code within the class Scope. It will run fine.


text:
Q: Understanding how mass spectroscopy works Let me start by saying that I've posted this question here as well. I've posted it here because I think the questions I've asked involve the physics of molecules.
So I'm trying to get a deeper understanding of how mass spectroscopy works. Most tutorials and textbooks I've encountered omit certain details about the process and I'm hoping someone out there who understands the process can fill in the gaps. I'll start by explaining the way I currently understand the process and then list where I start to get confused.
1 First a particular molecule is bombarded with a beam of electrons (ionization step). This step works to free an electron from the molecule under analysis which generates a cation.
Note: It's important to remember that the only reason why this molecule was ionized is to make use of a magnetic field to bend its direction. Only ions will be affected by this magnetic field which allows us to pinpoint the molecule in question.
2 Next, these ions are accelerated by an electric field toward a magnetic field that bends the moving ions by a certain amount.

Question 1: What's the difference between an electric field and a magnetic field? And why does the magnetic field bend the ions while the electron field does not. Is this just a consequence of the shape of the apparatus? Could you use a magnetic field to accelerate a particle and a electric field to do the bending? I'm just really confused as to the difference between electric fields and magnetic fields.

3 The ions that bend will travel around a tube by a certain degree and hit a detector. The amount of bending will tell us about the mass of a particular molecule. Heavier molecules will bend less and lighter molecules will bend more.

Question 2: I've come across a tutorial that said that what this detector is actually measuring is the mass to charge ratio. How is this calibrated and how does this step allow us to measure the mass of a single molecule. Won't there be multiple particles hitting the detector at the same time, will this not affect the mass reading of a particular molecule? I'm just confused about this final step and how we can get an accurate mass reading for a particular molecule.

Any help understanding this concept would be appreciated.

A: Regarding your first question, a magnetic field will not normally speed up a particle as it can do no work on it, while an electric field can both accelerate it and bend its path, depending on the configuration. An electric field along a particle's velocity will accelerate it, while an electric field orthogonal to it will bend the path. The maths behind this is the Lorentz force,
$$\mathbf{F}=q\left(\mathbf{E}+\mathbf{v}\times\mathbf{B}\right),$$
where the magnetic component is always orthogonal to the velocity. If you are still confused about the roles of electric and magnetic fields I'd recommend you read the introductory sections of Griffiths or the like.
This leads directly to the fact that it is only the charge-to-mass ratio that enters the equation, since from Newton's 2nd law, $\mathbf{F}=m\mathbf{a}$, the equation of motion is
$$\mathbf{a}=\frac qm\left(\mathbf{E}+\mathbf{v}\times\mathbf{B}\right),$$
where only $q/m$ enters. Bigger masses mean smaller $q/m$ ratios which mean smaller effective fields and less impact on the trajectory, which then bends less. This is not really a problem in calibration since charges are typically small multiples (i.e. one or two times) of the electron charge, and this causes easily distinguishable peaks that correspond to different charge states.
If there are multiple particles hitting the detector at the same time, then they will hit it in different spots if they have different masses, which will make two different pixels light up (and we can then distinguish them and treat them independently). The only problem occurs when multiple ions of the same charge and mass hit the detector in close succession, in which there is a danger of undercounting (i.e. counting just a single hit). This must be avoided by using integration times smaller than the typical hit-to-hit time.


text:
Q: Transformar classe com métodos estaticos em interface Tenho uma custom class chamada ArrayList, que criei para manusear objetos em um pequeno projeto meu, mas gostaria de abstrai-la ainda mais, transformando em interface. Desta forma, eu poderia criar outras classes que fazem a mesma coisa com bancos diferentes(nessa classe, salva em um txt, mas eu tenho outra que faz as mesmas coisas em um arquivo JSON e futuramente vou fazer uma pra salvar em MySQL).
Como posso efetuar essa transformação, caso ela seja viável?
Segue a classe ArrayList
class ArrayList {

    private static $list = null;

    private function __construct() {

    }

    private static function getList() {
        if (!isset(self::$list)) {
            $linha = "";
            if (file_exists(dirname(__DIR__) . '/model/DB.txt')) {
                $banco = dirname(__DIR__) . '/model/DB.txt';
                $a = fopen($banco, 'r');
                $linha = fread($a, filesize($banco));
                self::$list = unserialize($linha);
            } else {
                self::$list = Array();
            }
        }
    }

    public static function add($item) {
        self::getList();
        self::$list[] = $item;
    }

    public static function remove($item) {
        self::getList();
        for ($i = 0; $i < self::size(); $i++) {
            if (self::get($i) === $item) {
                unset(self::$list[$i]);
                break;
            }
        }
        self::$list = array_values(self::$list);
    }

    public static function get($indice) {
        self::getList();
        return self::$list[$indice];
    }

    public static function size() {
        self::getList();
        return sizeof(self::$list);
    }

    private static function gravar() {
        $texto = serialize(self::$list);
        $a = fopen(dirname(__DIR__) . '/model/DB.txt', 'w');
        fwrite($a, $texto);
        fclose($a);
    }

    public static function atualizarDB() {
        self::gravar();
    }

}

O que eu estou tentando fazer seria algo assim:
interface ArrayList{
getList();
add($item);
save();
}

A: A primeira coisa que teria que fazer é deixar de usar elementos estáticos nesta classe. Não faz sentido usar uma interface em uma classe essencialmente estática.
Eu acho estranho ter um método de atualização de banco de dados dentro de uma estrutura de dados genérica assim. Eu acho que isto deveria estar fora, mas fica a seu critério.
Também não sei os requisitos e exatamente o objetivo da criação da interface, mas acredito que o que deseja é isto:
interface iArrayList {
    public function add($item);
    public function remove($item);
    public function get($indice);
    public function size();
}

Se quiser pode colocar outros métodos obrigatórios e que sejam gerais.
Aí essa classe, além das mudanças sugeridas seria escrita assim:
class ArrayListDB implements iArrayList

A próxima provavelmente seria:
class ArrayListJson implements iArrayList

Coloquei no GitHub para referência futura.


text:
Q: Merge HTML String I am trying to find the best way to merge two HTML String in Javascript (JQuery/AngularJS) such as :
var context = '

itemA

itemB

';

merged with :
var additionnalInfo = '

itemC

itemD

';

should modify context variable to :
'

itemA

itemB

itemC

itemD

';

Any idea ?

A: Should be able to do something like this, as long as your additional info contains only the elements you want to add (which you can easily strip down to).
var additionnalInfo = '
itemC

itemD
';

var list = getElementById('list');
list.innerHTML += additionalInfo;

Edit
If you must be able to match on several ids, then its possible you could use jQuery to iterate through all elements of a type (all lists for example), and just check the ids for equality, then append as above.  Ex:
var additionalInfo = $.parseHTML('

itemC

itemD

');
var elements = additionalInfo.find($('ul'));
var lists = $('ul').get();

elements.each(function(){
    var el = this;
    lists.each(function(){
        if($(this).attr('id') == el.attr('id')){
            el.innerHTML += $(this).innerHTML;
        }
});

There are more efficient ways of doing this, but it should be a good basis for what you need.  Essentially just loop through all of the "parent" list elements in the additional html.  Compare those ids against the list ids within your existing html, and if they are the same, then append the new innerHTML to the existing list.
You can also make it more generic so that once you parse your html string, get the type of any element with an id, and do a find for that type.  A lot of ways to do this, its just a matter of applying the proper method of iterating through your data without wasting a ton of cycles.  Hope this helps a bit more.


text:
Q: HighCharts turn animation false for line chart I'm new to highCharts and want to know how I can turn off the animation for line charts.
I've tried setting it to false in plotlines but no success.

A: If you want to completely disable all animations in Highcharts (also these happening when toggling lines on or off) use the following:
chart: {
    animation: false
}

See http://api.highcharts.com/highcharts#chart.animation for more information. (demo)

A: It's the same that I answered here but you have to change column to line.
plotOptions: {
    line: {
        animation: false
    }
}

demo
If you want to remove animation from all types you can use series instead.
plotOptions: {
    series: {
        animation: false
    }
}


text:
Q: Angular2 directive based on dynamically added css class Angular router's [routerLink] directive adds CSS class router-link-active to active link. I'd like to write directive based on this class.
import { Directive, ElementRef} from '@angular/core';
@Directive({selector: '.router-link-active'})
export class HighlightDirective {
    constructor(el:ElementRef) {
        el.nativeElement.style.backgroundColor = 'yellow';
    }
}

However it doesn't work as I expect.
It works if directive is hard coded in template:
Feature1

but it doesn't work when css class is added dynamically by routerLink:
Feature1

Although CSS class is added, directive code is not fired.
These are my very first steps with Angular2, so maybe the solution is easy, but I cannot find the answer.

A: That's not supported. Angular2 instantiates components and directives only to selectors that match HTML statically added to a components template. Anything dynamic is ignored (HTML added using [innerHTML]="..." or attributes or classes added dynamically.


text:
Q: UITextField move up when keyboard appears in Swift I use this code for move the view up when keyboard appears, in my login page this code worked great, but in the signup page it did not work.
func textFieldDidBeginEditing(textField: UITextField) {
    animateViewMoving(true, moveValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
    animateViewMoving(false, moveValue: 100)
}

func animateViewMoving (up:Bool, moveValue :CGFloat){
    var movementDuration:NSTimeInterval = 0.3
    var movement:CGFloat = ( up ? -moveValue : moveValue)
    UIView.beginAnimations( "animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration )
    self.view.frame = CGRectOffset(self.view.frame, 0,  movement)
    UIView.commitAnimations()
}

I have another function to return key on the keyboard, it also worked on the login page but not on the signup page. All things are same between the two pages.
  func textFieldShouldReturn(textField: UITextField) -> Bool {

    textField.resignFirstResponder()
    return true
}

A: have you assigned your delegate of UITextField in your ViewController class?
if not set it to self.
self.youttextfield.delegate = self

A: Demo link : https://github.com/harshilkotecha/UIScrollViewWhenKeyboardAppearInSwift3
when you have multiple textview it is so difficult so best solution ->
step 1 : add UITextFieldDelegate
class ScrollViewController: UIViewController,UITextFieldDelegate {

step 2 :create new IBOutlet but don't connect with any text field
//  get current text box when user Begin editing
    @IBOutlet weak var activeTextField: UITextField?

step 3 : write this two method when user focus on text filed object pass the reference and store in activeTextField
// get current text field
    func textFieldDidBeginEditing(_ textField: UITextField)
    {
        activeTextField=textField;
    }
    func textFieldDidEndEditing(_ textField: UITextField)
    {
        activeTextField=nil;
    }

step 5 : set Notification in viewdidload setNotificationKeyboard
 override func viewWillAppear(_ animated: Bool) {
            // call method for keyboard notification
            self.setNotificationKeyboard()
        }

        // Notification when keyboard show
        func setNotificationKeyboard ()  {
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: .UIKeyboardWillShow, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: .UIKeyboardWillHide, object: nil)
        }

step 6 : two method for hide and unhide
func keyboardWasShown(notification: NSNotification)
    {
        var info = notification.userInfo!
        let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
        let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height+10, 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect : CGRect = self.view.frame
        aRect.size.height -= keyboardSize!.height
        if let activeField = self.activeTextField
        {
            if (!aRect.contains(activeField.frame.origin))
            {
                self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
            }
        }
    }
// when keyboard hide reduce height of scroll view

 func keyboardWillBeHidden(notification: NSNotification){
        let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0,0.0, 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        self.view.endEditing(true)
    }


text:
Q: Google Cast Video Player becomes unresponsive after network error I am working on a Chromecast custom receiver app, built on top of the sample app provided by Google (sampleplayer.CastPlayer)
The app manages a playlist, I would like the player to move on to the next item in the list after a video fails to play for whatever reason.
I am running into a situation where, after a video fails to load because of a network error, the player becomes unresponsive: in the 'onError_()' handler, my custom code will do this
var queueLoadRequest = ...
var mediaManager = ...
setTimeout (function(){mediaManager.queueLoad(queueLoadRequest)}), 5000

...the player does receive the LOAD event according to the receiver logs, but nothing happens on the screen, the player's status remains IDLEand the mediaManager.getMediaQueue().getItems() remains undefined. Same result trying to use the client controller to try to load a different video.
I have tried to recover with mediaManager.resetMediaElement() and player.reset() in the onError_ handler, but no luck.
For reference, here is a screenshot of the logs (filtered for errors only) leading up to the player becoming unresponsive. Note that I am not interested in fixing the original error, what I need to figure out is how to recover from it:

My custom code is most likely responsible for the issue, however after spending many hours + stripping the custom code to a bare minimum in an effort to isolate the responsible bit of code, I have not made any progress. I am not looking for a fix but rather for some guidance in troubleshooting the root cause: what could possibly cause the Player to become unresponsive? or alternatively how can one recover from an unresponsive Player?


text:
Q: How to fix "free(): double free detected in tcache 2" error? So, I have created a derived class template called unorderedSet that uses a pointer member variable to hold the location of an array on the heap (using new).
I am trying to overload the arithmetic operators to find both the intersection and union of two different unorderedSet objects, and the code I have written so far (with the help of another user on this site) manages that. However, upon running the program I get the error in the title. I will post the relevant parts of my code below.
template <class elemType>
class unorderedSet: public unorderedArrayListType<elemType>
{
public:
  void insertAt(int location, const elemType& insertItem);
  void insertEnd(const elemType& insertItem);
  void replaceAt(int location, const elemType& repItem);
  const unorderedSet<elemType> operator+(const unorderedSet<elemType>&);
  // Function to overload the binary operator + to find the union of a pair/group of sets
  // Postcondition: Finds the union of the sets

  const unorderedSet<elemType> operator-(const unorderedSet<elemType>&);
  // Function to overload the binary operator - to find the intersection of a pair/group of sets
  // Postcondition: Finds the intersection of the sets

  unorderedSet(int size = 100);
  unorderedSet(const unorderedSet<elemType>& otherSet);
  ~unorderedSet();

protected:
  elemType *set;
  int length;
  int maxSize;
};

template <class elemType>
const unorderedSet<elemType> unorderedSet<elemType>::operator+(const unorderedSet<elemType>& otherSet)
{
  unorderedSet<elemType> unSet(this->length + otherSet.length); // Initializes new set to hold values of the union set

  for (int i = 0; i < this->length; i++)
    unSet.insertEnd(this->list[i]); // Assigns all values of the activating operand to the union set using insertEnd

  for (int i = 0; i < otherSet.length; i++)
    unSet.insertEnd(otherSet.list[i]); // Calls insertEnd() to both check for duplicate values and add unique values to the union of the sets

  return unSet; // Should return the union set, but dumps the core at the moment
} // end operator overload

template <class elemType>
unorderedSet<elemType>::unorderedSet(int size) : unorderedArrayListType<elemType>(size)
{
  if (size <= 0)
  {
    cout << "The array size must be positive. Creating an array of the size 100. " << endl;

    this->maxSize = 100;
  }
  else
    this->maxSize = size;

    this->length = 0;

    set = new elemType[this->maxSize];
}

template <class elemType>
unorderedSet<elemType>::~unorderedSet()
{
  delete [] set;
}

template <class elemType>
unorderedSet<elemType>::unorderedSet(const unorderedSet<elemType>& otherSet)
{
  this->maxSize = otherSet.maxSize;
  this->length = otherSet.length;

  set = new elemType[this->maxSize];

  for (int j = 0; j < length; j++)
    set[j] = otherSet.set[j];
}

The following code comes from my test client program.
int main()
{
  int intArr1[6] = {0, 1, 2, 3, 4, 5};
  unorderedSet<int> testIntSet1;

  for (int i = 0; i < (sizeof(intArr1) / sizeof(intArr1[0])); i++)
    testIntSet1.insertEnd(intArr1[i]);
  // Some more code before the function call

  int intArr2[6] = {0, 1, 3, 6, 7, 9};
  unorderedSet<int> testIntSet2, testIntSet3;

  for (int i = 0; i < (sizeof(intArr2) / sizeof(intArr2[0])); i++)
    testIntSet2.insertEnd(intArr2[i]);

  testIntSet3 = testIntSet1 + testIntSet2;
  // Some more code
}

I also have an assignment operator overload function in the base class of this class's base class. The code is as follows
template <class elemType>
const arrayListType<elemType>& arrayListType<elemType>::operator= (const arrayListType<elemType>& otherList)
{
  if (this != &otherList)    //avoid self-assignment
  {
    delete [] list;
    this->maxSize = otherList.maxSize;
    this->length = otherList.length;

    list = new elemType[this->maxSize];

    for (int i = 0; i < this->length; i++)
      list[i] = otherList.list[i];
  }

  return *this;
}

I have attempted to create another version of this in my unorderedSet class, but when I run it the testIntSet3 variable outputs nothing (not even some random garbage). I decided to remove it since the code seemed to at least function properly before.

A: One issue is that your orderedSet is missing the user-defined assignment operator:
template <class elemType>
class unorderedSet: public unorderedArrayListType<elemType>
{
  public:
      unorderedSet<elemType>& operator=(const unorderedSet<elemType>&);
  //...
};

That function needs to be implemented.  The simplest way to do that, assuming you have a fully functional, working, copy constructor and destructor for unorderedSet, would be the following:
template <class elemType>
unorderedSet<elemType>& unorderedSet<elemType>::operator=(const unorderedSet<elemType>& otherSet)
{
   if (this != &otherSet)
   {
      unorderedSet<elemType> temp = otherSet;
      std::swap(temp.set, set);
      std::swap(temp.length, length);
      std::swap(temp.maxSize, maxSize);
   }
   return *this;
}

This uses the copy-swap idiom.
Your arrayListType's assignment operator should be written in the same fashipn.

A: Just to illustrate how valgrind can be used to diagnose this issue, I converted your program into a more minimal example (Try it online!).
When I run valgrind against the program (compiled as g++ -g x.cpp), there is output that reads:

==598== Invalid free() / delete / delete[] / realloc()
==598==    at 0x4C3373B: operator delete[](void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==598==    by 0x108E78: unorderedSet<int>::~unorderedSet() (x.cpp:68)
==598==    by 0x108CC7: main (x.cpp:93)
==598==  Address 0x5b80630 is 0 bytes inside a block of size 400 free'd
==598==    at 0x4C3373B: operator delete[](void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==598==    by 0x108E78: unorderedSet<int>::~unorderedSet() (x.cpp:68)
==598==    by 0x108CBB: main (x.cpp:98)
==598==  Block was alloc'd at
==598==    at 0x4C3289F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==598==    by 0x108E40: unorderedSet<int>::unorderedSet(int) (x.cpp:62)
==598==    by 0x108ECC: unorderedSet<int>::operator+(unorderedSet<int> const&) (x.cpp:41)
==598==    by 0x108C97: main (x.cpp:98)

The valgrind output is saing that the address being freed points inside an already freed block. Hence, the issue is a double free.
Helpfully, it locates the two distinct locations of the double free.

 93   unorderedSet<int> testIntSet2, testIntSet3;

and

 98   testIntSet3 = testIntSet1 + testIntSet2;

The second free is detected on line 93, so the first one occurred on line 98. We deduce the destruction is from the temporary returned by operator+.
Since the destruction was not expected to trigger a double free, your hypothesis is that the copy was not deep for some reason, and the same pointer was used in the copy that was allocated in the original object.


text:
Q: trying to understand multiprocessing I am starting to learn how to use multiprocessing, and, the best to learn is to make some trials and see what happens. So I did, but in my first attempt, I am getting something that I am not sure to understand, so I would appreciate your comments, or your corrections:
So, I did a very easy program, just read a pytable and print the results, depending on a single given parameter:
from tables import *
import scipy as sc

def getP(pathToTable, p):

    with openFile(pathToTable,'r') as f:

        tab = f.getNode("/mainTab")
        a = [row['value'] for row in tab.where("(page == p) & (ok == 1)")]

        print (p, sc.mean(a), sc.std(a))

And, to test it, I am doing like this:
>>> import multiprocessing
>>>pags = [1,2,3,4,5,6,7,8]
>>> te = 'C:\Desktop\testMultiProc.h5'
>>>import testMp as m
>>> for i in pags:
...     p = multiprocessing.Process(target=m.getP, args=(te,i))
...     p.start()
...     p.join()
...

This works, and I am getting the results like this:
(1, 9.0953793794588282, 0.33533126564851207)
(2, 9.0871612678994946, 0.33453983570210977)
(3, 9.0466206717415556, 0.32227094723414906)
(4, 9.1115445293825204, 0.32247317223440275)
(5, 9.1731876730458826, 0.33230456228097616)
(6, 8.9801903625732713, 0.32238759095899067)
(7, 9.0102797573336719, 0.34441213144617178)
(8, 8.8340961470191885, 0.32342748738790894)

So here come my questions:
If I am not wrong, this is happening simultaneously, then, why I am getting the output in order?? I mean, let's say that for p = 3 the process ends the first because there are few values in the table with p=3, so why I do not get (3, 9.0466206717415556, 0.32227094723414906)as the first output for example??
That makes me think that either I am doing it wrong or I do not understand yet what is happening here.
I have selected pags = [1,2,3,4,5,6,7,8] with an idea in mind....I did that because, first I did:
>>> multiprocessing.cpu_count()
8

So my idea was to take profit of 8 cores.

A: No, this is not happening simultaneously because you're calling join.
join will block until the process has completed.
Effectively:

*

*You start a separate process to deal with the first item

*You wait for that process to complete

*You start a separate process to deal with the second item

*You wait for that process to complete

*... and so on

You need to drop the join call inside that loop. If you want to wait for all the subprocesses to complete, store the result from calling multiprocessing.Process and join on those values in a separate loop, something like (untested):
processes = []
for i in pags:
    p = multiprocessing.Process(target=m.getP, args=(te,i))
    p.start()
    processes += [p]

for p in processes:
    p.join()


text:
Q: VirtualStringTree - Embedding Controls In Cells - Control Not Showing So, my end game here is to have a way to list items (like a TListView in vsReport) with the add/remove buttons inside the client area.
Ex:
|----------------|
|Old Item 1    X |
|Old Item 2    X |
|Add new item... |
|                |
|----------------|

If you know of a component that does this without all this extra work, please let me know!
So I picked out an red close "X" and am using a TJvTransparentButton (Jedi Components - JVCL) to display it. It handles the press/not pressed states and only shows the image. I original used a TButton but I didn't need all the fluff that goes around the glyph.
Now, I keep the image button in the record associated with each node.
Code is as follows:
procedure TfrmMain.AddNewAccount(const Username, Password: String);
var
  Data : PTreeData;
  XNode : PVirtualNode;
Begin
  XNode := vstAccounts.AddChild(nil);
  If vstAccounts.AbsoluteIndex(XNode) > -1 Then
    begin
    Data := vstAccounts.GetNodeData(Xnode);
    Data^.Column0 := Username;
    Data^.Column1 := '';
    Data^.DeleteButton := TJvTransparentButton.Create(nil);
    With Data^.DeleteButton Do
      begin
      Parent := vstAccounts;
      Left := 0;
      Top := 0;
      Width := 16;
      Height := 16;
      Anchors := [];
      AutoGray := False;
      BorderWidth := 0;
      FrameStyle := fsNone;
      Images.ActiveImage := iListView;
      Images.ActiveIndex := 0;
    end;
  end;
end;

In the OnAfterCellPaint event I manage the positioning of the image button like so:
procedure TfrmMain.vstAccountsAfterCellPaint(Sender: TBaseVirtualTree;
  TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
  CellRect: TRect);
var
  Data : PTreeData;
begin
  If Column = 1 Then
    begin
    Data := vstAccounts.GetNodeData(Node);
    If Assigned(Data) Then
      begin
      With Data^.DeleteButton Do
        begin
        BoundsRect := CellRect;
      end;
    end;
  end;
end;

Now the problem is that this doesn't show the item at all. I know that the Image from the TImageList is fine because I can create the button at design time and it looks fine at runtime.
I also know that this code should work because if I make the TJvTransparentButton a regular TButton (without changing the code logic) it works just fine and shows up fine!
The only thing I can think of is that a TButton inherits from a TWinControl while the TJvTransparentButton inherits from a TControl.
Any ideas?

A: I assume the TJvTransparentButton is a TGraphicControl and as such is displayed as part of the Parent's background (that's why a Tlabel will always be behind a TEdit or TButton in the same Parent).
The TButton is a TWinControl and as such is painted on top of the Parent and above or below the other WinControls in the same Parent.
So, either, you paint yourself again the TJvTransparentButton after the regular drawing of the cell happened (updating BoundsRect is not enough) or you use a WinControl.
For instance, using a TPanel with the TJvTransparentButton in it should work.
Disclaimer: I'm not familiar with VirtualStringTree nor TJvTransparentButton ...

A: You're doing this in a wrong way. You must write your own editor for TVirtualStringTree which implements IVTEditLink interface. Then in OnCreateEditor event you need to create your editor:
procedure TForm1.VSTCreateEditor(Sender: TBaseVirtualTree;
  Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink);
begin
  EditLink:=TStringEditLink.Create;
end;

You can get more info here.


text:
Q: Android: header in a ListView I would like to have a header on top of a ListView, but in a way that if the user scrolls down the ListView, the header is ALWAYS stack to the top of the view (right below of the Action Bar).
I created a RelativeLayout where I include my LinearLayout with the header and below it, the ListView, but still when the ListView is scrolled down, the header disappears. I also tried with addHeaderView but no luck yet.
Can anybody throw some light here?
EDIT:
My layouts are this:

<include
    android:id="@+id/IncludeFiltersZoekAndBoek"
    android:layout_above="@+id/AcommodatiesListView"
    layout="@layout/filters_header_layout" />

<ListView
    android:id="@+id/AcommodatiesListView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_above="@+id/LoadMoreAccommodaties"
    android:layout_alignParentTop="true"
    android:scrollingCache="false" >

</ListView>

<Button
    android:id="@+id/LoadMoreAccommodaties"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="Laad meer resultaten..."
    android:visibility="gone" />

and for the header:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="Populariteit" />

    <ImageButton
        android:layout_width="15dip"
        android:layout_height="15dip"
        android:src="@drawable/triangle" />

    <ImageButton
        android:layout_width="15dip"
        android:layout_height="15dip"
        android:src="@drawable/triangle" />
</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="Prijs" />

    <ImageButton
        android:layout_width="15dip"
        android:layout_height="15dip"
        android:src="@drawable/triangle" />

    <ImageButton
        android:layout_width="15dip"
        android:layout_height="15dip"
        android:src="@drawable/triangle" />
</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="Rating" />
</LinearLayout>

Now, it seems ok, the only problem is that the ListView is below the header, and when scrolling down, you can see the header on top of the items of the ListView.

A: With your requirements, you dont actually need to set header view for your ListView, because headers are scrollable together with the other contents of list.
In your case, simply add that view on top (above) of your ListView which should act as its header. By then it will stay there even if you scroll the list.

A: you need something like this:
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/darker_gray"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="THIS IS A HEADER"
        android:textColor="@android:color/black"
        android:textSize="20sp"
        android:typeface="serif" />
</LinearLayout>

<ListView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollingCache="false"
    >
</ListView>

</LinearLayout>

A: You have to set header weight and then see the result. :)