text:
Q: Escape tags without converting characters I am using jinja2 to safely render templates for email messages from a web contact form. The problem is the characters   &, <, >, ', and " are converted to HTML-safe sequences. So

That's all folks!

becomes
That's all folks!

I want to remove any HTML tags to prevent XSS without any without any character encoding. Is that possible in jinja2?
Note: the striptags utility also converts characters.

A: I don't think that's possible. How would you deal with a message such as That's only true when x<y and x>0. The parts between < and > are part of the message, but could be interpreted as an (borked) HTML tag.
It's up to the browser to read That's all folks! and display it correctly by decoding the characters.


text:
Q: Sorting a formatted LINQ query A sequence of non-empty strings stringList is given, containing only uppercase letters of the Latin alphabet. For all strings starting with the same letter, determine their total length and obtain a sequence of strings of the form "S-C", where S is the total length of all strings from stringList that begin with the character C. Order the resulting sequence in descending order of the numerical values of the sums, and for equal values of the sums, in ascending order of the C character codes.
This question is related to one of my previous questions.
One solution that works is this one:
stringList.GroupBy(x => x[0]).Select(g => $"{g.Sum(x => x.Length)}-{g.Key}");

The problem is that with this given example I don't know where to add the OrderByDescending()/ThenBy() clauses in order to get the correctly sorted list.

A: Create an intermediate data structure to store needed info and use it for sorting and then building the output:
stringList
    .GroupBy(x => x[0])
    .Select(g => (Length: g.Sum(x => x.Length), Char: g.Key))
    .OrderByDescending(t => t.Length)
    .ThenBy(t => t.Char)
    .Select(t => $"{t.Length}-{t.Char}");

A: You're almost there. The cleanest way of doing it would be to make a more complex object with the properties you care about, use those to sort, then keep only what you want in the output. Like:
stringList
    .GroupBy(x => x[0])
    .Select(g => new {
        Len = g.Sum(x => x.Length),
        Char = g.Key,
        Val = $"{g.Sum(x => x.Length)}-{g.Key}"
    })
    .OrderByDescending(x => Len)
    .ThenBy(x => x.Char)
    .Select(x => x.Val);

A: You can add a Select after the GroupBy to transform the groups into an anonymous object containing the things you want to sort by. Then you can use OrderByDescending and ThenBy to sort. After that, Select the formatted string you want:
stringList.GroupBy(x => x[0]) // assuming all strings are non-empty
    .Select(g => new {
        LengthSum = g.Sum(x => x.Length),
        FirstChar = g.Key
    })
    .OrderByDescending(x => x.LengthSum)
    .ThenBy(x => x.FirstChar)
    .Select(x => $"{x.LengthSum}-{x.FirstChar}");

Alternatively, do it in the query syntax with let clauses, which I find more readable:
var query = from str in stringList
    group str by str[0] into g
    let lengthSum = g.Sum(x => x.Length)
    let firstChar = g.Key
    orderby lengthSum descending, firstChar
    select $"{lengthSum}-{firstChar}";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Уведомления Android. Непонятное поведение activity У меня есть простой чат.
Диалог посетителей и администратора. Т.е. максимум только между 2-мя участниками. Для получения сообщений в режиме онлайн и определения кому должно придти сообщение я использую отправку в FireBase RealTime Database.
Например. Администратор имеет 2 разных диалога. С юзером_1 и юзером_2
Для имитации я запускаю в студии 2 виртуальных устройства. Первое админ, второе юзер_2. И пишу с админа ему.
Чтобы определить что письмо должно отправиться юзеру_2, а не юзеру_1 в приложении я реализую слушатель.
myRef.addValueEventListener(new ValueEventListener() {
...
здесь я перебираю в RealTime все новые сообщения и показываю только то, где адресат я (юзер_2)

...
}

Всё работает отлично. Теперь мне нужно реализовать уведомления о новых сообщениях.
Задача в том, что уведомления должны быть только если пользователь свернул работающее приложение. И вот тут для меня начинается большая странность.
Когда приложение сворачивается, вызывается метод onPause и onStop
Тогда по умолчанию я сделал переменную String proverka = "no";
Когда приложение свёрнуто в методе onStop я назначаю proverka = "yes";
И в слушатель дополнительно задаю условие для уведомления
if (proverka.equals("yes"))
{

Intent intent = new Intent(getApplicationContext(), ListMessages.class);

intent.putExtra("id_d", dialog_id);  // Задаю ИД диалога, что бы знать куда возвращаться
intent.putExtra("user_to", user_db); // Здесь помещаю отправителя, для показа в уведомлении от кого

PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(),
CHANNEL_ID)
                            .setSmallIcon(...)
                            .setContentTitle("Сообщение от " user_db)
                            .setContentText(...)
                            .setContentIntent(pendingIntent)
                            .setAutoCancel(true)
                            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(getApplicationContext());
notificationManager.notify(47457, builder.build());

}

Т.е. если приложение сворачивается, при вызове онСтоп я задаю переменной "yes", а в слушателе FireBase я проверяю эту переменную, если она стала "yes", то показываю уведомления у нужного пользователя. А при нажатии на уведомление вызывается метод onResume, где я задаю переменной опять "no". Разворачивается приложение и уведомления не должны приходить.
Всё работает прекрасно если я сворачиваю приложение и разворачиваю опять. НО! Если я разворачиваю приложение по переходу через уведомление, не смотря на то что при onResume опять назначается "no", каким то образом при запуске слушателя FireBase переменная опять становится "yes" и уведомления показываются даже при развёрнутом приложении. Всю голову сломал почему так происходит

A: Как мне здесь подсказали, это и оказался верный ответ. Необходимо вместо переменных использовать сохранения данных в SharedPreferences. Там же менять и их же проверять


text:
Q: Is there anything wrong with a python infinite loop and time.sleep()? I had a program that ran recursively, and while 95% of the time it wasn't an issue sometimes I would hit a recursion limit if I was doing something that took too long. In my efforts to convert to and iterative code, I decided to try something along the lines of this:
while True:
    do something

    #check if task is done
    if done:
        print 'ALL DONE'
        break
    else:
        time.sleep(600)
        continue

I've tested my code and it works fine, but I was wondering if there is anything inherently wrong with this method? Will it eat up RAM or crash the box if it was left to run for too long?
Thanks in advance!
EDIT:
The "do something" I refer to is checking a log file for certain keywords periodically, as data is constantly being written to the log file. Once these lines are written, which happens at varying length of times, I have the script perform certain tasks, such as copying specific lines to a separate files.
My original program had two functions, one called itself periodically until it found keywords, which would then call the 'dosomething' function. The do something function upon completion would then call original function, and this would happen until the task was finished or I hit the recursion limit

A: There is nothing inherently wrong in this pattern.  I have used the daemon function in init.d to start a very similar python script.  As long as "do something" doesn't leak, it should be able to run forever.

A: I think that either way
 time.sleep()

will not stop the recursion limit
Because sleep only pauses the execution , and doesn't free any kind of memory
check https://docs.python.org/2/library/time.html the Time.sleep() description
It suspends the operation , but it will not do any memory optimization

A: The pattern you describe is easy to implement, but usually not the best way to do things.  If the task completes just after you check, you still have to wait 5 minutes to resume processing.  However, sometimes there is little choice but to do this; for example, if the only way to detect the task is complete is to check for the existence of a file, you may have to do it this way.  In such cases the time interval choice needs to balance the CPU consumed by the "spin" with wait time.
Another pattern that is also fairly easy is to simply block while waiting on the task to complete.  Whether this is easy or not depends on the particular API you are using.  But this technique does not scale because all processing must wait for a single activity to complete.  Imagine not being able to open a new browser tab while a page is loading.
Best practice today generally uses one of several models for asynchronous processing.  Much like writing event handlers for mouse clicks, etc. in a website or GUI, you write a callback function that handles the result of processing, and pass that callback to the task.  No CPU is wasted and the response is handled immediately without waiting.  Many frameworks support this model today.  Tulip uses the actor model.
Specifically regarding the recursion limit, I don't think your sleep loop is responsible for hitting the stack frame limit.  Maybe it was something happening within the task itself.


text:
Q: JavaScript - Hide all divs by class and show one by ID I need a JavaScript function that will allow me to change "display" property for one element to block but keep the others set to none (they are on top one another). Click image1 = display content1, but when you click image2, set content1 back to invisible and display content2 only.

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

A: JS
function disp(a){
    document.getElementById('content0').style.display='none';
    document.getElementById('content1').style.display='none';
    document.getElementById('content2').style.display='none';
    document.getElementById('content3').style.display='none';
    document.getElementById('content'+a).style.display='block';
}

HTML

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

A: this is a little improvement of First dev's answer
html

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

js
var  content= document.getElementsByClassName('co');

for (var i = 0; i < content.length; i ++) {
    content[i].style.display = 'none';
}
function disp(a){
    document.getElementById('content'+a).style.display='block';
    for (var i = 0; i < content.length; i ++) {
        if(i!=a)
        content[i].style.display = 'none';
    }
}

A: Solution using forEach():
EDIT - Just realised that in the original post, the code does not include classes, which the title of the question refers to. So this example mistakenly works only with IDs.

// Array of unique suffixes used for images and content
var availableIds = '0 1 2 3'.split( ' ' );

function showContent( imageId ) {

  var selectedId = imageId.replace( 'image', '' );

  availableIds.forEach(function _showContent_forEach( availableId ) {

    var displayBlock = selectedId === availableId;
    var contentId = 'content' + availableId;

    document.getElementById( contentId )
      .style.display = displayBlock ? 'block' : 'none';
  });
}

showContent( '0' ); // Default
img {
  width: 50px;
  height: 50px;
  border: 1px solid black;
}

Lorem Ipsum 1

Lorem Ipsum 2

Lorem Ipsum 3

Lorem Ipsum 4


text:
Q: gradient background iOS
This rectangular region has a gradient background which is also transparent. Texts can be written on the rectangle. The colour of the rectangle changes when the user touches it. When the user releases it, it takes you to a new screen. How should something like this be implemented in iOS?

A: Use

*

*UIImageView with gradient backgroundImage

*set its alpha to 0.6 -.75 so that background view is visible

*Use Tap gesture recognizer on ImageView to change background Image when user tap and navigate to next view


text:
Q: Bigtable CellsColumnLimitFilter and ValueRangeFilter not working as intended I'm new to Bigtable and I've been testing out the filtering features based on this documentation.
https://cloud.google.com/bigtable/docs/using-filters
I've tried this in this repo under testcsvbigtablefilters.py which I have some problems. For the record, I am testing this on Bigtable Emulator on my local machine
https://github.com/limjix/GoogleCloudBigDataTest
I have some issues with 2 filters:

*

*CellsColumnLimitFilter (Line 100-110, uncomment to try)
This filter doesn't seem to be working. I have a table of 3 columns but when I put CellsColumnLimitFilter(1) or CellsColumnLimitFilter(2), I still get all 3 columns?

     rows = table.read_rows(filter_=row_filters.CellsColumnLimitFilter(10))
     for row in rows:
         print_row(row)

*ValueRangeFilter (Line 172-183)
This filter doesn't work because, for example I have the 1st column with values around 10000 to 14000.
When I put the start value at 10,000 to 14,000, nothing comes up.
When I put 0 to 3, the 10k to 14k value start showing up. This makes no sense and the filter does not seem to work at all

    rows = table.read_rows(
        filter_=row_filters.ValueRangeFilter(start_value=b'0',end_value=b'3'))

    for row in rows:
        print_row(row)

Also, I want to ask, how do I query for cells that have been overwritten? I know bigtable saves the mutation of cells over a period of time. How do I query and filter for a specific time for that cell?
Any help would be appreciated guys, there isn't much tutorials or documentation anywhere else so I hope the community can help.
Thank you!

A: Hey limjix thanks for the questions! The Bigtable filtering documentation has just been introduced, so questions like this can help us improve it moving forward.

*

*CellsColumnLimitFilter
The CellsColumnLimitFilter limits the number of cells in each column that are included in the output row. In the documentation it is listed as cells per column filter, so I can see how this function name would be a bit confusing.
If you only have a row with a few columns that only have one cell or one version for those values, then CellsColumnLimitFilter would return all of them. If you're looking to only receive one of the column's data you can use the CellsRowLimitFilter which filters on cells per row. Or you could specify specific columns with any of the column qualifier filters.

*ValueRangeFilter
I did some digging and I believe I know what your issue here is, but I'm not 100%. And am happy to troubleshoot further with you if you need.
It looks like you set the cell values directly from the CSV:
bigtablerow.set_cell(column_family_id,
             "column1",
             #str(float(csvrow[20])+i),
             csvrow[20],
             timestamp=datetime.datetime.utcnow())

This works fine for string, but if you set a cell value to a number, the python client will treat that as an incrementable value and encode it as a 64-bit big-endian signed integer and will not be comparable with the b'10000' that you have.
For example this code wont return any rows:
client = bigtable.Client(project=project_id, admin=True)
instance = client.instance(instance_id)
table = instance.table(table_id)

rows = []
for i in range(10):
    row_key = 'test_num{}'.format(i).encode()
    row = table.direct_row(row_key)
    row.set_cell("cf".encode(),
                 "col".encode(),
                 random.randint(10000, 14000)
                 )
    rows.append(row)
table.mutate_rows(rows)

rows = table.read_rows(
    filter_=row_filters.ValueRangeFilter(start_value=b'10000',
                                         end_value=b'14000'))
for row in rows:
    print(row)

But when I turn the integer into a string I get all the rows
    row.set_cell("cf".encode(),
                 "col".encode(),
                 str(random.randint(10000, 14000))
                 )
    rows.append(row)

I would recommend using the CBT tool to check out what the data looks like. For example, when I do cbt read the first rows look like this:
test_num0
  cf:col                                   @ 2020/09/20-22:24:43.835000
    "\x00\x00\x00\x00\x00\x003\xd1"
----------------------------------------
test_num1
  cf:col                                   @ 2020/09/20-22:24:43.835000
    "\x00\x00\x00\x00\x00\x001t"

whereas the string ones look like this (they have two values since I used the same rowkeys actually, but you should get the point):
test_num0
  cf:col                                   @ 2020/09/20-22:36:12.075000
    "11510"
  cf:col                                   @ 2020/09/20-22:24:43.835000
    "\x00\x00\x00\x00\x00\x003\xd1"
----------------------------------------
test_num1
  cf:col                                   @ 2020/09/20-22:36:12.075000
    "12048"
  cf:col                                   @ 2020/09/20-22:24:43.835000
    "\x00\x00\x00\x00\x00\x001t"

*Querying for cells that have been overwritten

This is similar to what you were trying to do in the first example. For cells that have been overwritten you're looking for filters around cell timestamps (TimestampRangeFilter) or number of cells per column (CellsColumnLimitFilter again).


text:
Q: jQuery get li from nested delete image I am very close to solving this problem but I can't seem to grab the outer html from my
.
I am adding my
's to a
 like this
    function addTab() {
        tabs.append('
'
                         + ''
                         + title
                         + ''
                         + ''
                         + ''
                         + ''
                         + '
');
    };

Then I'm trying to delete them with this
$("body").on("click", ".deleteImage", function (e) {
    var removeItem = $(this).closest('li').html(); // problem
    console.log(removeItem);
    listItems = jQuery.grep(listItems, function (value) {
        console.log(value);
        return value != removeItem;
    });
});

But the problem is, my remove item variable has this value
Test

and I need it to have the outer html value as well, like this

Test

the class value I initially assign to the
 called "navHighlight" will of been removed by this time because it's only there for aesthetic purposes. It is toggled when another
 item is clicked, so that point of reference is out the window. I've tried a lot of different things, but I can't seem to grab the outer html
 tag.
Any help is appreciated.

A: You can use outerHTML to get the outside wrapper li as well:
var removeItem = $(this).closest('li')[0].outerHTML;


text:
Q: see values of chart points when the mouse is on points I have a chart and I want the user to see the values when the pointer is on the points.
By using digEmAll's help in the page finding the value of the points in a chart ,I could write the following code:
Point? prevPosition = null;
ToolTip tooltip = new ToolTip();

void chart1_MouseMove(object sender, MouseEventArgs e)
{
    var pos = e.Location;
    if (prevPosition.HasValue && pos == prevPosition.Value)
        return;
    tooltip.RemoveAll();
    prevPosition = pos;
    var results = chart1.HitTest(pos.X, pos.Y, false, ChartElementType.PlottingArea);
    foreach (var result in results)
    {
        if (result.ChartElementType == ChartElementType.PlottingArea)
        {
            chart1.Series[0].ToolTip = "X=#VALX, Y=#VALY";
        }
    }
}

by the above code,the user can see the values when the pointer is near to a series.But now How can I let the user to see the values only when the pointer is on the points?
I replaced
int k = result.PointIndex;
if (k >= 0)
{
    chart1.Series[0].Points[k].ToolTip = "X=#VALX, Y=#VALY";
}

instead of
chart1.Series[0].ToolTip = "X=#VALX, Y=#VALY";

to solve my problem.But It wasn't usefull.

A: I would take this solution:
Add custom tooltip event handler:
 this.chart1.GetToolTipText += this.chart1_GetToolTipText;

Implement event handler:
  private void chart1_GetToolTipText(object sender, ToolTipEventArgs e)
  {
     // Check selected chart element and set tooltip text for it
     switch (e.HitTestResult.ChartElementType)
     {
        case ChartElementType.DataPoint:
           var dataPoint = e.HitTestResult.Series.Points[e.HitTestResult.PointIndex];
           e.Text = string.Format("X:\t{0}\nY:\t{1}", dataPoint.XValue, dataPoint.YValues[0]);
           break;
     }
  }

A: Consider the following as a possible better option than tooltips...use the label feature of the chart control.
DataPoint _prevPoint;
void chart1_MouseMove(object sender, MouseEventArgs e)
{
    // this if statement clears the values from the previously activated point.
    if (_prevPoint) {
        _prevPoint.MarkerStyle = MarkerStyle.None;
        _prevPoint.IsValueShownAsLabel = false;
    }

    var result = chart1.HitTest(e.X, e.Y, ChartElementType.DataPoint);
    if (result.ChartElementType == ChartElementType.DataPoint)
    {
        var prop = result.Object as DataPoint;
        if (prop != null)
        {
            prop.IsValueShownAsLabel = true;
            prop.MarkerStyle = MarkerStyle.Star4;
        }
    }
}

I've tested this and i'm using it currently.  It's very nice on charts with a lot of points since it shows the marker on the chart as well.

A: You should modify the code in this way:
Point? prevPosition = null;
ToolTip tooltip = new ToolTip();

void chart1_MouseMove(object sender, MouseEventArgs e)
{
    var pos = e.Location;
    if (prevPosition.HasValue && pos == prevPosition.Value)
        return;
    tooltip.RemoveAll();
    prevPosition = pos;
    var results = chart1.HitTest(pos.X, pos.Y, false,
                                    ChartElementType.DataPoint);
    foreach (var result in results)
    {
        if (result.ChartElementType == ChartElementType.DataPoint)
        {
            var prop = result.Object as DataPoint;
            if (prop != null)
            {
                var pointXPixel = result.ChartArea.AxisX.ValueToPixelPosition(prop.XValue);
                var pointYPixel = result.ChartArea.AxisY.ValueToPixelPosition(prop.YValues[0]);

                // check if the cursor is really close to the point (2 pixels around the point)
                if (Math.Abs(pos.X - pointXPixel) < 2 &&
                    Math.Abs(pos.Y - pointYPixel) < 2)
                {
                    tooltip.Show("X=" + prop.XValue + ", Y=" + prop.YValues[0], this.chart1,
                                    pos.X, pos.Y - 15);
                }
            }
        }
    }
}

The idea is to check if the mouse is very close to the point e.g. 2 pixels around it  (because is really unlikely to be exactly on the point) and show the tooltip in that case.
Here's a complete working example.


text:
Q: Naming a POJO variable "public" I am working with MongoDB and have a hard requirement to use the MongoDB Java Driver (v.3.0.2) I also can not change the structure of the database in any way.
One of the documents in the db holds a field with a name of "public" which is a POJO.
Retrieval of the documents for display is trivial because I'm just casting the BSON document collection to JSON directly. However, on a PUT/POST, changing this attribute to something other than the name "public" will cause the schema to change, which is not allowed.
I am planning at this point to rename the field in the POJO but that means having to manually hydrate the object in the POST/PUT and also manually build the BSON document to get the naming right.
Just wanted to see if someone has run into a similar issue and if there are any suggestions to easily get around this, without using an extraneous mapping framework?
Thanks.

A: I utilized a combination of JAX XMLElement tags and the GSON SerializedName tags like such:
@XmlRootElement
public class _Document {
    @XmlElement(name="public")
    @SerializedName("public")
    private String _public;
    ...

Any other suggestions?


text:
Q: Bitnami Redmine showing error after upgrade from 2.4.2-0 to 2.6.0-0 We have upgraded the Bitnami Redmine from 2.4.2-0 to 2.6.0-0 on a Windows server.
When we try to access (localhost/redmine) but after upgrading Redmine, it shows the following error:

Internal error
An error occurred on the page you were trying to access.
  If you continue to experience problems please contact your Redmine administrator for assistance.
  If you are the Redmine administrator, check your log files for details about the error.

Below is the error found in log file,
GET "/redmine/" for 127.0.0.1 at 2014-11-18 14:19:53 +0530
Processing by WelcomeController#index as HTML Current user: anonymous Completed 500 Internal Server Error in 65.0ms
NoMethodError (undefined method passwd_changed_on' for #<AnonymousUser:0x67c50d8>): app/controllers/application_controller.rb:149:in force_logout_if_password_changed'

A: You should run this command:

% ruby bin/rake db:migrate RAILS_ENV=production

In the root directory of your redmine install.


text:
Q: Problem with introducing arctanh in solving an integral stackexchange! I'm having some trouble finding out how to progress with solving my integral
$\int\frac{1}{aw^2+bw} dw$. I have read that and wants to show that
$\int\frac{1}{aw^2+bw} dw = -\frac{2}{b} arctanh(\frac{2aw}{b}+1)$
I have tried my hand at this problem and has come this far:
$\int\frac{1}{aw^2+bw} dw$=$\int \frac{1}{w(aw+b)} dw$
using partial fractions i obtain
=$\int \frac{A}{w}+\frac{B}{aw+b} dw $
Therefore  $\frac{1}{(w(aw+b)}= \frac{A}{w}+\frac{B}{aw+b} $.
Multiplying by $w(aw+b)$ which gives $1=A(aw+b)+Bw=Aaw+Ab+Bw=w(Aa+B)+Ab.$
By comparing coefficients, we see that $Aa+B=0$ and $Ab=1$.
Therefore $A=1/b$ so that $Aa+B=\frac{a}{b}+B=0→B=-\frac{a}{b}$.
Therefore the integral becomes $\int \frac{A}{x}+\frac{B}{ax+b} dx=\int \frac{1}{bw}-\frac{a}{b(aw+b)} dw= \frac{1}{b} \int \frac{1}{w} dw-\int \frac{a}{b(aw+b)} dw=  \frac{lnǀwǀ}{b}-\frac{1}{b} \int \frac{a}{aw+b}  dw$.
By substituting $u=aw+b$ it is seen that $ \frac{du}{dw}=a→dw=\frac{1}{a} du $ so that $ \frac{lnǀwǀ}{b}-\frac{1}{b} \int \frac{a}{au} du = \frac{lnǀwǀ}{b}-\frac{1}{b} \int \frac{1}{u}  du = \frac{lnǀwǀ}{b}-\frac{lnǀuǀ}{b}+k = \frac{lnǀwǀ}{b}-\frac{lnǀaw+bǀ}{b}+k $ $ = \frac{1}{b} (lnǀwǀ-lnǀaw+bǀ)+k=-\frac{1}{b}(lnǀaw+bǀ-lnǀwǀ).$
If $w≠0$ you get $-\frac{ln|\frac{aw+b}{w}|}{b}+k.$
Now i know that $arctanh(x)= \frac{1}{2} ln(\frac{1+x}{1-x})$ for $ǀxǀ<1$, but i can't seem to use this to show that $-\frac{ln|\frac{aw+b}{w}|}{b}+k=-\frac{2}{b} arctanh(\frac{2aw}{b}+1)$
Do any of you know what to do from here or spot a mistake in my logic so far? Thank you for your time in advance.

A: Okay, i think i got it now :-)
So by completing the square you obtain $\int \frac{1}{ (w\sqrt{a}+\frac{b}{2\sqrt{a}})^2-\frac{b^2}{4a}}dw$ so by setting $u=w\sqrt{a}+\frac{b}{2\sqrt{a}} \to \frac{du}{dw}=\sqrt{a} \to dw=\frac{1}{\sqrt{a}}du$ This gives $\frac{1}{\sqrt{a}}\int\frac{1}{u^2-\frac{b^2}{4a}}du$ (what happends if $u^2-\frac{b^2}{4a}=0$ though?? )
Taking $-1$ out we get $\frac{-1}{\sqrt{a}}\int\frac{1}{\frac{b^2}{4a}-u^2}du$.
We can drag out another constant and obtain $\frac{-1}{\sqrt{a}(\frac{b^2}{4a})}\int\frac{1}{1-\frac{4a}{b^2}u^2}du$.
Put $z^2=\frac{4a}{b^2}u^2 \to z=\frac{2\sqrt{a}}{b}u \to \frac{dz}{du}=\frac{2\sqrt{a}}{b} \to du=\frac{b}{2\sqrt{a}}dz = -\frac{\frac{b}{2\sqrt{a}}}{\sqrt{a}\frac{b^2}{4a}}\int \frac{1}{1-z^2}dz=\frac{-2}{b}\int \frac{1}{1-z^2}dz.$
Therefore we can use partial fractions as $\int \frac{1}{(1+z)(1-z)}dz=\int \frac{A}{1+z}+\frac{B}{1-z}dz=\int \frac{A(1-z)+B(1+z)}{(1+z)(1-z)}dz$ By compareing coefficients we get that $B-A=0$ and $B+A=1 \to B=A=\frac{1}{2}$.
Therefore the integral becomes $\frac{1}{2} \int \frac{1}{1+z}dz+\frac{1}{2} \int \frac{1}{1-z}dz$. By substituting $q=1+z \to dq=dz$ and also $p=1-z \to -dp=dz.$ From the expression $\frac{1}{2} \int \frac{1}{q} dq+\frac{1}{2} \int \frac{1}{p} dp$ you can integrate directly and get $\frac{1}{2}(ln|1+z|-ln|1-z|)+k.$ If $1-z \neq0$ you get $\frac{1}{2} ln|\frac{1+z}{1-z}|+k=arctanh(z)+k.$
Subsituting back we obtain $\frac{-2}{b} \int \frac{1}{1-z^2}dz=\frac{-2}{b}arctanh(z)=\frac{-2}{b}arctanh(\frac{2\sqrt{a}}{b}u)=\frac{-2}{b}arctanh(\frac{2\sqrt{a}}{b}(w\sqrt{a}+\frac{b}{2\sqrt{a}}))=\frac{-2}{b}arctanh(\frac{2aw}{b}+1)$
as desired.


text:
Q: Pandas compare all DataFrame columns with eachother How can I compare all columns in a DataFrame with each other, removing columns that are 'less than' other columns according to an arbitrary comparison function (where the comparison function is transitive).
e.g. If I have the DataFrame
  0 1 2 3 4 5
0 4 1 1 3 6 2
1 4 2 2 7 2 6
2 4 3 3 3 6 2
3 4 8 3 7 2 6

and my function is "column A is < column B if A[i] < B[i] for all rows i", the result would be
  0 1 3 4
0 4 1 3 6
1 4 2 7 2
2 4 3 3 6
3 4 8 7 2

dropping column 2 as (4>1, 4>2, 4>3, 4>3) and column 5 as (3>2, 7>6, 3>2, 7>6).
My initial/obvious-but-slow approach is that this can be done in n^2 time with (pseudo code; I haven't done much Pandas programming before... answers with real code would be appreciated)
for i in range(0, n):
  for j in range(0, n):
    if my_less_than_function(col(i), col(j)):
      # i < j
      drop col(i)

If the less than function is transitive I could also remember which columns I've already dropped and skip them when iterating i and j. I could also iterate j in range(i + 1, n) if my comparison function returned (-1, 0, 1) for (less, equal, more) instead of (true, false) for (less, equal or more)
Note the comparison function may not be pairwise by row e.g. it could be sum(col A) < sum(col B) or number_of_primes_in(col A) < number_of_primes_in(col B)
Thank you

A: Setup
df = pd.DataFrame([
        [4, 1, 1, 3, 6, 2],
        [4, 2, 2, 7, 2, 6],
        [4, 3, 3, 3, 6, 2],
        [4, 8, 3, 7, 2, 6]
    ], columns=list('abcdef'))

print(df)

   a  b  c  d  e  f
0  4  1  1  3  6  2
1  4  2  2  7  2  6
2  4  3  3  3  6  2
3  4  8  3  7  2  6

numpy broadcasting
For your definition of less_than we can use numpy
v = df.values
lt = pd.DataFrame((v.T[:, None] < v.T).all(-1), df.columns, df.columns)

print(lt)

       a      b      c      d      e      f
a  False  False  False  False  False  False
b  False  False  False  False  False  False
c   True  False  False  False  False  False
d  False  False  False  False  False  False
e  False  False  False  False  False  False
f  False  False  False   True  False  False

You can pull out specific columns in the following way:
all columns that are >= 'f'
df.loc[:, lt.loc['f']]

   d
0  3
1  7
2  3
3  7

all columns that < 'f'
df.loc[:, ~lt.loc['f']]

   a  b  c  e  f
0  4  1  1  6  2
1  4  2  2  2  6
2  4  3  3  6  2
3  4  8  3  2  6

A: try this:
In [278]: df
Out[278]:
   0  1  2  3  4  5
0  4  1  1  3  6  2
1  4  2  2  7  2  6
2  4  3  3  3  6  2
3  4  8  3  7  2  6

In [279]: cols2drop = [col for col in df.columns if df.T.gt(df[col]).all(1).any()]

In [280]: cols2drop
Out[280]: [2, 5]

In [282]: df = df.drop(cols2drop, 1)

In [283]: df
Out[283]:
   0  1  3  4
0  4  1  3  6
1  4  2  7  2
2  4  3  3  6
3  4  8  7  2

Explanation:
In [286]: df.T.gt(df[2])
Out[286]:
       0      1      2      3
0   True   True   True   True
1  False  False  False   True
2  False  False  False  False
3   True   True  False   True
4   True  False   True  False
5   True   True  False   True

In [287]: df.T.gt(df[2]).all(1)
Out[287]:
0     True
1    False
2    False
3    False
4    False
5    False
dtype: bool

In [288]: df.T.gt(df[2]).all(1).any()
Out[288]: True


text:
Q: Ho do I add controls to an html5 video? (how to make commands video in background html) Here is my code to play a video in the background using the html5 video tag:
<video autoplay poster="polina.jpg" id="bgvid">
<source src="polina.webm" type="video/webm">
<source src="det/img/bgv.mp4" type="video/mp4">
</video>

But how do I add the controls? (play video play, pause, stop)

A: You can achieve this with javascript
Basic example from MSDN:

<video id="Video1" >
//  Replace these with your own video files.
     <source src="demo.mp4" type="video/mp4" />
     <source src="demo.ogv" type="video/ogg" />
     HTML5 Video is required for this example.
     Download the video file.
</video>

    <button id="restart" onclick="restart();">[]</button>
    <button id="rew" onclick="skip(-10)"><<</button>
    <button id="play" onclick="vidplay()">></button>
    <button id="fastFwd" onclick="skip(10)">>></button>

A: you could add the attribute "controls" to the  tag
<video autoplay poster="polina.jpg" id="bgvid" controls>...</video>
you could use javascript to hook into the video object.  Tie this to a button click or any other type of event that makes sense for your application.
var v = document.getElementsByTagName("video")[0];
v.play();
If applicable it might be useful to consider looking into using a javascript library designed to make using the video tag easier.
For more Research:
Mozilla::Using_HTML5_audio_and_video
Microsoft::Using JavaScript to control the HTML5 video player


text:
Q: connecting multiple signals to I am currently working on a control system GUI, and have run into a roadblock when it comes to storing and accessing data accross threads. Currently, I am reading the pressure from a gauge, and updating a LCD display in the UI, which works fine. This issue that I have run into is when I am trying to control my system. I need to access the pressure gauges data for my control loop in real time while updating the pressure display simultaneously, but if I try to two commands (Control feedback, and display) to the gauge at the same time, I get a serial read error. Therefore, I am wondering if there is a good way to have a function just read in the data from the gauge, store it, and send the data to the pressure display and the control function whenever necessary. Here is the simplified code that I have:
Class MainWindow():
#has a bunch of buttons and images that are used
#Define the threading object
self.obj=Reader.worker()
self.thread=QThread()
self.obj.moveToThread(self.thread)

def PresDisplay(self,i):
     self.presNumber.display("%s", i)

def on_presReadButton_clicked(self):
     self.obj.intReady.connect(self.presDisplay)
     self.thread.started.connect(self.obj.collector)
     self.thread.start()

This section of the code all works very well. However, from here I am somewhat lost as to what I should do. In my worker class, I have the following:
#
Class Worker(QObject):
  intReady=pyqtSignal(str)
  pres=pyqtSignal(str)

  def collector(self):
    while True:
        i=gauge.check()   #read the pressure from the gauge
        self.pres.connect(self.presSender)
        self.pres.emit(i)

  def presSender(self,i):
        self.intReady.emit(i)

  def control(self, setpoint, i):
     #This method must take in the pressure setpoint from the main GUi thread and use the pressure readings from collector at any given time to conduct the close loop control. It will be initiated from the click of a button (not the pressure read button above)

I understand that this is a very open ended question, but there are probably numerous ways to go about solving it.
If anyone has any ideas, I am open to giving them a try. I have been trying to solve this problem for the greater part of three weeks now.

A: You probably don't want to keep reconnecting a signal on every iteration of the loop.  It's going to create duplicate connections and the same callback is going to be called multiple times each time you emit the signal
while True:
    i=gauge.check()
    self.pres.connect(self.presSender) # This is bad
    self.pres.emit(i)

You generally only want to connect a signal once, and usually in the __init__ method.  In this case, you're emitting a signal (pres) just to emit another signal with the exact same arguments (intReady).  Just get rid of the pres signal and emit intReady directly from the collector method.
while True:
    i=gauge.check()   #read the pressure from the gauge
    self.intReady.emit(i)

Also, I'm not sure how long gauge.check() takes to respond, but you may want to insert a sleep on each iteration so you're not constantly spamming the main thread with millions of signals when you only need a resolution of like 1-10 hz.
while True:
    i=gauge.check()   #read the pressure from the gauge
    self.intReady.emit(i)
    QtCore.QThread.msleep(100)

The same thing goes for the main thread.  You probably don't want to connect the signal and re-start the thread every time the button is pushed.  Either move everything inside the on_click handler into the __init__ method, or do a check to only connect the signal and start the thread if it hasn't been done yet.


text:
Q: Why does sorting a list return None? My code is written in python 3 and it is meant to print out palindromes.
It should iterate through all the palindromic products of 2 3-digit numbers as shown below:
mylist=[]
for i in range(999,99,-1):
    for x in range(999, i-1, -1,):
        number=i*x
        number=str(number)
        if number==number[::-1]:
            #print(number)
            mylist.append(number)
mylist=mylist.sort(reverse=True)
print(mylist)

Note the commented out print. When this was still in place, all the palindromes that should have been printed out came out.
When I run my code, without the print statement, the console only prints out 'None'.
As far as I can see my logic is in order, so why is this happening?
EDIT:
Also, when I sort my list in reverse order, 99999 comes first. I gather this is because python looks at the consecutive 9's and thinks it is the biggest.
However, is there an easy way to get the actual biggest number?

A: list.sort() always returns None (the list is sorted in-place). What you want is sorted(list) which returns a new sorted list.
Then you can sort them like this:
mylist = [int(x) for x in mylist]
mylist.sort(reverse=True)
mylist = [str(x) for x in mylist]


text:
Q: Is it important to dispose unused IDisposable return values? There are certain static methods such as Process.Start() and File.Create() that construct and return IDisposable instances that are often discarded. It's so normal to use these methods as though they return void that if you aren't paying attention you might miss the fact that they even have return values at all.
I understand that it's good practice to always dispose of IDisposable instances. Does this apply to unused return values? Instead of writing Process.Start(processPath); should you always write Process.Start(processPath).Dispose();?
I'd think this would be an obvious yes but I have to second guess myself because I only ever see it done without the Dispose(). Does C# perhaps have some automatic way of handling those situations?

A: In most of the cases, prefered way of dealing with IDisposable instances is by using using statement:
using (var file = File.Create())
{
   //use file instance
}

This syntactic sugar will make sure that file instance is explicitly disposed after you exit using statement block. Under the hood, it actually wraps your code into try/finally block.

A: .NET has concept of Finalizer and many BCL types which implement IDisposable, also implement Finalizer. You can check MSDN Dispose Pattern article and this CodeProject post for more details. So if you won't dispose some object manually, it will likely be disposed later anyway. The question is if later (and other potential issues) is OK for you, or you need it to be disposed explicitly and deterministically at some specific point.
Downsides of skipping Dispose method call and relying on Finalizer are described in this thread and include:

*

*Performance issues

*Issues with locked resources which are in use longer than you expect

*Crash risk even if you have exception handling policy

In general I would strongly recommend always calling the Dispose method explicitly to avoid quirky problems.
But you should dispose only those objects which you own (you created and know when they are not used anymore). I've faced situations when I use some IDisposable resource, get another IDisposable as property of it and obviously I shouldn't dispose a property of an object before I stop using the referencing object - it will do it on it's own when disposed.


text:
Q: How do I make my date field show in a particular format in crystal reports I am a bit new to crystal reports even though I've been doing a bit of heavy lifting with it.
I have this crystal report that has a datetime field.
This field has a default datetime of 1753-01-01 00:00.
Now I want this field to display only date like "01-03-2011" and also anywhere it sees the default date, it should display an empty string like ''.
To achieve this I used this formular (in the display string)
if CurrentFieldValue = DateValue('1753-01-01 00:00:00') then
       ''
else
    totext(CurrentFieldValue)

This successfully changes the default date to empty string. But now I can no longer change the format to dates only.

A: I found my own workaround.
In case there is anyone who might be interested in the method I used, here it is
     if CurrentFieldValue = DateValue('1753-01-01 00:00:00') then
        ''
     else
        totext(CurrentFieldValue, 0)

Can you imagine, just a little 0 after the currentFieldValue!

A: Here's another approach which will let you do the date formatting at the field level instead of the formula level:
if CurrentFieldValue <> DateValue('1753-01-01 00:00:00') then
    CurrentFieldValue


text:
Q: How to write this into php code? Alt of the Image How to write this into code please?
if the alt of the image is "your alt here" then its 1.
Here is the code that i made.
public function getSiteAdvisor($domain)
        {
            try
            {
                $callback_url = "https://www.mcafee.com/threat-intelligence/site/default.aspx?url=" . $domain;

            $curl_response = $this->curl->get($callback_url);

            if ($curl_response->headers['Status-Code'] == "200") {

                libxml_use_internal_errors(TRUE);
                $this->dom_doc->loadHTML($curl_response);
                libxml_use_internal_errors(FALSE);

                $xpath = new DOMXPath($this->dom_doc);
                $tmp = $xpath->query('/html/body//div[@class="threeFourth"]//img/@alt')->item(0);

I don't know how to code the 'alt' of the image.
I add some code but not sure if this is correct.

                    if ($tmp->hasAttribute('src')) {

                    $tmp = $tmp->getAttribute('src');

                    if (stripos($tmp, "Minimal") !== false) {
                        $siteadvisor_rating = 1;
                    } elseif (stripos($tmp, "Moderate") !== false) {
                        $siteadvisor_rating = 2;
                    } elseif (stripos($tmp, "High") !== false) {
                        $siteadvisor_rating = 3;
                    } else {
                        $siteadvisor_rating = 0;
                    }
                } else {
                    $siteadvisor_rating = 0;
                }

            } else {
                $siteadvisor_rating = 0;
            }

            $response = array(
                'status' => 'success',
                'data' => array(
                    'siteadvisor' => (int)$siteadvisor_rating
                )
            );
        }
        catch (Exception $e)
        {
            $response = array(
                'status' => 'error',
                'msg' => $e->getMessage()
            );
        }
        return $response;
    }

Thanks

A: I found an answer by using this:

 if ($tmp->hasAttribute('src')) {

                $tmp = $tmp->getAttribute('alt');

                if (stripos($tmp, "Minimal") !== false) {
                    $siteadvisor_rating = 1;
                } elseif (stripos($tmp, "Moderate") !== false) {
                    $siteadvisor_rating = 2;
                } elseif (stripos($tmp, "High") !== false) {
                    $siteadvisor_rating = 3;
                } else {
                    $siteadvisor_rating = 0;
                }
            } else {
                $siteadvisor_rating = 0;
            }

        } else {
            $siteadvisor_rating = 0;


text:
Q: DynamoDB is ignoring use of Index I have a dynamoDB table called Bank-Statements.
It has a Primary partition key:-

*

*Name: TransactionID (Number)

It has an Index:-

*

*Name: StatementType-index

*Status: Active

*Type: GSI

*Partition Key: StatementType (String)

In the StatementType column there are several records marked "RBS"
I wrote this in C#:
    public async Task<string> GetRecordList()
    {
        try
        {
            var request = new QueryRequest
            {
                TableName = "Bank-Statements",
                KeyConditionExpression = "StatementType = :searchKey",
                ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
                    {":searchKey", new AttributeValue { S =  "RBS" }}}
            };

            var response = await dynamoDbClient.QueryAsync(request);  //Error occurs here

            foreach (Dictionary<string, AttributeValue> item in response.Items)
            {
        //do something with item
            }
        }
        catch (Exception e)
        {
            logger.Info("Failed while Getting Record List");
            logger.Info("Error: " + e.Message);
        }

        return "DONE";
    }

I'm getting this error "Query condition missed key schema element: TransactionID"
Why am I getting this when I'm using the StatementType-index as the key?

A: In a different tutorial I found this setting:
IndexName = "StatementType-index".
This code works:
public async Task<string> GetRecordList()
{
    try
    {
        var request = new QueryRequest
        {
            TableName = "Bank-Statements",
            IndexName = "StatementType-index",
            KeyConditionExpression = "StatementType = :searchKey",
            ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
                {":searchKey", new AttributeValue { S =  "RBS" }}}
        };

        var response = await dynamoDbClient.QueryAsync(request);  //Error occurs here

        foreach (Dictionary<string, AttributeValue> item in response.Items)
        {
    //do something with item
        }
    }
    catch (Exception e)
    {
        logger.Info("Failed while Getting Record List");
        logger.Info("Error: " + e.Message);
    }

    return "DONE";
}


text:
Q: Mudar nome do processo tenho um script feito no CMD do Windows e queria ver se é possível alterar o nome do processo quando ele for executado.
Exemplo:
Tenho 3 script (1- ler_log.bat; 2 - recicle.bat; 3 - Alarm_alter.bat) quando eles são executados no Task Manager o nome do processo é cmd.exe (por rodar dentro do CMD) porém eu precisaria que cada um deles gerassem um processo com os seus respectivos nomes (pois eles rodam a cada 5 minutos e as vezes travam e tenho que fechar todos e ao abrir configurar todos novamente por causa de 1 só travado)

A: Nesse caso vc pode usar o PID dos process o diferenciar eles com o title
exemplo :
@echo off

set "$title=test2"

title %$title%

tasklist /FI "WINDOWTITLE eq %$title%" | find /i "console" >nul && echo processus com titulo [%$title%] encontrado || echo processus com titulo [%$title%] nao encontrado

saida :
processus com titulo [test2] encontrado

agora se mudar o title por test23 :
@echo off

set "$title=test2"

title test23

tasklist /FI "WINDOWTITLE eq %$title%" | find /i "console" >nul && echo processus com titulo [%$title%] encontrado || echo processus com titulo [%$title%] nao encontrado

Saida :
processus com titulo [test2] nao encontrado

so bastar fazer um outro bat que vai testar os 3 titulos em loop

A: Por todos serem em .bat não deve ser possivel gerar processos diferente, já que todos são interpretados pelo cmd. Sugiro que crie arquivos executáveis .exe para gerar processos diferentes. Esse video mostra como converter .bat em .exe: video


text:
Q: Letter in solid filled circle One of my coauthors wants to typeset a letter that is inside a solid filled circle. I went through various symbol lists of packages, yet without luck. I am not sure if my memory is doing a trick on me, but I am sure I have seen it in publications.
Here is also an image of the desired result.

A: A possible solution with TiKz.
\documentclass[]{article}
\usepackage{tikz}
\tikzset{%
pics/mycirc/.style args={#1}{
      code = {
\node [draw, circle,fill] {\color{white}#1};
}}}
\begin{document}
This is \tikz [anchor=base,baseline] \pic {mycirc=B}; as mycircle.
\end{document}

A: There is a package for just that: circledsteps.
\documentclass{article}
\usepackage{xcolor}
\usepackage{circledsteps}
\newcommand\myCircled[2][]{\ifmmode
\Circled[fill color=black,inner color=white,#1]{\mathsf{#2}}
\else
\Circled[fill color=black,inner color=white,#1]{\sffamily#2}
\fi
}
\begin{document}
\scriptsize A \myCircled{B} C

\footnotesize A \myCircled{B} C

\normalsize A \myCircled{B} C

\large A \myCircled{B} C

\Large A \myCircled{B} C

${\scriptstyle A \myCircled{B} C}$

$A \myCircled{B} C$

$A \myCircled{B} C_{{A \myCircled{B} C}_{A \myCircled{B} C}}$

\end{document}

A: With XeTeX and LuaTeX, you can directly input  (Unicode U+1F151) as long as your font includes this symbol (Quivira is quite good IMHO):
\documentclass{standalone}
\usepackage{fontspec}
\newfontfamily\nicetest{Quivira}
\begin{document}
%\char"1F151\relax
{\nicetest }
\end{document}


text:
Q: Derivatives of functions with arbitrary number of variables? I am trying to define a function f[x1,x2,...,xn] with n integer but not specified. And then I would like this funktion to behave properly under the derivative operation, so that D[f[x1,x2,...,xn],xi] actually results in an expression which unambiguously displays that it is the first derivative in respect to the i-th variable. Up until now I had little success in employing the Mathematica function D[x_,y_] and have been simply substituting it for a place holder d[x_,y_]. However, this is not very convenient, since those placeholders do not respect commutativity. Maybe there is such functionality already, which I do not know of? Or maybe one can implement it? Thank you for any suggestion!
EDIT:
Please note, I am not looking to define custom functions of a finite number of variables tied to the derivative operation. What I am actually interested in, is defining a function which is dependent on an unspecified number of variables n. And introducing a formalism such that taking derivatives in respect to one of these variables of an unspecified index i still works consistently.
EDIT2:
To explain what I mean in more detail, I would like to be able to define a function f[v] in which I would like to treat v as a 1-dimensional list v={v1,v2,v3,...,vn}. However, I would like to keep the amount of elements in v arbitrary (without specifying to a certain length). And then I would like to define a derivative operation, which would allow expressions like D[f[v],v1] or D[f[v],v2] and even D[f[v],vi] which should not evaluate to zero, but to some meaningful expression, from which I still could extract the information which derivative it is, and with respect to which of the n variables.

A: I hope this toy example helps.
First I define some function of an arbitrary number of arguments, such that
f[v1, v2, v3,...] == v1 + 2 v2 + 3 v3 + ...

I do this with
f[v__] := Plus @@ MapIndexed[#1 First@#2 &, {v}, {1}]

I can then, without knowing the exact number of arguments, take a derivative with respect to a given argument by
i = 3
Derivative[Sequence@@(ConstantArray[0,i-1]~Join~{1})][f]
(* 3 & *)

Unfortunately, it doesn't allow a purely symbolic approach. I can't clear the i and do this:
Clear[i]
Derivative[Sequence@@(ConstantArray[0,i-1]~Join~{1})][f]
(* i & <--- ain't happening *)

Also problems arise if the derivative is dependent on the number of arguments. e.g.
f[v__] := Times @@ MapIndexed[Exp[#1] First@#2 &, {v}, {1}]
Derivative[0, 1][f]
(* 2 E^(#1 + #2) & *)
Derivative[0, 1, 0][f]
(* 6 E^(#1 + #2 + #3) & *)


text:
Q: Using a global variable vs reading and writing to file I'm afraid this is a bit of an abstract question. I'm basically writing an iPhone game which revolves around a Pet, a bit like a tamagotchi for example. I've created a Pet object, which contains all the data relevant to the Pet's status. The rest of the program accesses the Pet's data and performs relevant actions.
The pet is saved to file using encodeWithCoder and initWithCoder methods. So whenever a method in the program needs to access any pet data, it creates a new instance of the pet by loading it from file. If any changes are made, they are done within methods of the Pet class. These methods always end by writing the Pet to file.
So as the program is running, it is constantly writing to file and reading from file, every time a change is made. If I then want to add a new variable to the Pet, say a BOOL variable called showReaction (to determine whether or not to show the Pet's reaction to a certain event say), I have to include this variable in both my encodeWithCoder and initWithCoder methods. This seems a bit cumbersome since these methods are consequently growing larger and larger. And constantly reading and writing to file seems inefficient.
I would have thought a better approach would be to have a global variable which represents the Pet. And that any method in the program can accesses this global variable in order to change it. The only time I write to file is when the player exits the game, and I only read from file once when the game loads.
My question is - I'm not exactly sure of the best approach to this. And whether or not this is good programming practice? Should I declare the global variable in my main ViewController and then refrain from releasing it during the program's running? Will I be able to alter variables in the Pet class and have this data retained during the running of the program. I.e. setting showReaction to TRUE in one method, reading it in another method and setting it to FALSE in another method...
Any advice would be much appreciated. I've been writing this program for a while now, and am wondering if I should make these changes now before I ingrain any bad practices further. But given the size of my code, I don't want to experiment too much without checking with the experts first!
Thanks,
Michael

A: Why don't you create a singleton? that way your code won't need to worry about how it is being done. Try to decouple your code.

A: I think its a bit difficult to say on an abstract level what is best in your case but often what seems simpler is often the best approach. Having just a global instance which you interact with seems to be a pretty straightforward way.


text:
Q: Alternative name support in moshi for converting to json I have members in Json format, which are named different when serializing and deserializing. Do moshi have any concept like alternate provided in gson..
FromJson: I get:
{
name:"Ted"
}
ToJson
{
firstname:"Ted"
}
In moshi, can this be solved by one model class with single adapter or by using annotation ?

A: There's nothing like this in Moshi and the mainteners don't think it's a fit for the library, but this issue might point you to a workaround: https://github.com/square/moshi/issues/303.


text:
Q: Why does PhpStorm not recognize my import for Method and Template being used in Annotations? I have a symfony 3.4 project in PhpStorm 2020.2. I import the following annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

and use them, for example here:
/** @Route("/feedback/delete/{id}", name="feedbackDelete") @Method("DELETE") */

and
/** @Route("/dashboard", name="dashboard") @Template() */

Now PhpStorm tells me Import 'Sensio\Bundle\FrameworkExtraBundle\Configuration\Method' is never used - same for Template. That is not true, but why does PhpStorm not recognize it?
I use the plugins PHP Annotations 7.1.3 and Symfony Support 0.21.202.
It's annoying because it always shows up in code analyses and I can't auto-optimize imports, because it breaks the code.
I thought, why bothering to ask - symfony 3.4 is old and I will probably soon migrate to symfony 5.X. But migration is a headache and since I recently talked with someone from a big symfony project where they still use 2.*, I thought there might actually be more people with this problem.

A: After experimenting a bit, I found the problem:
The PhpStorm plugin PHP Annotations does recognize the annotation, if it is starting in a new line of the PhpDoc. So while @Template is not recognized as used here:
/** @Route("/dashboard", name="dashboard") @Template() */

it works, if I change it to
/**
 * @Route("/dashboard", name="dashboard")
 * @Template()
 */

or even this is enough:
/** @Route("/dashboard", name="dashboard")
 *  @Template() */

I don't really like that since I like to keep my line count low and I don't see any advantage of putting this small annotation in a new line, but at least now I have a work-around.
I also opened an issue for this which can be found here: https://github.com/Haehnchen/idea-php-annotation-plugin/issues/211


text:
Q: Why it Printing out different name? in Django I want to Print all the result same.
my code:
models.py:
class Product(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(upload_to='images')
    description = models.TextField(max_length=10000, blank=True, null=True)
    category = models.ManyToManyField(Category, related_name='category')
    company = models.ForeignKey(Company, related_name='company', on_delete=models.CASCADE)
    price = models.IntegerField()
    discount = models.IntegerField(default=0)

views.py:
        excludeCompanyId = []
        company = Company.objects.all().order_by('?').exclude(id__in=excludeCompanyId)[:1]#random 1 company
        companyName = company[0].name
        print(companyName)

        companyProduct = Product.objects.filter(company=company).order_by('?')[:10]
        print(companyProduct[0].company)

        for i in companyProduct:
            print(i.company)

Result will be different at different time.
But I want to show you one result:
Tesla
Apple Inc.
Sony
Sony
Sony
Sony

I want to print all the result same. how do i do that?

A: .order_by('?') orders the queryset randomly. But it seems you do want a random Company, the real problem here is that you don't actually use the random company you get and reuse the QuerySet instead effectively making a subquery.
Below is a copy of your code with comments to explain what exactly goes wrong:
excludeCompanyId = []
company = Company.objects.all().order_by('?').exclude(id__in=excludeCompanyId)[:1]
# company here is not an instance of a company it is a QuerySet

companyName = company[0].name # You make a query when you write `company[0]` but note `company` remains unevaluated
print(companyName)

companyProduct = Product.objects.filter(company=company).order_by('?')[:10]
# You write `filter(company=company)`
# This effectively makes a subquery, meaning for each row in `Product`
# a random `Company` is selected if this company is the same as the products
# company then the product is selected
print(companyProduct[0].company)

What you need to do is actually evaluate the query and get a product and use that in your other query. Also instead of the slice [:1] simply use .first() [Django docs]:
excludeCompanyId = []
company = Company.objects.all().order_by('?').exclude(id__in=excludeCompanyId).first()

if company is None:
    # there are no matching companies return something appropriate here
print(company.name)

companyProduct = Product.objects.filter(company=company).order_by('?')[:10]
for i in companyProduct:
    print(i.company.name)


text:
Q: How to check if point is a vertex of a set Consider the set $K=\{x\in \mathbb{R}^4: Ax=a,~x_i\geq  0\}$
with
$$A=\begin{pmatrix}1&-1&-1&2\\ \:\:\:\:0&1&0&3\\ \:\:\:\:2&0&-2&10\end{pmatrix}\quad a=\begin{pmatrix}2\\ 7\\ 18\end{pmatrix}$$
Which of the vectors is a vertex of the set?
$$x_1=\begin{pmatrix}10\\ \:7\\ \:0\\ \:0\end{pmatrix},~x_2=\begin{pmatrix}0\\ \:\:1\\ \:\:1\\ \:\:2\end{pmatrix},~x_3=\begin{pmatrix}1\\ \:\:\:1\\ \:\:\:2\\ \:\:\:2\end{pmatrix},~ x_4=\begin{pmatrix}9\\ \:\:\:7\\ \:\:\:\:0\\ \:\:\:\:0\end{pmatrix}$$
So I checked that
$Ax_2=a$, $Ax_3=a$ and $Ax_4=a$. But $Ax_1=\begin{pmatrix}3\\ 7\\ 20\end{pmatrix}$ so $x_1$ is not in $K$. How do I check if the other points are vertices?
Vertex;
$$G\subseteq \mathbb{R}^n~\text{convex}, z\in  G ~\text{vertex} \iff~x,y\in G: z=\frac{x+y}{2} \Rightarrow x=y=z$$

A: First, consider the vector $x_2$ . . .

Let's attempt to represent $x_2$ as the midpoint of two distinct points of $K$.

Thus, suppose $x_2\pm v\in K$, for some nonzero $v\in\mathbb{R}^4$.

Equivalently, $v\in\mathbb{R}^4$ is such that
$$
\begin{cases}
Av=0\\[4pt]
x_2\pm v \ge 0\\
\end{cases}
$$
Since $x_2[1]=0$, the conditions $x_2\pm v \ge 0$ force $v[1]=0$, hence
$$v=\begin{pmatrix}0\\q\\r\\s\end{pmatrix}$$
for some $q,r,s\in\mathbb{R}$, not all zero.

Expressing the condition $Av=0$ as a system of equations, we get
$$
\begin{cases}
q+3s=0\\[4pt]
 -q-r+2s=0\\[4pt]
-r+5s = 0\\[4pt]
\end{cases}
$$
which has the general solution
\begin{cases}
q=-3s=0\\[4pt]
r=5s
\end{cases}
where $s\in\mathbb{R}$ is arbitrary.

If $s$ is sufficiently small, but not zero (e.g., $s={\large{\frac{1}{10}}}$), we get $x_2\pm v\ge 0$.

It follows that $x_2$ is not a vertex of $K$.

Next, consider the vector $x_3$ . . .

Let's attempt to represent $x_3$ as the midpoint of two distinct points of $K$.

Thus, suppose $x_3\pm v\in K$, for some nonzero $v\in\mathbb{R}^4$.

Equivalently, $v\in\mathbb{R}^4$ is such that
$$
\begin{cases}
Av=0\\[4pt]
x_3\pm v \ge 0\\
\end{cases}
$$
Write
$$v=\begin{pmatrix}p\\q\\r\\s\end{pmatrix}$$
for some $p,q,r,s\in\mathbb{R}$, not all zero.

Expressing the condition $Av=0$ as a system of equations, we get
$$
\begin{cases}
p-q-r+2s= 0\\[4pt]
p-r+5s=0\\[4pt]
q+3s=0\\
\end{cases}
$$
which has the general solution
\begin{cases}
r=p+5s\\[4pt]
q=-3s\\[4pt]
\end{cases}
where $p,s\in\mathbb{R}$ are arbitrary.

If $p,s$ are sufficiently small, and $s,p+5s$ are not both zero (e.g., $p=s={\large{\frac{1}{10}}}$), we get $x_3\pm v\ge 0$.

It follows that $x_3$ is not a vertex of $K$.

Finally, consider the vector $x_4$ . . .

Let's attempt to represent $x_4$ as the midpoint of two distinct points of $K$.

Thus, suppose $x_4\pm v\in K$, for some nonzero $v\in\mathbb{R}^4$.

Equivalently, $v\in\mathbb{R}^4$ is such that
$$
\begin{cases}
Av=0\\[4pt]
x_4\pm v \ge 0\\
\end{cases}
$$
Since $x_4[3]=x_4[4]=0$, the conditions $x_4\pm v \ge 0$ force $v[3]=v[4]=0$, hence
$$v=\begin{pmatrix}p\\q\\0\\0\end{pmatrix}$$
for some $p,q\in\mathbb{R}$, not both zero.

Expressing the condition $Av=0$ as a system of equations, we get
$$
\begin{cases}
q=0\\[4pt]
p-q=0\\[4pt]
p= 0\\
\end{cases}
$$
which has no solutions other than $p=q=0$.

It follows that $x_4$ is a vertex of $K$.


text:
Q: Update every record in a column of a table with a PHP generated UUID I've got a table called "partners" which contains a very large amount of contact information. After having extensively cleaned up the data from which I received it in, I've added a UUID column which I would ideally like to populate with UUID's via the PHP $generateobjectid=(uniqid('AGF'));
Is there a simple script I could write that would go through the database and enter in a uniqid for each and every row this one single time?
I'd prefer to keep the uniqid generated via PHP so that I can manage the prefix between the various entries.

A: why not use the mysql function UUID()
UPDATE XXX set FIELD=CONCAT('AGF',UUID())


text:
Q: How to I change the order of my columns so it doesn't break an import with pg_restore I'm trying to export data from a live Postgres DB into a local Postgres DB and have used pg_dump (via DataGrip) to dump the database into a tar file. I am using the INSERT option from the DataGrip dialogue which is giving the following.
--dbname="XXX" --format=t --file="XXX/DataGrip Backup/{timestamp}" --inserts

When I try and import the tar file using pg_restore (once again through DataGrip), one of my tables (the most important one!) won't import.
The error I'm getting is:

pg_restore: error: could not execute query: ERROR:  invalid input syntax for type numeric: "AUD"

The table has a numeric field and a varchar field. One for the discount and one for the currency being used.
This is from a model (Django) using the MoneyField:
coupon_discount = MoneyField(
    decimal_places=2, max_digits=10, null=True, default_currency="AUD", default=0.00
)

An example of the data I am importing is:
Command was: INSERT INTO public.customers_customer VALUES (2557, '', NULL, 3, NULL, NULL, NULL, NULL, '2022-08-14 08:45:50.466306+00', '2022-08-14 08:45:50.466454+00', '2022-08-14 08:45:50.466459+00', 2559, '90h0nbJgDU', 0, 0.00, 'AUD', false, false, NULL, 1);
pg_restore: error: could not execute query: ERROR:  invalid input syntax for type numeric: "AUD"
LINE 1: ...10:31:35.347403+00', 2560, 'o4VxTmqlOa', 0, 0.00, 'AUD', fal...

When I look at the external Postgres DB the order of the two fields in the table is:

I assume this is the order the fields are given in the tar field. But when I check the local DB the order is different:

I don't think I've done anything to have it this way as Django is creating the tables and hence I assume the order?
Is there a way I can change this to have the data imported?
Do I need to export the data in a different way? I really just want the actual data to be imported. I already seem to have to use the --ignore-triggers somewhere to stop a whole host of problems with migration tables and others.

A: Use the option --column-inserts (instead of --inserts) for pg_dump.
That will generate INSERT statements that will qualify the target columns.


text:
Q: PHP: Validate a given string is a valid number I am trying to write a function that validates whether or not a given string is a valid number. I know I can use PHP is_numeric(), but the requirements is that the function needs to recognize commas as valid when:

*

*Commas are in the whole number part of the number

*Each comma has 3 whole number digits following it

*At least one digit left of each comma

*No more than 3 contiguous digits to the left of a comma

For instance:
It should recognize: 1,000,230 not ,021,201 or 1,023,12
It should also recognize positive and negative and dollar sign in front of it.
I am thinking to use preg_match to check the number format but I am not familiar with preg_match. Can you help me with this ? Any tip is appreciated ! Thank you !

A: No regex needed. Strip commas, then reformat with number_format. If that matches your original input, you're good.
if (number_format(str_replace(',', '', $number)) === $number) {
   // pass
}

You can adjust how you want to handle decimals by providing a second argument to number_format().

A: You could use this function:
function hasNumericFormat($str) {
    return preg_match("/^[-+]?[$]?([1-9]\d{0,2}(,\d{3})*|0)(\.\d+)?$/", $str);
}

Test code:
function test($str) {
    if (hasNumericFormat($str)) {
        echo "$str is OK
";
    } else {
        echo "$str violates numerical format
";
    }
}

test("-$1,234,567.89"); // ok
test(",123,567.89"); // not ok: digit missing before comma
test("1,123,56"); // not ok: not 3 digits in last group
test("-0,123,567"); // not ok: first digit is zero
test("+0"); // ok

See it run on eval.in

A: The Intl library's NumberFormatter may be sufficient for you.
The NumberFormatter class
NumberFormatter::parse
NOTE: You may need to install or enable the Int library extension to use NumberFormatter class.

*

*To enable the extension, check your php.ini file(C:\xampp\php\php.ini) and search for extension=intl. Remove the prepended ; if it exists. Restart Apache server and give it a try.

This extension is bundled with PHP as of PHP version 5.3.0.
/**
 * Parse a number.
 *
 * @param string $locale - The locale of the formatted number.
 * @param string $number - Formatted number.
 * @return mixed - The value of the parsed number or FALSE on error.
 */
function parse_number(string $number, $locale)
{
    return (new NumberFormatter($locale, NumberFormatter::DECIMAL))
        ->parse(trim($number));
}

echo parse_number('4.678.567.345,3827', 'de_DE'); // 4678567345.3827
echo parse_number('4.678567.345,3827', 'de_DE'); // FALSE

echo parse_number('4,678,567,345.3827', 'en_US'); // 4678567345.3827
echo parse_number(',678567,345.3827', 'en_US'); // FALSE

A: I will write it like this:
if (preg_match('~\A(?>[1-9][0-9]{0,2}(?:,[0-9]{3})*|0)(?:\.[0-9]+)?\z~', $number)) {
    // true
} else {
    // false
}

details:
~ # my favourite pattern delimiter
\A # start of the string
(?>  # group for integer part:
     # I made it atomic to fail faster when there aren't exactly 3 digits
     # between commas
    [1-9] [0-9]{0,2} # beginning doesn't start with a zero
    (?:,[0-9]{3})*   # zero or more 3 digits groups
  |                  # OR
    0                # zero alone
)
(?:  # optional group for decimals
    \.[0-9]+ # at least 1 digit
)?
\z # end of the string
~

Note that I have chosen to not allow numbers with a leading zero like 012, numbers without an integer part like .12 or integers with a dot like 12. but feel free to edit the pattern if it isn't what you want.


text:
Q: Java Mail Authentication Trying to connect mail using java
Exception in thread "main" javax.mail.AuthenticationFailedException: No POP server defined. Use real server address instead of 127.0.0.1 in your account.
    at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:208)
    at javax.mail.Service.connect(Service.java:295)
    at javax.mail.Service.connect(Service.java:176)
    at POP3Clint.main(POP3Clint.java:28)
Java Result: 1

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class POP3Clint {

  public static void main(String[] args) throws Exception {

String host = "192.168.10.205";
  String user = "test";
  String password = "test";
  // Get system properties
  Properties properties = System.getProperties();

  // Get the default Session object.
  Session session = Session.getDefaultInstance(properties);

  // Get a Store object that implements the specified protocol.
  Store store = session.getStore("pop3");

  //Connect to the current host using the specified username and password.
  store.connect(host, user, password);

  //Create a Folder object corresponding to the given name.
  Folder folder = store.getFolder("inbox");

  // Open the Folder.
  folder.open(Folder.READ_ONLY);

  // Get the messages from the server
  Message[] messages = folder.getMessages();

  // Display message.
  for (int i = 0; i < messages.length; i++) {
  System.out.println("------------ Message " + (i + 1) + " ------------");
  // Here's the big change...
  String from = InternetAddress.toString(messages[i].getFrom());
  if (from != null) {
  System.out.println("From: " + from);
  }
  String replyTo = InternetAddress.toString(
  messages[i].getReplyTo());
  if (replyTo != null) {
  System.out.println("Reply-to: " + replyTo);
  }
  String to = InternetAddress.toString(
  messages[i].getRecipients(Message.RecipientType.TO));
  if (to != null) {
  System.out.println("To: " + to);
  }
  String cc = InternetAddress.toString(
  messages[i].getRecipients(Message.RecipientType.CC));
  if (cc != null) {
  System.out.println("Cc: " + cc);
  }
  String bcc = InternetAddress.toString(
  messages[i].getRecipients(Message.RecipientType.BCC));
  if (bcc != null) {
  System.out.println("Bcc: " + to);
  }
  String subject = messages[i].getSubject();
  if (subject != null) {
  System.out.println("Subject: " + subject);
  }
  Date sent = messages[i].getSentDate();
  if (sent != null) {
  System.out.println("Sent: " + sent);
  }
  Date received = messages[i].getReceivedDate();
  if (received != null) {
  System.out.println("Received: " + received);
  }
  System.out.println();
  }

  folder.close(true);
  store.close();
  }
}

---EDITTED__
Exception in thread "main" javax.mail.AuthenticationFailedException: EOF on socket
    at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:208)
    at javax.mail.Service.connect(Service.java:295)
    at javax.mail.Service.connect(Service.java:176)
    at POP3Clint.main(POP3Clint.java:35)
Java Result: 1

this exception comes if we disable anitivirus


text:
Q: Итератор для бинарного дерева Всем привет. Задача реализовать бинарное дерево поиска. Обязательное условие реализовать итератор. Уже несколько дней пытаюсь найти решение, гугл не помогает, везде в основном примеры методов для вывода на печать всех элементов, но мне нужно реализовать именно итератор, с методами next и hasNext. Буду очень признателен за вербальный алгоритм, и бесконечно благодарен за пример в коде.
P.S. Метод add() реализован, элементы корректно добавляются.
 @Override
    public Iterator<E> iterator() {
      int expectedModCount = modCount;
       return new Iterator<E>() {
        BinNode<E> curr = root;
        @Override
        public boolean hasNext() {
            return curr != null;
        }

        @Override
        public E next() {
            checkModCount();
            //todo
             return ;
        }

        private void checkModCount() {
            if (expectedModCount != modCount) {
                throw new ConcurrentModificationException();
            }
        }
    };
}

}

A: Давайте заменим java на автомастерскую. "Ребят, собрал машину, двигатель впихнул, ездит. Вот только тормоза не могу запилить. Облазил весь интернет, а там только показывают как двери менять. Машина обычная - на колесах, они такие крутятся и она вперед-назад". Не надо так ) Понял ваш вопрос только потому что сам когда то учился в универе.
class Node {
     Object value;
     Node left, right;
}

Я так понимаю ваша проблема, заключается в том, что вы знаете как реализовывать классический рекурсивный вариант:
void go(Node root) {
    go(root.left);
    go(root.right);
}

А он не ложится на стандартный итартор. Проблема в том, что вам нужно сделать обход не рекурсивным. А для этого придется сохранять путь назад вручную (в случае с рекурсией, он сохраняется в стеке, я думаю ошибка StackOverflow вам знакома).
В общем чтобы не изобретать велосипед, уже был похожий вопрос.


text:
Q: Showing bound on operator $||Tx|| \ge \frac{||x||}{||(T')^{-1}||}$ T is an bounded linear operator on a Banach space, X, and I'm given that it's adjoint $T'$ is invertible, I'm trying to show: $||Tx|| \ge \frac{||x||}{||(T')^{-1}||}$. I feel like this should be simple but I'm finding it very frustrating!
My ideas so far: $T'$ is invertible so we have that for any $x \in X$, $(T')^{-1} T g (x) = g(x)$ and then taking norms of this, and using the fact everything is bounded we find: $||g(x)|| \le ||(T')^{-1}|| ||T|| ||g|| ||x||$. I'm having trouble then deducing the inequality from this even though I feel it should follow?
Thaanks

A: Fix $x\in X$. If $f\in X'$ then $|f(x)|=|[(T')^{-1}T'f](x)|=|(T')^{-1}f(Tx)|\leq\|(T')^{-1}\|\|f\|\|Tx\|$. Hence
$$\|Tx\|\geq\frac{|f(x)|}{\|f\|}\cdot\frac1{\|(T')^{-1}\|}.$$
By a corollary to the Hahn-Banach theorem, there exists $f\in X'$ with $\|f\|=1$ and $f(x)=\|x\|$, completing the proof. This method manages to avoid any spectral theory.

A: Since $T'$ is invertible, $\operatorname{spec}(T')=\operatorname{spec}(T)$ is bounded away from zero, and we can define:
$$\lambda^- = \min_{\lambda\in\operatorname{spec}(T)}|\lambda|.$$
Obviously we have:
$$ \| T x\| \geq \lambda^{-}\|x\|,$$
hence it is sufficient to check that:
$$ \lambda^{-} = \frac{1}{\|T'^{-1}\|} $$
that follows from:
$$ \|T^{-1}\| = \max_{\lambda\in\operatorname{spec}{T'^{-1}}}|\lambda| =\frac{1}{\min_{\lambda\in\operatorname{spec}{T'}}|\lambda|}=\frac{1}{\lambda^-}.$$


text:
Q: Stay on Current Tab while using window.open() I am opening a window in another tab in my code, but the problem is the focus shifts to new tab opened, I want the focus to remain on the current window
I have searched for it, but have not got any solution, the focus() function is as I have understood is useful when opening popups.
I am using : window.open() function
window.open("myurl");

A: http://www.pageresource.com/jscript/jwinopen.htm also check this
You can't directly control this, because it can be configured by the user. You might try "_newtab" which might work for Firefox but really you shouldn't rely on a new tab being opened. The user may have their browser settings set to open a new tab when a popup window is opened or it may show up as a popup. It just all depends on the browser settings.


text:
Q: Run Upstart with Forever We have a series of node.js scripts on an Ubuntu (13.10) server that we want to keep up and running as much as possible, and restart automatically in the event of a server reboot. We've tried a few different techniques, but have yet to find a solution that works.
Setup: None of the scripts run on port 80, instead we run them on ports above 8000.
Node.js files are currently running in /usr/lib/sites/path/Node
We have set them up and running individually using Forever while running in the context of a well privileged (but not root) user, simply by running the following from the context of the folder containing the scripts:
forever start server_process.js

We want to run these scripts at server start up, and have some ability later (if needed) to restart them.
Upstart sounds like it should be the solution, but we've not yet managed to get it working. The following script starts, then stops without indicating why...
description "Our app"
version "1.0"
author "Nautilytics"

start on startup
stop on shutdown

expect fork

env FOREVER_PATH=/usr/bin/forever
env APPLICATION_DIRECTORY=/usr/lib/sites/path/Node
env APPLICATION_START=ourapp.js
env LOG_PATH=/var/log/ourapp.log

chdir /usr/lib/sites/path/Node

script
    exec $FOREVER_PATH start --sourceDir $APPLICATION_DIRECTORY -f -v $APPLICATION_START >> $LOG_PATH 2&>1
end script

Through blunt trial and error, a couple of times we have been able to get errors that indicate that other files (required by ourapp.js) could not be found, as if the chdir has not worked or passed through into the forever start.

A: After scouring the internet for a solution, we decided to stick with nodejs and not use forever for this task. It was much easier and with respawn it does just about everything we needed forever to do for us.
start on runlevel [2345]

stop on shutdown

respawn

script
    exec sudo nodejs /usr/lib/sites/path/Node/ourapp.js 2>&1 >> /var/log/ourapp.log
end script

A: A bit more secure upstart config script might be (hardened-nodejs.conf):
description "Managing and monitoring nodejs application"

# start when filesystem is mounted networking is up
start on (filesystem and net-device-up IFACE!=lo)
# stop on shutting down the system
stop on runlevel [016]

# application environment
# staging and development instances should use hardened-nodejs.override to define environment
env NODE_ENV=production

# respawn the job up to 10 times within a 5 second period.
# If the job exceeds these values, it will be stopped and marked as failed.
respawn
respawn limit 10 5

# ssl-cert group can read certificates
setuid www-data
setgid ssl-cert

exec  /usr/bin/nodejs /usr/lib/sites/path/Node/ourapp.js 2>&1 >> /var/log/ourapp.log

One of solutions to run nodejs application listening on a low port might be to use capabilities tools.
If serving over SSL user or group must have read access to the certificate. Check ssl-cert package and this answer for basic concepts.

A: Have you checked process.cwd()?  It could be that your process is running elsewhere.


text:
Q: Catching play event in video on mobile safari I have an iOS app that contains a lot of local web content.  Some of that content is video/audio.  I have a click event attached to the video and audio tags that fires an analytics url that I'm going to catch in the UIWebView.  The problem is that click event doesn't register.  I'm assuming this is because iOS replaces the video with its own special movie player.  How do I catch the play event so I can do something with it.  Here's my jQuery code for the click event.
 function videoClick() {
    $("video").click(function () {
        alert("here");
        //document.location = "ignoretap:///";
        var videoTitle = $(this).attr("data-mediatitle");
        var videoSrc = $(this).children("source").attr("src");
        if (videoTitle != null && videoTitle.length > 0) {
            document.location = "analytics:///" + "page" + videoTitle;
        }
        else {
            document.location = "analytics:///" + "page" + videoSrc;
        }
    });
}

Here's my html for the video
 <video width="100%" controls="controls" data-mediatitle="testing">
      <source src="StoryOfIyal.mp4" type="video/mp4" poster="IyalVideo.htm-iyalvideoscreenshot_lg.jpg"></source>
      Your Browser does not support the video tag
 </video>

A: Figured it out.  You have to bind to the "play" event in jQuery, not the click event.  Here's the updated function.
 function videoClick() {
    $("video").bind('play', function () {
        alert("here");
        //document.location = "ignoretap:///";
        var videoTitle = $(this).attr("data-mediatitle");
        var videoSrc = $(this).children("source").attr("src");
        if (videoTitle != null && videoTitle.length > 0) {
            document.location = "analytics:///" + "page" + videoTitle;
        }
        else {
            document.location = "analytics:///" + "page" + videoSrc;
        }
    });
}


text:
Q: How to increase Selenium grid session timeout? While running my test, I need to have long delays (~40 seconds).
And I see, that Selenium session gets deleted during that time.
Please help: How can I configure session timeout to increase?
Here what I see in less, that 30 secs, after delay started in the Selenium node log:

INFO org.openqa.selenium.remote.server.DriverServlet - Session
  7f5fffec-4882-4c4c-b091-c780c66d379d deleted due to client timeout

And after 40 seconds sleep, I'm getting this exception in my code:

org.openqa.selenium.remote.SessionNotFoundException

I tried to increase all possible timeouts.
Here is how I start hub:
java -jar selenium-server-standalone.jar -role hub
-hubConfig selenium_hub.json
-nodeTimeout 61
-remoteControlPollingIntervalInSeconds 180
-sessionMaxIdleTimeInSeconds 240
-newSessionMaxWaitTimeInSeconds 250
-timeout 59

And here is selenium_hub.json:
{
  "host": null,
  "port": 4444,
  "newSessionWaitTimeout": -1,
  "servlets": [],
  "prioritizer":  null,
  "capabilityMatcher": "org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
  "throwOnCapabilityNotPresent": true,
  "nodePolling": 5000,
  "cleanUpCycle": 5000,
  "timeout": 60000,
  "browserTimeout": 60000,
  "maxSession": 5,
  "jettyMaxThreads": -1
}

No any timeouts configured on the nodes.
Here is what I see in my Grid console:
browserTimeout : 60000
capabilityMatcher : org.openqa.grid.internal.utils.DefaultCapabilityMatcher
cleanUpCycle : 5000
host : null
hubConfig : /usr/local/selenium/config/selenium_hub.json
jettyMaxThreads : -1
maxSession : 5
newSessionMaxWaitTimeInSeconds : 250
newSessionWaitTimeout : -1
nodePolling : 5000
nodeTimeout : 61
port : 4444
prioritizer : null
remoteControlPollingIntervalInSeconds : 180
role : hub
servlets : []
sessionMaxIdleTimeInSeconds : 240
throwOnCapabilityNotPresent : true
timeout : 59000

I'm using Selenium 2.45

A: I finally figured it out!
Solution is actually very easy: nodes needs to be restarted after configuration changed on the hub.
It is not really obvious:
When I changed configuration on the hub, then I restarted it. Node would re-register with the hub automatically. Then looking at the console, I can see new configuration parameters taking effect. Even more, as I'm looking at the node configurations, I see same parameters changed on the nodes. That's misleading! Because even though nodes re-registered, but their configuration has NOT been changed. It only changes, when node is restarted, too. I think, this is Selenium bug - node should re-configure during re-registration.

A: C#

driver = new RemoteWebDriver(new Uri("http://host:4444/wd/hub"), capabilities);
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds( desired_time ));

P.S.
I'm using Selenium grid 2.53 and firefox 46.0


text:
Q: Same query producing 2 different results I have the following query that I am running on 2 different servers, a development and production server.
SELECT TeacherID, COUNT(StudentID) AS Students
FROM TeacherStudentRecord tsr
JOIN TeachersApplicationRecord tar
ON tsr.TeacherID = tar.TeacherID
WHERE Semester = 1
AND Semester1 = 1
AND Semester1T= 0
AND Year = 2016
GROUP BY TeacherID
HAVING COUNT(StudentID) = (
    SELECT MIN(COUNT)
    FROM (
                SELECT COUNT(tsr.StudentID) as COUNT
                FROM TeacherStudentRecord tsr
                JOIN TeachersApplicationRecord tar
                ON tar.TeacherID = tsr.TeacherID
                WHERE Semester = 1
                AND Year = 2016
                GROUP BY TeacherID)
    AS T)

Both servers have the same tables with the same data. When I run the query on development server, I get the response I expect. When I run it on production, I get "MySQL returned an empty result set".
The only difference AKAIK between the two servers is the version of pma. The dev server is running pma 4.1.12 and the prod server is running pma 3.5.2.2. Do the different versions of pma interpret SQL differently? Or is there something else in my query that is causing this issue?


text:
Q: Wordpress broken image on admin edit I am trying to figure this out , but cant get a accurate solution any where.
when I click edit the image is broken
I checked my functions.php for any white space, there is none.
I check if gd-modules are installed, they are installed.
I tried using a funtion to force the use of gd, but even that didnt work out.

A: be sure to get installed phpx-gd this library is necesary to edit images, maybe too need imagick installed instead GD.


text:
Q: Which design pattern should I use to output different content using one template? I need to extend a piece of code that writes a paragraph using constant strings defined in an interface:
public class paragraphGenerator implements EnglishParaGraph(){
    public StringBuffer outputParagraph = new StringBuffer();

    public void generate(){
        writeParagraph(PARA1);
        //some long and complicated logic here
        writeParagraph(PARA2);
        //some long and complicated logic here
        writeParagraph(PARA3);
    }

    public void writeParagraph(String content){
        //manipulates the paragraph and puts it in stringbuffer
    }
}

public interface EnglishParaGraph{
    public static final String PARA1 = "Hello";
    public static final String PARA2 = "Thank you";
    public static final String PARA3 = "Goodbye";
}

Running generate() should write something like "Hello Thank you Goodbye".
Now I want to generate a French equivalent so the output looks something like "Bonjour Merci Salut".
According to Template Method Pattern can overwrite generate() in a subclass and change each writeParagraph's input argument, but that will repeat most of the code which is not desirable.
What's the most suitable design pattern to use here? I was told to use as little replicating code as possible.

A: The design of the interface and extending class is simply wrong. To be clear, interfaces are specifically used to avoid defining implementation details. The code you posted does the exact opposite of that and defines implementation details using an interface.
At worst, you want to make the interface define something like this:
public interface ParagraphSource{
    public String getParagraph1Text();
    public String getParagraph2Text();
    public String getParagraph3Text();
}

public class EnglishSource extends ParagraphSource {

    public String getParagraph1Text() {
        return "Hello";
    }
    public String getParagraph2Text() {
        return "Thank you";
    }
    public String getParagraph3Text() {
        return "Goodbye";
    }
}

public class FrenchSource extends ParagraphSource {

    public String getParagraph1Text() {
        return "Bonjour";
    }
    public String getParagraph2Text() {
        return "Merci";
    }
    public String getParagraph3Text() {
        return "Au revoir";
    }
}

Then your paragraph generator can use different sources:
public class ParagraphGenerator {
    public StringBuffer outputParagraph = new StringBuffer();

    public void generate(ParagraphSource source){

        writeParagraph(source.getParagraph1Text());
        //some long and complicated logic here
        writeParagraph(source.getParagraph2Text());
        //some long and complicated logic here
        writeParagraph(source.getParagraph3Text());
    }
}


text:
Q: Android fatal signal 11 (SIGSEGV) runOnUiThread I am trying to make a simple Android animation of dog paw walking on the screen. I am doing that by making one XML screen with 6 dog paws, and setting visibility each of them in the code. The code is organized in a way that there is on UI thread that changes visibility on every 500ms. After 10 cycles, I try to start a new Activity. At this point I get exception and my app restarts. What could be a problem ? There is the snippet of my code:
Thread UI_thread = new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
                try {
                    //Thread.sleep(300);

                    while (cnt < 11) {

                     Thread.sleep(500);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                             if (cnt == 10) {
                                 // Start second screen
                                 Img1.setVisibility(View.INVISIBLE);
                                 Img2.setVisibility(View.INVISIBLE);
                                 Img3.setVisibility(View.INVISIBLE);
                                 Img4.setVisibility(View.INVISIBLE);
                                 Img5.setVisibility(View.INVISIBLE);
                                 Img6.setVisibility(View.INVISIBLE);
                                 Intent IntroScreen2Act = new Intent(IntroScreen1.this, IntroScreen2.class);
                                 startActivity(IntroScreen2Act);

                             }

                            switch (cnt) {
                            case 0:
                                Img1.setVisibility(View.VISIBLE);
                                break;

                            case 1:
                                Img2.setVisibility(View.VISIBLE);
                                break;

                            case 2:
                                Img3.setVisibility(View.VISIBLE);
                                break;

                            case 3:
                                Img4.setVisibility(View.VISIBLE);
                                break;

                            case 4:
                                Img5.setVisibility(View.VISIBLE);
                                break;

                            case 5:
                                Img6.setVisibility(View.VISIBLE);
                                break;

                            }

                        }
                    });
                     cnt ++;
                     Log.d("Thread", "Cycle " + Integer.toString(cnt));
                    }
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
            }

    });

    UI_thread.start();

LogCat:
07-30 14:19:34.082: E/dalvikvm-heap(22071): Out of memory on a 44049616-byte allocation. 07-30 14:19:34.102: A/libc(22071): Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 22071

A: When you call runOnUiThread(), the code isn't run immediately. It's just added as a request on the message queue of the display thread. So it will be executed "a little later", where the OS decides when "a little later" is.
The big problem is you're starting a background thread that uses runOnUiThread() to access the main thread which is fine, but once startActivity() is called the current UI thread is being destroyed. But

*

*setVisibility(View.INVISIBLE) is being queued/called

*the current UI thread is being "deleted"/"taken off the stack" because startActivity() is called

*you aren't calling finish() or returning to explicitly tell the system to end the activity NOW so the rest of the run() method is still being executed. This means the UI thread may still be busy and startActivity() will take effect "a little later".

My guess is the combination of those 3 items above is causing the UI thread to be accessed after the OS has started cleaning it up, hence the segfault i.e. a view is being referenced too late


text:
Q: Преобразовать число с запятой в число с точкой Из top получаю необходимое значение загрузки ЦП процессом, оно выдается в виде 10,0 (может быть и 1,6 к примеру) и может быть больше или меньше. Необходимо сравнить это значение с пороговым (статическим) и в случае превышения порогового выполнить действие.
Через bc что-то не выходит, но через него можно успешно сравнивать числа вида 10.0. Так что подойдет вариант замены "," на ".". Как это сделать?

A: программа top нормально локализована, и поэтому для правильного отображения т.н. «десятичной точки» (decimal point) использует текущую локаль.
у вас, скорее всего, используется локаль ru_RU.UTF-8.
посмотреть значение «десятичной точки» для какой-нибудь локали можно так:
$ LC_ALL=имя-локали locale -c decimal_point

например, для ru_RU.UTF-8 это будет запятая:
$ LC_ALL=ru_RU.UTF-8 locale -c decimal_point
LC_NUMERIC
,

а для специальной локали C (она же «умолчальная» «posix-овая» локаль) — точка:
$ LC_ALL=C locale -c decimal_point
LC_NUMERIC
.

резюме:
если вы будете запускать программу top с локалью C, т.е., не просто:
$ top опции-и-параметры

а
$ LC_ALL=C top опции-и-параметры

вы получите в выводе то, что вам требуется — точку в качестве разделителя целой и дробной части:
$ LC_ALL=C top -bn1 -p1 | tail -n 1
    1 root      20   0  2300  744  640 S   0.0  0.0   0:27.46 init

A: Bash умеет это сам:
$ a="10,32"
$ echo ${a/,/.}
10.32

A: Полагаю, можно попробовать с помощью sed 's/foo/bar/' - заменит foo на bar, в Вашем случае записать sed 's/,/./'


text:
Q: Getting an empty json entity and can't persist in runtime with Spring Boot I'm writing my first CRUD as Spring Boot application. Now I'm facing the problem that i somehow get an empty entity in my response array and also can't add another entity.
I have a classic MVC structure where I have a resource class which provides the resources for a frontend (GET and POST at the time), a service class (which actually just bypasses the data), a controller class which provides the objects and sets up a test object.
@RestController
@RequestMapping("/genesysAgents")
@Configuration
@ComponentScan(basePackageClasses = GenesysService.class)
public class GenesysAgentResource {

    @Autowired
    private GenesysService genesysService;

    @GetMapping
    public List<GenesysAgent> getAllGenesysAgents() { return genesysService.getAllGenesysAgents();}

    @PostMapping
    public ResponseEntity<?> addGenesysAgent(GenesysAgent genesysAgent) {
        genesysService.addGenesysAgent(genesysAgent);
        return new ResponseEntity<GenesysAgent>(genesysAgent, HttpStatus.CREATED);
    }

@Configuration
@ComponentScan(basePackageClasses = GenesysController.class)
public class GenesysService {

    @Autowired
    private GenesysController genesysController;

    private static final AtomicInteger id = new AtomicInteger(10);

    @Bean
    public List<GenesysAgent> getAllGenesysAgents() {
        return genesysController.getAgents();
    }

    @Bean
    public GenesysAgent addGenesysAgent(GenesysAgent genesysAgent) {
        genesysAgent.setId(id.getAndIncrement());
        genesysController.addAgent(genesysAgent);
        return genesysAgent;
    }

@Component
@Configuration
@ComponentScan(basePackageClasses = GenesysAgent.class)
public class GenesysController {

        List<GenesysAgent> genesysAgents = new ArrayList<GenesysAgent>();

        public GenesysController(){
        GenesysAgent agent1 = new GenesysAgent();
        agent1.setId(0);
        agent1.setFirstName("Max");
        agent1.setLastName("Muster");
        agent1.setNtAccount("testAccount");
        genesysAgents.add(agent1);
        }

    @Bean
    public List<GenesysAgent> getAgents(){
        return genesysAgents;
    }

    @Bean
    public GenesysAgent addAgent(GenesysAgent genesysAgent){
        genesysAgents.add(genesysAgent);

        return genesysAgent;
    }

When i now run the Application and do a GET i get:
[
    {
        "id": 0,
        "firstName": "Max",
        "lastName": "Muster",
        "ntAccount": "testAccount"
    },
    {
        "id": 10,
        "firstName": null,
        "lastName": null,
        "ntAccount": null
    }
]
I can't explain where the secound entry comes from.
Also wenn i do a POST with the following Data:
{
    "firstName": "Max",
    "lastName": "Muster",
    "ntAccount": "test"
}
I get a 201 but the response is:
{
    "id": 0,
    "firstName": null,
    "lastName": null,
    "ntAccount": null
}