text:
Q: Diophantine Equations : Solving $a^2+ b^2=2c^2$ I was working through some number theory problems , when I came across the following question :

Find all solutions of $a^2+b^2=2c^2$

My Solution (Partial) :

*

*We can rewrite the above equation as : $c^2 = (a^2 + b^2)/2 $

*So $\Rightarrow$ $a^2 , c^2 , b^2$ are in an Arithmetic Progression $\Rightarrow$ there exist infinite solutions

*WLOG , let $a^2$ be $t$ , $b^2$ be $s$ and $c^2$ be $m$

*The equation can be re-written as $ t + s = 2m$

*Now , what I was thinking was that should I solve this Diophantine equation for $t$ & $s$ in terms of $m$ ; substitute their values back into the equation and find out $m$ ; and then finally put this value of $m$ back into the values of $t$ and $s$ to derive a general solution

Can someone help me out ? Maybe a hint ...

A: Hint: In $\mathbb Z[i]$, let $x:=a+bi$, $y:=c$, then $x\bar x=(1+i)(1-i)y^2$. $\mathbb Z[i]$ being UFD implies that $1+i\mid x$ or $1-i\mid x$. If $1+i\mid x$, write $z:=\frac x{1+i}=\frac {x(1-i)}2=\frac{a+b}2+\frac{b-a}2i$. Then we have $(\frac{a+b}2)^2+(\frac{b-a}2)^2=z\bar z=y^2=c^2$.

A: Here is a geometric way to look at the posted answers: Integer solutions to $a^2+b^2=c^2$ correspond to ${\mathbb Q}$-points $(a/c,b/c)$ on the circle $S$ defined by $x^2+y^2=1$. Integer solutions to $a^2+b^2=2c^2$ correspond to ${\mathbb Q}$-points $(a/c,b/c)$ on the circle $T$ defined by $x^2+y^2=2$. Let $r:=\sqrt{2}$. There are various correspondences between the circles $S$ and $T$, the most obvious being $(x,y)\mapsto(rx,ry):S\to T$. The problem is that the coefficients being used in this map are not all elements of ${\mathbb Q}$, so this map does not send ${\mathbb Q}$-points to ${\mathbb Q}$-points. The observation being made in several of the comments above is that, if we precompose this map with the rotation $(x,y)\mapsto((x-y)/r,(x+y)/r):S\to S$, then the resulting map $(x,y)\mapsto(x+y,x-y):S\to T$ $is$ defined over ${\mathbb Q}$ ($i.e.$, has coefficients in ${\mathbb Q}$), and so it will carry ${\mathbb Q}$-points to ${\mathbb Q}$-points. This then gives a correspondence between integer solutions to $a^2+b^2=c^2$, aka Pythagorean triples, and integer solutions to $a^2+b^2=2c^2$. This brings up the question of when two ${\mathbb Q}$-conic sections are ${\mathbb Q}$-isomorphic, something that may well be known, but not by me.

A: Assume you have the Pythagorean relation $u^2 + v^2 = c^2$
Then
$$
\begin{align}
(u^2 + v^2) + (u^2 + v^2) & = 2c^2\\
(u^2 + v^2 + 2uv) + (u^2 + v^2 - 2uv) & = 2c^2\\
(u + v)^2 + (u - v)^2 & = 2c^2\\
\end{align}
$$
Thus if $a = u + v$ and $b = |u - v|$
$a^2 + b^2 = 2c^2$

Update
Given any triple of integers $a, b, c : a^2 + b^2 = 2c^2$
$a^2 + b^2 \equiv 0 \mod 2$
Which implies $a + b \equiv 0 \mod 2$,
So $a \equiv b \mod 2$ and
$a - b \equiv 0 \mod 2$
WLOG, assume $a \ge b$
Both $a + b$ and $a - b$ are even.
Let $2u = a + b$ and $2v = a - b$
$4u^2 + 4v^2 = (a + b)^2 + (a - b)^2 = 2(a^2 + b^2) = 4c^2$
$u^2 + v^2 = c^2$
i.e., $u, v, c$ is a Pythagorean triple.
So every triple of integers $a, b, c : a^2 + b^2 = 2c^2$ corresponds to a Pythagorean triple.


text:
Q: multiple variables not defined - template I am trying to check whether none of 3 variables is defined in Django template to display a warning but I cannot find a way to do it correctly. I've tried:
{% if ((approved_users is None) and (approve_awaiting_users is None) and (archived_users is None) %},
{% if not (approved_users or approve_awaiting_users or archived_users) %},
{% if not approved_users and not approve_awaiting_users and not archived_users %},
all with multiple bracket versions but they cannot be parsed. What is the correct way to do it?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Given a word and a number for each letter of this word, how to create a full tree of every combinations? Let's say I have the word "stack" and for each of its letters there is a number that will define the number of times the letter has to be repeated. In a JSON file I would have the following:
{
   "s": 4,
   "t": 3,
   "a": 2,
   "c": 5,
   "k": 2
}

From this I would like to generate the complete tree of every possible combinations, namely:
Depth 1: stack
Depth 2: stack, sstack, ssstack, sssstack
Depth 3: stack, sttack, stttack, sstack, ssttack, sstttack,ssstack, sssttack, ssstttack, sssstack, ssssttack, sssstttack
Depth 4: ... with 'a'
Depth 5: ... with 'c'
Depth 6: ... with 'k'

This would give 4*3*2*5*2 = 240 possibilities. Also, I have these functions from someone I asked few days ago here, and on which I modified a little bit:
def all_combinations(itr):
    lst = list(itr)
    for r in range(1, len(lst) + 1):
        for perm in itertools.combinations(lst, r=r):
            yield perm

def all_repeats(n, letters, word):
    for rep in all_combinations(letters):
        yield ''.join(char * n if char in rep else char for char in word)

Which gives me:
word = 'stack'
for i in range(1,5):
    liste.append(''.join(list(all_repeats(i, ['s'], word))))

Output: ['stack', 'sstack', 'ssstack', 'sssstack']

From this, how can I recursively call this function to create all possibilities, given the couple (letter, number) in the JSON file?

A: a couple of versions, first we work with a list because it's easier to index
options = [
   ("s", 4),
   ("t", 3),
   ("a", 2),
   ("c", 5),
   ("k", 2),
]

now we can get a long form version, to help understand what's going on:
output = ['']

for letter, repeats in options:
    tmp = []
    for num in range(repeats):
        postfix = letter * (num+1)
        for cur in output:
            tmp.append(cur + postfix)
    output = tmp

if you print(output) you'll get what you expect.  I'd suggest running in a debugger or inserting lots of print statements to understand what's happening
as a second version, we can shorten this all down using itertools as:
from itertools import product

tmp = [[l*(i+1) for i in range(num)] for l, num in options]
output = [''.join(l) for l in product(*tmp)]

you could even put it all on one line, but it becomes a little too unreadable in my opinion
a recursive solution would fit nicely as well, but I'll leave that to you

A: You can also use recursion:
data = {'s': 4, 't': 3, 'a': 2, 'c': 5, 'k': 2}
def combos(d):
  yield ''.join(map(''.join, d))
  for i in data:
     if any(c[0] == i and len(c) < data[i] for c in d):
        yield from combos([c+[i] if c[0] == i and len(c) < data[i] else c for c in d])


text:
Q: Typesafe Activator commands don't work in CentOs Installed Typesafe Activator in CentOs, when typing any commands, command line displays a message
"killed"!

Java installed, I can not understand what was going on.

A: I've already answered on russian SO, but I think it would be well if I duplicate an answer in English:
I think you don't have enough memory. Let's try over another ssh-connection and type:
free -m -s 1.
It will show amount of free memory, so you should also (in parallel terminal) type command that crashes with "killed". I think in that moment free will show that your memory is running out and (after process killing) there will be enough amount of memory again.
Some virtualization technologies (for instance OpenVZ) doesn't support swap space so you can try to move to virt tech that supports swap (for instance Xen)..


text:
Q: Randomly Sample a python Set without converting to list Question
I have spent a good amount of time reading various answers about getting a random sample in python, and random.sample seems to be the natural and most common choice, however I am attempting to sample from a python set object and was hoping to do it efficiently.
I am using a set due to the very nice and efficient set functionality in python (intersections, difference, etc.). For my purposes sets are a very efficient data structure, and lists are specifically not.  I have an algorithm situation where I have N elements in a set, and potentially need to take up to N subsamples of an arbitrary size for each sampling of the set.  Each subsampling of the set is not of the exact same set, and is defined by the properties of each element I must generate a subsample of.  Here is some vague code which demonstrates the complexity of the algorithm:
main_set = set(...) # Values sourced from elsewhere.
capacity = 20

for element in list:
    potential_values = main_set - element.set # Exclude values already in element
    sample_size = capacity - len(element.set) # Num needed to fill the set to capacity
    new_vals = sample(potential_values, sample_size) # <- insert sampling idea here

    element.set = element.set | new_vals # Union of sample and element set

From what I have gathered online and in some tests, random.sample appears to convert a set into a list object.  The size of main_set - element.set, potential_values is almost always much greater than the size of element.set, and so if potential_values must be transformed into a list on each sampling the algorithm will suffer performance immensely.
So does anyone have any advice or ideas on how to go about doing this efficiently with sets?  I appreciate any input on this matter, and before anyone jumps to the 'premature optimization' routine, I have a very good idea of the scale on which this is going to be executing and the difference between O(n) and O(n^2) is pretty substantial.

Clarification Edit:
I specifically do not care about the output of whatever sample()method provided.  The actual samples I am pulling from the potential_values are small compared to the size of potential_values.  Rather, all of the suggested sample() methods require a list-like input to work, meaning potential_values must be converted to an indexable type first, which is what I wanted to avoid.
Also I realize now that I brought up big-O notation in a really vague way and probably shouldn't have.  When I mean I wanted to avoid O(n^2), I really meant I wanted to avoid adding another O(n) operation inside the loop.  As it was pointed out to me main_set - element.set is of same time-complexity as list(main_set), so it is already O(n^2).  Adding list conversion makes the whole algorithm more like O(2n^2), but none of that is really important.

A: You can use heapq.nlargest which can take any iterable and provide it with a random key to pick, eg:
import random, heapq

sample = heapq.nlargest(sample_size, your_set, key=lambda L: random.random())

Note - this will give you a list object back, so you'll need to cater to convert it if necessary...

A: A quick attempt at timing in IPython suggests that using heapq.nlargest isn't necessarily better than your existing method, adjust to the characteristics of your actual data as appropriate:
import random
import heapq

set_size = 100000
sample_size = 1000

def sample_heapq(your_set, sample_size):
    sample = heapq.nlargest(sample_size, your_set, key = lambda e: random.random())
    return sample

def sample_original(your_set, sample_size):
    sample = random.sample(your_set, sample_size)
    return sample

eg_set = set(range(sample_size))

Running these through timeit:
%timeit sample_heapq(eg_set, sample_size)
1000 loops, best of 3: 523 µs per loop

%timeit sample_original(eg_set, sample_size)
1000 loops, best of 3: 479 µs per loop

A: As @user2357112 suggested, here is a Rejection Sampling version of the code in my original question that efficiently samples n elements from the source set given that I am only sampling values from main_set that are not already in elements.set.
main_set = set(...) # Values sourced from elsewhere.
capacity = 20
listed_set = list(main_set) # initially convert set to list so we can sample
for element in list:
    while len(element.set) < capacity
        item = random.choice(listed_set)
        element.set.add(item) # Sets cannot contain duplicates, no conditional required

Although this doesn't answer the question of how to sample directly from a set in python, it does efficiently solve what my algorithm is attempting to do.  If after a while, no one comes up with either an idea to sample directly from a set or something more efficient than this, I will probably mark this as the answer.  Thanks for the idea @user2357112!

As @LieRyan pointed out, if element.set overlaps with main_set by a large percentage, this algorithm would fail to get a non-overlapping item from random.choice().  Therefore if we are expecting a high overlap, such as perhaps 50%, then simply getting the unique items between the two sets with main_set - element.set, and converting that to a list will be much faster than this method.  Essentially this algorithm is for the case when main_set has very little overlap with element.set as a percentage of main_set.

A: Depending on your definition of random.
Just some elements, I don't care which:
[s.copy().pop() for i in range(count)]  # with replacement

copy = s.copy()
[copy.pop() for i in range(count)]  # without replacement

Elements with decent [pseudo-]random distribution:
copy = list(s)
random.sample(copy, count)

Repeatable pseudo-random distribution:
copy = sorted(s)
# random.seed(...)
random.sample(copy, count)

Repeatable pseudo-random, hypothetically with less runtime overhead:
heapq.nlargest(...)  # per Jon or Marius

Discussion:

*

*set.pop() already removes and returns arbitrary element, however it's quite predictable if object hash value is same in set, e.g. if it's same set of numbers every time, it may be acceptable if set is different each time

*set.copy() is O(N)

*sorted();list.sort() are O(NlogN) amortised, likely as set is randomised by hash

*heapq.nlargest could be O(N) per Median of Medians, Python implementation is a binary heap of constant size, making it O(N*log(n)), as N elements are filtered through a heap sieve of size n. Note that sing key= adds a notable linear overhead, thus O(C*N*log(n)), your domain will determine if C*log(n) <?> logN


text:
Q: newlib-cygwin build. no rule to make target install I try to build newlib-cygwin on CentOS.  Got those error.
make[4]: Leaving directory `/home/me/src/build-newlib/i686-pc-cygwin/newlib'
make[3]: Leaving directory `/home/me/src/build-newlib/i686-pc-cygwin/newlib'
make[2]: Leaving directory `/home/me/src/build-newlib/i686-pc-cygwin/newlib'
make[2]: Entering directory `/home/me/src/build-newlib/i686-pc-cygwin /winsup'
make[2]: *** No rule to make target `install'.  Stop.
make[2]: Leaving directory `/home/me/src/build-newlib/i686-pc-cygwin/winsup'
make[1]: *** [install-target-winsup] Error 2
make[1]: Leaving directory `/home/me/src/build-newlib'
make: *** [install] Error 2


text:
Q: When a UITableViewCell is in editing mode and we reload the UITableView, how to keep that particular cell in editing mode even after reload When a cell is in editing mode, and we reload the table view. Is there any way to keep that particular cell still in editing mode showing "Delete" button.
Thanks in advance

A: Maintain an array of selected items. Don't forget to remove the item when deselecting the rows.
class ViewController: UIViewController {

var selectedData = [IndexPath]()

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.selectedData.append(indexPath)
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath){
    self.selectedData.removeAll(where: {$0 == indexPath})
}

Reload table view rows while in editing mode and reselect rows programmatically.
self.tableView.beginUpdates()
self.tableView.reloadRows(at: selectedData, with: .automatic)
self.tableView.endUpdates()
for item in selectedData {
    self.tableView.selectRow(at: item, animated: false, scrollPosition: .none)
}

Sample Code
Gist

A: You should keep track of cells that entered editing mode.
You can do it in your table view delegate method - tableView:willBeginEditingRowAtIndexPath:. I would suggest store all index path of cells currently in editing mode in NSMutableSet.
- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.editingCellIndexPaths addObject:indexPath];
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
     [self.editingCellIndexPaths removeObject:indexPath];
}

Than, while reloading, your data source will ask for cells. There you can call - setEditing:animated: method on cells that are in editing mode
- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     TableViewCell *cell = //here you get cell
     /*
       cell configure code here
     */

     if ([editingCellIndexPaths containsObject:indexPath]) {
         [cell setEditing:YES animated:NO];
     }
   return cell;
}

Hope that helps

A: Can you verify that you absolutely need to call reloadData when entering edit mode? Usually, it isn't necessary to reload the table's data until the table view will appear. This is because any change that you commit to the model should already be showing in the view, since the user made the changes before the data is saved.
If you need to process some data that is entered, resulting in the saved version being different than the entered version, then I would recommend showing the processed version in the input views before you save the data. This way, you still don't need to reload the data, since the view will already be in sync with the committed version.


text:
Q: How to set up logging in splat ReactiveUI? I need to enable logging in reactiveui. I implemented the ILogger interface:
public class Logger : Splat.ILogger
{
    public LogLevel Level { get; private set; }

    public Logger(LogLevel level)
    {
        Level = level;
    }

    public void Write([Localizable(false)] string message, LogLevel logLevel)
    {
        if (logLevel >= Level)
        Serilog.Log.Error(message);
    }

    public void Write(Exception exception, [Localizable(false)] string message, LogLevel logLevel)
    {
    if (logLevel >= Level)
        Serilog.Log.Error(exception, message);
    }

    public void Write([Localizable(false)] string message, [Localizable(false)] Type type, LogLevel logLevel)
    {
    if (logLevel >= Level)
        Serilog.Log.Error(message);
    }

    public void Write(Exception exception, [Localizable(false)] string message, [Localizable(false)] Type type, LogLevel logLevel)
    {
    if (logLevel >= Level)
        Serilog.Log.Error(exception, message);
    }
}

and register it:
var logger = new Logging.Logger(LogLevel.Info) { };
Locator.CurrentMutable.RegisterConstant(logger, typeof(ILogger));

And trying to use it like this:
LogHost.Default.Error("TestTestTest");

this.WhenAnyValue(x => x.IsHierarchical).Log(this, "ClusterableDictionaryValueSelector IsHierarchical exception")
.BindTo(this, x => x.ViewModel.IsHierarchical).DisposeWith(disposables);

But I can't found the log file. And when I call LogHost.Default no method is called. What's wrong?

A: We have a premade Serilog logger that is made for Splat.
You should be able to register it using
using Splat.Serilog;

// Then in your service locator initialisation
locator.CurrentMutable.UseSerilogWithWrappingFullLogger();

See https://github.com/reactiveui/splat#serilog for further details.
Then you would just register the logger as per normal.
The Splat Serilog also supports semantic logging out of the box, while the ILogger would strip that information.


text:
Q: proving limit of sequence when related limit is known Suppose I have the sequence $\{x_n\}$, where $ x_n >0$ for all $n\ge1$.
The sequence satisfies:
$$\lim_{n\rightarrow\infty}{x_n^{x_n}} = 4$$
I am trying to prove that
$$\lim_{n\rightarrow\infty}{x_n} = 2$$
I have tried logarithms and the definition of the limit, but to no avail...
Any hints?

A: Hint: You could e.g. show and use that $f(x)=x^x$ is continuous and strictly increasing for $x\geq 1$ (and $f(x)\leq 1$ for $x\leq 1$).


text:
Q: Django plain-text email template generates \n after template tags Interesting issue here: I have plain-text emails sent by my Django app, with the following code:
email_context = dict()
email_context['to'] = user.display_name
email_context['new'] = user_data['new']
email_context['for_reminder'] = user_data['for_reminder']

plaintext = get_template('email/notification.txt')
text_content = plaintext.render_to_string(email_context)

html = get_template('email/notification.html')
html_content = html.render(email_context)

email = EmailMultiAlternatives(
    subject='Assignments',
    body=text_content,
    to=[user.email],
    reply_to=[settings.DEFAULT_FROM_EMAIL],
)

# email.attach_alternative(html_content, "text/html")

email.send()

the 'email/notification_base.txt' template looks like such:
Dear {{ to }},
{% if new %}
You have been assigned to the following NEW cases:
{% block new %}
{% endblock %}
{% endif %}
{% if for_reminder %}
You still have the following previously assigned cases, which need your attention:
{% block for_reminder %}
{% endblock %}
{% endif %}
Thank you for your assistance.

Sincerely,
The Team

the 'email/notification.txt' template just extends base:
{% extends 'email/notification_base.txt' %}

{% load common_tags %}
{% load common_filters %}

{% block new %}
{% for dispute in new %}
Case #: {{ dispute.case_id.no}}
Assignment date: {{ dispute.assignment_date }}
{% endfor %}
{% endblock %}

{% block for_reminder %}
{% for dispute in for_reminder %}
Case #: {{ dispute.case_id.no }}
Assignment date: {{ dispute.assignment_date }}
{% endfor %}
{% endblock %}

My problem with it is, that the email it generates and sends to the addressee, actually gets rendered with a NEWLINE in every spot where the template had {% something %} tags. This results in a very unevenly formatted email text. As an example, if both blocks were missing the email would look like:
Dear Someone,

Thank you for your assistance.

Sincerely,
The Team

Are there any ways around this problem?


text:
Q: Как после consumer rebalance процесса, сбросить offset, что бы Consumer мог прочитать топик сначала? Есть ситуация, когда Consumer1 читает сообщения из кафка топика. При подключении второго Consumer2 с таким же groupId, происходит перераспределение партиций, можно ли как то сбросить offset, что бы после процесса перераспределения, оба Consumer'а читали топик с начала?
Мне нужно что бы во время процесса перерапределения партиций, выполнялась определенная логика, в том числе что бы после каждого перераспределения партиций сбрасывалось значение offset, что бы после перераспределения информация равномерно распределилась между потребителями. Я нашел, что процесс ре-балансировки партиций модно отследить реализовав интерфейс ConsumerRebalanceListener
@Service
public class KafkaRebalanceListenerHandler implements ConsumerRebalanceListener {

    @Override
    public void onPartitionsRevoked(Collection<TopicPartition> partitions) {

    }

    @Override
    public void onPartitionsAssigned(Collection<TopicPartition> partitions) {

    }
}

И далее указать переопределенный KafkaRebalanceListenerHandler при настройке KafkaConsumer
    @Bean
    @RefreshScope
    public ConcurrentKafkaListenerContainerFactory<String, String> listenerFactory() {
        final ConcurrentKafkaListenerContainerFactory<String, String> factory =
                new ConcurrentKafkaListenerContainerFactory<>();
        factory.setErrorHandler(kafkaListenerErrorHandler);
        factory.getContainerProperties().setConsumerRebalanceListener(kafkaRebalanceListenerHandler);
        factory.setConsumerFactory(consumerFactory());
        return factory;
    }

с этим вроде тоже разобрался. Остается неясность, как привязавшись к перераспределению партиций, застравить вычитывать топик заново.

A: По идее достаточно реализовать ConsumerSeekAware в вашем listener-e, а именно метод onPartitionsAssigned, чтоб он сбрасывал offset-ы на начало, когда партиция назначается данному Consumer-у:
public class KafkaMessageListener implements ConsumerSeekAware {
    @KafkaListener(topics = "my.topic")
    public void listen(byte[] payload) {
        // ...
    }

    @Override
    public void registerSeekCallback(ConsumerSeekCallback callback) {
    }

    @Override
    public void onPartitionsAssigned(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) {
        assignments.forEach((t, o) -> callback.seekToBeginning(t.topic(), t.partition()));
    }

    @Override
    public void onIdleContainer(Map<TopicPartition, Long> assignments, ConsumerSeekCallback callback) {
    }
}


text:
Q: Android-How to develop print option in web view? I have developed a android web view where a specific url is loaded. Now I want to develop a print option to print the full web view (just as the print option of any browser app has e.g. chorme browser of android version). Can anyone has any idea to do this? Besides, is it possible to print any screen from any android application??
N.B. ** I have to print in a wifi enabled printer which has NFS technology also
** I don't want to use google cloud printing.


text:
Q: Simulating push notifications with PHP and jQuery leads to server problems I am simulating push notifications using PHP the following way:

*

*A jQuery ajax call calls a script on the server.

*The script is being delayed using a for loop and a sleep after each iteration.

*If something happens - the loop is being breaked and the information returned to the jQuery.

*If the script runs for more than one minute - the script returns an empty value.

*When the jQuery receives an answer from the server it parses the information and starts the same procedure again.

That's a procedure, used by facebook and it works like a charm on their website. On my server I have the following problem:
For example if the script is being delayed for 60 seconds and I click on another link on my website on the 30-th second we still have 30 seconds left to generate the output. So my webserver is waiting those 30 seconds and my click request is being processed after those seconds, making my website almost impossible to use. I have doublechecked facebook and I found that, when you click on a link the page is never refreshed and the requests keep flowing on the same page. The adressbar however changes. What is the way to achieve the same thing on my website? Is there a way to force my server to process more then one PHP request at a time or we have to do this using javascript only. What am I missing?
P.S as far as I know there is no way to change the adressbar using javascript.

A: Actually there is in HTML 5. It's called History API.
You could find a quick demo with the source code on GitHub here:
http://html5demos.com/history

The complete chapter about it in Dive Into HTML5:
http://diveintohtml5.info/history.html


text:
Q: CngKey Assign permission to machine key I've created a machine wide CngKey (MachineKey=true), but my applications aren't able to access it.
How to I assign permissions to so that my App Pool can access the key? Preferably pragmatically so that I can build it into the installer.
Powershell create script:
[System.Security.Cryptography.CngKeyCreationParameters] $cngKeyParameter =  [System.Security.Cryptography.CngKeyCreationParameters]::new()
    $cngKeyParameter.KeyUsage = [System.Security.Cryptography.CngKeyUsages]::AllUsages
    $cngKeyParameter.ExportPolicy = [System.Security.Cryptography.CngExportPolicies]::AllowPlaintextExport

    $cngKeyParameter.Provider = [System.Security.Cryptography.CngProvider]::MicrosoftSoftwareKeyStorageProvider
    $cngKeyParameter.UIPolicy = [System.Security.Cryptography.CngUIPolicy]::new([System.Security.Cryptography.CngUIProtectionLevels]::None)
    $cngKeyParameter.KeyCreationOptions = [System.Security.Cryptography.CngKeyCreationOptions]::MachineKey

    #Create Cng Property for Length, set its value and add it to Cng Key Parameter
    [System.Security.Cryptography.CngProperty] $cngProperty = [System.Security.Cryptography.CngProperty]::new($cngPropertyName, [System.BitConverter]::GetBytes(2048), [System.Security.Cryptography.CngPropertyOptions]::None)
    $cngKeyParameter.Parameters.Add($cngProperty)

    #Create Cng Key for given $keyName using Rsa Algorithm
    [System.Security.Cryptography.CngKey] $key = [System.Security.Cryptography.CngKey]::Create([System.Security.Cryptography.CngAlgorithm]::Rsa, "MyKey", $cngKeyParameter)

A: The permissions for a CNG key are a bit indirect.
If you know the full set of permissions you want to apply you can do it at creation (you'll have to translate the C# to PowerShell, sorry):
CryptoKeySecurity sec = new CryptoKeySecurity();

sec.AddAccessRule(
    new CryptoKeyAccessRule(
        new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),
        CryptoKeyRights.FullControl,
        AccessControlType.Allow));

sec.AddAccessRule(
    new CryptoKeyAccessRule(
        new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null),
        CryptoKeyRights.GenericRead,
        AccessControlType.Allow));

const string NCRYPT_SECURITY_DESCR_PROPERTY = "Security Descr";
const CngPropertyOptions DACL_SECURITY_INFORMATION = (CngPropertyOptions)4;

CngProperty permissions = new CngProperty(
    NCRYPT_SECURITY_DESCR_PROPERTY,
    sec.GetSecurityDescriptorBinaryForm(),
    CngPropertyOptions.Persist | DACL_SECURITY_INFORMATION);

cngKeyParameter.Parameters.Add(permissions);

If you want to append a rule later (such as after creating it with the default permissions):
CngProperty prop = key.GetProperty(NCRYPT_SECURITY_DESCR_PROPERTY, DACL_SECURITY_INFORMATION);
CryptoKeySecurity sec = new CryptoKeySecurity();
sec.SetSecurityDescriptorBinaryForm(prop.GetValue());

sec.AddAccessRule(
    new CryptoKeyAccessRule(
        new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null),
        CryptoKeyRights.GenericRead,
        AccessControlType.Allow));

CngProperty newProp = new CngProperty(
    prop.Name,
    sec.GetSecurityDescriptorBinaryForm(),
    CngPropertyOptions.Persist | DACL_SECURITY_INFORMATION);

key.SetProperty(newProp);


text:
Q: passing arguments in python to c executable I have a c-executable that works as:
./avg filename opt1 opt2 opt3

Eg:
./avg one.dat 1 1 -1

returns something like
 127.504            2.244375804433813           1.111195552742103 blks: 500

When I try to call this from a python code, I have tried:
import os
os.system("./avg one.dat 1 1 -1")

as well as
import subprocess
#args = ("./avg","one.dat","1","1","-1")
args = ("./avg  one.dat  1  1  -1")
popen = subprocess.Popen(args, stdout=subprocess.PIPE)
popen.wait()
output = popen.stdout.read()
print output

Neither works, and the executable that not enough arguments are passed to the executable. It should get at least 4 options.
Any help will be appreciated, thanks in advance.

A: You cannot wait() for the subprocess before you read its output; wait waits for the child process to terminate, but child process is blocked writing its output! subprocess.check_output simplifies reading stdout of a process, so you can replace Popen, wait and read with
output = subprocess.check_output(['./avg', 'one.dat', '1', '1', '-1'])

And args = ("./avg","one.dat","1","1","-1") (or a list as above) is the proper way to do it; each argument need to be separate elements in an iterable.


text:
Q: su without password with pam su-authentication I've done the following configuration in ubuntu 14.04 but it's still asking password.
$ /etc/passwd

test:x:1004:1004::/home/test:/bin/bash

$/etc/pam.d/su

 auth       required   pam_wheel.so group=test
 auth       sufficient pam_wheel.so trust use_uid

Is there any  other method to do this?

A: su to root without a password
In the file /etc/pam.d/su put this as the line:
auth            sufficient      pam_permit.so

To restrict this just to your username, use this line instead, replace the yourusername with your actual username:
auth            sufficient      pam_succeed_if.so use_uid user = yourusername

You can also restrict this to a group, here the group allowedpeople can su without a password:
auth            sufficient      pam_succeed_if.so use_uid user ingroup allowedpeople

then login
su yourusername

A: You have to add this line in /etc/pam.d/su before:
auth       [success=ignore default=1] pam_succeed_if.so user = <username you want to su>

then,
To restrict this just to your username, use this line instead, replace the yourusername with your actual username:
auth            sufficient      pam_succeed_if.so use_uid user = yourusername

to restrict access to group
auth            sufficient      pam_succeed_if.so use_uid user ingroup allowedpeople


text:
Q: Can not perform a class transition in d3.js Why can not I perform a class transition in d3.js?
main.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>d3 playing around</title>
    <link rel="stylesheet" href="main.css">
    <!-- <script src="d3LibV5Min.js"></script> -->
    <script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>

    <div id="drawRegion">

    </div>

    <script src="main.js"></script>
</body>
</html>

main.css:
#drawRegion {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

#drawRegion .mainSvg {
    border: 2px #000 solid;
    background: #ddd953;
    width: 500px;
    height: 500px;
}

#drawRegion .mainSvg .blackCircle {
    border: 2px #fff solid;
    background: #000;
}

#drawRegion .mainSvg .whiteCircle {
    border: 2px #000 solid;
    background: #fff;
}

main.js:
var drawRegion = d3.select("#drawRegion");

var svg = drawRegion
    .append("svg")
    .classed("mainSvg", true);

var circle = svg
    .append("circle")
    .attr("cx", 250)
    .attr("cy", 250)
    .attr("r", 50)
    .classed("blackCircle", true);

var tr = d3
    .transition()
    .duration(5000);
circle
    .transition(tr)
    .classed("blackCircle", false)
    .classed("whiteCircle", true);

What I expect from this code to do is to show a black circle with a white border and transition into a white circle with a black border gradually after 5 seconds. But that just does not happen. I am learning the d3.js over here and according to the tutorial I am doing everything correctly.
Here is the fiddle. Will be grateful for any help provided here.
I know other approaches like, for example, using the css-transitions, but I would like to feel the power of d3.js since I decided to learn it profoundly.

A: Simply put, you are trying to do this:
circle.classed("blackCircle",true);

circle.transition()
  .classed("blackCircle",false);
  .classed("whiteCircle",true);

The issue is that a transition doesn't offer a classed method. If you look at the error message you get, you can confirm this: circle.transition(...).classed is not a function.
(See the docs for available methods)
 A d3 transition interpolates between a starting value and an end value - and as a boolean value is either true or false, it is hard to transition between these two points using only those two values. Hence, classed cannot be a method of a d3 transition in its current form.
If you would like this to work with d3, you could abandon the class approach and apply styles directly using selection.style() and transition.style().
For example:

var svg = d3.select("body")
  .append("svg");

var circle = svg.append("circle")
  .attr("cx",100)
  .attr("cy",50)
  .attr("r", 20)
  .style("fill","steelblue");

var t = d3.transition()
  .duration(3000);

circle.transition(t)
  .style("fill","orange");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

I'll also add that something like:
circle.attr("class","whiteCircle");

circle.transition().attr("class","blackCircle");

Won't work as well, despite .attr() being a method of d3.transition(). This is because the interpolator will attempt to interpolate the string values between start and end using d3.interpolateString. Given two strings without numbers, the second value will be used at all points on the transition (See this fiddle).
Also, you use background as a css property for the svg circle, you need to use fill when working with svg elements. Likewise, instead of border you need to use stroke, stroke-width, etc


text:
Q: How to return valid JSON format from db through swagger in .net 6 I have nvarchar content in my db like:
"{"prop1": {"test7": "test"}}"
and my program return is like:
"{\r\n  \"prop":{\r\n  \"test7":\"test"}"

Return method has return type async Task<IActionResult> and it returns like return Ok(response)
What I want is to have proper json format with indentation instead.
I use System.Json as well as NewtonsoftJson library. Booth cases are fine for me. I believe is something due encoding but I'm not sure. Thanks
UPDATE #1:
It looks like its not problem with my swagger, but with my _dbcontext.
var allByExternalId = _requests.Where(x => x.CorrelationId == correlationId); //this line return IQueryable with property which contains CRLF

How to tell EF COre not to parse this string as CRLF but to keep json indentation? thanks


text:
Q: Representation theory of simple Lie algebras Let $V$ be a simple complex Lie algebra.
Let $W=\Lambda^2V$ be the second exterior power of $V$.
Is it possible to find a basis for $W$ that consists of elements of the form
$v \wedge w$, where $v$ and $w$ are a pair of nilpotent elements of an $\mathfrak{sl}_2$ triplet?

A: Yes, and in fact it suffices to use only the the $\mathfrak{sl}_2$-triple associated with the minimal nilpotent orbit of $V$.
Let $G$ be the adjoint group of $V$, so that $V={\rm Lie}(G)$. Then $\wedge^2 V$ is spanned by all $G$-conjugates of
$e\wedge f$ where $e=e_{\alpha}$ and $f=e_{-\alpha}$ and $\alpha$ is the highest root of $V$ (we can choose any Borel subgroup of $G$).  Note that $V$ is an irreducible $G$-module where we assume that $G$ acts on $V$ via the adjoint representation. This also induces a natural action of $G$ on $\wedge^2 V$. Although $\wedge^2 V$ is no longer $G$-irreducible (if ${\rm rk}\, V\ge 2$) we still know that it is generated (as a $G$-module) by $e\wedge f$. Indeed, let $W$ be $G$-submodule generated by $e\wedge f$. We first apply positive root vectors to $e\wedge f$ to deduce that $W$ contains $e\wedge v$ for $v\in V$. After that we apply negative root vectors to $e\wedge v$ to deduce by induction (on height of roots involved in $u$) that $u\wedge v\in W$ for all $u,v\in V$.
Since any spanning set contains a basis of $\wedge^2V$, we are done. If $V=\mathfrak{sl}_2$ one just need three $G$-conjugates of $e\wedge f$, say $e\wedge f$, $({\rm Ad}\,g_1)(e)\wedge ({\rm Ad}\,g_1)(f)$ and $({\rm Ad}\,g_2)(e)\wedge ({\rm Ad}\,g_2)(f)$ for some $g_1,g_2$ in $G={\rm SL}_2$. There is plenty of choice for that.


text:
Q: White lines crossing rendered cube
I got this while trying to render a cube on Three.js, using THREE.MeshBasicMaterial() and a loaded texture.
Is this normal? How can I fix it?

A: Set the option overdraw:true.
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: true } );


text:
Q: React Query with firebase returns undefined I am very new to state management libraries and the one that I chose was React Query. I have followed multiple tutorials about it with mock data, but when I try to use my firebase imported data, it returns undefined. I am attaching all of my code with instances of React Query in it. This app is in next js 12.
file where I want to fetch and render data
const fetchDbData = async () => {
    const {currentUser} = UseAuth();
    function getLoc() {
        if (currentUser) {
            return 'users/' + currentUser.uid + '/userInvestments'
        } else {
            return 'users/TestDocumentForDatabase/userInvestments'
        };
    }
    const loc = getLoc();
    const q = query(collection(db, loc));
    const snapshot = await getDocs(q);
    console.log(snapshot)
    const {data, status, error} = useQuery(
        ['firebaseData'],
        () => snapshot.forEach(doc => doc.data()),
        {
            refetchOnWindowFocus: false
        },
        {
            retry: false
        },
    )
    return {data, status, error}
}

export default function usePortfolio() {
    const {data, status, error} = fetchDbData
    .....

_app.js

export const queryClient = new QueryClient({
  defaultOptions: {
      queries: {
          refetchOnWindowFocus: false,
          useInfiniteQury: false,
      },
  }
})
export default function App({ Component, pageProps }) {
  return (
    <QueryClientProvider client={queryClient}>
      <AuthProvider >
        <RootLayout>
          <Component {...pageProps} />
        </RootLayout>
      </AuthProvider>

    </QueryClientProvider>
)}


text:
Q: Ways to setup Ubuntu I just finished building my computer for the first time and I'm hoping to run Ubuntu or at least a Linux dist on it. Currently I have Windows 7 installed on my computer and my question is that how should I install Ubuntu? I have my W7 installed on my 128GB SSD and I have two 1TB HDD; one for progams and the other one for regular files.
Should I install it with Windows on the SSD?
Install it on a HDD? Or how does dual boot work?
Install it on a USB?
What's a good way to install Ubuntu for a person that is completely new to Linux like me? Sorry if I sound ambiguous, I'd be happy to provide more information if needed.

A: Glad to hear, that you are interessted in open alternatives.
Ubuntu is not problematic to install at all. I would install it on the SSD as dual boot on a partition of 30GB (maybe less, if you're just trying Ubuntu).
Just download the ISO image of Ubuntu or Kubuntu, burn it to CD-ROM and boot from it. You could use an USB stick to boot from, too. Therefore you could use the program "unetbootin" (it can download the latest image, write it to the USB stick and make it bootable).
The setup process is very self-explaining. In particular you just have to know how to partition a harddisk. I would set the "noatime" flag for your SSD, since it reduces harddisk access for read operations. But this is not necessary.
Once the system is set up, you can install new programs from the Ubuntu repository via Synaptics or via console per sudo apt-get install packagename.
You can make further optimizations for your SSD if you want.


text:
Q: JavaScript statement execution order In the following code how can I still have the second and third statement executed even if the first one returns false?
// so in this one if Required fails I dont get the email error :(
function validate() {
    if (checkRequired(myForm.requiredElements)
        && checkEmail(myForm.emailInputs)
        && checkTelephone(myForm.telInputs)) {
        return true;
    }
    else {
        return false;
    }
}

A: Use the single-ampersand version of and, it doesn't shortcircuit like the double-ampersand one.
function validate() {
    if (checkRequired(myForm.requiredElements)
        & checkEmail(myForm.emailInputs)
        & checkTelephone(myForm.telInputs)) {
        return true;
    }
    else {
        return false;
    }
}


text:
Q: Override behaviors in Entity Framework We have a data model that has some requirements.  I would like to find a way to make these requirements be as transparent as possible while using EF.
First, the model must support soft-delete.  I've seen some questions around this and I think it would be relatively straight forward.
Second, We have an "insert only" policy.  That means no updates.  When an update is made, a new entry must be inserted instead.  I would like to be able to treat the operation as an update, and have the framework change it to an insert behind the scenes.
Third, Due to #2 when we query, we need to order by descending on the identity column and return the first record only.  Even when doing a query that returns many records.  Essentially, this creates a version history.
Fourth, we don't want to have to implement this logic in each query.  It would be nice to have the framework do it for us so we can treat each query as if it were a normal CRUD type transaction.
Has anyone implemented such a data model in EF?  What techniques did you use?
I'm aware that some of this can be done in Views and/or Sprocs, but if you use views then you have to maintain all relationships manually (EF can't read the relationships through the views).  Triggers are also a possibility, but our DBA's want as few triggers as possible, and have a very extensive review policy on all triggers that takes a long time to accomplish.  I'd rather not use a trigger if I don't have to.
I work primarily in a database first approach, but i use dbcontext.
EDIT:
Given Ladislav's comments below, I'd also be interested in any comments about other ORM's that may be able to handle these requirements.

A: *

*This is possible with conditional mapping where additional column will be used to differ deleted records and custom SQL command / mapped stored procedure for every entity requiring soft delete to perform Update instead of Delete.

*I doubt EF will handle this transparently. If you modify attached instance loaded from database it will perform update. You can again map stored procedure to perform insert instead of update but that change will not be reflected in your application logic. You will have to dispose context and reload data with a new context instance to see changes correctly. Better option is simply force your application somewhere to clone entity and insert the clone as a new one.

*EF will not allow you adding such condition to autogenerated queries transparently unless you map it as a view or custom SQL query. Once you use view or SQL query you must also use SQL commands or stored procedures from insert, update and delete operations. Using custom SQL query has same disadvantages as using views.

*If you don't use SQL query, you will have to write query yourself for example in form of custom reusable extension method and use it everywhere but be aware that eager or lazy loading will not reflect this. In case of eager and lazy loading you will always get all versions.

Stored procedure mapping requires EDMX. Custom SQL command and query mapping requires EDMX and without any other commercial tool you will also have to manually maintain EDMX.


text:
Q: how to print all the processes listed on one particular core of the Processor in Linux? I would like to write a small program which will ask me the core(or CPU) number and would list out all the currently executing processes on that particular entered core.
for example,
output would be something like this,
Enter the CPU(or Core) Number : 1
process 1,
process 2,
process 3,
...... So On.
Enter the CPU(or Core) Number : 2 or any valid core number
process 1,
process 2,
process 3,
...... So On.

A: The following article talks about the CPU utilities in linux
http://www.cyberciti.biz/tips/how-do-i-find-out-linux-cpu-utilization.html
For your case I believe you might try taskset like
# taskset -p <PID>

This may be useful to find the affinity of a particular process to the CPU.
There is this other article on csets (groups of CPUs for specific applications/processes) which is a little more organized than taskset - https://rt.wiki.kernel.org/index.php/Cpuset_management_utility/tutorial

A: Unless otherwise specified, the kernel will dispatch timeslices of each process/thread to whichever core is currently available.
i.e. any results you could get are immediately obsolete.


text:
Q: What query would get me this result? JSON and PHP {
    "cars": {
        "toyota": [
            {"model":"*****", "doors":"*","color":"*****"},
            {"model":"*****", "doors":"*","color":"*****"}
                  ],
        "Ford": [
            {"model":"*****", "doors":"*","color":"*****"},
            {"model":"*****", "doors":"*","color":"*****"}
        ]
    }
}

What query would give me the following result?
It's a JSON object (cars), that contains the multiple arrays each for a different model of car. In each array would be other types of data e.g. doors, color, years.... and more
I tried this code:
<?php

require 'conn_pdo.php';

$conn -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);

$sql = "select * from test_cars where cars in (select cars from test_cars GROUP BY cars) ORDER BY RAND()";

$stmt = $conn -> prepare($sql);
$stmt -> execute();
$row = $stmt -> fetchAll();
$json['cars'] = $row;
echo json_encode($json);

?>

But the result is not that I hope
{ "cars":
         [ {"model":"*****", "doors":*","color":*****"},
           {"model":"*****","doors":"*","color":*****"} ,
           {"model":"*****", "doors":"*","color":*****"},
           {"model":"*****", "doors":"*","color":*****"},
           .......
         ]
}

I got cars object, containing one arrays for all different model of car !!

A: Here is one way to do it. I've removed the GROUP BY approach, since the approach in the question doesn't use it correctly - it throws the grouping away by using an IN query. I think it's pretty easy to do in PHP anyway.
// It would be good to check to ensure you have a valid connection,
// and that the prepare/execute calls are successful
$sql = "SELECT * from test_cars";
$stmt = $conn->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll();

$out = [];
foreach ($rows as $row)
{
    // Let's process by brand (since you have not shown your
    // schema, you will need to adjust column names to suit)
    $brand = $row['brand'];

    // Get other data
    $model = $row['model'];
    $doors = $row['doors'];
    $colour = $row['colour'];

    // Check to ensure the brand is an array, so that we don't
    // get an error when we push
    if (!isset($out[$brand]))
    {
        $out[$brand] = [];
    }

    // Now push the data on to the end (using [])
    $out[$brand][] = [
        'model' => $model,
        'doors' => $doors,
        'colour' => $colour,
    ];
}

$json['cars'] = $out;
echo json_encode($json);

This is untested, but should give you the general idea. You should expect to have to adjust it a little bit, as with all answers on Stack Overflow. I've used the new array syntax (as of PHP 5.4) but it will work on earlier versions if you swap that to array().


text:
Q: Show html from javascript I want to show some html element from javascript in #muncul, but it's just error
Here's my code
Are my code wrong?
Sorry for my bad English
if(data.st == 0)
{
 $('#muncul').'

'.html(data.msg).'

';
}

A: Try this code:
if(data.st == 0)
{
 $('#muncul').html('

' + data.msg + '

');
}


text:
Q: understanding SUB used in an AWK command I need to understand how this command is working:
awk 'BEGIN{while(a++<30)s=s " "};{sub(/^.{6}/,"&" s)};l' myfile

I understand how the first part (the expression in the BEGIN{} section) creates a 30 character long string of spaces. But don't understand the second part (sub).
The sub adds the recently generated string "s" to the 6th column of 'myfile'. But the way I see the command, the search pattern /^.{6}/ should look for all lines that start with one character (.) and then {6} and replace those with space-added string!
Can you please help me to understand this better?

A: It has nothing to do with the 6th column, and it's not looking for a literal {6}.
The curly braces mean "this many of the preceding pattern" (if you invoke GNU awk with --posix or --re-interval).
So this pattern:
/^.{6}/

Is equivalent to this:
/^....../

What it's doing is adding the string s after the first 6 characters, which may be any characters.
The following awk command would do something similar:
awk 'BEGIN{while(a++<30)s=s " "} {print substr($0, 1, 6) s substr($0, 7)}' myfile

A: See @BillKarwin's answer for what it's doing, and see the 2nd awk script below for the more concise way to do it:
$ cat file
abcdefghi

$ awk 'BEGIN{while(a++<30)s=s " "} {sub(/^.{6}/,"&" s)} 1' file
abcdef                              ghi

$ awk '{printf "%-36s%s\n",substr($0,1,6),substr($0,7)}' file
abcdef                              ghi


text:
Q: Changes on archive-product.php doesn't work I'm trying to customize the standard woocommerce theme and so far that has worked well. I copied all template files from /plugins/woocommerce/templates to /mytheme/woocommerce and customized the files.
But when i'm change something in archive-product.php nothing happens? I even tried to customize this in the core files (/plugins/woocommerce/templates/archive-product.php) but i doesn't work.
I want to change the class of the h1 heading:
<?php woocommerce_page_title(); ?>
.
So i looked up all woocommerce template files, the class page-title occurs only in this one file (to prevent editing the wrong file).
Edit:
In detail, i want to customize the theme used in this path: http://example.com/product-category/mycategory

A: Here's how I fixed mine:

*

*Delete woocommerce.php in your theme folder.

*Copy TEMPLATE folder in woocommerce plugin dir, paste it in your THEME folder, and rename it to woocommerce.

*Open the folder you just renamed, go to shop folder, and edit wrapper-start.php and wrapper-end.php.

A: I tried all the above solutions, to no avail.  No matter what I did, the archive-product.php was not being used at all.  Instead, most woocommerce pages were using page.php from my theme.
The solution for me was to add theme support... Which, it's been a while since I used woocommerce, so I completely forgot about that.  But after adding the following line to my functions.php file, archive-product.php is now being used (/mytheme/woocommerce/archive-product.php) and I can update it, as I should be able to.
add_theme_support('woocommerce');

A: If you use the woocommerce.php method you cannot customize archive-product. You must use the hooks method

http://docs.woothemes.com/document/third-party-custom-theme-compatibility/
  Please note: when creating woocommerce.php in your theme's folder, you won't be able to override  the woocommerce/archive-product.php custom template as woocommerce.php has the priority over  archive-product.php. This is intended to prevent display issues.

A: Seems this is STILL an issue in Woocommerce. For anyone landing here, the following solution was working for me as of version 2.1.6.
Apparently the problem is due to the function woocommerce_content() outputting the wrong page for archive content.
I used the following to get around it:
replace woocommerce_content() in woocommerce.php with:
if ( is_singular( 'product' ) ) {
 woocommerce_content();
}else{
//For ANY product archive.
//Product taxonomy, product search or /shop landing
 woocommerce_get_template( 'archive-product.php' );
}

Credit: found the solution here

A: you need to edit the file "taxonomy-product_cat.php" and add a conditional is_product_category( 'mycategory' ).

*

*open your theme folder and add a new subfolder named "woocommerce" to it.

*copy the files "archive-product.php" and "taxonomy-product_cat.php" from /plugins/woocommerce/templates to the woocommerce subfolder in your theme.

*rename "archive-product.php" to "archive-mycategory.php" (or whatever you like, this will be the template file to the category).

*open "taxonomy-product_cat.php" and wrap the  wc_get_template( 'archive-product.php' ); with:

    if (is_product_category( 'mycategory' )){
        wc_get_template( 'archive-mycategory.php' );
    }  else {
        wc_get_template( 'archive-product.php' );
    }

A: For others searching here, doublecheck the path. It is for example not /mytheme/woocommerce/templates/archive-product.php but only /mytheme/woocommerce/archive-product.php. I didn't have to apply @Talk nerdy to me's patch or any other to make it work.


text:
Q: Exporting web in sharepoint solution gallery issue I am exporting web via SPExport Api of Microsoft and it works fine but I think it does not export solution gallery. Please tell me is there any work around for this problem. I am using this code for export exportSettings has all the settings set for export.
export = new SPExport(exportSettings);
export.Completed += new EventHandler<SPDeploymentEventArgs>(export_Completed);
export.ProgressUpdated += new EventHandler<SPDeploymentEventArgs>(export_ProgressUpdated);
export.Run();
strExportChangeToken = exportSettings.CurrentChangeToken;


text:
Q: Jeditable not working in IE, but works in FF, Chrome I have a table made of:
<td class='editable' id='<?=data['id']?>' col='<?=data['col_name']?>'>Content

$data is the mysql_fetch_assoc of the $query, when I click on , the jeditable plugin activates in FF or Chrome but doesn't work in IE.
$(function () {
    $(".editable").click(function (event) {
        $(this).editable('ajax_save.php',{
            id          : 'id',
            name        : $(this).attr('col'),
            submit      : 'Save',
            cancel      : 'Cancel',
            tooltip     : ''
        });
    });
});

I couldn't figure out why this is happening, can you please help me out?
Thanks

A: It seems like not all options work on IE 7/8 ...
This code works
$(document).ready(function() {
    $(".editable").editable("ajax.php",{
        type: "text"
    });
});

This doesnt
$(document).ready(function() {
    $(".editable").editable("ajax.php",{
        type: "text", submit:"OK",cancel:"Cancel"
    });
});

Asked Mika Tuupola about this, maybe there's something wrong with the way jquery or jeditable handles td elements, wrapping the information inside a div would create overhead DOM that affects performance in case we're dealing with huge reports.


text:
Q: Is it possible to have CommandManager requery only specific WPF command instead of all? I'm trying to implement a highly responsive UI for my MVVM application, so I've chosen to have all command handlers automatically execute in a BackgroundWorker so they don't block the UI.
But at the same time, I don't want the user to be able to execute the same command while it is still executing in the background. The solution seems obvious:

*

*When Executed handler is invoked, have the CanExecute handler return false

*Start the BackgroundWorker async

*When BackgroundWorker finishes, have the CanExecute handler return true again.

Problem is, I need to notify WPF after step 1 and again after step 3 that CanExecute has changed and that it should be required. I know I can do it by calling CommandManager.InvalidateRequerySuggested, but that causes CanExecute handlers of all other commands to be requeried as well. Having a lot of commands, that's not good.
Is there a way to ask for requery of a specific command - i.e. the one that is currently being executed?
TIA

A: I think you only need to raise the ICommand.CanExecuteChanged event for these two cases, and the corresponding control should update its IsEnabled state.

A: gehho is right, just raise the CanExecuteChanged event. But honestly, I don't know your implementation, but if your CanExecute predicate is simple, I think it will be hard to notice that wpf is requerying. I can't believe you will notice a performance hit. Have you tested performance? I mean let's say you have 20 ICommands in a ViewModel(which is probably too much) if the ICommand.CanExecute points to a boolean field that you are setting to true and false based on the backgroundworker it should take less than nanoseconds. But if the CanExecute is pointed to a method that evaluates, then it may be longer, but I still doubt it would be noticeable.
But hey, I don't know your implementation.

A: Use MVVM Helper's `DelegatingCommand' which exposes RaiseCanExecuteChanged() for the Command.
So you can subscribe to RunWorkercompleted event on BackgroundWorker and depending on the kind of work logged (maybe you can return as part of the Result) you call Command.RaiseCanExecuteChanged() from ViewModel.


text:
Q: Highlight active tabs Wanted to check if we can highlight the active tabs . i mean when the user is in one tab ("agh"), that tab should be underlined. Similarly for other tab as well. Reprex below
app.R
library(shiny)

shinyApp(
    navbarPage(
        tags$head(
            tags$style(
                HTML(".tabbable > .nav > li[class=active] > a {text-decoration: underline}")
            )
        ),
        tabPanel("Tab1"),
        tabPanel("Tab2"),
        tabsetPanel(
            tabPanel("agh",
                     numericInput("n", "Number to add", 5),
                     actionButton("add", "Add"),
                     verbatimTextOutput("sum", placeholder = TRUE)
            ),
            tabPanel("dfd")
        )
    ),
    function(input, output, session) {
        nums <- numeric()

        c_sum <- eventReactive(input$add, {
            nums <<- c(nums, input$n)
            sum(nums)
        })

        output$sum <- renderText({
            c_sum()
        })

    }
)

A: library(shiny)

shinyApp(
  fluidPage(
    tags$head(
      tags$style(
        HTML(".tabbable > .nav > li[class=active] > a {text-decoration: underline}")
      )
    ),
    br(),
    tabsetPanel(
      tabPanel("agh",
               numericInput("n", "Number to add", 5),
               actionButton("add", "Add"),
               verbatimTextOutput("sum", placeholder = TRUE)
      ),
      tabPanel("dfd")
    )
  ),
  function(input, output, session) {
    nums <- numeric()

    c_sum <- eventReactive(input$add, {
      nums <<- c(nums, input$n)
      sum(nums)
    })

    output$sum <- renderText({
      c_sum()
    })

  }
)


text:
Q: What makes the proof of Cantor's theroem, for countably infinite sets, inapplicable to infinite sets? (This may be a naive question born out of ignorance, so bear with me)
What is the reason that Cantor's theorem can't be proven for infinite sets "simply" by indicating that for every element $ a $ added to set $ A$, $ P(A) $ will double its cardinality, resulting in an inability to satisfy surjection from $A$ to $P(A)$? (each added element in $A$ can only be mapped to one element in $P(A)$, whereas $P(A)$ has necessarily expanded by more than one element)
In other words, why isn't the $ n < 2^n $ argument regarding $ A $ and $P(A)$ cardinality  sufficient?
Thanks!

A: That could form the basis for a solid induction argument that would show $|A| \le |P(A)|$ for all finite sets $A$. Note that, at no point do you deal with an infinite set; the sets you're dealing with are just larger and larger finite sets. This way, if you formalised this argument with induction, you could deal with every possible finite set, but there's no path to infinite sets.
Remember how induction works:

*

*You establish a base case, i.e. prove what you want to prove for some specific $n$, usually $0$ or $1$,

*You show that if the $n$th case works, then so must the $(n+1)$th case (the induction step).

This way, you have shown that any (finite) case works. Because you proved it for $n = 0$, you therefore know, from the inductive step, that the $n = 1$ case works too. From this case, you know that $n = 2$ case works, and the $n = 3$ case, and the $n = 4$ case, etc, etc. If you wanted a self-contained, induction-free proof that the $n = 200$ case worked, you could write down the $n = 0$ case, then write the induction step down $200$ times, incrementing $n$ each time.
Essentially, there needs to be a finite path from your base case to whichever case you want to establish. The $n = 200$ case has a path of $200$ induction steps. It's long, but it's there.
No such path exists from an infinite set to a finite set, by removing single elements from the set. Every time you remove a single element from an infinite set, you get a set that, as it turns out, is equally large as the set you started with. Removing a single element does not get you any closer to your base case, as it has no effect on the cardinality of the set, or indeed its power set.
If you want an example where this reasoning can go wrong, compare $A$ and $A \times A$ (for $|A| \ge 2$). While $|A|$ grows linearly, $|A \times A|$ grows quadratically, outpacing $|A|$. For every one element we add to $A$, we are adding $2|A| + 1 > 1$ elements to $|A \times A|$. By the same reasoning, we might expect $|A \times A| > |A|$ for infinite sets too. But, this is not the case; $\Bbb{N} \times \Bbb{N}$ has the same cardinality as $\Bbb{N}$.

A: Suppose you did have a surjection $f$ from $A$ to $P(A)$.
And now you want to prove that there is no surjection $g$ from $A\cup\{a\}$ to $P(A\cup\{a\})$.
From your question, it appears that you are assuming you "just" have to find an image for $a$, and $g(x)$ will always be the same as $f(x)$ for $x\in A$.  This is by no means the case, $g$ could in principle be an entirely new function.  This is what is missing from your suggested proof.


text:
Q: Datadog: enabling RUM allowedTracingOrigins raises CORS errors I tried to connect RUM with backend traces. In react SPA application I setup a datadog-rum and enabled allowedTracingOrigins option for it, after that our fetch and xhr requests to API started to fail.
How to connect RUM and backend traces properly?

A: *

*Use datadog-rum version >=2.16,  this one will not cut your custom headers such as Authorization (see. diff)

*Check your server CORS handler. Your server should allow x-datadog-* headers and return them in the access-control-allow-headers header


text:
Q: Moving a DOM object with Javascript I'm new to javascript, and am just trying to move link whenever it is moused over.
I was hoping the following code would do it. but it says Uncaught TypeError: Cannot set property 'left' of undefined.
$('a').mouseover(function(){
    yPosition = parseInt(Math.random() * window.screen.availHeight);
    xPosition = parseInt(Math.random() * window.screen.availWidth);
    $(this).style.left = xPosition + "px";
    $(this).style.top = yPosition + "px";
});

A: Using jQuery you'll have to replace
$(this).style.left = xPosition + "px";

by
$(this).css('left', xPosition + "px");

You can replace both style lines
$(this).style.left = xPosition + "px";
$(this).style.top = yPosition + "px";

by using this syntax:
$(this).css({ left: xPosition, top: yPosition });

The unit px can be omitted safely using this.
For reference, check the jQuery API:

http://api.jquery.com/css/

A: Use .css() . The reason why you had that error is because:

*

*.style is for plain JavaScript inline style properties.

*$(this) is a jQuery object thus you should use jQuery methods unless you dereference it: $(selector)[0]
Make sure to review Snippet in Full page mode, the links shoot off like scattering cockroaches.
SNIPPET

$('a').hover(function() {
  var yPosition = parseFloat(Math.random() * window.screen.availHeight)+'px';
  console.log(yPosition);
  var xPosition = parseFloat(Math.random() * window.screen.availWidth)+'px';
  console.log(xPosition);
  $(this).css({
    left: xPosition,
    top: yPosition
  });
});
a {
  position: relative;
}

LINK
LINK
LINK
LINK
LINK
LINK
LINK
LINK
LINK

A: Please replace your code with below version. It will work
   $('a').mouseover(function(){
    yPosition = parseInt(Math.random() * window.screen.availHeight);
    xPosition = parseInt(Math.random() * window.screen.availWidth);
    $(this).css('left', xPosition + "px");
    $(this).css('top', yPosition + "px");
   });

A: the $(this) creates a jquery object, and these do not have the style property.
Either use the raw DOM properties as you try
this.style.left = xPosition + "px";
this.style.top = yPosition + "px";

or if you want to use jQuery use .css and change both positions in one go
$(this).css({
    left: xPosition,
    top: yPosition
});


text:
Q: Converting datetime type to hex value prints wrong answer i'm working with c#. I'm trying to convert my variable date1 which type is system.datetime to hex value. According to converters online, it's value should be 0000015908178fd8. I was surfing the internet and found that I can convert datetime to hex by using ticks function. However I'm getting this output 8D425D2D3A13580. I guess there is flaw in my logic or somekind of misunderstanding. What I'm doing wrong?
public static void Main(string[] args)
    {
       DateTime date1 = new DateTime(2016, 12, 16, 16, 44, 39);
       Console.WriteLine(date1.ToString()); // output 16.12.2016 16:44:39

       Console.WriteLine(date1.Ticks.ToString("X2")); // output 8D425D2D3A13580
    }

A: You are working with Unix Time (but count milliseconds, not seconds):
DateTime date1 = new DateTime(2016, 12, 16, 16, 44, 39);

string result =
  ((long)(date1 - new DateTime(1970, 1, 1)).TotalMilliseconds).ToString("x");

Console.WriteLine(result);

Outcome:
15908856cd8

A: Your converter represents date time as "milliseconds which passed since January 1st 1970", like time is represented in javascript. So to achieve the same result in C# you have to do:
var date1 = new System.DateTime(2016, 12, 16, 16, 44, 39);
var timestamp = (long) (date1.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
Console.WriteLine(timestamp.ToString("X2"));
// outputs 1590772C458

Note that output depends on your current timezone, because date1 will be assumed as time in your local timezone in this case.


text:
Q: class initialization function definition in java I'm getting the error "Abstract methods do not specify a body" with the below code....
    DCWebView.setWebViewClient(new MyWebViewClient() {
        @Override
        public abstract void launchExternalBrowser(String url) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
        }
    });

MyWebViewClient is an abstract class.  I'm wondering what the above code is doing exactly.  It's clearly intending on defining the function for the class... can I just put any code within the new MyWebViewClient() { } to define variables and other functions?
What other awesome things can be done in here?

A: Just remove abstract and it will work. If the method launchExternalBrowser is not defined in MyWebViewCLient you should also remove @Override annotation. @Override means that you override a method which is defined in an extended class hierarchy.
DCWebView.setWebViewClient methods requires an object of type MyWebViewClient as a parameter. By writing new MyWebClient() { .. } you create an instance of an anonymous class which extends MyWebViewClient.
Anonymous classes are (almost) the same as "normal" classes. You can define both new variables and methods there. The main difference is that an anonymous class is defined in a place where it is used (there is no external class definition and because of that it has no name, it is "anonymous") and it is used only in this one place (as there is no external definition it cannot be used elsewhere).
Anonymous classes are very commonly used in Java, however this is something a little more advanced. As esaj said in his answer it is a good idea to read something about this. There is plenty of information in the web e.g. here or here.

A: An abstract method is used to define a method without implementation. A concrete (non-abstract) class extending from an abstract class must then implement the abstract methods of the extended abstract class. The implementation for the defined method is written without the abstract-keyword in its method signature.
You probably should read through the Java SE tutorial about abstract classes and methods: http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

can I just put any code within the new MyWebViewClient() { } to define
  variables and other functions?

Yes, but there's another catch: as it seems you are giving your "anonymous" implementation of MyWebViewClient to another class's (static?) method DCWebView.setWebViewClient(), the DCWebView probably is only aware of the methods declared in the (abstract?) MyWebViewClient, and cannot access any other methods, even if they are public. However, if you want to break down the anonymous implementation of the MyWebViewClient to separate private methods and use member-variables within it, you are free to do so.


text:
Q: Angular 2 Quickstart install failing via npm (Link - https://angular.io/docs/js/latest/quickstart.html) As given in the link I've been trying to get Angular 2 running on my Ubuntu 15.10 machine but I get the following error messages and the install fails.
I also tried to install Angular 2 via the npm package command, that is sudo npm install angular2@2.0.0-alpha.32 but this gave the same sort of errors.
Any help would be appreciated. Thank you.
Here are the errors. The log it mentions at the bottom can't be posted here because it is over a 1000 lines.
sudo npm install
npm WARN package.json angular2-quickstart@1.0.0 No description
npm WARN package.json angular2-quickstart@1.0.0 No repository field.
npm WARN package.json angular2-quickstart@1.0.0 No README data
npm ERR! 404 Not Found
npm ERR! 404
npm ERR! 404 'angular/common' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404 It was specified as a dependency of 'angular2-quickstart'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.

npm ERR! System Linux 4.2.0-16-generic
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install"
npm ERR! cwd /home/anshuman/angular2-quickstart
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.4.21
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/anshuman/angular2-quickstart/npm-debug.log
npm ERR! not ok code 0

A: you must update your node and your npm for the last versions.
node -v
v4.4.7

npm  -v
3.10.5

A: Also try to cleaar your npm cache
npm cache clear


text:
Q: Как лучше верстать? Друзья, сейчас верстаю макет. Опыта не много. Хотел узнать, как лучше будет сверстать конкретный блок. С помощью таблицы или дивами, но с применением display

A: Я может и не правильно сделал , но вроде похоже

.table{
 display:table;
 margin:auto;
}
.table-cell{
 display:table-cell;
 max-width:150px;
 min-width:150px;
 text-align:center;
 border:1px solid #ccc;
 font-size:12px;
 position:relative;
}
.ch{
position:absolute;
left:0;
}

Название

    Рейс

   Вылет

   Прилёт

    В пути

   Самолёт

   Класс

   <input type="checkbox" class="ch"> SN-120

   08:50 Чита

   11:50 Домодедово

    9:00

   Боинг 737-800

   Э / 4

     <input type="checkbox" class="ch">  SN-120

   08:50 Чита

   11:50 Домодедово

    9:00

   Боинг 737-800

   Э / 4

ссылка на песочницу  мне кажется что лучше


text:
Q: automatically activate whenever there is http://www... between div tags I searched stackoverflow , similar question doesn't exist.
Just wanted to know if there was any short html shortcut to activate hyperlinks whenever there is http://www. between div tags. thanks for info.

A: No. HTML provides no methods to search an element for text that looks like it might be a URL and turn it into a link.
There are, however, numerous questions about using programming languages to modify documents in a similar fashion.

A: try this code that detects url in text
jsfiddle: http://jsfiddle.net/6u5eM/1/
function findUrls( text ) //the text you want to search a url for
{
    var source = (text || '').toString();
    var urlArray = [];
    var url;
    var matchArray;

    // Regular expression to find FTP, HTTP(S) and email URLs.
    var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;

    // Iterate through any URLs in the text.
    while( (matchArray = regexToken.exec( source )) !== null )
    {
        var token = matchArray[0];
        urlArray.push( token );
    }

    return urlArray;
}
alert( findUrls( 'http://www.site.com fejisojfiosf fsehiofes ' ) ); //returns url from text


text:
Q: php multiple record insert to sql not working Hi all I have a form where I'm entering students marks for exams, what I am trying to do is enter multiple marks in at once...but it just is not working, could someone help please? It is adding only ONE result, doesn't enter all that I write in.
FORM Code:

A: The script does not know what is $i in this case.
Use for loop:
$mark=$_POST['mark'];
$time=$_POST['time'];
$meID=$_POST['meID'];
$sID=$_POST['sID'];

for($i = 0; $i < count($_POST['mark']); $i++) {
    $_mark = mysql_escape_string($mark[$i]);
    $_time = mysql_escape_string($time[$i]);
    $_meID = mysql_escape_string($meID[$i]);
    $_sID = mysql_escape_string($sID[$i]);

    $sql = "INSERT INTO Marks (mark, time, meID, sID) VALUES ($_mark, $_time, $_meID, $_sID)";
    $result = mysql_query($sql);
}

Additionally you will add each mark twice, because of two mysql_query() invocations. I've already deleted one from $sql variable in my answer. Also you have wrong variable names in the insert query.

A: there is no mysql_escape_string . try replace this;
   $_mark = mysql_escape_string($mark[$i]);

to
   $_mark = mysql_real_escape_string($mark[$i]);

and put $_mark in the query instead of $mark
and replace all others also.

A: I think the problem is with the variable names:
Following line:
$sql = "SELECT * FROM ModuleExamStudent WHERE mesID = '$mesID'";

But there is no $mesID. It should be $mes:
$sql = "SELECT * FROM ModuleExamStudent WHERE mesID = '$mes'";

Again:
$sql = mysql_query("INSERT INTO Marks (mark, time, meID, sID) VALUES ('$mark', '$time', '$meID', '$sID')");

Should be:
$sql = mysql_query("INSERT INTO Marks (mark, time, meID, sID) VALUES ('$_mark', '$_time', '$_meID', '$_sID')");

A: Yeah, a lot of mistakes in you're code.
Fuse michal.hubczyk and Ambrish answer to obtain wath you want.
If i can suggest another way to do it, i'll prefer to make only one query instead an elevated number of query succession inside a loop.
Try this method
Inserting multiple rows in a single SQL query?
and build your query in a way like this:
$sql = "INSERT INTO XX VALUES";
for($i=0;$i < count($_POST['mark']); $i++){
 $_mark = mysql_escape_string($mark[$i]);
 $_time = mysql_escape_string($time[$i]);
 $_meID = mysql_escape_string($meID[$i]);
 $_sID = mysql_escape_string($sID[$i]);
 $sql .= "(".$_mark.",".$_time",".$_meID.",".$sID.")";
 if($i<(count($_POST['mark']-1))){
  $sql .= ",";
}
$result = mysql_query($sql);

Another suggestion is to use mysqli libray instead mysql ( http://php.net/mysqli)


text:
Q: Change remove cart item url in Woocommerce My simple question is that how I can make this code working
esc_url( WC()->cart->get_cart_url->get_remove_url( $cart_item_key ) ),

the above i have tried and the current code is below
 esc_url( $woocommerce->cart->get_remove_url( $cart_item_key ) ),

so instead my current url : example.com/?removed_item=1
should be something like example.com/cart/?removed_item=1
Thanks for suggestion

A:
WC_Cart get_remove_url() method is deprecated and replaced by wc_get_cart_remove_url() function.

It can be used as follow:
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    // Get the remove Url for the current cart item
    $remove_url = wc_get_cart_remove_url( $cart_item_key );
}

this will give you an url like: https://www.example.com/cart/?removed_item=1…

Now to make changes on this Url, you can use woocommerce_get_remove_url dedicated filter hook, like in this example:
add_filter( 'woocommerce_get_remove_url', 'custom_item_remove_url', 10, 1 );
function custom_item_remove_url( $remove_url ) {
    $cart_page_url   = wc_get_page_permalink( 'cart' );
    $replacement_url = wc_get_page_permalink( 'shop' ); // Shop page

    // Change URL to shop page + remove Url query vars
    $remove_url = str_replace($cart_page_url, $replacement_url, $remove_url);

    return $remove_url;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.
this will give you an url like: https://www.example.com/shop/?removed_item=1…


text:
Q: How to ensure uniqueness with NULL values in cockroach DB I have a table of accounts which generates unique keys with a sequence. It is used to generate unique identities for accounts and account/user pairs.
I tried the following from pgsql:
CREATE INDEX ON accounts (account_id, user_id) WHERE user_id IS NULL;

and
CREATE UNIQUE INDEX ON accounts (account_id, COALESCE(user_id, ''));

But both cases are not supported in cockroach.
Is there another way of ensuring uniqueness with NULL values?
I also have a different UNIQUE index on user_id to allow unique IDs to be generated for users without an account.

A: You may be able to do something like create a computed column and then use that in an index:
alter table accounts add column user_null int null as (coalesce(user_id, 0));
create unique index on accounts (account_id, user_null);


text:
Q: URL auto-detection and highlighting in a block of text The user may enter text for example
This is some text, visit www.mysite.com. Thanks & bye.

The URL should be found and turned into a link, for display in a website. All other characters should appear as-is.
I have been searching and googling for some time. I'm sure this sort of thing must already exist. My temptation is to program this myself but I'm sure this is more complex than it looks.

*

*Dots can be part of a URL, or can be a sentence terminator as above. I think users have the expectation that this will be handled properly; Outlook handles this correctly, for example.

*There are various different protocols such as http:, https: etc., plus links are often entered without a protocol specifier, as above.

*It is necessary to produce HTML (so that the  tag can be inserted) therefore it would be necessary to replace e.g. & with & before doing that; however some URLs have & in them (e.g. xyz.cgi?a=b&c=d) and there we only want an & to be inserted in the displayable part of the URL not in the link itself (...&...)

I'm sure there are other issues that I will encounter as soon as I attempt to program this myself. I don't think that a simple reg-exp is the way forward.
Is there any library which already does this, ideally for Java? (If it's in another technology maybe I can take a look at it and convert it to Java)

A: While you are right that this is a common problem it's also one that isn't really satisfactorily solved anywhere, nor can it be. URIs without markup written in freetext like this can be ambiguous (see http://en.wikisource.org/wiki/1911_Encyclop%C3%A6dia_Britannica/Aga_Khan_I. for example, how would you know that '.' wasn't an "end of sentence" full stop and in fact is part of the URI?). You can have a look at the problem with urls for an introduction to the problem and quite an informative discussion in the comments. At the end of the day you can provide a best effort such as matching protocols, looking for valid top-level domains (which includes a lot more than you might think at first), but there will always be things slipping through the net.
To attempt to provide you with some pseudo-code I'd say something along these lines is what I'd start off with:
process() {
    List<String> looksLikeUri = getMatches(1orMoreValidUriCharacters + "\\." + 1orMoreValidUriCharacters);
    removeUrisWithInvalidTopLevelDomains(looksLikeUri);
    trimCharactersUnlikelyToBeInUris(looksLikeUri);
    guessProtocolIfNotPresent(looksLikeUri);
}

removeUrisWithInvalidTopLevelDomains() // Use a list of valid ones or limit it to something like 1-6 characters.

trimCharactersUnlikelyToBeInUris() // ,.:;? (at the very end) '(' at start ')' at end unless a starting one was in URI.

guessProtocolIfNotPresent() // Usually http unless string starts with something obvious like "ftp" or already has a protocol.

A: It would be probably fully solvable if the contained URL always contained protocol (such as HTTP).
Because this is not the case, any "word", which contains . character can potentially be URL (for example mysite.com) and moreover you cannot be sure with teh actual protocol (you may assume).
If you assume that user will be always online, you may make a method that will take all potential URLs, checks if URL exists and if it does, then produce HTML link.
I have wroted this code snippet:
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.*;

public class JavaURLHighlighter
{
    Pattern potentialURLAtTheBeginning = Pattern.compile("^[^\\s]+\\.[^\\s]+\\s");
    Pattern potentialURLintheMiddle = Pattern.compile("\\s[^\\s]+\\.[^\\s]+\\s");
    Pattern potentialURLAtTheEnd = Pattern.compile("\\s[^\\s]+\\.[^\\s]+$");
    private String urlString;
    ArrayList<String> matchesList=new ArrayList<String>();

    public String getUrlString() {
        return urlString;
    }

    public void setUrlString(String urlString) {
        this.urlString = urlString;
    }

    public void getConvertedMatches()
     {
        String match;
        String originalMatch;
        Matcher matcher;
        matcher = potentialURLAtTheBeginning.matcher(urlString);
        matchesList.clear();
        while (matcher.find())
        {
          match = matcher.group().trim();
          if (!match.startsWith("http://") && !match.startsWith("https://")) match = "http://"+match;
          if (match.endsWith(".")) match=match.substring(0, match.length()-1);
          if (urlExists(match)) matchesList.add(match);
        }
        matcher = potentialURLintheMiddle.matcher(urlString);
        while (matcher.find())
        {
          match = matcher.group().trim();
          if (!match.startsWith("http://") && !match.startsWith("https://")) match = "http://"+match;
          if (match.endsWith(".")) match=match.substring(0, match.length()-1);
          if (urlExists(match))matchesList.add(match);
        }
        matcher = potentialURLAtTheEnd.matcher(urlString);
        while (matcher.find())
        {
          match = matcher.group().trim();
          if (!match.startsWith("http://") && !match.startsWith("https://")) match = "http://"+match;
          if (match.endsWith(".")) match=match.substring(0, match.length()-1);
          if (urlExists(match)) matchesList.add(match);
        }

        for (int i=0; i< matchesList.size();i++) System.out.println(matchesList.get(i));
    }

    public static boolean urlExists(String urlAddress)
    {
        try
        {
          HttpURLConnection.setFollowRedirects(false);
          HttpURLConnection connection = (HttpURLConnection) new URL(urlAddress).openConnection();
          connection.setRequestMethod("HEAD");
          return (connection.getResponseCode() == HttpURLConnection.HTTP_OK);
        }
        catch (Exception e)  {return false;  }
    }

public static void main(String[] args)
{
    JavaURLHighlighter hg = new JavaURLHighlighter();

    hg.setUrlString("This is some text, visit www.mysite.com. Thanks & bye.");
    hg.getConvertedMatches();

    hg.setUrlString("This is some text, visit www.nonexistingmysite.com. Thanks & bye.");
    hg.getConvertedMatches();

}

}

It's not actual solution to your problem and I wrote it quicky, so it might not be completly correct, but it should guide you a bit. Here I just print the matches. Have a look here Java equivalent to PHP's preg_replace_callback for regexp replacing function with which you could embrace all modified matches with a hrefs. With provided information you should be able to write what you want - but possibly with not 100% reliable detection.


text:
Q: Inverse of an orthogonal matrix is its transpose I understand that if A is orthogonal, then $A^{-1} = A^T$. However, i cannot seem to understand the proof.
Can someone put in some numbers in the proof. This site tries to explain it but i cannot seem to get $A^TA$ becoming an identity matrix.
https://dyinglovegrape.wordpress.com/2010/11/30/the-inverse-of-an-orthogonal-matrix-is-its-transpose/
Thanks.

A: Suppose $A$ an orthogonal matrix. Then we can write $A$ as $A = (a^1,a^2,...,a^n)$. With $a^i$ the column vectors of $A$.
Then we know that $a^1,a^2,...,a^n$ are pairwise orthogonal. E.g. $(a^i,a^j) = 0$ with $i≠j$ and $(a^i,a^j)= 1$ with $i=j$.
Now if you do the matrix multiplication $A^TA$ or $AA^T$ only the positions $a^{i,i}$ become ones, all others zeros.

A: Let $A$ be an orthogonal matrix. Let us denote $A$ using columns:
$$A = \begin{pmatrix}
e_1 & e_2 & \ldots & e_n
\end{pmatrix}$$
where the columns $e_1, e_2, \ldots, e_n$ are orhtonormal. This means that $e_i \cdot e_j = \delta_{ij}$, where $\cdot$ denotes the inproduct and
$$\delta_{ij} = \begin{cases}
1 &\text{if } i = j\\
0 &\text{otherwise}
\end{cases}$$
Note that $A^{t}$, the transposed matrix is equal to
$$\begin{pmatrix}
e_1^{t} \\
e_2^{t}\\
\ldots \\
e_n^{t}
\end{pmatrix}$$
so $e_i^t$ is a rowvector. If we now compute the following product
$$A^tA =   \begin{pmatrix}
e_1^{t} \\
e_2^{t}\\
\ldots \\
e_n^{t}
\end{pmatrix}$$
we find
$$\begin{pmatrix}
e_1^t e_1 & e_1^te_2 & \ldots &e_1^te_n\\
e_2^te_1  & e_2^te_2 & \ldots &e_2^te_n\\
\vdots & \vdots & \ldots & \vdots\\
e_n^te_1 & e_n^te_2 & \ldots &e_n^te_n
\end{pmatrix}
=
\begin{pmatrix}
e_1 \cdot e_1 & e_1 \cdot e_2 & \ldots &e_1 \cdot e_n\\
e_2\cdot e_1  & e_2\cdot  e_2 & \ldots &e_2\cdot  e_n\\
\vdots & \vdots & \ldots & \vdots\\
e_n\cdot  e_1 & e_n\cdot  e_2 & \ldots & e_n\cdot e_n
\end{pmatrix}$$
which is the identity matrix. Therefore we have that (by uniqueness of the inverse matrix) that $A^t = A^{-1}$.


text:
Q: How to check whether a MySql connection is alive in C API? From the documentation, I know how to check MySql connection state in C++

These methods can be used to check the connection state or reconnect:

*

*sql::Connection::isValid() checks whether the connection is alive.

*sql::Connection::reconnect() reconnects if the connection has gone down.

Is there a C API to do the same thing?

A: Yes, the link you shared is to Connector/C++, which is a C++ API. What you're looking for is Connector/C, or just the regular C API.
mysql_stat is a function which will return status of the server to tell you if the connection is gone.


text:
Q: Sometime networkonmainthreadexception in AsyncTask I am getting NetworkonMainThreadException sometime.I dont know what is the problem. First time it opens with no error, But after few times closing and opening cause the NetworkOnMainThreadException.

Below is my MainActivity

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new DownloadWebpageTask().execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class DownloadWebpageTask extends AsyncTask<String, Void, String> {

    List<Member> members = new ArrayList<Member>();
    ListView listView = (ListView) findViewById(R.id.listView1);
    String ss = "";
    InputStream is;
    HttpURLConnection connection ;

    @Override
    protected String doInBackground(String... urls) {

        try {

            URL url = new URL("http://192.168.1.107:8080/SEWS_webservice/rest/members");
            connection = (HttpURLConnection) url.openConnection();
            is = connection.getInputStream();
        } catch (IOException e) {
            System.out.println(e+"***********************&&&&&&&&&&&&&");
        }finally {
            connection.disconnect();
        }

        return ss;
    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {

        XmlPullParserHandler parser = new XmlPullParserHandler();
        parser.parse(is);
        members = parser.getMembers();
        ArrayAdapter<Member> adapter = new ArrayAdapter<Member>(getApplicationContext(),android.R.layout.simple_list_item_1, members);
        listView.setAdapter(adapter);

    }
}

}

This is XMLPullParser handler

public class XmlPullParserHandler {
    private List<Member> members= new ArrayList<Member>();
    private Member member;
    private String text;

    public List<Member> getMembers() {
        return members;
    }

    public List<Member> parse(InputStream is) {

           try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser  parser = factory.newPullParser();

            parser.setInput(is, null);

            int eventType = parser.getEventType();

            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagname = parser.getName();
                switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (tagname.equalsIgnoreCase("member")) {
                        // create a new instance of employee
                        member = new Member();
                    }
                    break;

                case XmlPullParser.TEXT:
                    text = parser.getText();
                    break;

                case XmlPullParser.END_TAG:
                    if (tagname.equalsIgnoreCase("member")) {
                        // add employee object to list
                        members.add(member);
                    }else if (tagname.equalsIgnoreCase("memberId")) {
                        member.setMemberId(Integer.parseInt(text));
                    }
                    else if (tagname.equalsIgnoreCase("firstName")) {
                        member.setFirstName(text);
                    }
                    else if (tagname.equalsIgnoreCase("middleName")) {
                        member.setMiddleName(text);
                    }
                    else if (tagname.equalsIgnoreCase("lastName")) {
                        member.setLastName(text);
                    }

                    break;
                default:
                    break;
                }
                eventType = parser.next();
            }

        } catch (XmlPullParserException e) {e.printStackTrace();}
        catch (IOException e) {e.printStackTrace();}
        return members;
    }
}

A: The problem is even though you are connecting up to the website properly in the background you are reading from the underlying socket using the InputStream. You need to refactor your solution so that you are returning a String or raw data from your InputStream as the result of doInBackground and closing out any http connections. Something like
@Override
    protected String doInBackground(String... urls) {
    try {

        URL url = new URL("http://192.168.1.107:8080/SEWS_webservice/rest/members");
        connection = (HttpURLConnection) url.openConnection();
        is = connection.getInputStream();

        ByteArrayOutputStream oStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int numRead = -1;
        while ((numRead = (is.read(buffer))) > -1) {
           oStream.write(buffer, 0, numRead);
        }
        return new String(oStream.getBytes(), "UTF-8");
    } catch (IOException e) {
        System.out.println(e+"***********************&&&&&&&&&&&&&");
    }finally {
        connection.disconnect();
    }

    return ss;
}

// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {

    XmlPullParserHandler parser = new XmlPullParserHandler();
    parser.parse(result);
    members = parser.getMembers();
    ArrayAdapter<Member> adapter = new ArrayAdapter<Member>(getApplicationContext(),android.R.layout.simple_list_item_1, members);
    listView.setAdapter(adapter);

}

Should do it if the XmlPullParserHandler can read Strings, otherwise that too will need to get moved to the background portion.

A: Seems like XmlPullParser doesn't like to work on UI thread :)
I could not find exact proves of this, but even official example makes it work in AsyncTask.
In your case just try to move next lines:
XmlPullParserHandler parser = new XmlPullParserHandler();
parser.parse(is);
members = parser.getMembers();

into doInBackground() method and check the result.

PS. Not relating to question, but what is purpose of this String ss = "";?
You can change AsyncTask<String, Void, String> to AsyncTask<String, Void, Void> if you don't want to return anything.
Or, better way, - you can do this AsyncTask<String, Void, List<Member>>.
Then you make protected void onPostExecute(List<Member> result) and use this result in your Adapter code.


text:
Q: bash script Keyboard Interrupt hand over to Python Script I have a bash script that starts my python script. Point of this is, that I hand over a lot of (sometimes changing) arguments to the python script. So I found it useful to start my python script with a bash script where I "save" my argument list.
#!/bin/bash
cd $(dirname $0)
python3 script.py [arg0] [arg1]

In my Python script I have the KeyboardInterrupt-Exception implemented which would save some open files and then exit the python script.
Now my question: When I run the shell script I have to at least press 3-times Strg+C, get some python errors and it will stop.
Am i guessing right, that my Strg+C is not recognized by python, but by the shell script instead?
Is there a way to hand over the Keyboard Interrupt from the shell script to the python script running in it?
btw: the python script is running an infinite loop (if this is important)
Python script looks like this for the exception. As pointed out, it runs an infinite loop.
    while True:
        try:
            #doing stuff here

        except KeyboardInterrupt:
            for file in files:
                file.close()
            break

A: try "trap" command to assign custom action on signals. For Ctrl-C you need to ignore  SIGINT, also you can ignore SIGTERM:
function ignore_ctrlc() {
        echo "ignored"
}

trap ignore_ctrlc SIGINT SIGTERM
declare -i counter=0
while true; do
  echo "sleep for 1 sec"
  sleep 1
  counter+=1
  [[ $counter -gt 10 ]] && exit 0
done

In the script above, Ctrl-C will interrupt executing command (most probability it will be sleep 1), but will not interrupt the script itself. In your case, your python script should ignore Ctrl-C, so I think it will be ignored at all.

A: If that's your entire script, why not tail-call python?  Bash will get completely out of the way.
#!/bin/bash
cd $(dirname $0)
exec python3 script.py [arg0] [arg1]