text:
Q: Add CSS File To Layout Zend Framework I'm trying to add a css file in my zend application layout.php the problem is it resides in

/application/media/css/style.css

when i do
 <?php echo $this->headLink()->appendStylesheet('/media/css/style.css')  ?>

it generates the path like

appname/public/media/css/style.css

where as i need to generate the path like

appname/application/media/css/style.css

how can i tell zend to look for the css file at a apecific location in layout.php

A: I have solved the problem. Always is simple. :D
I added
<link rel="stylesheet" href="css/site.css" type="text/css" media="screen, projection">

in head tag. And css folder is in public folder.
thanks
ohm

A: Everything in application directory is not accessible via your web server you would either have to move the file to the public directory or setup a symlink to it.

A: Just to complete all the answers, is not "correct" put your CSS, JS, fonts, and all other media in 'application' folder.  The 'public' folder is there for that.
Then, to remove the '/public' from all your URLs, just make a simple change in your  .htaccess
RewriteEngine On
RewriteBase / # you could put some subfolder, if you need
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

And in your index.php
<?php

define('RUNNING_FROM_ROOT', true);
include 'public/index.php';

And then you could use this to append your styles
<?php echo $this->headLink()->appendStylesheet('/public/media/css/style.css')  ?>

Hope it helps.

A: You should use this code:
<link rel="stylesheet" type="text/css" media="screen" href="<?=$this->baseUrl();?>/yourpathtocss" />

A: I think the correct way is to do this from layout.phtml as follows
<?php echo $this->headLink()->appendStylesheet('/css/site.css') ?>

A: here 'TestZend' is Project name
<?php echo $this->headLink()->appendStylesheet('/TestZend/public/css/bootstrap.css'); ?>

A: Just add this code snippet in the layout  section to make sure the MEDIA folder is created inside yourProjectFoder/public/media/css/style.css
<head>
  // some code here...
  <?= $this->headLink()
    //added from the new template
    ->prependStylesheet($this->basePath('media/css/style.css'))

  ?>
  // some other code here
</head>


text:
Q: Fading away from curve using fillbetween library I have two paths defined that I would like to have filled and have fading. I want the fading to be 100% along some curve, and then fading as it gets further away from that curve. So specifying [top color, bottom color, etc] is not going to be sufficient here.
The following code produces the plot below, but I want red!50 to be along the log(x) curve.
Any idea how to achieve this?
\documentclass{standalone}

\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}

\begin{document}
\begin{tikzpicture}

  \begin{axis}[xmin=1, xmax=10, ymin=0, ymax=1]
    \addplot[red, domain=1:10, name path=constraint] {log10(x)};
    \path[name path=edge] (axis cs:1,1) -- (axis cs:10,1);
    \addplot [bottom color=red!50, top color=white]
      fill between [of=edge and constraint];
  \end{axis}

\end{tikzpicture}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Attribute Error when running script: type object 'BaseCommand' has no attribute 'option_list' I saw this post on how to run a python script from django:  http://www.djangotutsme.com/how-to-run-python-script-from-django/
I tried the example but get the following error when running python manage.py runscript myscript.
I have Python 2.7, Django 1.10 and django extensions 1.6.1 installed.
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/lib/python2.7/site-packages/Django-1.10.dev20151201151517-py2.7.egg/django/core/management/__init__.py", line 349, in execute_from_command_line
    utility.execute()
  File "/usr/lib/python2.7/site-packages/Django-1.10.dev20151201151517-py2.7.egg/django/core/management/__init__.py", line 341, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/lib/python2.7/site-packages/Django-1.10.dev20151201151517-py2.7.egg/django/core/management/__init__.py", line 193, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/usr/lib/python2.7/site-packages/Django-1.10.dev20151201151517-py2.7.egg/django/core/management/__init__.py", line 40, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/usr/lib/python2.7/site-packages/django_extensions-1.6.1-py2.7.egg/django_extensions/management/commands/runscript.py", line 6, in <module>
    from django_extensions.management.email_notifications import \
  File "/usr/lib/python2.7/site-packages/django_extensions-1.6.1-py2.7.egg/django_extensions/management/email_notifications.py", line 10, in <module>
    class EmailNotificationCommand(BaseCommand):
  File "/usr/lib/python2.7/site-packages/django_extensions-1.6.1-py2.7.egg/django_extensions/management/email_notifications.py", line 49, in EmailNotificationCommand
    **option_list = BaseCommand.option_list + (
AttributeError: type object 'BaseCommand' has no attribute 'option_list'**

Any idea what the problem is?  Is this a bug in django?

A: BaseCommand.option_list is deprecated in Django 1.8 and removed in Django 1.10. It looks like Django-extensions has been updated, but there hasn't been a new release since then.
You could try installing django-extensions from the master branch, but it would be a better idea to use the latest release of Django, currently 1.9.2.
Django 1.10 has not been released yet, and is still under development.


text:
Q: GWT Widget does not allow long-touch-to-copy selections We're developing a mobile application using GWT and are facing the following problem:
iPhone offer a long touch function to do copy&paste for all kinds of stuff. But when we're using the HTML widget or another widget that has explicit ClickHandlers, those events are not forwarded. This even occurs, when there is no clickhandler defined.
How can we monitor long touches (since there is no click/touchup, the onclick method is not being triggered) and how can we prevent the prevention of such events?
There seems to be no method for removing all events on a widget.

A: We found many more problems with GWT on mobile platforms - basically performance issues with long tables or large contents which made us sit down, think about it and finally throw the stuff away.
We've now developed a native client for Android and iOS - which took in turn about the same time for development as an optimized pseudo-single-html-all-in-all-solution.


text:
Q: Struck in foreach while looping around GridViewRow 'System.Web.UI.WebControls.GridView' does not contain a public definition for 'GetEnumerator' Foreach statement cannot operate on variables of type System.Web.UI.WebControls.GridView because

'System.Web.UI.WebControls.GridView' does not contain a public
  definition for 'GetEnumerator'

I don't know why it is appearing. I've google it too but didn't get enough help.
Here is my code
HyperLink A;
foreach (GridView row in GridView2)
{
    A=(HyperLink)row.FindControl("hyp");
    A.NavigateUrl += A.Text;
}

Points about Code
I've a GridView where i'm showing some hyperlinks when user click on a link it will take him to the desired location through query string

A: Use GridView2.Rows instead of GridView.

 foreach (GridViewRow row in GridView2.Rows)
     {
         A=(HyperLink)row.FindControl("hyp");
         A.NavigateUrl += A.Text;
     }

A: GridView2 is not a collection. foreach work only for Collections that implement IEnumerable or IEnumerable<T>. In your case you want to iterate over GridView2.Rows and not GridView2. So your foreach shoulb be like
         foreach (GridViewRow row in GridView2.Rows)
         {
             A=(HyperLink)row.FindControl("hyp");
            A.NavigateUrl += A.Text;
         }


text:
Q: NancyFx - this.Context.EnableOutputCache - Does the cache check include headers? I can't find any documentation for NancyFx's EnableOutputCache. There is a demo of using it here at the nancy repository.
I would like to know if just the url is checked in the cache check or if headers (particularly the Authorization Header) is checked because I would only like to cache on a per user basis and the user is obtained from the token in the authorization header.


text:
Q: Queries in IFD environment We are migrating our applications from on-premise to IFD.  We have some webpages that creates some kind of queries to the CRM Views (ie Select * from account). These queries work well in on-premise environment but when we run on IFD environment we have this exeception

Login failed for user 'NT AUTHORITY\IUSR'.

How can we do this in IFD, being sure that the query returns only the rows the user has permission?

A: when moving over from on premise you have to start "impersonating" users as you are not working on active directory anymore...
first of all you should NEVER be using the account table, you should be using the filteredaccount views as this is the supported way.


text:
Q: Difference between "Identity providers" and "authentication providers" I don't get the difference between the User Pools > Identity providers and
Federated Identities > Authentication providers.
Can someone explain?

A: Identity pools (Federated identities) allow you to grant users authenticated by third parties (e.g. login with Google) temporary IAM credentials to use you AWS resources in a limited way. Identity pools are free of cost and you only pay for the resources your users use via the IAM credentials.
User pools allow you to store your own users, they can sign up directly to the user pool and not have to use a third party provider like Google or Facebook. Confusingly user pools also have a 'federation' option (Identity providers) but this will actually create externally federated users in the pool. User pools provide OpenID tokens (access, id, refresh), not IAM credentials, which you can use with your own endpoints (ec2, fargate, api-gateway). User pools have costs associated with them based on the active users per month.


text:
Q: The meaning of "EiC" It appears that I am unable to find what "EiC" stands for.
It has been used as an interpreter, semantic front end IDE similar to "Clang", but a little bit older.
What is the meaning of it and why can I not find any reference to it?

A: EiC - Extensible Inteactive C ia a free, pointer-safe, bytecode C interpreter, which has three main modes of operations:

*

*Interactive Mode - via immediate statements

*Non - Interactive Mode

*Scripting Mode - for running shell scripts

Each mode uses the C programming language, it provides a seamless way of moving from one programming task to another.
EiC has its own built in ISO C preprocessor and its own internal set of house keeping commands.
EiC is an aid in teaching C for fast prototype of new programs and as a research tool. It allows the user to quickly interface and call compiled C routines, experiment with user supplied code, standard ISO C and POSIX.1 functions, and all via immediate statements, which are statements that are executed immediately.

A: EiC stands for Extensible, Interactive C-interpreter. It is a complete and clean ANSI-C Interpreter.
It is a very fast interpreter, has its own stack machine inside, but it depends on UNIX (POSIX headers).
Description

EiC is the original work of Edmond J. Breen, and
   contributors.
EiC hasn't been available from its erstwhile SourceForge home since at
   least 2005. It perhaps hasn't been developed actively since a few
   years earlier.

Links
Until 2005, EiC was an open-source project hosted at sourceforge. This project link no longer appears active.
It is also on Github.
License
The EiC package is made available under the the provisions of the original Artistic license grant by EiC's original author Edmond J. Breen. This license allows the package to be redistributed with improvements.
All Linux Box changes to EiC from its 4.3.3 version may be considered to be in the public domain.
Copyright

(C) Copyright May 7 1995, Edmond J. Breen. Changes (C) Linux Box Corporation, 2008.

Authors

Edmond J. Breen

Sources
detlefreimers
compilers.iecc.com
linuxbox.com (You can also get a source bundle from here)


text:
Q: Printing HTML: Can't place DIVs on page 2 I am building a HTML page specifically for printing. I want to place text boxes (DIVs) on the printed report exactly where the customer wants them.
Challenge:

*

*My HTML needs to print 2 pages.

*Each page needs to contain a box one inch from the left and one inch from the top. The box should be 1 inch wide and 1 inch high.

Sounds easy, right?
I came up with the following HTML code, but it contains a problem.
On page 2, the box is printed just a tiny bit higher than on page 1. You can spot the problem int the print preview. The problem appears in every browser I tried... so I can't even blame the browser!
Any ideas?
This is my attempt:
<!DOCTYPE html>

this box is placed properly.

this box is just a bit too high!

A: There is default margin on body, in my browser it is 8px so you should change it to:
body {
    margin: 0px;
}

The top position is now the same, but my browser shown an extra page at the end, you can do some trick to get rid of it:
.page {
    border: 1px solid transparent;
}

See also: HTML default body margin, how to avoid extra blank page at end while printing?


text:
Q: How to count words on each line of input in C Im trying to make a program so it counts the words on each line.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_LINES 50

int main()
{
char text[NUM_LINES];
int count = 0;
int nw = 0;
char *token;
char *space = " ";
printf("Enter the text:\n");

while (fgets(text, NUM_LINES, stdin)){

    token = strtok(text, space);

    while (token != NULL){

        if (strlen(token) > 0){
            ++nw;
        }
        token = strtok(NULL, space);
    }

    if (strcmp(text , "e") == 0 || strcmp(text , "e\n") == 0){
        break;
    }

}
printf("%d words", nw-1);

return 0;
}

For example if the input is:
Hello my name is John
I would like to have a snack
I like to play tennis
e

My program outputs the total words (17 in this case) how do I count the words on each line individually. So the output I would want is "5 7 5" in this example.

A:
How do I count the words on each line individually?

Simply add a local counter line_word_count.
Suggest expanding the delimiter list to cope with spaces after the last word.
char *space = " \r\n";

while (fgets(text, NUM_LINES, stdin)){
    int line_word_count = 0;
    token = strtok(text, space);
    while (token != NULL){
        if (strlen(token) > 0){
            line_word_count++;
        }
        token = strtok(NULL, space);
    }
    if (strcmp(text , "e") == 0 || strcmp(text , "e\n") == 0){
        break;
    }
    printf("%d ", line_word_count);
    nw += line_word_count;
}
printf("\n%d words\n", nw);


text:
Q: PyQt5. textBrowser.append не работает при вызове во второстепенном потоке from PyQt5 import QtWidgets, QtCore
from mydesign import Ui_MainWindow
import sys
from time import sleep
from threading import Thread
import datetime
from PyQt5.QtCore import QRunnable, QThreadPool

class Runnable(QRunnable):
    def __init__(self, this):
        super().__init__()
        self.this = this

    def run(self):
        while not self.this.isClosed:
            sleep(1)
            ctime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.this.ui.textBrowser.append(ctime)  # <-- Error!

class mywindow(QtWidgets.QMainWindow):

    def __init__(self):
        super(mywindow, self).__init__()
        self.this = self
        self.isClosed = False
        self.setWindowOpacity(0.95)
        self.bt_count = 0
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(
            self.button_evt
        )
        self.runTasks()  # <-- Error!

    def button_evt(self):
        self.ui.textBrowser.setText(
            "Вы нажали на кнопку %d раз(а)" % self.bt_count)
        self.bt_count += 1

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_End:
            self.close()
        exit()

    def thread(self):
        self.t1 = Thread(target=self.Operation, daemon=True)
        self.t1.start()

    def runTasks(self):
        pool = QThreadPool.globalInstance()
        runnable = Runnable(self)
        pool.start(runnable)

    def event(self, event):

        if event.type() == QtCore.QEvent.Close:
            print(f"Oкно закрытo (QCloseEvent).")
            self.isClosed = True
        return QtWidgets.QWidget.event(self, event)

app = QtWidgets.QApplication([])
application = mywindow()
application.show()
sys.exit(app.exec())

Вывод:

Вываливаются непредсказуемые ошибки.
Так как все-таки вызвать textBrowser.append в другом потоке?

A: *

*НЕЛЬЗЯ взаимодействовать с виджетами в дополнительном потоке.
Сигналы и слоты используются для связи между объектами.
Механизм сигналов и слотов - центральная особенность Qt и, вероятно,
часть, которая больше всего отличается от функций, предоставляемых другими фреймворками.
Больше https://doc.qt.io/qt-5/signalsandslots.html

*Нет необходимости использовать дополнительные библиотеки
(time, threading, datetime).
Вот вам одно из возможных решений:
import sys
#from time import sleep
#from threading import Thread
#import datetime

from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.Qt import *
# ? from mydesign import Ui_MainWindow

class WorkThread(QThread):
    threadSignal = pyqtSignal(str)

    def __init__(self):
        super().__init__()

    def run(self, *args, **kwargs):
        while True:
            self.msleep(1000)
#            ctime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ctime = QDateTime.currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
            self.threadSignal.emit(ctime)

class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.bt_count = 0
        self.setWindowOpacity(0.95)

        self.centralWidget = QtWidgets.QWidget()
        self.setCentralWidget(self.centralWidget)

        self.textBrowser = QTextBrowser()
        self.pushButton = QPushButton('Button')
        self.pushButton.clicked.connect(self.button_evt)

        self.layout = QtWidgets.QGridLayout(self.centralWidget)
        self.layout.addWidget(self.textBrowser)
        self.layout.addWidget(self.pushButton)

        self.runTasks()

    def button_evt(self):
        self.bt_count += 1
        self.textBrowser.setText(
            "Вы нажали на кнопку %d раз(а)" % self.bt_count)

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_End:
            self.close()
#        exit()

    def runTasks(self):
        self.thread = WorkThread()
        self.thread.threadSignal.connect(self.on_threadSignal)
        self.thread.start()

    def on_threadSignal(self, ctime):
        self.textBrowser.append(ctime)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    application = MyWindow()
    application.show()
    sys.exit(app.exec_())

A: Почитайте:
realpython.com/python-pyqt-qthread
stackoverflow.com/questions/6783194/background-thread-with-qthread-in-pyqt


text:
Q: Why does every single Pokemon run away? Or, what is a soft ban? No matter what, every single Pokemon that I try to catch runs away from me! I can't spin any Pokestops, and I can't fight any gyms!
I've heard about something called a soft ban. Is that what's happening to me?

A: Yes, you are probably soft banned.
Soft banning occurs when the game detects that you're moving around too quickly. This can happen if:

*

*You use GPS spoofing to fake your current location.

*You travel in a vehicle at an excessive speed.

*You disable your GPS, travel a significant distance, then re-enable it.

*You lose data service, travel a significant distance, then re-connect.

The following are symptoms of a soft ban:

*

*When you throw a Pokeball at a Pokemon, it wiggles around a bit, then flees without fail.

*When you try and spin a Pokestop, it never turns purple, and you never get any items.

*You are unable to challenge or train at any gyms.

If you are soft banned, the ban will lift itself within a few hours.
Here's a video of what a soft ban looks like:

Currently, there is speculation that the soft ban mechanism functions similarly to the "bubble effect" in Ingress, the last ARG developed by Niantic. This effect is explained here:

No matter what speed you are traveling, you can perform an action as long as you haven't performed one in the last 15 minutes. Once you perform an action, a figurative "bubble" is created. This bubble expands at the rate of 60 km/h. If you travel out of this bubble, you will not be able to successfully perform actions. So, once you slow down, you have to wait for the bubble to catch up with you before you can perform actions again. After 15 minutes, the bubble goes away, and you can perform actions again even if the bubble hadn't caught up to you yet.

(For US readers, 60 km/h is approximately 37 mph.)


text:
Q: Cannot use layout_alignParentTop among others in autocomplete I am wanting to use autocomplete in android studio but it does not work for all code options. I cannot get autocomplete for TextView.setText, for layout_alignParentTop and a lot of other things. I looked at other questions but their's is only for xml tab. Mine is for the whole project.
With the text I am typing, before I finish typing it I get a red error:
missing value validates resource references inside android xml files
If you see the image there is no option for android:layout_alignParentTop

A: It depends on the view group you are using. The layout parameter you're intending to use belongs to a specific view group hence autocomplete isn't showing you that option.
I recommend reading on View Groups and Layout Parameters
Your text view has to be inside the relative layout group like so
<RelativeLayout
    //codes >
   <TexView
       android:layout_ //you should already see suggestions here />
</RelativeLayout>


text:
Q: String manipulation in SQL Server-- adding placeholder characters I'm a little green when it comes to SQL Server string manipulation functions.  If I have a string with six characters in it, say:
DECLARE @p_MyStringVariable VARCHAR (100)
SET @p_MyStringVariable = 'FANFFF'

And I want to insert, say, the letter 'M' in the first and seventh positions of the final string and assign that to another VARCHAR variable to read 'MFANFFMF', how can I best do that?  And am I correct in reading that SQL Server strings are indexed starting from one, instead of zero?  I'm thinking of the SUBSTRING() function, for instance.
(Note that some strings will be up to 100 characters in length, thus the VARCHAR(100) declaration above, even for a six-character string)
Thanks much for your help.

A: You could also take a look at the STUFF function.
SELECT STUFF(STUFF(@p_MyStringVariable,1,0,'M'),7,0,'M')

A: Yes, SQL Server indexes varchar etc columns starting at one.
To insert at specfic points, use STUFF (and see Joes's answer for examples)


text:
Q: Can I use "Stop" as subroutine name in VB? I'd like to create an object... say a "Movie" object. The object should have a method name "Stop", so I can have this code below
dim Mov as new Movie
Mov.Stop ' To execute the Stop method.

In my Movie class, I should have something like this.
Sub Stop()
'code here needed for the Stop subroutine
End Sub

However, I can't use "Stop" as name as this is a reserved word. I see a VB code that has "Stop" as one of the method. Unfortunately, the code is protected so I can't view it.
How can I name a subroutine as "Stop"?

A: It might work if you created a typelib with Stop and your other methods and properties and then use Implements in your class.  I haven't tested this though.
Update:
See Tutorial: Using Reserved Words as VB6 Class Member Names

A: Stop is a statement used to break the app when debugging (same as setting a breakpoint) so choose another name.

A: Stop is a keyword in Vb6.
You will have to rename your method to something different.
Say MovieStop

A: try this:
Sub [Stop]()
   ' code
end sub


text:
Q: PCA: How to get the vector that points to the origin of the new coordinate system? The PCA projects the original data points into a new coordinate system and I would like to determine the vector that connects the origin of the old coordinate system with the origin of the new coordinate system in R.
This is what I have coded so far:
data <- data.frame(cbind(c(5,15,21,29,31,43,49,51,61,65),
c(33,35,24,21,27,16,18,10,4,12)))

# Subtract columns by their mean and
# divide with their standard deviation
scaled_data <- scale(data, center=TRUE, scale=TRUE)
scaled_data
plot(scaled_data)

# Correlation Matrix
corrmat <- cor(scaled_data)
corrmat

# Compute Eigenvalues and Eigenvectors
eigen <- eigen(corrmat)

eigenvectors <- eigen$vectors
eigenvectors

eigenvalues <- eigen$values
eigenvalues

# Transform data
transformed_data <- (data.matrix(scaled_data) %*% eigenvectors)*sqrt(2)
transformed_data

plot(transformed_data)

A: The origin of the new coordinate system is the barycenter (a.k.a. center of mass) of your data set:
colMeans(data)
# X1 X2
# 37 20


text:
Q: .htaccess changes to move site to SSL/https Those are the lines of concern currently in my .htaccess file,
note that i have two domains pointing to the same site:
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule .* http://www.example.com/ [L,R]

RewriteCond %{HTTP_HOST} ^example2\.com$ [NC]
RewriteRule .* http://www.example.com/ [L,R=301]

RewriteCond %{HTTP_HOST} ^www\.example2\.com$ [NC]
RewriteRule .* http://www.example.com/ [L,R=301]

Now I need to convert my site to SSL, I was instructed to use the following
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

I think that this code misses my other domain and the www rewrite part,
how to enable SSL while accounting for my other domain and also for the WWW part?

A: You can use:
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^example\.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^(www.)?example2\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,L,R=301]


text:
Q: What happens when you use foreach loop on a 2D array int[][] winningPositions =
{{0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}};

    for (int[] winningPosition : winningPositions)
    System.out.println(winningPosition[2]);

this prints
2
5
8
6
7
8
8
6
I dont understand why, this is so random, what is the foreach loop trying to do ? why is it not printing the third set of arrays {6,7,8} ?
how does this work ?

A: Your for each loop is Actually printing the third element of each winningPosition array inside 2D array winningPositions:
{{0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}}

this statement winningPosition[2] will get each third element of the inner array in the 2D array winningPositions.
also you can break down for each loop to understand it well :
in the first iteration of for each loop it will get the first element of winningPositions:
{0,1,2}

then this statement winningPosition[2] will get the third element in this sub array which is 2
in the second iteration of for each loop it will get the second element of winningPositions:
{3,4,5}

after that winningPosition[2] will get the third element in this sub array which is 5and so on.
it's much like getting winningPositions[1][2] in the traditional for loop.
Update:

why is it not printing the third set of arrays {6,7,8} ?

I understand from your question that you want to print the third sub array of the 2D array winningPositions.
to print it you don't need any for each loop
you can simply use method Arrays.toString to print it:
System.out.println(Arrays.toString(winningPositions[2]));

output:
[6, 7, 8]

A: int[][] winningPositions =
            {{0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8},
{2,4,6}};

                for (int[] winningPosition : winningPositions){
                    for(int i = 0; i < winningPosition.length; i ++){
                        System.out.println(winningPosition[i]);
                   }
               }

Image having a drawer that have 1 note each in it. The note has x on top, in the middle y, and on the bottom z. With your loop you open every drawer and look at the third line of every note. Printing only z.
For each time you open the drawer you need to look at all the lines. So that you can for every line of the note print the contents. winningPosition.length is how many lines on that note there is.
Look up nested loops.

A: Your for loop is going though each array and prints after it's done the integer it has in it's memory out. Since you typed:
for (int[] winningPosition : winningPositions)

You are asking to get int[] out of winningPositions. And so after it puts the 3 integers in such an array, it has the last integer in it's memory of the array he just configured. that's why it's only printing out the last integer of the array.
if you wanna print out all of the original winningPositions, do:
for (int winningPosition : winningPosition)

if you wanna print out a specific number of each array in the original winningPosition, do:
for (int[] winningPosition : winningPosition)
    System.out.println(winningPosition[x];

X is the index spot of the integer you wanna print out. (the first index number of an array is always 0.)
You can also use the last method I said to continue a selection you originally wanted to do. (By for example using another for loop to go through the int[] winningPosition you created in the previous for loop.)
Hope this helps you!

A: Iam providing something similar i am building at the moment.... this is printing all numbers and seperate arrays with new line and numbers with [], play a bit with the code and you will be able to print what you like...
public class ArrayFinal {

public static void main(String[] args) {

    System.out.println("Array\t Nummbers");
    int Array[][] = { { 2, 43, 23, 43, 23, 43 }, { 3, 5, 6, 7, 6, 5 }, { 34, 42, 44, 24, 6, 7 },
            { 2, 34, 54, 332, 23, 43 }, { 2, 43, 45, 54, 34, 34 }, { 2, 34, 54, 54, 34, 23 } };

    display(Array);

}

// methodos gia na dimiourgisoume to rows kai ta columns
public static void display(int x[][]) {

    for (int row = 0; row < x.length; row++) {

        StringBuilder str_buf = new StringBuilder();
        str_buf.append((row + 1) + ".");
        for (int column = 0; column < x[row].length; column++) {

            str_buf.append("\t" + "[" + x[row][column] + "]");// tiponi ta noumera pou vriskonte mesa stin klirosi

        }
        System.out.println(str_buf.toString());// tiponi to noumero tis klirosis

    }
}

}
results:
1.  [2] [43] [23] [43] [23] [43]
2.  [3] [5] [6] [7] [6] [5]
3.  [34] [42] [44] [24] [6] [7]
4.  [2] [34] [54] [332] [23] [43]
5.  [2] [43] [45] [54]  [34] [34]
6.  [2] [34] [54] [54]  [34] [23]

iam new in java and since this post is active it would be great if someone can show me the way to displayOccurances from those arrays, i have tried almost everything....


text:
Q: Exclude duplicate lines from two different files and generate new? I have few wordlist files which is based on word per line.
Now, i want to generate new file, that should be:
compared first and second file and putting words from second file, that are not found in first, putting them in third file.
File_1

word1
word2
word3
word4
word5

File_2

word1
word3
word5
word7
word9

I tried few things:
cat file.1 file.2 | sort -n | uniq -u | cat > file.3

But i get:
File_3

word2
word4
word7
word9

Also i tried:
cat file.1 file.2 | sort -n | uniq -d | cat > file.3

but again I get:
File_3

word1
word3
word5

I tried also with ECHO
echo $(cat file.{1,2} | sort -n | uniq -u) > file.3

But i get same words, and what is worst it prints all at one line.
The final File_3 should contain:

word7
word9

Beacause these words are not found in first file.
Any idea how to accomplish this?

A: Try this.
grep -F -x -v -f file.1 file.2 >file.3

A: If your file is not big you can basically cat first file twice:
cat file.1 file.1 file.2 | sort -n | uniq -u | cat > file.3

but this is expensive for big files.
or using grep you can achieve this (thanks to @tripleee):
grep -F -x -v -f file.1 file.2 > file.3

A: Maybe use awk:
$ awk 'NR==FNR{a[$0];next}!($0 in a)' file_1 file_2 > file_3
$ cat file_3
word7
word9

A: You can use the comm program to do this:
comm -13 <(sort file_1) <(sort file_2)


text:
Q: Byte Buddy - java.lang.NoClassDefFoundError: javax/servlet/ServletRequest I am trying to instrument service method of javax.servlet.Servlet interface implementations as following:
.transform(
                        new AgentBuilder.Transformer.ForAdvice()
                                .include(MyAgent.class.getClassLoader())
                                .advice(
                                        named("service")
                                                .and(takesArgument(0, ServletRequest.class))
                                                .and(takesArgument(1, ServletResponse.class))
                                        , "com.MyAdvice"
                                )
                )

Now, if I attach this agent to an already running Spring boot application via agentmain - I see below exception on trying to access any web page
java.lang.LinkageError: loader constraint violation: when resolving method 'void javax.servlet.http.HttpServletRequestWrapper.<init>(javax.servlet.http.HttpServletRequest)'
the class loader org.springframework.boot.loader.LaunchedURLClassLoader @18be83e4 of the current class,
org/springframework/web/servlet/resource/ResourceUrlEncodingFilter$ResourceUrlEncodingRequestWrapper, and the class loader 'app' for the method's defining class, javax/servlet/http/HttpServletRequestWrapper,
have different Class objects for the type javax/servlet/http/HttpServletRequest used in the signature (org.springframework.web.servlet.resource.ResourceUrlEncodingFilter$ResourceUrlEncodingRequestWrapper is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @18be83e4, parent loader 'app'; javax.servlet.http.HttpServletRequestWrapper is in unnamed module of loader 'app')

I understand its because javax/servlet/http/HttpServletRequest instance is loaded from 2 different jars - one that came through agent and another through spring boot embedded tomcat. If I try to set scope as provided in agent's pom.xml [ since I do not want to include servlet-api in agent bundled jar and try use already provided servlet-api implementation from Spring boot ], I get Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletRequest - possibly because the classloader loading the agent can't see spring boot provided servlet api.
Is there any possible workaround or fix to resolve this situation? Thank you for your time and feedback.

A: Ideally, your agent does not contain such classes. Rather, match classes by their name: takesArgument(0, named("javax.servlet.ServletRequest")), for instance.


text:
Q: Is it possible to disable opening a new tab or window in browser using JavaScript? My application is online testing. When user clicks the browser button, it goes to directly to my online exam page. User should not be able to open a new tab or window in the browser. Is it possible to disable a new tab or window in the browser using JavaScirpt?

A: No, it's not possible. If it was possible, it could be easily abused by malicious sites, and wouldn't really solve your problem—someone could use another device, for example their phone.


text:
Q: Kernel panic libcryptsetup.so.12 missing, once upgrading to 18.04 I selected OS upgrade from 17.10 to 18.04 LTS. Update encountered error and reported that system might be unstable. After trying to reboot I get kernel panic complaining about missing libcryptsetup.so.12.
The issue here is I don't know how to access my home folder using live CD (home folder is in LVM volume which is crypted) -or is it even possible... I can see the uncrypted volume in /dev/mapper (after cryptsetup luksOpen )and mount it, but the home folder is empty (except .Private and that stuff). 18.04 doesn't have ecryptfs-recover-private like previous releases, if I boot using liveCD 17.10 and try to use  ecryptfs-recover-private nothing happens, expect permission denied messages while access gvfs files. Please any idea how to fix this?
Regards,
J


text:
Q: How execute expl3 commands inside lua code When I try execute expl3 commands inside Lua code, I get an error:
! Undefined control sequence.
\\  ->\let \reserved@e
                       \relax \let \reserved@f \relax \@ifstar {\let \reserv...

l.13 \test{1}

Yes, I know, what the example below possible write using fully expl3 functions, but I have some code, which save some data in Lua, so I need in example, how to execute expl3 code in Lua. Help me please that my example work in Lua. The second question, how I can in \directlua use space instead of ~, because ~ used in Lua too.
\documentclass{article}
\usepackage{expl3}
\ExplSyntaxOn
\prop_gset_from_keyval:Nn \g__my_prop
  { value0 = -1 , value1 = 0 }
\cs_new_eq:NN \PropRemovecn \prop_remove:cn
\ExplSyntaxOff
\newcommand{\test}[1]{%
  \directlua{%
    if #1==1 then
      tex.print("\\PropRemovecn{g__my_prop}{value1}")
    end
  }}
\begin{document}
\test{1}
\end{document}

A: Your error comes from \directlua trying to expand \\. You get the same error from \edef\x{\\} (in LaTeX versions older than 2020-02-02). You need to make sure that \\ becomes two character tokens before the Lua interpreter kicks in. You can use either \string\\prop... or \luaescapestring{\prop...} (or, more expl3-y, \lua_escape:e).
Also, different from expanding a macro, whose replacement text is already tokenized, when you do tex.print it is as if you typed those tokens in the input file, at the time \directlua is expanded. Since you use your \test command outside of an expl3 code context, _ and : are not letters, so \prop_remove:cn is misinterpreted as \prop _remove:cn. As if you were typing the code yourself, you have to use \ExplSyntaxOn/Off:
tex.print("\luaescapestring{\\ExplSyntaxOn\\prop_remove:cn{g__my_prop}{value1}\\ExplSyntaxOff}")

However this has some overhead, and if you happened to use \test in the middle of some expl3 code, then it would recklessly do \ExplSyntaxOff without you wanting it to. I recommend defining an interface for \prop_remove:cn:
\documentclass{article}
\usepackage{expl3}
\ExplSyntaxOn
\prop_gset_from_keyval:Nn \g__my_prop
  { value0 = -1 , value1 = 0 }
\cs_new_eq:NN \PropRemovecn \prop_remove:cn
\ExplSyntaxOff
\newcommand{\test}[1]{%
  \directlua{%
    if #1==1 then
      tex.print("\luaescapestring{\PropRemovecn{g__my_prop}{value1}}")
    end
  }}
\begin{document}
\test{1}
\end{document}

You can also pass a catcode table to tex.print as Ulrike suggested, then LuaTeX will print the tokens with that catcode setting. If you load l3cctab then you can use \int_use:N \c_code_cctab (the code definition has to be inside \ExplSyntaxOn/Off, in this case):
\documentclass{article}
\usepackage{expl3}
\usepackage{l3cctab}
\ExplSyntaxOn
\prop_gset_from_keyval:Nn \g__my_prop
  { value0 = -1 , value1 = 0 }
\cs_new_eq:NN \PropRemovecn \prop_remove:cn
\newcommand{\test}[1]{%
  \lua_now:e {%
    if~#1==1~then~
      tex.print(\int_use:N \c_code_cctab,
        "\lua_escape:e {\prop_remove:cn{g__my_prop}{value1}}")
    end
  }}
\ExplSyntaxOff
\begin{document}
\test{1}
\end{document}

As for your second question: if you need lots of spaces, define the command outside of the expl3 code environment (the fact that it's in \directlua doesn't matter, as the tokenization rules still apply when you define the \test macro).


text:
Q: Difference between Fourier Space and Real-Space coordinates from a image? I'm writing a code in Python about phase unwrapping with noise regard a paper published. I have a raw data phase for interferometry [-pi,pi] and I want to unwrap this, but I look data and it has noise in some points.
My trouble with this FFT is I'm very confuse with the difference between (x,y) coordinates from original image and (p,q) coordinates from Fourier Transform (Look the image that I include).
When I make a Fourier transform to a image, the pixel coordinates change?
Besides, for the position (0,0) in
Fourier coordinates, I will have a 0 as result. How I can handle the zero division?
This is the algorithm:

PS: The paper that I get the algorithm is this: https://sci-hub.se/https://doi.org/10.1364/OL.28.001194

A: The coordinates p and q can be obtained through numpy.fft.fftfreq if FFT(f(x,y)) is obtained through np.fft.fft.
I'd have to read the paper to make sure I understand their definition of p and q. Here I assume they are integer values (because of how they are used, I think this is correct, but I might be wrong!). I'm also assuming that N is the size of the image f(x,y) along both axes. If these assumptions are correct, then you need to set
f = np.fft.fftfreq(N, 1/N)
p = f[:,None]
q = f[None,:]

(The indexing operations to obtain p and q there create 2D arrays where the values run along the one row or one column, respectively.)
Now Broadcasting then allows the operations to produce the right results:
tmp = (p**2 + q**2) * np.fft.fft2(f)
out = -(2 * np.pi / N)**2 * np.fft.ifft2(tmp)

(and similarly for the 2nd expression.)


text:
Q: Select the last record in MySQL in WHERE condition I have a table that store ticket and statue relation
ticketstatus_Id ticket_Id status_Id
===================================
1                1          1
2                1          2
3                1          3
4                2          1
5                2          2   *
6                3          1
7                4          1
8                3          2   *

I want to select rows that last status_Id equal 2 ,Rows are marked in table.
 I think I have to use GROUP BY on column ticket_Id but it return with first status_Id.

A: This problem is a good candidate for ROW_NUMBER:
WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ticket_Id ORDER BY ticketstatus_Id DESC) rn
    FROM yourTable
)

SELECT ticketstatus_Id, ticket_Id, status_Id
FROM cte
WHERE rn = 1 AND status_Id = 2;

The above logic finds all latest rows for each ticket_Id, as ordered by the ticketstatus_Id, whose status_Id values also happens to be 2.

A: All records with status_Id= '2'
Select * from TABLENAME where status_Id = '2'

Last record with status_Id= '2'
Select * from TABLENAME where status_Id = '2' order by  ticketstatus_Id  desc limit 1

A: SELECT * from TABLENAME where status_Id = '2' ORDER BY  ticketstatus_Id DESC LIMIT 1;

A: You can do this with group by and a having clause:
select ticket_Id, max(ticketstatus_Id)
from ticketstatuses
group by ticket_id
having max(ticketstatus_Id) = max(case when status_id = 2 then ticketstatus_Id end);

It would be interesting to know if this has better performance than the row_number() version.  However, for performance, this is probably best:
select ts.*
from ticketstatuses ts
where ts.ticketstatus_Id = (select max(ts2.ticketstatus_Id)
                            from ticketstatus ts2
                            where ts2.ticket_id = ts.ticket_id
                           ) and
      ts.status_id = 2;

This can take advantage of an index on (ticket_id, ticketstatus_id).


text:
Q: Relation between net.inet.tcp.recvspace, SO_RCVBUF, Direct ByteBuf and ByteBufAllocator in Netty Can someone quickly explain how Netty/NIO consumes TCP buffers from OS?
I reckon the TCP sliding window ACKs are managed by OS TCP stack (recvspace) and are sent back after each packet (MTU size) till the recvspace is full.
Then after NIO selector triggers a receive event, NIO (in direct buf mode) creates a direct buffer pointing to the same memory area and marks it as read? Or does it copy from recvspace into another buffer?
If this is the case, then what's each application's SO_RCVBUF? Is it relevant at all?
My goal is to read from then next buffer (and hence send new ACKs to read more) only after fully consuming the buffer.

A:
I reckon the TCP sliding window ACKs are managed by OS TCP stack (recvspace) and are sent back after each packet (MTU size) till the recvspace is full.

Correct. This happens from the socket receive buffer, which is in the kernel.

Then after NIO selector triggers a receive event, NIO (in direct buf mode) creates a direct buffer

Not necessarily. I don't see a reason for it to be a direct buffer.

pointing to the same memory area

No. It is in the application space.

and marks it as read?

No.

Or does it copy from recvspace into another buffer?

Correct. It reads, by calling ReadableByteChannel.read(), which ultimately calls recv(), which copies data out of the socket receive buffer into application memory.

If this is the case, then what's each application's SO_RCVBUF? Is it relevant at all?

It's the first thing mentioned above.


text:
Q: Mongoose - Consultas con OR y AND Estoy tratando de hacer una query en mongoose y no se me ocurre muy bien como armarla.
En SQL sería algo asi:
SELECT * FROM MATERIAS
WHERE
     activo = true AND
     nivel = $nivel_id AND
    (alldisc = true OR disciplina = $disciplina_id)

siendo $nivel_id y $disciplina_id variables.
Esto mismo lo estoy escribiendo en nodejs y mongoose y no se me ocurre bien como hacerlo.
Lo que he hecho hasta ahora es:
function getMateriasFilter(req, res) {
    var query = Materia.find({'active': true});

    if (req.query.nivel)        query.where('nivel', req.query.nivel);
    if (req.query.disciplina)   query.where('disciplina', req.query.disciplina).or('alldisc', true);

    query
        .populate('nivel')
        .populate('periodo')
        .populate('disciplina')
        .exec(function(err, result) {
            if (err) res.send(err);
            res.json(result);
        });
}

La linea con el if de disciplina me complica.
Esa condición sería que si existe el filtro de disciplina, me tiene que traer el que coincida con la disciplina o los que tengan el campo alldisc en true.
Desde ya muchas gracias.

A: Te recomiendo siempre trabajar en capas, delegar funcionalidades específicas a cada una para que se tenga una sola responsabilidad. Recuerda que una aplicación altamente acoplada/cohesiva, significa una muy baja probabilidad de que pueda escalar y mantenerse en un futuro.
La siguiente clase actúa como repositorio para una colección. Su función es simplemente consultar a la base de datos.

Consejo: de preferencia tiende a usar Promesas en lugar de callbacks ya que provee una sintaxis limpia en procesos complejos (evitando los callback hell) y además, te verás beneficiado si decides usar la recientemente aprobada especificación async/await que saldrá en ES2017.

class MateriaRepository {
  filter (nivel disciplina) {
    let where = { active: true };

    if (nivel) {
      where.nivel = nivel;
    }

    if (disciplina) {
      where.$or = [
        {
          alldisc: true
        },
        {
          disciplina
        }
      ]
    }

    return (
      Materia
        .find(where)
        .populate('nivel')
        .populate('periodo')
        .populate('disciplina')
        .exec()
    );
  }
}

De esta manera puedes usar dichos métodos en cualquier lugar.
function getMateriasFilter (req, res) {
  let repository = new MateriaRepository();
  let { nivel, disciplina } = req.query;

  repository
    .filter(nivel, disciplina)
    .then((materias) => (
      res.jsonp(materias)
    ));
}

La anterior consulta se explica de la siguiente manera:

*

*Por defecto, el where solo especifica que se seleccionen solo las materias activas (active: true).

*Si el parámetro nivel está disponible, añade una entrada al where para que se seleccione solo las materias activas y tengan el nivel especificado.

*Si el parámetro disciplina está disponible, se añade una entrada de tipo $or al where para seleccionar las materias activas, de cierto nivel y de cierta disciplina o si la materia tiene alldisc: true.


text:
Q: JavaScript function does consol.log(var) but doesn't var2 = var I follow this tutorial: https://developers.google.com/web/fundamentals/codelabs/push-notifications#notification_click and implemented it to VueJS.
On the created hook, I run this function:
register() {
      if ("serviceWorker" in navigator && "PushManager" in window) {
        console.log("Service Worker and Push is supported");

        navigator.serviceWorker
          .register("/sw.js")
          .then(function (swReg) {
            console.log("Service Worker is registered", swReg);
            swRegistration = swReg;
          })
          .catch(function (error) {
            console.error("Service Worker Error", error);
          });
      } else {
        console.warn("Push messaging is not supported");
        pushButton.textContent = "Push Not Supported";
      }
    }

My console in Chrome, Safari and Firefox prints:
"Service Worker and Push is supported"
"Service Worker is registered >ServiceWorkerRegistration"
"Service Worker Error ReferenceError: swRegistration is not defined"

Does anybody know why swReg could be logged, but swRegistration not be assigned?
.then(function (swReg) {
                console.log("Service Worker is registered", swReg);
                swRegistration = swReg;

A: Maybe because swRegistration is not defined? Try to add let swRegistration at the top of your snippet, and everything will be ok.
Enjoy.

A: You should declare the swRegistration first, you don't face same
issue with swReg because its the result of register promise.
register() {
      let swRegistration = null;
      if ("serviceWorker" in navigator && "PushManager" in window) {
        console.log("Service Worker and Push is supported");

        navigator.serviceWorker
          .register("/sw.js")
          .then(function (swReg) {
            console.log("Service Worker is registered", swReg);
            swRegistration = swReg;
          })
          .catch(function (error) {
            console.error("Service Worker Error", error);
          });
      } else {
        console.warn("Push messaging is not supported");
        pushButton.textContent = "Push Not Supported";
      }
    }


text:
Q: Angular 6 : PrimeNG Tab View : How to preserve state when move between tab panel In Angular 6 application, I'm using PrimeNG Tabview control. There are two tab panel. One is for search and second is for customer listing. My requirement is once I search something on first panel and move between two panel then I don't want to loose data what I've searched on first panel.
In primeNG Tabview there's cache property but It's for lazy loading only.
Following is sample code.

I want to keep onChange event to refresh the customerlist everytime I click on that tab.
If need more code please do let me know so I will copy whole my code for your reference.


text:
Q: Blog posts permalinks correct but recent post widgets goes to my website and not staying on my blog site I am a novice, but I have my website, online store and blog looking the way I want them.  I had to change my blog theme because the widgets were in the wrong place so I chose another theme (raindrops). The only problem is that my blog widgets such as categories, recent posts, etc., when clicked on go to my website instead of my blog site.
The blog and store are subdomains under digitaldesignzonline.com  and all have separate folders and wordpress installs.  My website digitaldesignzonline.com (so far) is working great, and my store: digitaldesignzonline.com/store seems to be also.
The only problem is my blog: digitaldesignzonline.com/blog.  When I click on the recent posts widget in the sidebar, the address show the correct post link and name, but actually goes to my website (digitaldesignzonline.com)
My blog pages direct back to the website, but that doesn't bother me.  I think it is where the problem may be? It is a child theme.
I have tried different themes, deleted  a ton of plugins that were not activated, checked the permalinks settings, and tried everything I can think of.
I have googled for 12 hours and can't find the problem.  Please help me before I have a stroke trying to figure this out!
PS I am a novice at php, etc., but can follow instructions if clear and precise.
You will be my hero if you can help me!

A: Make sure your "WordPress address (URL)" is set correctly under Settings > General.


text:
Q: Hidden Stacklayout taking up space in xamarin forms I'm creating a form in Xaml using Xamrin which  contains absolute layout in which i'm hiding a stacklayout. but one more stacklayout just down below of hidden stacklayout but hidden stacklayout is taking up space.
What i want to do.When i did hide one stacklayout another stacklayout should take place of hidden staklayout.

A: Thanks for help and supports.
I've resolved the issue:
I followed this link
https://forums.xamarin.com/discussion/83632/hiding-and-showing-stacklayout in this link they said that use grid and make row height auto and it will automatically adjust the extra space of layout.
<Grid VerticalOptions="Fill">
    <Grid.RowDefinitions>
        <RowDefinition Height="100"/>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <StackLayout Grid.Row="1" Spacing="20">
        <StackLayout Margin="10,0">
            <Label Text="lable 1" VerticalOptions="Center" FontSize="Small" />
            <Label Text="lable 2" VerticalOptions="Center" FontSize="Small" />
        </StackLayout>
        <StackLayout IsVisible="{Binding IsStudent}" Margin="10,0">
            <Label Text="lable3" VerticalOptions="Center" FontSize="Small" />
            <Label Text="lable 4" VerticalOptions="Center" FontSize="Small" />
            <Label Text="lable 5" VerticalOptions="Center" FontSize="Small" />
            <Label Text="lable 6" VerticalOptions="Center" FontSize="Small" />
        </StackLayout>
    </StackLayout>
    <StackLayout Grid.Row="2" Spacing="20" >
        <local:Button
            x:Name="btnSave"
            Text="Submit"
            VerticalOptions="End"
            HorizontalOptions="FillAndExpand"
            IsVisible="{Binding IsBusy, Converter={x:Static local:InverseBoolConverter.Instance}}"
            AutomationId="saveButton" />
    </StackLayout>
</Grid>

A: No need for a grid.
Set the IsVisible AND HeightRequest properties.
 MyStackLayout.IsVisible = false;
 MyStackLayout.HeightRequest = 0; // trigger recalc of space layout.

The change in heightrequest triggers the desired recalculations.

A: I've too looked into why those hidden controls are taking space and well... they ARE taking space and that's it.
You can do a simple addition and removing of labels. Something like this:
public class MyStack : StackLayout
{
    Label
        _label1 = new Label(),
        _label2 = new Label(),
        _label3 = new Label();

    public void ShowLabels()
    {
        Children.Add(_label1);
        Children.Add(_label2);
        Children.Add(_label3);
    }

    public void HideLabels()
    {
        Children.Remove(_label1);
        Children.Remove(_label2);
        Children.Remove(_label3);
    }
}

A: My recomendation is putting a StackLayout at the bottom of the content, in order to keep the original height of the other elements at the top.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="CentroDono.Views.YOURVIEWPAGE"
              Title="YOURVIEWTITLE"
             x:Name="YOURPAGECONTENTNAME">
    <ContentPage.Content>
        <StackLayout>
        <!--VISIBLE CONTENT-->
            <Label Text="HELLO"/>
        </StackLayout>
        <StackLayout>
            <Label Text="FOOTER"/>
            <!--INVISIBLE CONTENT-->
            <Label x:Name="_searchText"  Text="Result1" IsVisible="False"/>
            <Label x:Name="_searchText2"  Text="Result2" IsVisible="False"/>
            <Label x:Name="_searchText3"  Text="Result3" IsVisible="False"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>


text:
Q: IndexError: list index out of range. How to resolve this? Hi i am trying to plot data through k means,and i want a single figure with the labels as well,However i am not able to plot the data, and i referred from this example "https://github.com/donglinchen/text_classification/blob/master/text_clustering_and_visualization.ipynb"
fig, axes = plt.subplots(2, sharey=True)
fig.set_size_inches(20, 10)
colors = ['green','orange', 'blue', 'purple', 'red']
for e in set(model.labels_):
    mark = model.labels_ == e
    axes[0].scatter(feature_pca[:, 0][mark], feature_pca[:, 1][mark], color=colors[e], label=e, alpha=0.9)
axes[0].legend().

But i am getting the plotted data as:


text:
Q: Group by query base on a composed field on the select So, I have these documents:
[
    { defaultName: "product X", brand: { name: "brand 00", id: "brand00-00" }, externalSpec: "spec00" },
    { defaultName: "product Y", brand: null, externalSpec: "spec01" },
    { defaultName: "product LL", brand: { name: "brand 01", id: "brand00-01" }, externalSpec: "spec00" },
    { defaultName: "product X", brand: { name: "brand 00", id: "brand00-00" }, externalSpec: "spec01" },
]

I'm using Group By with this query and it's working fine by a existing field on the documents:
SELECT ARRAY_AGG(p) FROM `BucketXXX` AS p
WHERE p.type = 'product'
AND p.deleted = false
GROUP BY p.defaultName

Now I would like to use my group by query but using a concatenated field on the select clause, I need this to check if the products are equal, something like:
    SELECT p.defaultName || p.brand.id || p.externalSpec AS custom_key, ARRAY_AGG(p) FROM `BucketXXX` AS p
    WHERE p.type = 'product'
    AND p.deleted = false
    GROUP BY custom_key

but no luck, currently getting error 3000 syntax error near AS, also keep in mind that brand could be null and I would like to add an empty string if that is null to continue with the externalSpec field,
Appreciate for the help,
Thanks

A: Projection Alias can be used in ORDER BY Only. Due to evaluation order (FROM, JOIN, LET, WHERE, GROUP BY, LETTING, PROJECTION, ORDER BY).
CB 6.5 or higher GROUP BY alias is supported
SELECT custom_key, ARRAY_AGG(p) FROM `BucketXXX` AS p
WHERE p.type = 'product'
AND p.deleted = false
GROUP BY p.defaultName || p.brand.id || p.externalSpec AS custom_key;

OR
SELECT custom_key, ARRAY_AGG(p) FROM `BucketXXX` AS p
LET custom_key = p.defaultName || p.brand.id || p.externalSpec
WHERE p.type = 'product'
AND p.deleted = false
GROUP BY custom_key;

You have null brand, If required use CONCAT(p.defaultName, IFMISSINGORNULL(p.brand.id,""), p.externalSpec)


text:
Q: Security Error in angular 2 application routing on using browser authentication in the URL I am running into a problem with my angular 2 application on using the URL with browser authentication credentials. If I load the URL without the credentials, it works as expected.
But if I trigger the URL in the format:
https://username:password@[REST_OF_URL], the different page sections are not loading withe such errors being thrown in the console:

EXCEPTION: Uncaught (in promise): SecurityError: The operation is
  insecure.

I am currently checking it in FireFox version 52.
I debugged, and the issue appears to be due to failure in the routing mechanism when authentication credentials are used.
I followed the router event tracking as suggested here:
How to detect a route change in Angular?
The NavigationStart and RoutesRecognized events are triggered as expected with correct resolution of routes. After this, NavigationError is triggered with the error mentioned above:

SecurityError: The operation is insecure.

How shall I address this? Any known issues to address with routing when using authentication credentials?


text:
Q: Map plot won't show in Shiny app, no error shown I am fairly new to R Shiny and I've been working on an app with an interactive world map which shows each country's performance at the Olympics, using scale_fill_gradient. The app user gets to choose the performance indicator (total medals won, gold only, weighted score) and the year (1996 to 2020).
The problem is there's no more error shown, but the plot doesn't show either! I have tried to run the functions as normal R script and they worked fine there (the plot showed up in the viewer pane). I found a few others who have also run into problems with no plot or error showing, but their cases are different to mine (e.g. mismatch in Output and Render) so the resolutions don't work for me.
It's a massive dataset so I've not included it here, I thought I might check first if the error could be spotted from the code alone. Here's what I've used:
function
world_map1 <- function(WorldMap, year, performance) {

  w_plot1 <- WorldMap %>%
    filter(Year == year) %>%
    select("long", "lat", "group", "region", all_of(performance)) %>%
    replace(is.na(.), 0) %>%
    rename_at(performance, ~ "Value") %>%
    mutate(Value = as.numeric(as.character(Value)))

  tooltip_css <- "background-color:#2E2E2E; font-family: Calibri; color:#F2F2F2;"

  w_g1 <- ggplot() +
    geom_polygon_interactive(data = subset(w_plot1, lat >= -60 & lat <= 90),
                             aes(x = long,
                                 y = lat,
                                 fill = Value,
                                 group = group,
                                 tooltip = sprintf("%s<br/>%s", region, Value))) +
    scale_fill_gradient(name = "Medals /Score",
                        low = "lightgoldenrodyellow",
                        high = "goldenrod1",
                        na.value = "white")

  return(
    girafe(
      ggobj = w_g1,
      options = list(
        opts_tooltip(
          css = tooltip_css
        )
      ))
  )
}

ui
ui <- fluidPage(
  titlePanel("Title"),
  sidebarLayout(
    sidebarPanel(
      radioButtons(inputId = "performance", label = "Performance measure:",
                   choices = c("Total medals won" = "Total",
                               "Gold medals won" = "Gold",
                               "Weighted points system" = "Weighted"
                   )),
      width = 3

    ),
    mainPanel(
      girafeOutput("mapPlot1"),
      sliderInput(inputId = "year", label = "Year:",
                  min = 1996, max = 2020, step = 4, value = 1996, ticks = FALSE, sep = ""
      )
    )
  )
)

server
server <- function(input, output) {
  output$mapPlot1 <- renderGirafe({
      ggiraph(code = print(world_map1(WorldMap, input$year, input$performance)))
    }

  )
}

run app
shinyApp(ui = ui, server = server)

Any help or insights appreciated!
I thought it was my theme() block so I removed that, as shown above. Also checked other cases on no plot showing here, couldn't find one with fixes that would work for me because it seems the underlying problem is different?


text:
Q: opening jar file with admin privilege I am getting this exception when i open jar file using cmd:
java.io.FileNotFoundException: C:\Windows\System32\drivers\etc\hosts.File (Access is denied)
How can i open jar file with administrator privilege?
Simply double clicking the jar file does not open the jar file.I am using win7 as OS.

A: If I understand correctly, you're trying to run java from a command prompt but want admin privileges. In that case, right-click on the "command prompt" and choose "run as administrator", then you can
java -jar myprogram.jar

from the command prompt as before.
However do you really want to allow this program to edit your hosts file? I'd recommend you find out what it's trying to do and make the change manually if you're happy with it.

A: If you want to run jar file with admin privileges from console or by double clicking, without explicitly executing it with admin rights Which is most obvious from user's point of view as he might just know how to click and not internal working. Then this is my post answering your quest in simple steps.
Run Java file as Administrator with full privileges


text:
Q: Troubles after upgrading react-native to 0.56 i have troubles updating the new version of react-native which appears to improve vastly and a lot of features.
After reading this article :
https://facebook.github.io/react-native/blog/2018/07/04/releasing-react-native-056
I've started to run this command : https://facebook.github.io/react-native/docs/upgrading.html
All goes well, the application is built after running react-native run-ios
The problem is the bundle which is buggy :

node node_modules/react-native/local-cli/cli.js start "--reset-cache"
  Scanning folders for symlinks in
  /Users/julestruong/Dev/BAP/flex/v1/flex-mobile-app/node_modules (14ms)
  warning: the transform cache was reset.
Cannot find module 'metro/src/transformer'
npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! flex@0.0.1 start:
  node node_modules/react-native/local-cli/cli.js start
  "--reset-cache" npm ERR! Exit status 1 npm ERR! npm ERR! Failed at
  the flex@0.0.1 start script. npm ERR! This is probably not a problem
  with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:

Tries :

*

*remove node_modules

*start --reset-cache

*delete package-lock.json and reinstall.

Nothing works ...

A: If you're using typescript you'll need to upgrade react-native-typescript-transformer to 1.2.10 since metro moved the transformer it relies on.


text:
Q: Kruskal - Wallis p-value matrix for data subsets with R Consider a dataset Data which has several factor and several numerical continuous variables. Some of these variables, let's say slice_by_1 (with classes "Male", "Female") and slice_by_2 (with classes "Sad", "Neutral", "Happy"), are used to 'slice' data into subsets. For every subset Kruskal-Wallis test should be run on variables length, preasure,pulse each grouped by the other factor variable called compare_by. Is there a quick way in R to accomplish this task and put calculated p values to a matrix?
I used dplyr package to prepare data.
Sample dataset:
library(dplyr)
set.seed(123)
Data <- tbl_df(
   data.frame(
       slice_by_1 = as.factor(rep(c("Male", "Female"), times = 120)),
       slice_by_2 = as.factor(rep(c("Happy", "Neutral", "Sad"), each = 80)),
       compare_by = as.factor(rep(c("blue", "green", "brown"), times = 80)),
       length   = c(sample(1:10, 120, replace=T), sample(5:12, 120, replace=T)),
       pulse    = runif(240, 60, 120),
       preasure = c(rnorm(80,1,2),rnorm(80,1,2.1),rnorm(80,1,3))
   )
   ) %>%
group_by(slice_by_1, slice_by_2)

Let's look at data:
Source: local data frame [240 x 6]
Groups: slice_by_1, slice_by_2

   slice_by_1 slice_by_2 compare_by length     pulse     preasure
1        Male      Happy       blue     10  69.23376  0.508694601
2      Female      Happy      green      1  68.57866 -1.155632020
3        Male      Happy      brown      8 112.72132  0.007031799
4      Female      Happy       blue      3 116.61283  0.383769524
5        Male      Happy      green      7 110.06851 -0.717791526
6      Female      Happy      brown      8 117.62481  2.938658488
7        Male      Happy       blue      9 105.59749  0.735831389
8      Female      Happy      green      2  83.44101  3.881268679
9        Male      Happy      brown      5 101.48334  0.025572561
10     Female      Happy       blue     10  62.87331 -0.715108893
..        ...        ...        ...    ...       ...          ...

An example of desired output:
    Data_subsets    length  preasure     pulse
1     Male_Happy <p-value> <p-value> <p-value>
2   Female_Happy <p-value> <p-value> <p-value>
3   Male_Neutral <p-value> <p-value> <p-value>
4 Female_Neutral <p-value> <p-value> <p-value>
5       Male_Sad <p-value> <p-value> <p-value>
6     Female_Sad <p-value> <p-value> <p-value>

A: You have most of it with the group_by, now you just need to do it:
Data %>%
    do({
        data.frame(
            Data_subsets=paste(.$slice_by_1[[1]], .$slice_by_2[[1]], sep='_'),
            length=kruskal.test(.$length, .$compare_by)$p.value,
            preasure=kruskal.test(.$preasure, .$compare_by)$p.value,
            pulse=kruskal.test(.$pulse, .$compare_by)$p.value,
            stringsAsFactors=FALSE)
    }) %>%
    ungroup() %>%
    select(-starts_with("slice_"))
## Source: local data frame [6 x 4]
##     Data_subsets    length  preasure     pulse
## 1   Female_Happy 0.4369918 0.1937327 0.8767561
## 2 Female_Neutral 0.3750688 0.8588069 0.2858796
## 3     Female_Sad 0.7958502 0.6274940 0.5801208
## 4     Male_Happy 0.3099704 0.6929493 0.3796494
## 5   Male_Neutral 0.4953853 0.2986860 0.2418708
## 6       Male_Sad 0.7159970 0.8528201 0.5686672

You have to do the ungroup() to remove the slice* columns, since group_by columns aren't dropped (I'd like to say "never dropped", but I am not certain of that).

A: We could use Map within do for doing the multiple column kruskal.test and then use unite from library(tidyr) to join the 'slice_by_1' and 'slice_by_2' columns to a single column 'Data_subsets'.
library(dplyr)
library(tidyr)
nm1 <- names(Data)[4:6]
f1 <- function(x,y) kruskal.test(x~y)$p.value

Data %>%
     do({data.frame(Map(f1, .[nm1], list(.$compare_by)))}) %>%
     unite(Data_subsets, slice_by_1, slice_by_2, sep="_")
#     Data_subsets    length     pulse  preasure
#1   Female_Happy 0.4369918 0.8767561 0.1937327
#2 Female_Neutral 0.3750688 0.2858796 0.8588069
#3     Female_Sad 0.7958502 0.5801208 0.6274940
#4     Male_Happy 0.3099704 0.3796494 0.6929493
#5   Male_Neutral 0.4953853 0.2418708 0.2986860
#6       Male_Sad 0.7159970 0.5686672 0.8528201

Or we can do this using data.table.  We convert the 'data.frame' to 'data.table' (setDT(Data)), create grouping variable ('Data_subsets') by pasteing the 'slice_by_1' and 'slice_by_2' columns, then we subset the columns of the dataset and pass that as input to Map, do the krusal.test and extract the p.value.
library(data.table)
setDT(Data)[, Map(f1, .SD[, nm1, with=FALSE], list(compare_by)) ,
             by = .(Data_subsets= paste(slice_by_1, slice_by_2, sep='_'))]
#     Data_subsets    length     pulse  preasure
#1:     Male_Happy 0.3099704 0.3796494 0.6929493
#2:   Female_Happy 0.4369918 0.8767561 0.1937327
#3:   Male_Neutral 0.4953853 0.2418708 0.2986860
#4: Female_Neutral 0.3750688 0.2858796 0.8588069
#5:       Male_Sad 0.7159970 0.5686672 0.8528201
#6:     Female_Sad 0.7958502 0.5801208 0.6274940


text:
Q: Writing an upstart file which allows the user to input username and password I'm trying to write an upstart file for OpenConnect. The task is pretty simple, but I'm stuck because I don't want to provide the username and password in a config file, but prompt the user to provide them each time.
The upstart file, placed in /etc/init/openconnect.conf is
exec /usr/sbin/openconnect --script=/etc/vpnc/vpnc-script my-gw.example.com

However, when I execute
start openconnect

the process is backgrounded immediately and I get no chance to provide input.
How can I make this upstart job ask the user for input?

A: I can't speak to Upstart doing something requiring user input, but it sounds like that is a no go from the comments.
If you wanted to use openconnect with Upstart, no additional config file, AND not ask for user input then you can use -u is for the username and --passwd-on-stdin for the password. For example:
script
  echo 'pw_here' | openconnect --passwd-on-stdin vpn_domain_here -u username_here
end script


text:
Q: How to create modal popup in Android? I'm not up to date with Android solutions and I wonder what is the most current way to display popup/modal/alert dialog in application?
2 years ago I used to use alert (or fragment) dialogs with custom view. I heard that nowadays this is possible by special activity.
What are the current patterns for that case?

A: You can use the android:theme to make an activity look like a dialog. Add a tag similar to this to your activity in the Android Manifest.
<activity
....
android:theme="@android:style/Theme.Holo.Light.Dialog"
..../>


text:
Q: MediaWiki: Parameters for external images I'm trying to set some parameters (e.g. size, alignment) for external images on my MediaWiki.
I have both $wgAllowExternalImages and $wgAllowImageTag set to true, but it still doesn't work. Trying
[[Image:https://upload.wikimedia.org/wikipedia/commons/a/a0/Sega-Genesis-Model2-32X.jpg|50px]]

or
[[File:Sega-Genesis-Model2-32X.jpg|link=https://upload.wikimedia.org/wikipedia/commons/a/a0|caption]]

doesn't work.
Just displaying images, without setting any parameters, works by https://upload.wikimedia.org/wikipedia/commons/a/a0/Sega-Genesis-Model2-32X.jpg.
However, everything works with internal images.
Sources: Help:Images - MediaWiki

A: Your use case is an image on Wikimedia Commons, which is not an external image but an image from a foreign repo. Just enable InstantCommons (and make sure your thumbnailer is configured, of course).
$wgUseInstantCommons = true;

Then use the image as a local one:
[[Image:Sega-Genesis-Model2-32X.jpg|50px]]


text:
Q: Excel;seek medianvalue with if statement over a range of values I seek the median value for a group of ages: 18-24, 25-29, 30-34 and so on. I have the data in sheeet Wages; wages in column G and ages in column I.
In the output sheet I have formed a range of ages in B9:B58 from 18 years in B9 to 67 years in B58 to "help" to form the formula. I tried this for 18-24 years (7 years interval in B9:B15):
=MEDIAN(IF((Wages!$I$1:$I$7000=B9:B15),Wages!$G$1:$G$7000)).

(The rest should be in 5 years interval)

A: Write or generate in columns A and B the bounds of your ranges, so that A9:B9 = 18, 24, A10:B10 = 25, 29 etc... until A18:B18 = 65, 69. Then write this Array Formula (paste then click Ctrl+Shift+Enter) in C9 :
=MEDIAN(IF((Wages!$I$1:$I$7000>=$A9)*(Wages!$I$1:$I$7000<=$B9), Wages!$I$1:$I$7000))

Then you can copy/paste C9 into C10:C18.


text:
Q: futures.ThreadPoolExecutor Exceptions I'm implementing futures.ThreadPoolExecutor and would like to change the broad Exception to specific exceptions (e.g. ValueError). Using the example below should I add the exceptions generated by load_url instead of the broad Exception? which Exceptions this section of code is referring to.
Using this page as reference:
import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the url and contents
def load_url(url, timeout):
    if not url:
       raise ValueError('Invalid URL')
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))


text:
Q: automatic change post date when post is 30 days old I am using below code, but not working. pls tell me is there any other way or where i am doing mistake?
//cron work
function isa_add_every_minutes( $schedules ) {

    $schedules['every_minutes'] = array(
            'interval'  => 60,
            'display'   => __( 'Every 1 Minutes', 'textdomain' )
    );

    return $schedules;
}
add_filter( 'cron_schedules', 'isa_add_every_minutes' );

// Add function to register event to WordPress init
add_action( 'init', 'register_event');

// Function which will register the event
function register_event() {

    // Make sure this event hasn't been scheduled
    if( !wp_next_scheduled( 'post_status_change' ) ) {
        // Schedule the event
        wp_schedule_event( time(), 'every_minutes', 'post_status_change' );
    }
}

add_action( 'post_status_change', 'post_status_change_all' );

// This function will run once the 'delete_post_revisions' is called
function post_status_change_all() {

 global $wpdb;
  $daystogo = "5";
  $sql = "UPDATE wp_posts SET post_status = 'draft' WHERE post_type = 'post' AND DATEDIFF(NOW(), post_date) > '$daystogo')";
  echo $sql;
  $wpdb->query( $sql );
}

Thanks..

A: This is solved now. I have been added : 'date_default_timezone_set('Asia/Calcutta'); '
there was the time error. current time, i was getting wrong.


text:
Q: Is using $.get to manipulate data a bad idea? In the Steven Sanderson book, it's said that using get to delete, update,... he recomand ti use Post. Is not a good idea. Let's say I have a link that says "disable" to disable a record. I'd like to use
$.get(...)

Instead of
@html.ActionLink("Disable",

To disable that row. is it still bad to use getajax function?
EDIT
Disable

Thanks for helping

A: Once someone made Delete Database links (as an a href) which posted GET requests to the server, then a search engine came along and found this "hidden admin page" and clicked each link.
GET requests are a developer's way to label something "safe" for search engines, browser pre-caching, etc. Never use them for data-changing functionality.

A: Basically, the main problem with this method is that browsers tend to assume "getting" something to be a pretty harmless action. And not just browsers - even web crawlers from search engines, looking around at each available link, might go to that URL to see what might be there.
Plus, it means that all the details of every request is very easy to snoop on - even an HTTPS-encrypted transmission could show the URL requested as "updatePatientDetails.php?diagnosisTitle=Anal_Inflammation&patientSSN=100101011"
Yeah, this is not one of those "light" recommendations that everyone just ignores anyway. At the very least, I'd rather someone improperly use POST requests for everything - but not GET.


text:
Q: How to in-place-construct an optional aggregate? How to in-place construct an optional aggregate? It seems I can only construct an optional single thing, and not an optional aggregate of things.
#include <optional>
#include <iostream>

struct Unmovable
{
    Unmovable(const Unmovable&) = delete;
    Unmovable(Unmovable&&) = delete;
    Unmovable& operator=(const Unmovable&) = delete;
    Unmovable& operator=(Unmovable&&) = delete;

    explicit Unmovable(const char* msg) {
        std::cout << msg << '\n';
    }
};

struct Things
{
    Unmovable one;
    Unmovable two;
};

int main(int argc, char* argv[]) {
    const bool y = argc > 1 && argv[1][0] == 'y';

    std::optional<Unmovable> optionalThing = y
        ? std::optional<Unmovable>{"works"}
        : std::nullopt;

    std::optional<Things> optionalThings = y
        ? std::optional<Things>{
#if ATTEMPT == 1
            "jadda", "neida"
#elif ATTEMPT == 2
            {"jadda", "neida"}
#elif ATTEMPT == 3
            Things{"jadda", "neida"}
#elif ATTEMPT == 4
            Unmovable{"jadda"}, Unmovable{"neida"}
#elif ATTEMPT == 5
            {Unmovable{"jadda"}, Unmovable{"neida"}}
#elif ATTEMPT == 6
            Things{Unmovable{"jadda"}, Unmovable{"neida"}}
#elif ATTEMPT == 7
            std::in_place_t{}, "jadda", "neida"
#elif ATTEMPT == 8
            std::in_place_t{}, {"jadda", "neida"}
#elif ATTEMPT == 9
            std::in_place_t{}, Things{"jadda", "neida"}
#elif ATTEMPT == 10
            std::in_place_t{}, Unmovable{"jadda"}, Unmovable{"neida"}
#elif ATTEMPT == 11
            std::in_place_t{}, {Unmovable{"jadda"}, Unmovable{"neida"}}
#elif ATTEMPT == 12
            std::in_place_t{}, Things{Unmovable{"jadda"}, Unmovable{"neida"}}
#endif
        } : std::nullopt;
}

A: If you can use C++20, then what you want is
std::optional<Things>{std::in_place, "jadda", "neida"};

as seen in this live example.  The reason you need C++20 is that the std::in_place_t constructor uses the form of
T(std::forward<Args>(args)...)

to initialize the object, but () only works for classes that have a constructor, which Things does not.  C++ was updated to fix this, and that change made it into C++20.
In C++17 you can get this code to work by providing a constructor for Things that will  initialize the members.  That would look like
struct Things
{
    Things(const char* msg1, const char* msg2) : one(msg1), two(msg2) {}
    Unmovable one;
    Unmovable two;
};

int main()
{
    std::optional<Things>{std::in_place, "jadda", "neida"};
}

and you can see that working in this live example

In case you were curious, the new language added to handle this in C++20 can be found in [dcl.init.general]/15.6.2.2


text:
Q: Change password is firing when the enter key is hit in any textbox I have a searchbar on my site, but the problem is that when the user is in their profile I display a changepassword asp.net object. I'm using Visual Studio 2012.
<asp:ChangePassword ID="ChangePassword1" runat="server" SuccessTextStyle-HorizontalAlign="Center" CancelButtonText="" CancelButtonType="Link" ContinueButtonText="" ContinueButtonType="Link">
</asp:ChangePassword>

When I try to add my searchbar
<asp:TextBox ID="txtSearch123" runat="server" OnTextChanged="txtSearch123_TextChanged" Width="217px" Text="Search for an item..." OnClick="this.value=''" AutoCompleteType="Disabled"></asp:TextBox>

When the user presses enter, the search never completes because the textboxes inside in the change password are empty and they light up as if the user is trying to change their password. Even though they aren't linked what so ever.
Any ideas?
Following Works:
<asp:ChangePassword ID="ChangePassword2" runat="server" ValidationGroup="Password"> </asp:ChangePassword>
<asp:TextBox ID="txtSearch123" runat="server" OnTextChanged="txtSearch123_TextChanged" Width="155px" Text="Search for an item..." OnClick="this.value=''" AutoCompleteType="Disabled" ValidationGroup="SearchItem"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="" Width="0" Height="0" ValidationGroup="SearchItem" Visible="false" />
IF that does not work, do the following...
Make a button with the same validation as the text box.
Set the height and width to the button to 0.
Set the border type to none
Set the background of the button to the background you are trying to place it on.
Boom, your button is hidden in plain sight and your validation group still works.
<asp:TextBox ID="txtSearch123" runat="server" OnTextChanged="txtSearch123_TextChanged" Width="217px" Text="Search for an item..." OnClick="this.value=''" AutoCompleteType="Disabled" ValidationGroup="SearchItem"></asp:TextBox>

<asp:Button ID="btnSearch" runat="server" Text="" Width="0" Height="0" ValidationGroup="SearchItem" BackColor="#5F605F" BorderStyle="None" />

A: There's two concepts you need to understand first.
The fact is, that everything on a (normal) ASP.NET page is inside one single form. This also means that things like "pressing enter to send form" are a bit tricky, since they submit the whole form, which usually isn't what you want.
Now to the concepts:

*

*ValidationGroup - this setting on .NET validators (and buttons etc.) allows you to separate different logical forms inside the one superform. The validators will only evaluate if the originator of the submit action (eg. the "change password button") is in the same ValidationGroup. Properly configuring validation groups should make this part of your issue disappear.

*What happens on enter key press - by default, you send the whole form, without doing any button's action. So, if you have multiple logical forms on one page, you have to put each inside its own Panel, which has a DefaultButton property, which says "if I press enter inside this panel, it will act as if I clicked on this button".

A: SET ValidationGroup in your TextBox
<asp:TextBox ID="txtSearch123" runat="server" OnTextChanged="txtSearch123_TextChanged" Width="217px" Text="Search for an item..." OnClick="this.value=''" AutoCompleteType="Disabled" ValidaionGroup="Something"></asp:TextBox>

Specifying Validation Groups


text:
Q: GWT - paint to CanvasPixelArray with filling I am searching (did not find yet) for a library that can paint to a CanvasPixelArray object with filling abilities.
I wan to be able to call beginFill function, draw some lines and than call endFill.
Is there such library?
Maybe GWT has such functionality?


text:
Q: $\sum _{n=0}^{\infty } \frac{x^n}{n+3}$, sum, area of convergence & center I want to find the
$$\sum _{n=0}^{\infty } \frac{x^n}{n+3}$$
now this is how I thought about doing it but I get stuck.
$$\sum _{n=0}^{\infty } x^n=\frac{1}{1-x}$$ given that absolute value of x is less then zero.
$$\int x^n \, dx=\frac{x^{n+1}}{n+1}$$
I keep integrating the result until I get
$$\frac{x^{n+3}}{(n+3) (n+1) (n+2)}=\frac{3 x^2}{4}-\frac{1}{2} x^2 \log (1-x)-\frac{x}{2}+x \log (1-x)-\frac{1}{2} \log (1-x)$$
I thought about multiplying by $$\frac{(n+1) (n+2)}{x^3}$$
However, the answer should be this: $$\sum _{n=0}^{\infty } \frac{x^n}{n+3}=-\frac{\log (1-x)}{x^3}-\frac{1}{x^2}-\frac{1}{2 x}$$
On the interval [-1,1), and $\frac{1}{3}$ if x=0.
Could someone please show me what I did wrong and how the steps should be to get the correct answer?

A: I approached it in a slightly different way using Taylor expansions.
The sum for $x=0$ is trivial.
For $x \in (-1,1)$
$$\log(1+x)=x-\frac{x^2}{2}+\frac{x^3}{3}-\frac{x^4}{4}+\frac{x^5}{5}-\dots$$
$$-\log(1-x)=x+\frac{x^2}{2}+\frac{x^3}{3}+\frac{x^4}{4}+\frac{x^5}{5}+\dots$$
$$-\log(1-x)-x-\frac{x^2}{2}=\frac{x^3}{3}+\frac{x^4}{4}+\frac{x^5}{5}+\dots$$
$$-\frac{\log(1-x)}{x^3}-\frac{1}{x^2}-\frac{1}{2x}=\frac{1}{3}+\frac{x}{4}+\frac{x^2}{5}+\dots = \sum _{n=0}^{\infty } \frac{x^n}{n+3}$$

A: I think this is a good way of handling these series:
Let $s(x)=\sum_{n=0}^{+\infty} \frac{x^n}{n+3}$ (defined for $|x|<1$). Then
$$
x^3s(x)=\sum_{n=0}^{+\infty}\frac{x^{n+3}}{n+3},
$$
and hence
$$
(x^3s(x))'=\sum_{n=0}^{+\infty}x^{n+2}=x^2\sum_{n=0}^{+\infty}x^n=\frac{x^2}{1-x}.
$$
Integrating from $0$ to $t$, we get
$$
t^3s(t)-0^3s(0)=\int_0^t\frac{x^2}{1-x}\,dx = -t-\frac{t^2}{2}-\log(1-t),
$$
so (switching back to $x$ as variable)
$$
s(x)=-\frac{1}{x^2}-\frac{1}{2x}-\frac{\log(1-x)}{x^3}.
$$


text:
Q: Power rule for Logarithms While I understand the proof of the power rule for logarithms for positive integers, I can not prove them for fractional and negative powers. Also curious to know what would a proof for irrational powers look like?
http://www.youtube.com/watch?v=O5jXlG4yHQo

A: If you don't mind using calculus, start with
$$ \ln(x) = \int_1^x \frac{dt} t .$$
Make the substitution $t = s^a$, so $dt = a s^{a-1} ds$, and you get
$$ \ln(x^a) = \int_1^{x^a} \frac{dt} t = a \int_1^{x} \frac{ds} s = a \ln(x).$$

A: Since you didn't specify, I assume that logarithms are defined as the inverse of exponentiation. Specifically, $a^{\log_a(x)} = x$ for any $a>1$ and $x>0$, which also gives $\log_a(a^x)=x$ for any $a>1$ and $x \in \mathbb{R}$. It is easy to prove the rule $a^{bc} = (a^b)^c$ for any $a>0$ and $b,c \in \mathbb{R}$, by first dealing with integer $b$,$c$ and then rationals and then approximating irrational by a limiting sequence of rationals. Now apply $\log_a$ to both sides to get $bc = \log_a((a^b)^c)$. Note that $b = \log_a(a^b)$, so if we substitute $b = \log_a(x)$ for $x>0$, we get $c \cdot \log_a(x) = \log_a((a^{\log_a(x)})^c) = \log_a(x^c)$ for any $a>0$ and $x>0$ and $c \in \mathbb{R}$.

A: You are actually asking if the following true for $a,b\in\mathbb R$.
$$(x^a)^b=x^{ab}.$$
For irrational number, you can find an explanation here.


text:
Q: Is Rogue's power absorption ability limited to just the skin on her hands? In the X-Men movies whenever Rogue touched someone she would temporarily get their powers. And that is why she had to wear gloves all the time, but what I'm wondering is was it only her hands that had this "power"? Or could any part of her body come in contact with another mutant and gain their ability?

A: In the X-Men movies, Rogue's power was to steal the life force from anyone she had skin to skin contact with.  In the case of another mutant, she also stole their power.  I believe the only one capable of surviving prolonged contact with her was Wolverine.

A: Rogue's mutant ability wasn't confined to her hands, but her entire skin.
According to the Marvel Universe Wiki

Rogue is a mutant who formerly possessed the ability to absorb the memories, abilities, personality, and outward physical characteristics of other beings through skin-to-skin contact. Such transfers lasted for 60 times longer than the contact time, with extended contact resulting in the possibility of permanent absorption. No upper limit had been determined for the number of beings Rogue could simultaneously imprint.
  Upon absorbing another's memories, Rogue also gained any associated emotional responses. Rogue was typically able to control such emotions, however absorbing psyches more powerful than her own resulted in Rogue's psyche being supplanted.


text:
Q: Reset ubuntu to its default state I'd like to delete all files and programs on ubuntu 12.10 except the preinstalled ones (in one word, I want to reset the system to it's default state).
Is there any way to do this without reinstalling the OS?


text:
Q: Adding Geo-IP data to Query in Access SQL Ok this sounds like a problem that someone else should have solved already, but I can't find any help on it, just that their should be a better way of doing it than using an unequal join.
I have a log file of session info with a Source IP, and I am trying to create a query, that actually runs, to combine the Log file with Geo-IP data to tell the DB where users are connecting from. my first attempt came to this:-
SELECT coco, region, city
FROM GT_Geo_IP
WHERE (IP_Start <= [IntIP] AND IP_End >=[IntIP])
ORDER BY IP_Start;

it seemed to run quite quick and returns the correct record for a given IP. but when I tried to combine it with the log data, like this:-
SELECT T.IP,G.coco,G.region, g.city
FROM GT_Geo_IP as G, Log_Table as T
WHERE G.IP_Start <= T.IntIP AND G.IP_End >= T.IntIP
ORDER BY T.IP;

it locks access for over 45 mins (pegging one of my cpu cores) before i finally decide i need some CPU back or i should actually have a go at something else. From hunting around and  this is actually slower than i realize, I found this article and indexed both IP_Start and IP_End to optimize the Search, and based on it came up with this:-
SELECT TOP 1 coco, region, city
FROM GT_Geo_IP
WHERE G.IP_Start >= [IntIP]
ORDER BY G.IP_Start;

But with my SQL skills i cant work out how to combine it with my log data.
Basically the question is how do i use the better method with my log data to get the required result? or is there a better way to do it?
The GeoIP data is from IP2Location's LITE-DB3
I have thought about nested queries, but i couldn't work out how to construct it, I thought about using VBA, but i'm not sure it will be any quicker

A: @EnviableOne
Please try this SQL statement.
SELECT
L.IP,
(
SELECT TOP 1
CONCAT(coco, ', ', region, ', ', city)
FROM
GT_Geo_IP
WHERE
IP_Start >= L.intIP ORDER BY IP_Start
) AS Location
FROM
Log_Table AS L;


text:
Q: Shared Polymer/webcomponents I started on a project and wanted to wrap up a component and then share it to another project, however because of company constraints I can't publish it to github as per the documentation suggests.
I managed to share the component through IIS, however I am not sure if this is the best way, as the desired result is having a CDN like way of referencing components into applications.
Here is the code:

This is the component that i want to share: base-element.html

<link rel="import" href="bower_components/polymer/polymer.html">

<dom-module id="base-element">
    <template>

Hello

    </template>

</dom-module>

Here is the bower.json file:

{
  "name": "base-element",
  "private": true,
  "dependencies": {
    "polymer": "Polymer/polymer#^1.2.0"
  },
  "devDependencies": {
    "web-component-tester": "^4.0.0"
  },
  "ignore": []
}

In IIS i setup this as the main application then I setup a virtual app called client which then references this html file.

In the index.html file of the client app

    <link rel="import" href="../base-element.html"/>

Then in the view that I want to display the component:

<base-element></base-element>

This functions however, it would be nice if I could achieve this using grunt serve or something. Any suggestions?

A: A an idea, see my answer to my own question here How can I replace the server in Web Component Tester
This suggests using a proxy server to forward requests at for your base element to your main running server. (or another instance using a nodejs style server).

A: See if this helps - Using Bower as the Package Management tool for Internal, Private Libraries
You can share your component via a private repository and this can be included as a bower dependency. Check the documentation.


text:
Q: Sublime installation on ubuntu (add-apt-repository error) I am trying to install sublime onto my ubuntu server via the following method.
sudo add-apt-repository ppa:webupd8team/sublime-text-3
sudo apt-get update
sudo apt-get install sublime-text-installer

But when I put the first command it gives me this error
sudo: add-apt-respository: command not found

Can anyone help me please?
Tried "Lets_eat_potatos" solution but couldnt solve the prob. this is the snapshot of the error https://www.dropbox.com/s/brsn2tpg8a2mmwj/Selection_201.png?dl=0

A: You need to install it first and then use:
sudo apt-get install software-properties-common python-software-properties

A: That's because the add-apt-repository command is not found.
You need to install python-software-properties for it :
sudo apt-get install python-software-properties


text:
Q: Block editor not loading with rest api custom code We have a custom code to delete Divi's shortcodes in rest api. To achieve that, we have this code with rest_api_init in functions.php. For some reason, this code avoids the block editor to load when we want to write posts. Can some shed me some light about what is happening?
    add_action( 'rest_api_init', function (){
        register_rest_field(
            'post',
            'content',
            array(
                'get_callback'    => 'ap3_divi_do_shortcodes',
                'update_callback' => null,
                'schema'          => null,
            )
        );
        register_rest_field(
            'post',
            'excerpt',
            array(
                'get_callback'    => 'ap3_divi_do_shortcodes',
                'update_callback' => null,
                'schema'          => null,
            )
        );
    });

---

     function ap3_divi_do_shortcodes( $object, $field_name, $request ) {
        ob_start();
        global $wp_query;
       $wp_query->is_singular = true;
        if( !defined('ONLY_ONCE_ap3_divi_do_shortcodes') && function_exists('et_builder_init_global_settings') && function_exists('et_builder_add_main_elements') ) {
            define('ONLY_ONCE_ap3_divi_do_shortcodes', true);
          et_builder_add_main_elements();
        }
        global $post;
        $post = get_post($object['id']);
        $output = array();
        //Apply the_content's filter, one of them interpret shortcodes
     switch( $field_name ) {
            case 'content':
                $output['rendered'] =  apply_filters( 'the_content', $post->post_content );
                break;
            case 'excerpt':
                $output['rendered'] =  apply_filters( 'the_excerpt', $post->post_excerpt );
                break;
        }
        $output['protected'] = false;
        return $output;
        ob_end_flush();

    }


text:
Q: Does Jetbrains Upsource have an API? Would like to write some integration for Upsource, does it have an API ?  I can't seem to find one.
Perhaps the creators could answer if there is or will be one ?

A: Upsource will have an HTTP API starting with version 2.0 that is currently in Early Access.
So far we don't have any documentation for the API though, apart from a mere listing of the exposed methods that is accessible from the right side of the footer in Upsource 2.0 builds.
EDIT: Basic documentation is now available

A: I think the way to start is https://upsource.jetbrains.com/~api_doc/index.html which is JetBrains code review server documentation.
If you want to know for what version the documentation is check bottom left here: https://upsource.jetbrains.com


text:
Q: PHP echo appears to work but doesnt show up in HTML I am trying to use a php script to generate HTML in order to save lines and what not. I am using jQuery to call my php and then put the result into a specified div as shown below:
function createSidebarRow(div, cellNum, rowName, rowDesc) {
            $("#" + div).load("createIndexSidebarRow.php?cellNum=" + cellNum + "&rowName=" + rowName + "&rowDesc=" + rowDesc);
        }

However, when this is executed the HTML is not updated on the page, I can see that the code has worked because the browser network activity confirms it. I am trying to figure out what is causing it to not update.
This is the network activity confirming the echo'd HTML.

A: It might be so, that the div is not yet created in the DOM. (the div that should received the html).
Are you calling createSidebarRow directly on page load?
If so, put the function call in a document ready:
jQuery(document).ready(function(){
    createSidebarRow (... );
});

A: Sorry for stating the obvious, but the div you are trying to fill up does exist with that particular id right?
If so, try this:
$("#" + div).load("createIndexSidebarRow.php?cellNum=" + cellNum + "&rowName=" + rowName + "&rowDesc=" + rowDesc, function() {
    alert('success');
});

If the id does exist (and it's unique) and you get an alert there should be no reason for it not to work.

A: Turns out jQuery doesn't play ball when you include spaces in the POST URL. I removed the space and used %20 instead and all is well now. Thanks for any advice.